instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public List<Object> getAllPrincipals() {
throw new UnsupportedOperationException("SpringSessionBackedSessionRegistry does "
+ "not support retrieving all principals, since Spring Session provides "
+ "no way to obtain that information");
}
@Override
public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
Collection<S> sessions = this.sessionRepository.findByPrincipalName(name(principal)).values();
List<SessionInformation> infos = new ArrayList<>();
for (S session : sessions) {
if (includeExpiredSessions
|| !Boolean.TRUE.equals(session.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) {
infos.add(new SpringSessionBackedSessionInformation<>(session, this.sessionRepository));
}
}
return infos;
}
@Override
public SessionInformation getSessionInformation(String sessionId) {
S session = this.sessionRepository.findById(sessionId);
if (session != null) {
return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository);
}
return null;
}
/*
* This is a no-op, as we don't administer sessions ourselves.
*/
@Override
public void refreshLastRequest(String sessionId) {
}
/*
* This is a no-op, as we don't administer sessions ourselves.
*/
@Override
public void registerNewSession(String sessionId, Object principal) {
} | /*
* This is a no-op, as we don't administer sessions ourselves.
*/
@Override
public void removeSessionInformation(String sessionId) {
}
/**
* Derives a String name for the given principal.
* @param principal as provided by Spring Security
* @return name of the principal, or its {@code toString()} representation if no name
* could be derived
*/
protected String name(Object principal) {
// We are reusing the logic from AbstractAuthenticationToken#getName
return new TestingAuthenticationToken(principal, null).getName();
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedSessionRegistry.java | 1 |
请完成以下Java代码 | public WorkPackageBuilder setAsyncBatchId(@Nullable final AsyncBatchId asyncBatchId)
{
if (asyncBatchId == null)
{
return this;
}
assertNotBuilt();
this.asyncBatchId = asyncBatchId;
this.asyncBatchSet = true;
return this;
}
@Override
public IWorkPackageBuilder setAD_PInstance_ID(final PInstanceId adPInstanceId)
{
this.adPInstanceId = adPInstanceId;
return this;
}
@NonNull
private I_C_Queue_WorkPackage enqueue(@NonNull final I_C_Queue_WorkPackage workPackage, @Nullable final ILockCommand elementsLocker)
{
final IWorkPackageQueue workPackageQueue = getWorkpackageQueue();
final IWorkpackagePrioStrategy workPackagePriority = getPriority();
final String originalWorkPackageTrxName = getTrxName(workPackage);
try (final IAutoCloseable ignored = () -> setTrxName(workPackage, originalWorkPackageTrxName))
{
// Fact: the workpackage trxName is used when creating the workpackage and its elements.
// Therefore, we temporarily set it to be our _trxName.
// Otherwise, if the current trx fails, the workpackage will have been created, but not have been flagged as "ReadyForProcessing" (which sucks).
setTrxName(workPackage, _trxName);
// Set the Async batch if provided
if (asyncBatchSet)
{
workPackage.setC_Async_Batch_ID(AsyncBatchId.toRepoId(asyncBatchId));
} | if (userInChargeId != null)
{
workPackage.setAD_User_InCharge_ID(userInChargeId.getRepoId());
}
@SuppressWarnings("deprecation") // Suppressing the warning, because *this class* is the workpackage builder to be used
final I_C_Queue_WorkPackage enqueuedWorkpackage = workPackageQueue.enqueueWorkPackage(
workPackage,
workPackagePriority);
try (final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(enqueuedWorkpackage))
{
// Create workpackage parameters
if (_parametersBuilder != null)
{
_parametersBuilder.setC_Queue_WorkPackage(enqueuedWorkpackage);
_parametersBuilder.build();
}
createWorkpackageElements(workPackageQueue, enqueuedWorkpackage);
//
// Lock enqueued workpackage elements
if (elementsLocker != null)
{
final ILock lock = elementsLocker.acquire();
lock.unlockAllAfterTrxRollback();
}
//
// Actually mark the workpackage as ready for processing
// NOTE: method also accepts null transaction and in that case it will immediately mark as ready for processing
workPackageQueue.markReadyForProcessingAfterTrxCommit(enqueuedWorkpackage, _trxName);
}
return enqueuedWorkpackage;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HibernateConf {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); | dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\bootstrap\HibernateConf.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CmmnDeploymentQuery orderByDeploymentTime() {
return orderBy(CmmnDeploymentQueryProperty.DEPLOY_TIME);
}
@Override
public CmmnDeploymentQuery orderByDeploymentName() {
return orderBy(CmmnDeploymentQueryProperty.DEPLOYMENT_NAME);
}
@Override
public CmmnDeploymentQuery orderByTenantId() {
return orderBy(CmmnDeploymentQueryProperty.DEPLOYMENT_TENANT_ID);
}
// results ////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getCmmnDeploymentEntityManager(commandContext).findDeploymentCountByQueryCriteria(this);
}
@Override
public List<CmmnDeployment> executeList(CommandContext commandContext) {
return CommandContextUtil.getCmmnDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getCategory() {
return category;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getKey() {
return key;
}
public String getParentDeploymentId() {
return parentDeploymentId;
} | public String getParentDeploymentIdLike() {
return parentDeploymentIdLike;
}
public List<String> getParentDeploymentIds() {
return parentDeploymentIds;
}
public boolean isLatest() {
return latest;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentQueryImpl.java | 2 |
请完成以下Java代码 | public static UOMConversionRate one(@NonNull final UomId uomId)
{
return builder()
.fromUomId(uomId)
.toUomId(uomId)
.fromToMultiplier(BigDecimal.ONE)
.toFromMultiplier(BigDecimal.ONE)
.build();
}
public UOMConversionRate invert()
{
if (fromUomId.equals(toUomId))
{
return this;
}
return UOMConversionRate.builder()
.fromUomId(toUomId)
.toUomId(fromUomId)
.fromToMultiplier(toFromMultiplier)
.toFromMultiplier(fromToMultiplier)
.build();
}
public boolean isOne()
{
return (fromToMultiplier == null || fromToMultiplier.compareTo(BigDecimal.ONE) == 0)
&& (toFromMultiplier == null || toFromMultiplier.compareTo(BigDecimal.ONE) == 0);
}
public BigDecimal getFromToMultiplier()
{
if (fromToMultiplier != null)
{
return fromToMultiplier;
}
else
{
return computeInvertedMultiplier(toFromMultiplier);
}
} | public static BigDecimal computeInvertedMultiplier(@NonNull final BigDecimal multiplier)
{
if (multiplier.signum() == 0)
{
throw new AdempiereException("Multiplier shall not be ZERO");
}
return NumberUtils.stripTrailingDecimalZeros(BigDecimal.ONE.divide(multiplier, 12, RoundingMode.HALF_UP));
}
public BigDecimal convert(@NonNull final BigDecimal qty, @NonNull final UOMPrecision precision)
{
if (qty.signum() == 0)
{
return qty;
}
if (fromToMultiplier != null)
{
return precision.round(qty.multiply(fromToMultiplier));
}
else
{
return qty.divide(toFromMultiplier, precision.toInt(), precision.getRoundingMode());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionRate.java | 1 |
请完成以下Java代码 | protected void stopExecutingJobs() {
stopJobAcquisitionThread();
}
public void executeJobs(List<String> jobIds, ProcessEngineImpl processEngine) {
try {
threadPoolExecutor.execute(getExecuteJobsRunnable(jobIds, processEngine));
} catch (RejectedExecutionException e) {
logRejectedExecution(processEngine, jobIds.size());
rejectedJobsHandler.jobsRejected(jobIds, processEngine, this);
} finally {
int totalQueueCapacity = calculateTotalQueueCapacity(threadPoolExecutor.getQueue().size(),
threadPoolExecutor.getQueue().remainingCapacity()); | logJobExecutionInfo(processEngine, threadPoolExecutor.getQueue().size(), totalQueueCapacity,
threadPoolExecutor.getMaximumPoolSize(), threadPoolExecutor.getPoolSize());
}
}
// getters / setters
public ThreadPoolExecutor getThreadPoolExecutor() {
return threadPoolExecutor;
}
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\ThreadPoolJobExecutor.java | 1 |
请完成以下Java代码 | public void setC_HierarchyCommissionSettings_ID (final int C_HierarchyCommissionSettings_ID)
{
if (C_HierarchyCommissionSettings_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_HierarchyCommissionSettings_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_HierarchyCommissionSettings_ID, C_HierarchyCommissionSettings_ID);
}
@Override
public int getC_HierarchyCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_HierarchyCommissionSettings_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getCustomer_Group()
{
return get_ValueAsPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setCustomer_Group(final org.compiere.model.I_C_BP_Group Customer_Group)
{
set_ValueFromPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class, Customer_Group);
}
@Override
public void setCustomer_Group_ID (final int Customer_Group_ID)
{
if (Customer_Group_ID < 1)
set_Value (COLUMNNAME_Customer_Group_ID, null);
else
set_Value (COLUMNNAME_Customer_Group_ID, Customer_Group_ID);
}
@Override
public int getCustomer_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_Customer_Group_ID);
}
@Override
public void setIsExcludeBPGroup (final boolean IsExcludeBPGroup)
{
set_Value (COLUMNNAME_IsExcludeBPGroup, IsExcludeBPGroup);
}
@Override
public boolean isExcludeBPGroup()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeBPGroup);
}
@Override
public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory)
{
set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory);
}
@Override
public boolean isExcludeProductCategory()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null); | else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_T_MRP_CRP[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_PInstance getAD_PInstance() throws RuntimeException
{
return (I_AD_PInstance)MTable.get(getCtx(), I_AD_PInstance.Table_Name)
.getPO(getAD_PInstance_ID(), get_TrxName()); }
/** Set Process Instance.
@param AD_PInstance_ID
Instance of the process
*/
public void setAD_PInstance_ID (int AD_PInstance_ID)
{
if (AD_PInstance_ID < 1)
set_Value (COLUMNNAME_AD_PInstance_ID, null);
else
set_Value (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID));
}
/** Get Process Instance.
@return Instance of the process
*/
public int getAD_PInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record | */
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Temporal MRP & CRP.
@param T_MRP_CRP_ID Temporal MRP & CRP */
public void setT_MRP_CRP_ID (int T_MRP_CRP_ID)
{
if (T_MRP_CRP_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, Integer.valueOf(T_MRP_CRP_ID));
}
/** Get Temporal MRP & CRP.
@return Temporal MRP & CRP */
public int getT_MRP_CRP_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_T_MRP_CRP_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_T_MRP_CRP.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPayPwd() {
return payPwd;
}
public void setPayPwd(String payPwd) {
this.payPwd = payPwd;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim(); | }
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo == null ? null : accountNo.trim();
}
public String getStatusDesc() {
return PublicStatusEnum.getEnum(this.getStatus()).getDesc();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserInfo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PredicateProperties {
@NotNull
private @Nullable String name;
private Map<String, String> args = new LinkedHashMap<>();
public PredicateProperties() {
}
public PredicateProperties(String text) {
int eqIdx = text.indexOf('=');
if (eqIdx <= 0) {
throw new ValidationException(
"Unable to parse PredicateDefinition text '" + text + "'" + ", must be of the form name=value");
}
setName(text.substring(0, eqIdx));
String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ",");
for (int i = 0; i < args.length; i++) {
this.args.put(NameUtils.generateName(i), args[i]);
}
}
public @Nullable String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getArgs() {
return args;
}
public void setArgs(Map<String, String> args) { | this.args = args;
}
public void addArg(String key, String value) {
this.args.put(key, value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PredicateProperties that = (PredicateProperties) o;
return Objects.equals(name, that.name) && Objects.equals(args, that.args);
}
@Override
public int hashCode() {
return Objects.hash(name, args);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("PredicateDefinition{");
sb.append("name='").append(name).append('\'');
sb.append(", args=").append(args);
sb.append('}');
return sb.toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\PredicateProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TextToSpeechService {
private OpenAiAudioSpeechModel openAiAudioSpeechModel;
@Autowired
public TextToSpeechService(OpenAiAudioSpeechModel openAiAudioSpeechModel) {
this.openAiAudioSpeechModel = openAiAudioSpeechModel;
}
public byte[] makeSpeech(String text) {
return this.makeSpeech(text, OpenAiAudioSpeechOptions.builder().build());
}
public byte[] makeSpeech(String text, OpenAiAudioSpeechOptions speechOptions) {
SpeechPrompt speechPrompt = new SpeechPrompt(text, speechOptions); | SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);
return response.getResult().getOutput();
}
public Flux<byte[]> makeSpeechStream(String text) {
SpeechPrompt speechPrompt = new SpeechPrompt(text);
Flux<SpeechResponse> responseStream = openAiAudioSpeechModel.stream(speechPrompt);
return responseStream
.map(SpeechResponse::getResult)
.map(Speech::getOutput);
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\transcribe\services\TextToSpeechService.java | 2 |
请完成以下Java代码 | public class SpnegoEntryPoint implements AuthenticationEntryPoint {
private static final Log LOG = LogFactory.getLog(SpnegoEntryPoint.class);
private final String forwardUrl;
private final HttpMethod forwardMethod;
private final boolean forward;
/**
* Instantiates a new spnego entry point. Using this constructor the EntryPoint will
* Sends back a request for a Negotiate Authentication to the browser without
* providing a fallback mechanism for login, Use constructor with forwardUrl to
* provide form based login.
*/
public SpnegoEntryPoint() {
this(null);
}
/**
* Instantiates a new spnego entry point. This constructor enables security
* configuration to use SPNEGO in combination with a fallback page (login form, custom
* 401 page ...). The forward method will be the same as the original request.
* @param forwardUrl URL where the login page can be found. Should be relative to the
* web-app context path (include a leading {@code /}) and can't be absolute URL.
*/
public SpnegoEntryPoint(String forwardUrl) {
this(forwardUrl, null);
}
/**
* Instantiates a new spnego entry point. This constructor enables security
* configuration to use SPNEGO in combination a fallback page (login form, custom 401
* page ...). The forward URL will be accessed via provided HTTP method.
* @param forwardUrl URL where the login page can be found. Should be relative to the
* web-app context path (include a leading {@code /}) and can't be absolute URL.
* @param forwardMethod HTTP method to use when accessing the forward URL
*/
public SpnegoEntryPoint(String forwardUrl, HttpMethod forwardMethod) {
if (StringUtils.hasText(forwardUrl)) {
Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), "Forward url specified must be a valid forward URL");
Assert.isTrue(!UrlUtils.isAbsoluteUrl(forwardUrl), "Forward url specified must not be absolute");
this.forwardUrl = forwardUrl;
this.forwardMethod = forwardMethod;
this.forward = true;
}
else {
this.forwardUrl = null;
this.forwardMethod = null; | this.forward = false;
}
}
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
throws IOException, ServletException {
if (LOG.isDebugEnabled()) {
LOG.debug("Add header WWW-Authenticate:Negotiate to " + request.getRequestURL() + ", forward: "
+ (this.forward ? this.forwardUrl : "no"));
}
response.addHeader("WWW-Authenticate", "Negotiate");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
if (this.forward) {
RequestDispatcher dispatcher = request.getRequestDispatcher(this.forwardUrl);
HttpServletRequest fwdRequest = (this.forwardMethod != null) ? new HttpServletRequestWrapper(request) {
@Override
public String getMethod() {
return SpnegoEntryPoint.this.forwardMethod.name();
}
} : request;
dispatcher.forward(fwdRequest, response);
}
else {
response.flushBuffer();
}
}
} | repos\spring-security-main\kerberos\kerberos-web\src\main\java\org\springframework\security\kerberos\web\authentication\SpnegoEntryPoint.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
fireEditingStopped();
}
});
}
private final JCheckBox checkbox = new CCheckBox();
/**
* Return Selection Status as IDColumn
*
* @return value
*/
@Override
public Object getCellEditorValue()
{
return checkbox.isSelected();
}
/**
* Get visual Component
*
* @param table
* @param value
* @param isSelected
* @param row
* @param column | * @return Component
*/
@Override
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column)
{
final boolean selected = DisplayType.toBooleanNonNull(value, false);
checkbox.setSelected(selected);
return checkbox;
}
@Override
public boolean isCellEditable(final EventObject anEvent)
{
return true;
}
@Override
public boolean shouldSelectCell(final EventObject anEvent)
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\SelectionColumnCellEditor.java | 1 |
请完成以下Java代码 | private Iterator<I_C_Invoice> retrieveSelection(@NonNull final PInstanceId pinstanceId)
{
return queryBL
.createQueryBuilder(I_C_Invoice.class)
.setOnlySelection(pinstanceId)
.create()
.iterate(I_C_Invoice.class);
}
private boolean canVoidPaidInvoice(@NonNull final I_C_Invoice invoice)
{
final I_C_Invoice inv = InterfaceWrapperHelper.create(invoice, I_C_Invoice.class);
if (hasAnyNonPaymentAllocations(inv))
{
final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder()
.contentADMessage(MSG_SKIPPED_INVOICE_NON_PAYMENT_ALLOC_INVOLVED)
.contentADMessageParam(inv.getDocumentNo())
.recipientUserId(Env.getLoggedUserId())
.build();
notificationBL.send(userNotificationRequest);
return false;
}
if (commissionTriggerService.isContainsCommissionTriggers(InvoiceId.ofRepoId(invoice.getC_Invoice_ID())))
{
final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder()
.contentADMessage(MSG_SKIPPED_INVOICE_DUE_TO_COMMISSION)
.contentADMessageParam(inv.getDocumentNo()) | .recipientUserId(Env.getLoggedUserId())
.build();
notificationBL.send(userNotificationRequest);
return false;
}
return true;
}
@NonNull
private IInvoicingParams getIInvoicingParams()
{
final PlainInvoicingParams invoicingParams = new PlainInvoicingParams();
invoicingParams.setUpdateLocationAndContactForInvoice(true);
invoicingParams.setIgnoreInvoiceSchedule(false);
return invoicingParams;
}
private boolean hasAnyNonPaymentAllocations(@NonNull final I_C_Invoice invoice)
{
final List<I_C_AllocationLine> availableAllocationLines = allocationDAO.retrieveAllocationLines(invoice);
return availableAllocationLines.stream()
.anyMatch(allocationLine -> allocationLine.getC_Payment_ID() <= 0);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\RecreateInvoiceWorkpackageProcessor.java | 1 |
请完成以下Java代码 | protected String getCaseDefinitionKey(String caseDefinitionKeyExpression, VariableContainer variableContainer, ExpressionManager expressionManager) {
if (StringUtils.isNotEmpty(caseDefinitionKeyExpression)) {
return (String) expressionManager.createExpression(caseDefinitionKeyExpression).getValue(variableContainer);
} else {
return caseDefinitionKeyExpression;
}
}
@Override
public void completing(DelegateExecution execution, DelegateExecution subProcessInstance) throws Exception {
// not used
}
@Override
public void completed(DelegateExecution execution) throws Exception {
// not used
}
public void triggerCaseTaskAndLeave(DelegateExecution execution, Map<String, Object> variables) { | triggerCaseTask(execution, variables);
leave(execution);
}
public void triggerCaseTask(DelegateExecution execution, Map<String, Object> variables) {
execution.setVariables(variables);
ExecutionEntity executionEntity = (ExecutionEntity) execution;
if (executionEntity.isSuspended() || ProcessDefinitionUtil.isProcessDefinitionSuspended(execution.getProcessDefinitionId())) {
throw new FlowableException("Cannot complete case task. Parent process instance " + executionEntity + " is suspended");
}
// Set the reference id and type to null since the execution could be reused
executionEntity.setReferenceId(null);
executionEntity.setReferenceType(null);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\CaseTaskActivityBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PageController {
/**
* 跳转到 首页
*
* @param request 请求
*/
@GetMapping("/index")
public ModelAndView index(HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
String token = (String) request.getSession().getAttribute(Consts.SESSION_KEY);
mv.setViewName("index");
mv.addObject("token", token);
return mv;
}
/**
* 跳转到 登录页
*
* @param redirect 是否是跳转回来的
*/
@GetMapping("/login")
public ModelAndView login(Boolean redirect) { | ModelAndView mv = new ModelAndView();
if (ObjectUtil.isNotNull(redirect) && ObjectUtil.equal(true, redirect)) {
mv.addObject("message", "请先登录!");
}
mv.setViewName("login");
return mv;
}
@GetMapping("/doLogin")
public String doLogin(HttpSession session) {
session.setAttribute(Consts.SESSION_KEY, IdUtil.fastUUID());
return "redirect:/page/index";
}
} | repos\spring-boot-demo-master\demo-session\src\main\java\com\xkcoding\session\controller\PageController.java | 2 |
请完成以下Java代码 | public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public void applyTo(ModificationBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) {
for (ProcessInstanceModificationInstructionDto instruction : instructions) {
instruction.applyTo(builder, processEngine, objectMapper);
}
}
public String getAnnotation() { | return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ModificationDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void propagateQrForSplitHUs(@NonNull final I_M_HU sourceHU, @NonNull final ImmutableList<I_M_HU> splitHUs)
{
final ImmutableSet<HuId> idCandidatesToShareQrCode = qrCodeConfigurationService.filterSplitHUsForSharingQr(sourceHU, splitHUs);
if (idCandidatesToShareQrCode.isEmpty())
{
return;
}
final ImmutableSet<HuId> idsWithQrAlreadyAssigned = huQRCodesRepository.getQRCodeByHuIds(idCandidatesToShareQrCode).keySet();
final ImmutableSet<HuId> huIdsToShareQr = idCandidatesToShareQrCode.stream()
.filter(huId -> !idsWithQrAlreadyAssigned.contains(huId))
.collect(ImmutableSet.toImmutableSet());
if (!huIdsToShareQr.isEmpty())
{
getSingleQRCodeByHuIdOrEmpty(HuId.ofRepoId(sourceHU.getM_HU_ID()))
.ifPresent(qrCode -> assign(qrCode, huIdsToShareQr));
}
}
@NonNull
public Map<HUQRCodeUniqueId, HuId> getHuIds(@NonNull final Collection<HUQRCode> huQrCodes)
{
return huQRCodesRepository.getHUAssignmentsByQRCode(huQrCodes)
.stream()
.collect(ImmutableMap.toImmutableMap(HUQRCodeAssignment::getId, HUQRCodeAssignment::getSingleHUId));
}
public IHUQRCode parse(@NonNull final String jsonString)
{
return parse(ScannedCode.ofString(jsonString));
}
public IHUQRCode parse(@NonNull final ScannedCode scannedCode)
{
final PickOnTheFlyQRCode pickOnTheFlyQRCode = PickOnTheFlyQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (pickOnTheFlyQRCode != null)
{
return pickOnTheFlyQRCode;
}
final GlobalQRCode globalQRCode = scannedCode.toGlobalQRCodeIfMatching().orNullIfError();
if (globalQRCode != null)
{
if (HUQRCode.isHandled(globalQRCode))
{
return HUQRCode.fromGlobalQRCode(globalQRCode);
}
else if (LMQRCode.isHandled(globalQRCode))
{
return LMQRCode.fromGlobalQRCode(globalQRCode);
}
}
final CustomHUQRCode customHUQRCode = scannableCodeFormatService.parse(scannedCode)
.map(CustomHUQRCode::ofParsedScannedCode)
.orElse(null);
if (customHUQRCode != null)
{ | return customHUQRCode;
}
// M_HU.Value / ExternalBarcode attribute
{
final HuId huId = handlingUnitsBL.getHUIdByValueOrExternalBarcode(scannedCode).orElse(null);
if (huId != null)
{
return getFirstQRCodeByHuId(huId);
}
}
final GS1HUQRCode gs1HUQRCode = GS1HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (gs1HUQRCode != null)
{
return gs1HUQRCode;
}
final EAN13HUQRCode ean13HUQRCode = EAN13HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (ean13HUQRCode != null)
{
return ean13HUQRCode;
}
throw new AdempiereException("QR code is not handled: " + scannedCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesService.java | 2 |
请完成以下Java代码 | private String getWebApplicationContextAttribute() {
String dispatcherServletName = getDispatcherWebApplicationContextSuffix();
if (dispatcherServletName == null) {
return null;
}
return SERVLET_CONTEXT_PREFIX + dispatcherServletName;
}
/**
* Return the {@code <servlet-name>} to use the DispatcherServlet's
* {@link WebApplicationContext} to find the {@link DelegatingFilterProxy} or null to
* use the parent {@link ApplicationContext}.
*
* <p>
* For example, if you are using AbstractDispatcherServletInitializer or
* AbstractAnnotationConfigDispatcherServletInitializer and using the provided Servlet
* name, you can return "dispatcher" from this method to use the DispatcherServlet's
* {@link WebApplicationContext}.
* </p>
* @return the {@code <servlet-name>} of the DispatcherServlet to use its
* {@link WebApplicationContext} or null (default) to use the parent
* {@link ApplicationContext}.
*/
protected String getDispatcherWebApplicationContextSuffix() {
return null;
}
/**
* Invoked before the springSessionRepositoryFilter is added.
* @param servletContext the {@link ServletContext}
*/
protected void beforeSessionRepositoryFilter(ServletContext servletContext) { | }
/**
* Invoked after the springSessionRepositoryFilter is added.
* @param servletContext the {@link ServletContext}
*/
protected void afterSessionRepositoryFilter(ServletContext servletContext) {
}
/**
* Get the {@link DispatcherType} for the springSessionRepositoryFilter.
* @return the {@link DispatcherType} for the filter
*/
protected EnumSet<DispatcherType> getSessionDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC);
}
/**
* Determine if the springSessionRepositoryFilter should be marked as supporting
* asynch. Default is true.
* @return true if springSessionRepositoryFilter should be marked as supporting asynch
*/
protected boolean isAsyncSessionSupported() {
return true;
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\context\AbstractHttpSessionApplicationInitializer.java | 1 |
请完成以下Java代码 | public ProductId getProductId()
{
return product != null ? ProductId.ofRepoIdOrNull(product.getKeyAsInt()) : null;
}
@Nullable
public UomId getUomId()
{
return uom == null ? null : UomId.ofRepoIdOrNull(uom.getKeyAsInt());
}
private JSONLookupValue getClearanceStatus()
{
return clearanceStatus;
}
@Nullable
public I_C_UOM getUom()
{
final UomId uomId = getUomId();
if (uomId == null)
{
return null;
}
final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
return uomDAO.getById(uomId);
}
@NonNull
public I_C_UOM getUomNotNull()
{
return Check.assumeNotNull(getUom(), "Expecting UOM to always be present when using this method!");
}
public boolean isReceipt()
{
return getType().canReceive();
}
public boolean isIssue()
{
return getType().canIssue();
}
public boolean isHUStatusActive()
{
return huStatus != null && X_M_HU.HUSTATUS_Active.equals(huStatus.getKey());
}
@Override
public boolean hasAttributes()
{
return attributesSupplier != null;
} | @Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
if (attributesSupplier == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
}
final IViewRowAttributes attributes = attributesSupplier.get();
if (attributes == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
}
return attributes;
}
@Override
public HuUnitType getHUUnitTypeOrNull() {return huUnitType;}
@Override
public BPartnerId getBpartnerId() {return huBPartnerId;}
@Override
public boolean isTopLevel() {return topLevelHU;}
@Override
public Stream<HUReportAwareViewRow> streamIncludedHUReportAwareRows() {return getIncludedRows().stream().map(PPOrderLineRow::toHUReportAwareViewRow);}
private HUReportAwareViewRow toHUReportAwareViewRow() {return this;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRow.java | 1 |
请完成以下Java代码 | public boolean isUsing2FA() {
return isUsing2FA;
}
public void setUsing2FA(boolean isUsing2FA) {
this.isUsing2FA = isUsing2FA;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = (prime * result) + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} | if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
User user = (User) obj;
if (!email.equals(user.email)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", firstName=")
.append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", roles=").append(roles).append("]");
return builder.toString();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\model\User.java | 1 |
请完成以下Java代码 | public void onMovementQty(final I_PP_Cost_Collector cc)
{
updateDurationReal(cc);
}
/**
* Calculates and sets DurationReal based on selected PP_Order_Node
*/
private void updateDurationReal(final I_PP_Cost_Collector cc)
{
final WorkingTime durationReal = computeWorkingTime(cc);
if (durationReal == null)
{
return;
}
cc.setDurationReal(durationReal.toBigDecimalUsingActivityTimeUnit());
}
@Nullable
private WorkingTime computeWorkingTime(final I_PP_Cost_Collector cc)
{
final PPOrderId orderId = PPOrderId.ofRepoIdOrNull(cc.getPP_Order_ID());
if (orderId == null)
{
return null;
}
final PPOrderRoutingActivityId activityId = PPOrderRoutingActivityId.ofRepoIdOrNull(orderId, cc.getPP_Order_Node_ID()); | if (activityId == null)
{
return null;
}
final PPOrderRoutingActivity activity = orderRoutingRepository.getOrderRoutingActivity(activityId);
return WorkingTime.builder()
.durationPerOneUnit(activity.getDurationPerOneUnit())
.unitsPerCycle(activity.getUnitsPerCycle())
.qty(costCollectorBL.getMovementQty(cc))
.activityTimeUnit(activity.getDurationUnit())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Cost_Collector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result save(@RequestBody Picture picture, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (StringUtils.isEmpty(picture.getPath()) || StringUtils.isEmpty(picture.getRemark())) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
if (pictureService.save(picture) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("添加失败");
}
}
/**
* 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public Result update(@RequestBody Picture picture, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (null == picture.getId() || StringUtils.isEmpty(picture.getPath()) || StringUtils.isEmpty(picture.getRemark())) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
Picture tempPicture = pictureService.queryObject(picture.getId());
if (tempPicture == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
if (pictureService.update(picture) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("修改失败");
}
}
/**
* 删除 | */
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result delete(@RequestBody Integer[] ids, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (ids.length < 1) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
if (pictureService.deleteBatch(ids) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\PictureController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected List<String> getFileNames(@Nullable ClassLoader classLoader) {
return Arrays.asList(StandardConfigDataLocationResolver.DEFAULT_CONFIG_NAMES);
}
/**
* Get the locations to consider. A location is a classpath location that may or may
* not use the standard {@code classpath:} prefix.
* @param classLoader the classloader to use
* @return the configuration file locations
*/
protected List<String> getLocations(@Nullable ClassLoader classLoader) {
List<String> classpathLocations = new ArrayList<>();
for (ConfigDataLocation candidate : ConfigDataEnvironment.DEFAULT_SEARCH_LOCATIONS) {
for (ConfigDataLocation configDataLocation : candidate.split()) {
String location = configDataLocation.getValue();
if (location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
classpathLocations.add(location);
}
}
}
return classpathLocations;
}
/**
* Get the application file extensions to consider. A valid extension starts with a
* dot.
* @param classLoader the classloader to use
* @return the configuration file extensions
*/
protected List<String> getExtensions(@Nullable ClassLoader classLoader) {
List<String> extensions = new ArrayList<>(); | List<PropertySourceLoader> propertySourceLoaders = getSpringFactoriesLoader(classLoader)
.load(PropertySourceLoader.class);
for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) {
for (String fileExtension : propertySourceLoader.getFileExtensions()) {
String candidate = "." + fileExtension;
if (!extensions.contains(candidate)) {
extensions.add(candidate);
}
}
}
return extensions;
}
protected SpringFactoriesLoader getSpringFactoriesLoader(@Nullable ClassLoader classLoader) {
return SpringFactoriesLoader.forDefaultResourceLocation(classLoader);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationRuntimeHints.java | 2 |
请完成以下Java代码 | public String toString() {
return "VariableDeclaration[" + name + ":" + type + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSourceVariableName() {
return sourceVariableName;
}
public void setSourceVariableName(String sourceVariableName) {
this.sourceVariableName = sourceVariableName;
}
public Expression getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(Expression sourceExpression) {
this.sourceExpression = sourceExpression;
} | public String getDestinationVariableName() {
return destinationVariableName;
}
public void setDestinationVariableName(String destinationVariableName) {
this.destinationVariableName = destinationVariableName;
}
public Expression getDestinationExpression() {
return destinationExpression;
}
public void setDestinationExpression(Expression destinationExpression) {
this.destinationExpression = destinationExpression;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Expression getLinkExpression() {
return linkExpression;
}
public void setLinkExpression(Expression linkExpression) {
this.linkExpression = linkExpression;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\VariableDeclaration.java | 1 |
请完成以下Java代码 | private void fireLocalAndRemoteListenersNow(@NonNull final List<SumUpTransactionStatusChangedEvent> events)
{
final IEventBus eventBus = getEventBus();
// NOTE: we don't have to fireLocalListeners
// because we assume we will also get back this event and then we will handle it
events.forEach(eventBus::enqueueObject);
}
public void fireNewTransaction(@NonNull final SumUpTransaction trx)
{
fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofNewTransaction(trx));
}
public void fireStatusChangedIfNeeded(
@NonNull final SumUpTransaction trx, | @NonNull final SumUpTransaction trxPrev)
{
if (!isForceSendingChangeEvents() && hasChanges(trx, trxPrev))
{
return;
}
fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofChangedTransaction(trx, trxPrev));
}
private static boolean hasChanges(final @NonNull SumUpTransaction trx, final @NonNull SumUpTransaction trxPrev)
{
return SumUpTransactionStatus.equals(trx.getStatus(), trxPrev.getStatus())
&& trx.isRefunded() == trxPrev.isRefunded();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpEventsDispatcher.java | 1 |
请完成以下Java代码 | public String getFilePassword() {
return filePassword;
}
public void setFilePassword(String filePassword) {
this.filePassword = filePassword;
}
public boolean getUsePasswordCache() {
return usePasswordCache;
}
public void setUsePasswordCache(boolean usePasswordCache) {
this.usePasswordCache = usePasswordCache;
}
public String getOfficePreviewType() {
return officePreviewType;
}
public void setOfficePreviewType(String officePreviewType) {
this.officePreviewType = officePreviewType;
}
public FileType getType() {
return type;
}
public void setType(FileType type) {
this.type = type;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getCompressFileKey() {
return compressFileKey;
}
public void setCompressFileKey(String compressFileKey) {
this.compressFileKey = compressFileKey;
}
public String getName() {
return name;
}
public String getCacheName() {
return cacheName;
}
public String getCacheListName() {
return cacheListName;
}
public String getOutFilePath() {
return outFilePath;
}
public String getOriginFilePath() {
return originFilePath;
}
public boolean isHtmlView() {
return isHtmlView;
}
public void setCacheName(String cacheName) {
this.cacheName = cacheName;
}
public void setCacheListName(String cacheListName) {
this.cacheListName = cacheListName;
}
public void setOutFilePath(String outFilePath) {
this.outFilePath = outFilePath;
}
public void setOriginFilePath(String originFilePath) {
this.originFilePath = originFilePath;
}
public void setHtmlView(boolean isHtmlView) {
this.isHtmlView = isHtmlView;
}
public void setName(String name) { | this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getSkipDownLoad() {
return skipDownLoad;
}
public void setSkipDownLoad(Boolean skipDownLoad) {
this.skipDownLoad = skipDownLoad;
}
public String getTifPreviewType() {
return tifPreviewType;
}
public void setTifPreviewType(String previewType) {
this.tifPreviewType = previewType;
}
public Boolean forceUpdatedCache() {
return forceUpdatedCache;
}
public void setForceUpdatedCache(Boolean forceUpdatedCache) {
this.forceUpdatedCache = forceUpdatedCache;
}
public String getKkProxyAuthorization() {
return kkProxyAuthorization;
}
public void setKkProxyAuthorization(String kkProxyAuthorization) {
this.kkProxyAuthorization = kkProxyAuthorization;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\model\FileAttribute.java | 1 |
请完成以下Java代码 | public int getMaxResults() {
return maxResults;
}
public Object getParameter() {
return parameter;
}
public void setFirstResult(int firstResult) {
this.firstResult = firstResult;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
public void setParameter(Object parameter) {
this.parameter = parameter;
}
public void setDatabaseType(String databaseType) {
this.databaseType = databaseType;
}
public String getDatabaseType() {
return databaseType;
}
public AuthorizationCheck getAuthCheck() {
return authCheck;
}
public void setAuthCheck(AuthorizationCheck authCheck) { | this.authCheck = authCheck;
}
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public void setTenantCheck(TenantCheck tenantCheck) {
this.tenantCheck = tenantCheck;
}
public List<QueryOrderingProperty> getOrderingProperties() {
return orderingProperties;
}
public void setOrderingProperties(List<QueryOrderingProperty> orderingProperties) {
this.orderingProperties = orderingProperties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\ListQueryParameterObject.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ModificationRestServiceImpl extends AbstractRestProcessEngineAware implements ModificationRestService {
public ModificationRestServiceImpl(String engineName, ObjectMapper objectMapper) {
super(engineName, objectMapper);
}
@Override
public void executeModification(ModificationDto modificationExecutionDto) {
try {
createModificationBuilder(modificationExecutionDto).execute();
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public BatchDto executeModificationAsync(ModificationDto modificationExecutionDto) {
Batch batch = null;
try {
batch = createModificationBuilder(modificationExecutionDto).executeAsync();
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
return BatchDto.fromBatch(batch);
}
private ModificationBuilder createModificationBuilder(ModificationDto dto) {
ModificationBuilder builder = getProcessEngine().getRuntimeService().createModification(dto.getProcessDefinitionId());
if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) {
dto.applyTo(builder, getProcessEngine(), objectMapper);
}
List<String> processInstanceIds = dto.getProcessInstanceIds();
builder.processInstanceIds(processInstanceIds);
ProcessInstanceQueryDto processInstanceQueryDto = dto.getProcessInstanceQuery();
if (processInstanceQueryDto != null) {
ProcessInstanceQuery processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine());
builder.processInstanceQuery(processInstanceQuery);
} | HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = dto.getHistoricProcessInstanceQuery();
if(historicProcessInstanceQueryDto != null) {
HistoricProcessInstanceQuery historicProcessInstanceQuery = historicProcessInstanceQueryDto.toQuery(getProcessEngine());
builder.historicProcessInstanceQuery(historicProcessInstanceQuery);
}
if (dto.isSkipCustomListeners()) {
builder.skipCustomListeners();
}
if (dto.isSkipIoMappings()) {
builder.skipIoMappings();
}
if (dto.getAnnotation() != null) {
builder.setAnnotation(dto.getAnnotation());
}
return builder;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ModificationRestServiceImpl.java | 2 |
请完成以下Java代码 | public int getDoc_User_ID()
{
return handler.getDoc_User_ID(model);
}
@Override
public int getC_Currency_ID()
{
return handler.getC_Currency_ID(model);
}
@Override
public BigDecimal getApprovalAmt()
{
return handler.getApprovalAmt(model);
}
@Override
public int getAD_Client_ID()
{
return model.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return model.getAD_Org_ID();
}
@Override
public String getDocAction()
{
return model.getDocAction();
}
@Override
public boolean save()
{
InterfaceWrapperHelper.save(model);
return true;
}
@Override
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(model);
}
@Override
public int get_ID()
{
return InterfaceWrapperHelper.getId(model);
}
@Override
public int get_Table_ID()
{ | return InterfaceWrapperHelper.getModelTableId(model);
}
@Override
public String get_TrxName()
{
return InterfaceWrapperHelper.getTrxName(model);
}
@Override
public void set_TrxName(final String trxName)
{
InterfaceWrapperHelper.setTrxName(model, trxName);
}
@Override
public boolean isActive()
{
return model.isActive();
}
@Override
public Object getModel()
{
return getDocumentModel();
}
@Override
public Object getDocumentModel()
{
return model;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java | 1 |
请完成以下Java代码 | public boolean isAvailableForAnyBPartner(@NonNull final I_M_PickingSlot pickingSlot)
{
return PickingSlotUtils.isAvailableForAnyBPartner(pickingSlot);
}
@Override
public boolean isAvailableForBPartnerId(@NonNull final I_M_PickingSlot pickingSlot, @Nullable final BPartnerId bpartnerId)
{
return PickingSlotUtils.isAvailableForBPartnerId(pickingSlot, bpartnerId);
}
@Override
public boolean isAvailableForBPartnerAndLocation(
@NonNull final I_M_PickingSlot pickingSlot,
final BPartnerId bpartnerId,
@Nullable final BPartnerLocationId bpartnerLocationId)
{
return PickingSlotUtils.isAvailableForBPartnerAndLocation(pickingSlot, bpartnerId, bpartnerLocationId);
}
@Override
public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.getPickingSlotIdAndCaption(pickingSlotId);
}
@Override
public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final PickingSlotQuery query)
{
return pickingSlotDAO.retrievePickingSlotIdAndCaptions(query);
}
@Override
public QRCodePDFResource createQRCodesPDF(@NonNull final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions)
{
Check.assumeNotEmpty(pickingSlotIdAndCaptions, "pickingSlotIdAndCaptions is not empty");
final ImmutableList<PrintableQRCode> qrCodes = pickingSlotIdAndCaptions.stream()
.map(PickingSlotQRCode::ofPickingSlotIdAndCaption)
.map(PickingSlotQRCode::toPrintableQRCode) | .collect(ImmutableList.toImmutableList());
final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class);
return globalQRCodeService.createPDF(qrCodes);
}
@Override
public boolean isAvailableForAnyBPartner(@NonNull final PickingSlotId pickingSlotId)
{
return isAvailableForAnyBPartner(pickingSlotDAO.getById(pickingSlotId));
}
@NonNull
public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.getById(pickingSlotId);
}
@Override
public boolean isPickingRackSystem(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.isPickingRackSystem(pickingSlotId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotBL.java | 1 |
请完成以下Java代码 | public void write(StringWriter writer, ValidationResultFormatter formatter, int maxSize) {
int printedCount = 0;
int previousLength = 0;
for (var entry : collectedResults.entrySet()) {
var element = entry.getKey();
var results = entry.getValue();
formatter.formatElement(writer, element);
for (var result : results) {
formatter.formatResult(writer, result);
// Size and Length are not necessarily the same, depending on the encoding of the string.
int currentSize = writer.getBuffer().toString().getBytes().length;
int currentLength = writer.getBuffer().length();
if (!canAccommodateResult(maxSize, currentSize, printedCount, formatter)) {
writer.getBuffer().setLength(previousLength);
int remaining = errorCount + warningCount - printedCount;
formatter.formatSuffixWithOmittedResultsCount(writer, remaining);
return;
}
printedCount++;
previousLength = currentLength;
}
}
}
private boolean canAccommodateResult( | int maxSize, int currentSize, int printedCount, ValidationResultFormatter formatter) {
boolean isLastItemToPrint = printedCount == errorCount + warningCount - 1;
if (isLastItemToPrint && currentSize <= maxSize) {
return true;
}
int remaining = errorCount + warningCount - printedCount;
int suffixLength = formatter.getFormattedSuffixWithOmittedResultsSize(remaining);
return currentSize + suffixLength <= maxSize;
}
@Override
public Map<ModelElementInstance, List<ValidationResult>> getResults() {
return collectedResults;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\validation\ModelValidationResultsImpl.java | 1 |
请完成以下Java代码 | public int getExternalSystem_Service_Instance_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_Instance_ID);
}
@Override
public void setExternalSystem_Status_ID (final int ExternalSystem_Status_ID)
{
if (ExternalSystem_Status_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Status_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Status_ID, ExternalSystem_Status_ID);
}
@Override
public int getExternalSystem_Status_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Status_ID);
}
@Override
public void setExternalSystemMessage (final @Nullable java.lang.String ExternalSystemMessage)
{
set_Value (COLUMNNAME_ExternalSystemMessage, ExternalSystemMessage);
}
@Override
public java.lang.String getExternalSystemMessage()
{ | return get_ValueAsString(COLUMNNAME_ExternalSystemMessage);
}
/**
* ExternalSystemStatus AD_Reference_ID=541502
* Reference name: ExpectedStatus
*/
public static final int EXTERNALSYSTEMSTATUS_AD_Reference_ID=541502;
/** Active = Active */
public static final String EXTERNALSYSTEMSTATUS_Active = "Active";
/** Inactive = Inactive */
public static final String EXTERNALSYSTEMSTATUS_Inactive = "Inactive";
/** Error = Error */
public static final String EXTERNALSYSTEMSTATUS_Error = "Error ";
/** Down = Down */
public static final String EXTERNALSYSTEMSTATUS_Down = "Down";
@Override
public void setExternalSystemStatus (final java.lang.String ExternalSystemStatus)
{
set_Value (COLUMNNAME_ExternalSystemStatus, ExternalSystemStatus);
}
@Override
public java.lang.String getExternalSystemStatus()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Status.java | 1 |
请完成以下Java代码 | public void setDescription (String Description)
{
if (Description != null && Description.length() > 0)
super.setDescription (Description);
else
super.setDescription (getAD_Table_ID() + "#" + getRecord_ID());
} // setDescription
/**
* Get History as htlp paragraph
* @param ConfidentialType confidentiality
* @return html paragraph
*/
public p getHistory (String ConfidentialType)
{
p history = new p();
getEntries(false);
boolean first = true;
for (int i = 0; i < m_entries.length; i++)
{
MChatEntry entry = m_entries[i];
if (!entry.isActive() || !entry.isConfidentialType(ConfidentialType))
continue;
if (first)
first = false;
else | history.addElement(new hr());
// User & Date
b b = new b();
final I_AD_User user = Services.get(IUserDAO.class).getById(entry.getCreatedBy());
b.addElement(user.getName());
b.addElement(" \t");
Timestamp created = entry.getCreated();
if (m_format == null)
m_format = DisplayType.getDateFormat(DisplayType.DateTime);
b.addElement(m_format.format(created));
history.addElement(b);
// history.addElement(new br());
//
p p = new p();
String data = entry.getCharacterData();
data = StringUtils.maskHTML(data, true);
p.addElement(data);
history.addElement(p);
} // entry
//
return history;
} // getHistory
} // MChat | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MChat.java | 1 |
请完成以下Java代码 | public String getName() {
return this.name;
}
/**
* Sets the name.
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return this.description;
}
/**
* Sets the description.
* @param description the description
*/
public void setDescription(String description) {
this.description = description;
}
@Override
public String getApplicationName() {
return this.applicationName;
}
/**
* Sets the application name.
* @param applicationName the application name
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public String getPackageName() {
if (StringUtils.hasText(this.packageName)) {
return this.packageName;
}
if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) {
return this.groupId + "." + this.artifactId;
}
return null; | }
/**
* Sets the package name.
* @param packageName the package name
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
@Override
public String getBaseDirectory() {
return this.baseDirectory;
}
/**
* Sets the base directory.
* @param baseDirectory the base directory
*/
public void setBaseDirectory(String baseDirectory) {
this.baseDirectory = baseDirectory;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\MutableProjectDescription.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private WFProcess setScannedBarcode0(
@NonNull final WFProcess wfProcess,
@NonNull final WFActivity wfActivity,
@NonNull final String scannedBarcode)
{
return wfActivityHandlersRegistry
.getFeature(wfActivity.getWfActivityType(), SetScannedBarcodeSupport.class)
.setScannedBarcode(SetScannedBarcodeRequest.builder()
.wfProcess(wfProcess)
.wfActivity(wfActivity)
.scannedBarcode(scannedBarcode)
.build());
}
public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(
@NonNull final WFProcessId wfProcessId,
@NonNull final WFActivityId wfActivityId)
{
final WFProcess wfProcess = getWorkflowBasedMobileApplication(wfProcessId.getApplicationId()).getWFProcessById(wfProcessId);
final WFActivity wfActivity = wfProcess.getActivityById(wfActivityId);
return wfActivityHandlersRegistry
.getFeature(wfActivity.getWfActivityType(), SetScannedBarcodeSupport.class)
.getScannedBarcodeSuggestions(GetScannedBarcodeSuggestionsRequest.builder()
.wfProcess(wfProcess)
.build());
}
public WFProcess setUserConfirmation(
@NonNull final UserId invokerId,
@NonNull final WFProcessId wfProcessId,
@NonNull final WFActivityId wfActivityId)
{
return processWFActivity(
invokerId,
wfProcessId,
wfActivityId,
this::setUserConfirmation0);
}
private WFProcess setUserConfirmation0(
@NonNull final WFProcess wfProcess,
@NonNull final WFActivity wfActivity)
{
return wfActivityHandlersRegistry
.getFeature(wfActivity.getWfActivityType(), UserConfirmationSupport.class)
.userConfirmed(UserConfirmationRequest.builder()
.wfProcess(wfProcess)
.wfActivity(wfActivity)
.build());
}
private WFProcess processWFActivity(
@NonNull final UserId invokerId,
@NonNull final WFProcessId wfProcessId,
@NonNull final WFActivityId wfActivityId,
@NonNull final BiFunction<WFProcess, WFActivity, WFProcess> processor)
{
return changeWFProcessById(
wfProcessId,
wfProcess -> {
wfProcess.assertHasAccess(invokerId); | final WFActivity wfActivity = wfProcess.getActivityById(wfActivityId);
WFProcess wfProcessChanged = processor.apply(wfProcess, wfActivity);
if (!Objects.equals(wfProcess, wfProcessChanged))
{
wfProcessChanged = withUpdatedActivityStatuses(wfProcessChanged);
}
return wfProcessChanged;
});
}
private WFProcess withUpdatedActivityStatuses(@NonNull final WFProcess wfProcess)
{
WFProcess wfProcessChanged = wfProcess;
for (final WFActivity wfActivity : wfProcess.getActivities())
{
final WFActivityStatus newActivityStatus = wfActivityHandlersRegistry
.getHandler(wfActivity.getWfActivityType())
.computeActivityState(wfProcessChanged, wfActivity);
wfProcessChanged = wfProcessChanged.withChangedActivityStatus(wfActivity.getId(), newActivityStatus);
}
return wfProcessChanged;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\service\WorkflowRestAPIService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void afterPropertiesSet() throws Exception {
Assert.hasText(this.servicePrincipal, "servicePrincipal must be specified");
if (this.keyTabLocation != null && this.keyTabLocation instanceof ClassPathResource) {
LOG.warn(
"Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
}
if (!this.useTicketCache) {
Assert.notNull(this.keyTabLocation, "keyTabLocation must be specified when useTicketCache is false");
}
if (this.keyTabLocation != null) {
this.keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm();
if (this.keyTabLocationAsString.startsWith("file:")) {
this.keyTabLocationAsString = this.keyTabLocationAsString.substring(5);
}
}
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
HashMap<String, String> options = new HashMap<>(); | options.put("principal", this.servicePrincipal);
if (this.keyTabLocation != null) {
options.put("useKeyTab", "true");
options.put("keyTab", this.keyTabLocationAsString);
options.put("storeKey", "true");
}
options.put("doNotPrompt", "true");
if (this.useTicketCache) {
options.put("useTicketCache", "true");
options.put("renewTGT", "true");
}
options.put("isInitiator", this.isInitiator.toString());
options.put("debug", this.debug.toString());
return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), };
}
} | repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\config\SunJaasKrb5LoginConfig.java | 2 |
请完成以下Java代码 | public void afterConnectionEstablished(WebSocketSession session) {
log.info("和客户端建立连接");
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
session.close(CloseStatus.SERVER_ERROR);
log.error("连接异常", exception);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
log.info("和客户端断开连接");
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 获取到客户端发送过来的消息
String receiveMessage = message.getPayload();
log.info(receiveMessage); | // 发送消息给客户端
session.sendMessage(new TextMessage(fakeAi(receiveMessage)));
// 关闭连接
// session.close(CloseStatus.NORMAL);
}
private static String fakeAi(String input) {
if (input == null || "".equals(input)) {
return "你说什么?没听清︎";
}
return input.replace('你', '我')
.replace("吗", "")
.replace('?', '!')
.replace('?', '!');
}
} | repos\SpringAll-master\76.spring-boot-websocket-socketjs\src\main\java\cc\mrbird\socket\handler\MyStringWebSocketHandler.java | 1 |
请完成以下Java代码 | protected Object createMessage(InstanceEvent event, Instance instance) {
Map<String, String> messageJson = new HashMap<>();
messageJson.put("text", createContent(event, instance));
return messageJson;
}
@Override
protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Nullable
public URI getUrl() {
return url;
}
public void setUrl(@Nullable URI url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
} | @Nullable
public String getRoom() {
return room;
}
public void setRoom(@Nullable String room) {
this.room = room;
}
@Nullable
public String getToken() {
return token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\LetsChatNotifier.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Category.
@param R_Category_ID
Request Category
*/
public void setR_Category_ID (int R_Category_ID)
{
if (R_Category_ID < 1) | set_ValueNoCheck (COLUMNNAME_R_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Category_ID, Integer.valueOf(R_Category_ID));
}
/** Get Category.
@return Request Category
*/
public int getR_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Category.java | 1 |
请完成以下Java代码 | String fixedLocation(String location, String host, String path, StripVersion stripVersion, Pattern hostPortPattern,
Pattern hostPortVersionPattern) {
final boolean doStrip = StripVersion.ALWAYS_STRIP.equals(stripVersion)
|| (StripVersion.AS_IN_REQUEST.equals(stripVersion) && !VERSIONED_PATH.matcher(path).matches());
final Pattern pattern = doStrip ? hostPortVersionPattern : hostPortPattern;
return pattern.matcher(location).replaceFirst(host);
}
public enum StripVersion {
/**
* Version will not be stripped, even if the original request path contains no
* version.
*/
NEVER_STRIP,
/**
* Version will be stripped only if the original request path contains no version.
* This is the Default.
*/
AS_IN_REQUEST,
/**
* Version will be stripped, even if the original request path contains version.
*/
ALWAYS_STRIP
}
public static class Config {
private StripVersion stripVersion = StripVersion.AS_IN_REQUEST;
private String locationHeaderName = HttpHeaders.LOCATION;
private @Nullable String hostValue;
private String protocols = DEFAULT_PROTOCOLS;
private Pattern hostPortPattern = DEFAULT_HOST_PORT;
private Pattern hostPortVersionPattern = DEFAULT_HOST_PORT_VERSION;
public StripVersion getStripVersion() {
return stripVersion;
}
public Config setStripVersion(StripVersion stripVersion) {
this.stripVersion = stripVersion;
return this;
}
public String getLocationHeaderName() {
return locationHeaderName;
}
public Config setLocationHeaderName(String locationHeaderName) {
this.locationHeaderName = locationHeaderName;
return this;
} | public @Nullable String getHostValue() {
return hostValue;
}
public Config setHostValue(String hostValue) {
this.hostValue = hostValue;
return this;
}
public String getProtocols() {
return protocols;
}
public Config setProtocols(String protocols) {
this.protocols = protocols;
this.hostPortPattern = compileHostPortPattern(protocols);
this.hostPortVersionPattern = compileHostPortVersionPattern(protocols);
return this;
}
public Pattern getHostPortPattern() {
return hostPortPattern;
}
public Pattern getHostPortVersionPattern() {
return hostPortVersionPattern;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteLocationResponseHeaderGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
RefundItem refundItem = (RefundItem)o;
return Objects.equals(this.refundAmount, refundItem.refundAmount) &&
Objects.equals(this.lineItemId, refundItem.lineItemId) &&
Objects.equals(this.legacyReference, refundItem.legacyReference);
}
@Override
public int hashCode()
{
return Objects.hash(refundAmount, lineItemId, legacyReference);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class RefundItem {\n"); | sb.append(" refundAmount: ").append(toIndentedString(refundAmount)).append("\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n");
sb.append(" legacyReference: ").append(toIndentedString(legacyReference)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\RefundItem.java | 2 |
请完成以下Java代码 | public class FactorsOfInteger {
public static Set<Integer> getAllFactorsVer1(int n) {
Set<Integer> factors = new HashSet<>();
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
factors.add(i);
}
}
return factors;
}
public static Set<Integer> getAllFactorsVer2(int n) {
Set<Integer> factors = new HashSet<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
factors.add(i);
factors.add(n / i);
}
} | return factors;
}
public static Set<Integer> getAllFactorsVer3(int n) {
Set<Integer> factors = new HashSet<>();
int step = n % 2 == 0 ? 1 : 2;
for (int i = 1; i <= Math.sqrt(n); i += step) {
if (n % i == 0) {
factors.add(i);
factors.add(n / i);
}
}
return factors;
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-5\src\main\java\com\baeldung\factors\FactorsOfInteger.java | 1 |
请完成以下Java代码 | public class FlowableHttpRequestHandlerParser extends BaseChildElementParser {
@Override
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception {
FlowableHttpRequestHandler requestHandler = new FlowableHttpRequestHandler();
BpmnXMLUtil.addXMLLocation(requestHandler, xtr);
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_CLASS))) {
requestHandler.setImplementation(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_CLASS));
requestHandler.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_CLASS);
} else if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_DELEGATEEXPRESSION))) {
requestHandler.setImplementation(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_DELEGATEEXPRESSION));
requestHandler.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION);
} else if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_TYPE))) {
requestHandler.setImplementationType(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_TYPE));
} | if (parentElement instanceof HttpServiceTask) {
((HttpServiceTask) parentElement).setHttpRequestHandler(requestHandler);
if (ImplementationType.IMPLEMENTATION_TYPE_SCRIPT.equals(requestHandler.getImplementationType())) {
parseChildElements(xtr, requestHandler, model, new ScriptInfoParser());
} else {
parseChildElements(xtr, requestHandler, model, new FieldExtensionParser());
}
}
}
@Override
public String getElementName() {
return ELEMENT_HTTP_REQUEST_HANDLER;
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\child\FlowableHttpRequestHandlerParser.java | 1 |
请完成以下Java代码 | public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID)
{
if (C_CostClassification_Category_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CostClassification_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID);
}
@Override
public int getC_CostClassification_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description); | }
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CostClassification_Category_Trl.java | 1 |
请完成以下Java代码 | public Class<? extends BaseElement> getHandledType() {
return EndEvent.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, EndEvent endEvent) {
ActivityImpl endEventActivity = createActivityOnCurrentScope(bpmnParse, endEvent, BpmnXMLConstants.ELEMENT_EVENT_END);
EventDefinition eventDefinition = null;
if (!endEvent.getEventDefinitions().isEmpty()) {
eventDefinition = endEvent.getEventDefinitions().get(0);
}
// Error end event
if (eventDefinition instanceof org.flowable.bpmn.model.ErrorEventDefinition) {
org.flowable.bpmn.model.ErrorEventDefinition errorDefinition = (org.flowable.bpmn.model.ErrorEventDefinition) eventDefinition;
if (bpmnParse.getBpmnModel().containsErrorRef(errorDefinition.getErrorCode())) {
String errorCode = bpmnParse.getBpmnModel().getErrors().get(errorDefinition.getErrorCode());
if (StringUtils.isEmpty(errorCode)) {
LOGGER.warn("errorCode is required for an error event {}", endEvent.getId());
}
endEventActivity.setProperty("type", "errorEndEvent");
errorDefinition.setErrorCode(errorCode);
}
endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createErrorEndEventActivityBehavior(endEvent, errorDefinition)); | // Cancel end event
} else if (eventDefinition instanceof CancelEventDefinition) {
ScopeImpl scope = bpmnParse.getCurrentScope();
if (scope.getProperty("type") == null || !scope.getProperty("type").equals("transaction")) {
LOGGER.warn("end event with cancelEventDefinition only supported inside transaction subprocess (id={})", endEvent.getId());
} else {
endEventActivity.setProperty("type", "cancelEndEvent");
endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createCancelEndEventActivityBehavior(endEvent));
}
// Terminate end event
} else if (eventDefinition instanceof TerminateEventDefinition) {
endEventActivity.setAsync(endEvent.isAsynchronous());
endEventActivity.setExclusive(!endEvent.isNotExclusive());
endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createTerminateEndEventActivityBehavior(endEvent));
// None end event
} else if (eventDefinition == null) {
endEventActivity.setAsync(endEvent.isAsynchronous());
endEventActivity.setExclusive(!endEvent.isNotExclusive());
endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createNoneEndEventActivityBehavior(endEvent));
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\EndEventParseHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | String getResourceLocation() {
return this.resourceLocation;
}
boolean isMandatoryDirectory() {
return !this.configDataLocation.isOptional() && this.directory != null;
}
@Nullable String getDirectory() {
return this.directory;
}
@Nullable String getProfile() {
return this.profile;
}
boolean isSkippable() {
return this.configDataLocation.isOptional() || this.directory != null || this.profile != null;
}
PropertySourceLoader getPropertySourceLoader() {
return this.propertySourceLoader;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false; | }
StandardConfigDataReference other = (StandardConfigDataReference) obj;
return this.resourceLocation.equals(other.resourceLocation);
}
@Override
public int hashCode() {
return this.resourceLocation.hashCode();
}
@Override
public String toString() {
return this.resourceLocation;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataReference.java | 2 |
请在Spring Boot框架中完成以下Java代码 | PropertyDescriptor createPropertyDescriptor(String name, PropertyDescriptor propertyDescriptor) {
String key = ConventionUtils.toDashedCase(name);
if (this.items.containsKey(key)) {
ItemMetadata itemMetadata = this.items.get(key);
ItemHint itemHint = this.hints.get(key);
return new SourcePropertyDescriptor(propertyDescriptor, itemMetadata, itemHint);
}
return propertyDescriptor;
}
/**
* Create a {@link PropertyDescriptor} for the given property name.
* @param name the name of a property
* @param regularDescriptor a function to get the descriptor
* @return a property descriptor that applies additional source metadata if
* necessary
*/
PropertyDescriptor createPropertyDescriptor(String name,
Function<String, PropertyDescriptor> regularDescriptor) {
return createPropertyDescriptor(name, regularDescriptor.apply(name));
}
}
/**
* A {@link PropertyDescriptor} that applies source metadata.
*/
static class SourcePropertyDescriptor extends PropertyDescriptor {
private final PropertyDescriptor delegate;
private final ItemMetadata sourceItemMetadata;
private final ItemHint sourceItemHint;
SourcePropertyDescriptor(PropertyDescriptor delegate, ItemMetadata sourceItemMetadata,
ItemHint sourceItemHint) {
super(delegate.getName(), delegate.getType(), delegate.getDeclaringElement(), delegate.getGetter());
this.delegate = delegate;
this.sourceItemMetadata = sourceItemMetadata;
this.sourceItemHint = sourceItemHint;
}
@Override
protected ItemHint resolveItemHint(String prefix, MetadataGenerationEnvironment environment) {
return (this.sourceItemHint != null) ? this.sourceItemHint.applyPrefix(prefix)
: super.resolveItemHint(prefix, environment); | }
@Override
protected boolean isMarkedAsNested(MetadataGenerationEnvironment environment) {
return this.delegate.isMarkedAsNested(environment);
}
@Override
protected String resolveDescription(MetadataGenerationEnvironment environment) {
String description = this.delegate.resolveDescription(environment);
return (description != null) ? description : this.sourceItemMetadata.getDescription();
}
@Override
protected Object resolveDefaultValue(MetadataGenerationEnvironment environment) {
Object defaultValue = this.delegate.resolveDefaultValue(environment);
return (defaultValue != null) ? defaultValue : this.sourceItemMetadata.getDefaultValue();
}
@Override
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
ItemDeprecation itemDeprecation = this.delegate.resolveItemDeprecation(environment);
return (itemDeprecation != null) ? itemDeprecation : this.sourceItemMetadata.getDeprecation();
}
@Override
boolean isProperty(MetadataGenerationEnvironment environment) {
return this.delegate.isProperty(environment);
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ConfigurationPropertiesSourceResolver.java | 2 |
请完成以下Java代码 | public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_DeliveryDay.java | 1 |
请完成以下Java代码 | public String getTempleNumber() {
return TempleNumber;
}
public void setTempleNumber(String templeNumber) {
TempleNumber = templeNumber;
}
public String getTomb() {
return tomb;
}
public void setTomb(String tomb) {
this.tomb = tomb;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public King getSuccessor() {
return successor;
}
public void setSuccessor(King successor) {
this.successor = successor;
}
public List<FatherAndSonRelation> getSons() {
return sons;
} | public void setSons(List<FatherAndSonRelation> sons) {
this.sons = sons;
}
/**
* 添加友谊的关系
* @param
*/
public void addRelation(FatherAndSonRelation fatherAndSonRelation){
if(this.sons == null){
this.sons = new ArrayList<>();
}
this.sons.add(fatherAndSonRelation);
}
} | repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\King.java | 1 |
请完成以下Java代码 | public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTabLevel (final int TabLevel)
{
set_Value (COLUMNNAME_TabLevel, TabLevel);
}
@Override
public int getTabLevel()
{
return get_ValueAsInt(COLUMNNAME_TabLevel);
}
@Override
public org.compiere.model.I_AD_Tab getTemplate_Tab()
{
return get_ValueAsPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class);
}
@Override
public void setTemplate_Tab(final org.compiere.model.I_AD_Tab Template_Tab)
{
set_ValueFromPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class, Template_Tab);
}
@Override
public void setTemplate_Tab_ID (final int Template_Tab_ID)
{ | if (Template_Tab_ID < 1)
set_Value (COLUMNNAME_Template_Tab_ID, null);
else
set_Value (COLUMNNAME_Template_Tab_ID, Template_Tab_ID);
}
@Override
public int getTemplate_Tab_ID()
{
return get_ValueAsInt(COLUMNNAME_Template_Tab_ID);
}
@Override
public void setWhereClause (final @Nullable java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public java.lang.String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tab.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
/** The id of the parent activity instance. If the activity is the process definition,
{@link #getId()} and {@link #getParentActivityInstanceId()} return the same value */
public String getParentActivityInstanceId() {
return parentActivityInstanceId;
}
/** the id of the activity */
public String getActivityId() {
return activityId;
}
/** type of the activity, corresponds to BPMN element name in XML (e.g. 'userTask') */
public String getActivityType() {
return activityType;
}
/** the process instance id */
public String getProcessInstanceId() {
return processInstanceId;
}
/** the process definition id */
public String getProcessDefinitionId() {
return processDefinitionId;
}
/** Returns the child activity instances.
* Returns an empty list if there are no child instances. */
public ActivityInstanceDto[] getChildActivityInstances() {
return childActivityInstances;
}
public TransitionInstanceDto[] getChildTransitionInstances() {
return childTransitionInstances;
}
/** the list of executions that are currently waiting in this activity instance */
public String[] getExecutionIds() {
return executionIds;
}
/** the activity name */
public String getActivityName() {
return activityName;
}
/**
* deprecated; the JSON field with this name was never documented, but existed
* from 7.0 to 7.2
*/
public String getName() {
return activityName;
}
public String[] getIncidentIds() {
return incidentIds;
}
public ActivityInstanceIncidentDto[] getIncidents() { | return incidents;
}
public static ActivityInstanceDto fromActivityInstance(ActivityInstance instance) {
ActivityInstanceDto result = new ActivityInstanceDto();
result.id = instance.getId();
result.parentActivityInstanceId = instance.getParentActivityInstanceId();
result.activityId = instance.getActivityId();
result.activityType = instance.getActivityType();
result.processInstanceId = instance.getProcessInstanceId();
result.processDefinitionId = instance.getProcessDefinitionId();
result.childActivityInstances = fromListOfActivityInstance(instance.getChildActivityInstances());
result.childTransitionInstances = TransitionInstanceDto.fromListOfTransitionInstance(instance.getChildTransitionInstances());
result.executionIds = instance.getExecutionIds();
result.activityName = instance.getActivityName();
result.incidentIds = instance.getIncidentIds();
result.incidents = ActivityInstanceIncidentDto.fromIncidents(instance.getIncidents());
return result;
}
public static ActivityInstanceDto[] fromListOfActivityInstance(ActivityInstance[] instances) {
ActivityInstanceDto[] result = new ActivityInstanceDto[instances.length];
for (int i = 0; i < result.length; i++) {
result[i] = fromActivityInstance(instances[i]);
}
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ActivityInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookServiceImpl implements BookService {
// 模拟数据库,存储 Book 信息
// 第五章《数据存储》会替换成 H2 数据源存储
private static Map<Long, Book> BOOK_DB = new HashMap<>();
@Override
public List<Book> findAll() {
return new ArrayList<>(BOOK_DB.values());
}
@Override
public Book insertByBook(Book book) {
book.setId(BOOK_DB.size() + 1L);
BOOK_DB.put(book.getId(), book);
return book;
} | @Override
public Book update(Book book) {
BOOK_DB.put(book.getId(), book);
return book;
}
@Override
public Book delete(Long id) {
return BOOK_DB.remove(id);
}
@Override
public Book findById(Long id) {
return BOOK_DB.get(id);
}
} | repos\springboot-learning-example-master\chapter-4-spring-boot-web-thymeleaf\src\main\java\demo\springboot\service\impl\BookServiceImpl.java | 2 |
请完成以下Java代码 | public void setEventScopeActivityId(String eventScopeActivityId) {
this.eventScopeActivityId = eventScopeActivityId;
}
public boolean isStartEvent() {
return isStartEvent;
}
public void setStartEvent(boolean isStartEvent) {
this.isStartEvent = isStartEvent;
}
public String getEventType() {
return eventType.name();
}
public CallableElement getEventPayload() {
return eventPayload;
}
public void setJobDeclaration(EventSubscriptionJobDeclaration jobDeclaration) {
this.jobDeclaration = jobDeclaration;
}
public EventSubscriptionEntity createSubscriptionForStartEvent(ProcessDefinitionEntity processDefinition) {
EventSubscriptionEntity eventSubscriptionEntity = new EventSubscriptionEntity(eventType);
VariableScope scopeForExpression = StartProcessVariableScope.getSharedInstance();
String eventName = resolveExpressionOfEventName(scopeForExpression);
eventSubscriptionEntity.setEventName(eventName);
eventSubscriptionEntity.setActivityId(activityId);
eventSubscriptionEntity.setConfiguration(processDefinition.getId());
eventSubscriptionEntity.setTenantId(processDefinition.getTenantId());
return eventSubscriptionEntity;
}
/**
* Creates and inserts a subscription entity depending on the message type of this declaration.
*/
public EventSubscriptionEntity createSubscriptionForExecution(ExecutionEntity execution) {
EventSubscriptionEntity eventSubscriptionEntity = new EventSubscriptionEntity(execution, eventType);
String eventName = resolveExpressionOfEventName(execution);
eventSubscriptionEntity.setEventName(eventName);
if (activityId != null) {
ActivityImpl activity = execution.getProcessDefinition().findActivity(activityId);
eventSubscriptionEntity.setActivity(activity);
}
eventSubscriptionEntity.insert();
LegacyBehavior.removeLegacySubscriptionOnParent(execution, eventSubscriptionEntity);
return eventSubscriptionEntity;
} | /**
* Resolves the event name within the given scope.
*/
public String resolveExpressionOfEventName(VariableScope scope) {
if (isExpressionAvailable()) {
if(scope instanceof BaseDelegateExecution) {
// the variable scope execution is also the current context execution
// during expression evaluation the current context is updated with the scope execution
return (String) eventName.getValue(scope, (BaseDelegateExecution) scope);
} else {
return (String) eventName.getValue(scope);
}
} else {
return null;
}
}
protected boolean isExpressionAvailable() {
return eventName != null;
}
public void updateSubscription(EventSubscriptionEntity eventSubscription) {
String eventName = resolveExpressionOfEventName(eventSubscription.getExecution());
eventSubscription.setEventName(eventName);
eventSubscription.setActivityId(activityId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\EventSubscriptionDeclaration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RestTemplate restTemplate;
@Autowired
private CircuitBreakerFactory circuitBreakerFactory;
@GetMapping("/get_user")
public String getUser(@RequestParam("id") Integer id) {
return circuitBreakerFactory.create("slow").run(new Supplier<String>() {
@Override
public String get() {
logger.info("[getUser][准备调用 user-service 获取用户({})详情]", id); | return restTemplate.getForEntity("http://127.0.0.1:18080/user/get?id="
+ id, String.class).getBody();
}
}, new Function<Throwable, String>() {
@Override
public String apply(Throwable throwable) {
logger.info("[getUserFallback][id({}) exception({})]", id,
throwable.getClass().getSimpleName());
return "mock:User:" + id;
}
});
}
} | repos\SpringBoot-Labs-master\labx-24\labx-24-resilience4j-demo02\src\main\java\cn\iocoder\springcloud\labx24\resilience4jdemo\controller\DemoController.java | 2 |
请完成以下Java代码 | public java.sql.Timestamp getDateOrdered()
{
return get_ValueAsTimestamp(COLUMNNAME_DateOrdered);
}
@Override
public void setDatePromised (final @Nullable java.sql.Timestamp DatePromised)
{
set_Value (COLUMNNAME_DatePromised, DatePromised);
}
@Override
public java.sql.Timestamp getDatePromised()
{
return get_ValueAsTimestamp(COLUMNNAME_DatePromised);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID); | }
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRemotePurchaseOrderId (final @Nullable java.lang.String RemotePurchaseOrderId)
{
set_Value (COLUMNNAME_RemotePurchaseOrderId, RemotePurchaseOrderId);
}
@Override
public java.lang.String getRemotePurchaseOrderId()
{
return get_ValueAsString(COLUMNNAME_RemotePurchaseOrderId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate_Alloc.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TbLwM2MAuthorizer implements Authorizer {
private final TbLwM2MDtlsSessionStore sessionStorage;
private final TbMainSecurityStore securityStore;
private final SecurityChecker securityChecker = new SecurityChecker();
private final LwM2mClientContext clientContext;
@Override
public Authorization isAuthorized(UplinkRequest<?> request, Registration registration, LwM2mPeer sender) {
SecurityInfo expectedSecurityInfo = null;
if (securityStore != null) expectedSecurityInfo = securityStore.getByEndpoint(registration.getEndpoint());
if (securityChecker.checkSecurityInfo(registration.getEndpoint(), sender, expectedSecurityInfo)) {
if (sender.getIdentity() instanceof X509Identity) {
TbX509DtlsSessionInfo sessionInfo = sessionStorage.get(registration.getEndpoint());
if (sessionInfo != null) {
// X509 certificate is valid and matches endpoint.
clientContext.registerClient(registration, sessionInfo.getCredentials());
}
}
try { | if (expectedSecurityInfo != null && expectedSecurityInfo.usePSK() && expectedSecurityInfo.getEndpoint().equals(SecurityMode.NO_SEC.toString())
&& expectedSecurityInfo.getPskIdentity().equals(SecurityMode.NO_SEC.toString())
&& Arrays.equals(SecurityMode.NO_SEC.toString().getBytes(), expectedSecurityInfo.getPreSharedKey())) {
return Authorization.declined();
}
} catch (LwM2MAuthException e) {
log.info("Registration failed: FORBIDDEN, endpointId: [{}]", registration.getEndpoint());
return Authorization.declined();
}
return Authorization.approved();
} else {
return Authorization.declined();
}
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\secure\TbLwM2MAuthorizer.java | 2 |
请完成以下Java代码 | public void onDeleteMHUPI(final I_M_HU_PI pi)
{
final List<I_M_HU_PI_Version> piVersions = handlingUnitsDAO.retrieveAllPIVersions(pi);
for (final I_M_HU_PI_Version version : piVersions)
{
InterfaceWrapperHelper.delete(version);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = I_M_HU_PI.COLUMNNAME_IsDefaultForPicking
)
public void ensureOnlyOneDefaultForPicking(@NonNull final I_M_HU_PI newDefault)
{
try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(newDefault))
{
if (!newDefault.isDefaultForPicking()) | {
return;
}
final I_M_HU_PI previousDefault = handlingUnitsDAO.retrievePIDefaultForPicking();
if (previousDefault != null)
{
logger.debug("M_HU_PI={} is now IsDefaultForPicking; -> Change previousDefault M_HU_PI={} to IsDefaultForPicking='N'",
newDefault.getM_HU_PI_ID(), previousDefault.getM_HU_PI_ID());
previousDefault.setIsDefaultForPicking(false);
handlingUnitsDAO.save(previousDefault);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU_PI.java | 1 |
请完成以下Java代码 | public DomainInfo findDomainInfoById(TenantId tenantId, DomainId domainId) {
log.trace("Executing findDomainInfoById [{}] [{}]", tenantId, domainId);
Domain domain = domainDao.findById(tenantId, domainId.getId());
return getDomainInfo(domain);
}
@Override
public boolean isOauth2Enabled(TenantId tenantId) {
log.trace("Executing isOauth2Enabled [{}] ", tenantId);
return domainDao.countDomainByTenantIdAndOauth2Enabled(tenantId, true) > 0;
}
@Override
public void deleteDomainsByTenantId(TenantId tenantId) {
log.trace("Executing deleteDomainsByTenantId, tenantId [{}]", tenantId);
domainDao.deleteByTenantId(tenantId);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteDomainsByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findDomainById(tenantId, new DomainId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(domainDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
@Transactional
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
deleteDomainById(tenantId, (DomainId) id); | }
private DomainInfo getDomainInfo(Domain domain) {
if (domain == null) {
return null;
}
List<OAuth2ClientInfo> clients = oauth2ClientDao.findByDomainId(domain.getUuidId()).stream()
.map(OAuth2ClientInfo::new)
.sorted(Comparator.comparing(OAuth2ClientInfo::getTitle))
.collect(Collectors.toList());
return new DomainInfo(domain, clients);
}
@Override
public EntityType getEntityType() {
return EntityType.DOMAIN;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\domain\DomainServiceImpl.java | 1 |
请完成以下Java代码 | public MeterProvider<Counter> getServerCallCounter() {
return this.serverCallCounter;
}
public MeterProvider<DistributionSummary> getSentMessageSizeDistribution() {
return this.sentMessageSizeDistribution;
}
public MeterProvider<DistributionSummary> getReceivedMessageSizeDistribution() {
return this.receivedMessageSizeDistribution;
}
public MeterProvider<Timer> getServerCallDuration() {
return this.serverCallDuration;
}
public static Builder newBuilder() {
return new Builder();
}
static class Builder {
private MeterProvider<Counter> serverCallCounter;
private MeterProvider<DistributionSummary> sentMessageSizeDistribution;
private MeterProvider<DistributionSummary> receivedMessageSizeDistribution;
private MeterProvider<Timer> serverCallDuration;
private Builder() {}
public Builder setServerCallCounter(MeterProvider<Counter> counter) { | this.serverCallCounter = counter;
return this;
}
public Builder setSentMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) {
this.sentMessageSizeDistribution = distribution;
return this;
}
public Builder setReceivedMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) {
this.receivedMessageSizeDistribution = distribution;
return this;
}
public Builder setServerCallDuration(MeterProvider<Timer> timer) {
this.serverCallDuration = timer;
return this;
}
public MetricsServerMeters build() {
return new MetricsServerMeters(this);
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\metrics\MetricsServerMeters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class JacksonJsonbUnavailable {
}
}
private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions {
JacksonAndJsonbUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(JacksonHttpMessageConvertersConfiguration.JacksonJsonHttpMessageConvertersCustomizer.class)
static class JacksonAvailable {
} | @SuppressWarnings("removal")
@ConditionalOnBean(Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class)
static class Jackson2Available {
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jsonb")
static class JsonbPreferred {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\GsonHttpMessageConvertersConfiguration.java | 2 |
请完成以下Java代码 | public static String toGlobalQRCodeJsonString(final UserAuthQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final UserAuthQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
@NonNull
public static UserAuthQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static UserAuthQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!isTypeMatching(globalQRCode))
{
throw new AdempiereException("Invalid QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
} | final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode)
{
return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\qr\UserAuthQRCodeJsonConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class TomcatServletWebServerFactoryCustomizer
implements WebServerFactoryCustomizer<TomcatServletWebServerFactory>, Ordered {
private final TomcatServerProperties tomcatProperties;
TomcatServletWebServerFactoryCustomizer(TomcatServerProperties tomcatProperties) {
this.tomcatProperties = tomcatProperties;
}
@Override
public int getOrder() {
return 0;
}
@Override
public void customize(TomcatServletWebServerFactory factory) {
if (!ObjectUtils.isEmpty(this.tomcatProperties.getAdditionalTldSkipPatterns())) {
factory.getTldSkipPatterns().addAll(this.tomcatProperties.getAdditionalTldSkipPatterns());
}
if (this.tomcatProperties.getRedirectContextRoot() != null) { | customizeRedirectContextRoot(factory, this.tomcatProperties.getRedirectContextRoot());
}
customizeUseRelativeRedirects(factory, this.tomcatProperties.isUseRelativeRedirects());
}
private void customizeRedirectContextRoot(ConfigurableTomcatWebServerFactory factory, boolean redirectContextRoot) {
factory.addContextCustomizers((context) -> context.setMapperContextRootRedirectEnabled(redirectContextRoot));
}
private void customizeUseRelativeRedirects(ConfigurableTomcatWebServerFactory factory,
boolean useRelativeRedirects) {
factory.addContextCustomizers((context) -> context.setUseRelativeRedirects(useRelativeRedirects));
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\servlet\TomcatServletWebServerFactoryCustomizer.java | 2 |
请完成以下Java代码 | public LookupDescriptorProvider listByAD_Reference_Value_ID(@NonNull final ReferenceId AD_Reference_Value_ID)
{
return sql()
.setCtxTableName(null) // tableName
.setCtxColumnName(null)
.setDisplayType(DisplayType.List)
.setAD_Reference_Value_ID(AD_Reference_Value_ID)
.setReadOnlyAccess()
.build();
}
public LookupDescriptor productAttributes()
{
return sql()
.setCtxTableName(null) // tableName
.setCtxColumnName(I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID)
.setDisplayType(DisplayType.PAttribute)
.setReadOnlyAccess()
.build()
.provide()
.orElseThrow(() -> new AdempiereException("No lookup descriptor found for Product Attributes"));
}
/**
* @return provider which returns given {@link LookupDescriptor} for any scope
*/
public static LookupDescriptorProvider singleton(@NonNull final LookupDescriptor lookupDescriptor)
{
return new SingletonLookupDescriptorProvider(lookupDescriptor);
}
public static LookupDescriptorProvider ofNullableInstance(@Nullable final LookupDescriptor lookupDescriptor)
{
return lookupDescriptor != null ? singleton(lookupDescriptor) : NULL;
}
/**
* @return provider which calls the given function (memoized)
*/
public static LookupDescriptorProvider fromMemoizingFunction(final Function<LookupScope, LookupDescriptor> providerFunction)
{
return new MemoizingFunctionLookupDescriptorProvider(providerFunction);
}
//
//
//
private static class NullLookupDescriptorProvider implements LookupDescriptorProvider
{
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return Optional.empty();
}
} | @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ToString
private static class SingletonLookupDescriptorProvider implements LookupDescriptorProvider
{
private final Optional<LookupDescriptor> lookupDescriptor;
private SingletonLookupDescriptorProvider(@NonNull final LookupDescriptor lookupDescriptor)
{
this.lookupDescriptor = Optional.of(lookupDescriptor);
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return lookupDescriptor;
}
}
@ToString
private static class MemoizingFunctionLookupDescriptorProvider implements LookupDescriptorProvider
{
private final MemoizingFunction<LookupScope, LookupDescriptor> providerFunctionMemoized;
private MemoizingFunctionLookupDescriptorProvider(@NonNull final Function<LookupScope, LookupDescriptor> providerFunction)
{
providerFunctionMemoized = Functions.memoizing(providerFunction);
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return Optional.ofNullable(providerFunctionMemoized.apply(scope));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptorProviders.java | 1 |
请完成以下Java代码 | public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{
return "NullAttributeStorage []";
}
@Override
public BigDecimal getStorageQtyOrZERO()
{
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/
@Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute) | {
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java | 1 |
请完成以下Java代码 | class WFPopupItem extends JMenuItem
{
private static final long serialVersionUID = 4634863991042969718L;
public WFPopupItem(String title, WorkflowNodeModel node, WFNodeId nodeToId)
{
super(title);
m_node = node;
m_line = null;
this.nodeToId = nodeToId;
} // WFPopupItem
/**
* Delete Line Item
*
* @param title title
* @param line line to be deleted
*/
public WFPopupItem(String title, WorkflowNodeTransitionModel line)
{
super(title);
m_node = null;
m_line = line;
nodeToId = null;
} // WFPopupItem
/**
* The Node
*/
private final WorkflowNodeModel m_node;
/**
* The Line
*/
private final WorkflowNodeTransitionModel m_line;
/**
* The Next Node ID
*/
private final WFNodeId nodeToId;
/**
* Execute | */
public void execute()
{
// Add Line
if (m_node != null && nodeToId != null)
{
final I_AD_WF_NodeNext newLine = InterfaceWrapperHelper.newInstance(I_AD_WF_NodeNext.class);
newLine.setAD_Org_ID(OrgId.ANY.getRepoId());
newLine.setAD_WF_Node_ID(m_node.getId().getRepoId());
newLine.setAD_WF_Next_ID(nodeToId.getRepoId());
InterfaceWrapperHelper.save(newLine);
log.info("Add Line to " + m_node + " -> " + newLine);
m_parent.load(m_wf.getId(), true);
}
// Delete Node
else if (m_node != null && nodeToId == null)
{
log.info("Delete Node: " + m_node);
Services.get(IADWorkflowDAO.class).deleteNodeById(m_node.getId());
m_parent.load(m_wf.getId(), true);
}
// Delete Line
else if (m_line != null)
{
log.info("Delete Line: " + m_line);
Services.get(IADWorkflowDAO.class).deleteNodeTransitionById(m_line.getId());
m_parent.load(m_wf.getId(), true);
}
else
log.error("No Action??");
} // execute
} // WFPopupItem
} // WFContentPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFContentPanel.java | 1 |
请完成以下Java代码 | public NumberAndSumOfTransactions2 getTtlNtries() {
return ttlNtries;
}
/**
* Sets the value of the ttlNtries property.
*
* @param value
* allowed object is
* {@link NumberAndSumOfTransactions2 }
*
*/
public void setTtlNtries(NumberAndSumOfTransactions2 value) {
this.ttlNtries = value;
}
/**
* Gets the value of the ttlCdtNtries property.
*
* @return
* possible object is
* {@link NumberAndSumOfTransactions1 }
*
*/
public NumberAndSumOfTransactions1 getTtlCdtNtries() {
return ttlCdtNtries;
}
/**
* Sets the value of the ttlCdtNtries property.
*
* @param value
* allowed object is
* {@link NumberAndSumOfTransactions1 }
*
*/
public void setTtlCdtNtries(NumberAndSumOfTransactions1 value) {
this.ttlCdtNtries = value;
}
/**
* Gets the value of the ttlDbtNtries property.
*
* @return
* possible object is
* {@link NumberAndSumOfTransactions1 }
*
*/
public NumberAndSumOfTransactions1 getTtlDbtNtries() {
return ttlDbtNtries;
} | /**
* Sets the value of the ttlDbtNtries property.
*
* @param value
* allowed object is
* {@link NumberAndSumOfTransactions1 }
*
*/
public void setTtlDbtNtries(NumberAndSumOfTransactions1 value) {
this.ttlDbtNtries = value;
}
/**
* Gets the value of the ttlNtriesPerBkTxCd property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ttlNtriesPerBkTxCd property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTtlNtriesPerBkTxCd().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TotalsPerBankTransactionCode2 }
*
*
*/
public List<TotalsPerBankTransactionCode2> getTtlNtriesPerBkTxCd() {
if (ttlNtriesPerBkTxCd == null) {
ttlNtriesPerBkTxCd = new ArrayList<TotalsPerBankTransactionCode2>();
}
return this.ttlNtriesPerBkTxCd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TotalTransactions2.java | 1 |
请完成以下Java代码 | private Stream<PropertySource<?>> getPropertySources() {
if (this.environment == null) {
return Stream.empty();
}
return this.environment.getPropertySources()
.stream()
.filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source));
}
private void appendDetails(StringBuilder message, MutuallyExclusiveConfigurationPropertiesException cause,
List<Descriptor> descriptors) {
descriptors.sort(Comparator.comparing((descriptor) -> descriptor.propertyName));
message.append(String.format("The following configuration properties are mutually exclusive:%n%n"));
sortedStrings(cause.getMutuallyExclusiveNames())
.forEach((name) -> message.append(String.format("\t%s%n", name)));
message.append(String.format("%n"));
message.append(
String.format("However, more than one of those properties has been configured at the same time:%n%n"));
Set<String> configuredDescriptions = sortedStrings(descriptors,
(descriptor) -> String.format("\t%s%s%n", descriptor.propertyName,
(descriptor.origin != null) ? " (originating from '" + descriptor.origin + "')" : ""));
configuredDescriptions.forEach(message::append);
}
private Set<String> sortedStrings(Collection<String> input) {
return sortedStrings(input, Function.identity());
}
private <S> Set<String> sortedStrings(Collection<S> input, Function<S, String> converter) {
TreeSet<String> results = new TreeSet<>(); | for (S item : input) {
results.add(converter.apply(item));
}
return results;
}
private static final class Descriptor {
private final String propertyName;
private final @Nullable Origin origin;
private Descriptor(String propertyName, @Nullable Origin origin) {
this.propertyName = propertyName;
this.origin = origin;
}
static Descriptor get(PropertySource<?> source, String propertyName) {
Origin origin = OriginLookup.getOrigin(source, propertyName);
return new Descriptor(propertyName, origin);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java | 1 |
请完成以下Java代码 | protected <T> void configureAuthCheck(ListQueryParameterObject parameter,
ProcessEngineConfigurationImpl engineConfig,
CommandContext commandContext) {
AuthorizationCheck authCheck = parameter.getAuthCheck();
commandContext.getAuthorizationManager()
.enableQueryAuthCheck(authCheck);
boolean isEnableHistoricInstancePermissions = engineConfig.isEnableHistoricInstancePermissions();
authCheck.setHistoricInstancePermissionsEnabled(isEnableHistoricInstancePermissions);
}
protected class QueryServiceRowCountCmd implements Command<Long> {
protected String statement;
protected ListQueryParameterObject parameter;
public QueryServiceRowCountCmd(String statement, ListQueryParameterObject parameter) {
this.statement = statement;
this.parameter = parameter;
}
@Override
public Long execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl engineConfig = getProcessEngineConfiguration(commandContext);
configureAuthCheck(parameter, engineConfig, commandContext);
return (Long) commandContext.getDbSqlSession().selectOne(statement, parameter);
}
}
protected class ExecuteListQueryCmd<T> implements Command<List<T>> {
protected String statement;
protected QueryParameters parameter;
public ExecuteListQueryCmd(String statement, QueryParameters parameter) {
this.statement = statement;
this.parameter = parameter;
} | @Override
public List<T> execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl engineConfig = getProcessEngineConfiguration(commandContext);
configureAuthCheck(parameter, engineConfig, commandContext);
if (parameter.isMaxResultsLimitEnabled()) {
QueryMaxResultsLimitUtil.checkMaxResultsLimit(parameter.getMaxResults(), engineConfig);
}
return (List<T>) commandContext.getDbSqlSession().selectList(statement, parameter);
}
}
protected class ExecuteSingleQueryCmd<T> implements Command<T> {
protected String statement;
protected Object parameter;
protected Class clazz;
public <T> ExecuteSingleQueryCmd(String statement, Object parameter, Class<T> clazz) {
this.statement = statement;
this.parameter = parameter;
this.clazz = clazz;
}
@Override
public T execute(CommandContext commandContext) {
return (T) commandContext.getDbSqlSession().selectOne(statement, parameter);
}
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\db\QueryServiceImpl.java | 1 |
请完成以下Java代码 | public int getC_UOM_ID()
{
return forecastLine.getC_UOM_ID();
}
@Override
public void setC_UOM_ID(final int uomId)
{
forecastLine.setC_UOM_ID(uomId);
}
@Override
public void setQty(final BigDecimal qty)
{
forecastLine.setQty(qty);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyCalculated = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty);
forecastLine.setQtyCalculated(qtyCalculated);
}
@Override
public BigDecimal getQty()
{
return forecastLine.getQty();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final int forecastLine_PIItemProductId = forecastLine.getM_HU_PI_Item_Product_ID();
if (forecastLine_PIItemProductId > 0)
{
return forecastLine_PIItemProductId;
}
return -1;
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return forecastLine.getQtyEnteredTU();
} | @Override
public void setQtyTU(final BigDecimal qtyPacks)
{
forecastLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java | 1 |
请完成以下Java代码 | public class HibernateUtil {
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
ServiceRegistry serviceRegistry = configureServiceRegistry();
return makeSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
ServiceRegistry serviceRegistry = configureServiceRegistry(properties);
return makeSessionFactory(serviceRegistry);
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Student.class);
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build(); | return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
return configureServiceRegistry(getProperties());
}
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
public static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\HibernateUtil.java | 1 |
请完成以下Java代码 | public class NativeHistoricDetailQueryImpl
extends AbstractNativeQuery<NativeHistoricDetailQuery, HistoricDetail>
implements NativeHistoricDetailQuery {
private static final long serialVersionUID = 1L;
public NativeHistoricDetailQueryImpl(CommandContext commandContext) {
super(commandContext);
}
public NativeHistoricDetailQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
// results //////////////////////////////////////////////////////////////// | public List<HistoricDetail> executeList(
CommandContext commandContext,
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return commandContext
.getHistoricDetailEntityManager()
.findHistoricDetailsByNativeQuery(parameterMap, firstResult, maxResults);
}
public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) {
return commandContext.getHistoricDetailEntityManager().findHistoricDetailCountByNativeQuery(parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\NativeHistoricDetailQueryImpl.java | 1 |
请完成以下Java代码 | public java.lang.String getLastSyncStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_LastSyncStatus);
}
/** Set MKTG_ContactPerson.
@param MKTG_ContactPerson_ID MKTG_ContactPerson */
@Override
public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID)
{
if (MKTG_ContactPerson_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID));
}
/** Get MKTG_ContactPerson.
@return MKTG_ContactPerson */
@Override
public int getMKTG_ContactPerson_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.marketing.base.model.I_MKTG_Platform getMKTG_Platform() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class);
}
@Override
public void setMKTG_Platform(de.metas.marketing.base.model.I_MKTG_Platform MKTG_Platform)
{
set_ValueFromPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class, MKTG_Platform);
}
/** Set MKTG_Platform.
@param MKTG_Platform_ID MKTG_Platform */
@Override
public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
if (MKTG_Platform_ID < 1)
set_Value (COLUMNNAME_MKTG_Platform_ID, null);
else
set_Value (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID));
}
/** Get MKTG_Platform.
@return MKTG_Platform */ | @Override
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Externe Datensatz-ID.
@param RemoteRecordId Externe Datensatz-ID */
@Override
public void setRemoteRecordId (java.lang.String RemoteRecordId)
{
set_Value (COLUMNNAME_RemoteRecordId, RemoteRecordId);
}
/** Get Externe Datensatz-ID.
@return Externe Datensatz-ID */
@Override
public java.lang.String getRemoteRecordId ()
{
return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson.java | 1 |
请完成以下Java代码 | public static void createCopyOfSubProcessExecutionForCompensation(ExecutionEntity subProcessExecution) {
EventSubscriptionEntityManager eventSubscriptionEntityManager =
Context.getCommandContext().getEventSubscriptionEntityManager();
List<EventSubscriptionEntity> eventSubscriptions =
eventSubscriptionEntityManager.findEventSubscriptionsByExecutionAndType(
subProcessExecution.getId(),
"compensate"
);
List<CompensateEventSubscriptionEntity> compensateEventSubscriptions = new ArrayList<
CompensateEventSubscriptionEntity
>();
for (EventSubscriptionEntity event : eventSubscriptions) {
if (event instanceof CompensateEventSubscriptionEntity) {
compensateEventSubscriptions.add((CompensateEventSubscriptionEntity) event);
}
}
if (CollectionUtil.isNotEmpty(compensateEventSubscriptions)) {
ExecutionEntity processInstanceExecutionEntity = subProcessExecution.getProcessInstance();
ExecutionEntity eventScopeExecution = Context.getCommandContext()
.getExecutionEntityManager()
.createChildExecution(processInstanceExecutionEntity);
eventScopeExecution.setActive(false);
eventScopeExecution.setEventScope(true);
eventScopeExecution.setCurrentFlowElement(subProcessExecution.getCurrentFlowElement());
// copy local variables to eventScopeExecution by value. This way,
// the eventScopeExecution references a 'snapshot' of the local variables
new SubProcessVariableSnapshotter().setVariablesSnapshots(subProcessExecution, eventScopeExecution);
// set event subscriptions to the event scope execution:
for (CompensateEventSubscriptionEntity eventSubscriptionEntity : compensateEventSubscriptions) { | eventSubscriptionEntityManager.delete(eventSubscriptionEntity);
CompensateEventSubscriptionEntity newSubscription =
eventSubscriptionEntityManager.insertCompensationEvent(
eventScopeExecution,
eventSubscriptionEntity.getActivityId()
);
newSubscription.setConfiguration(eventSubscriptionEntity.getConfiguration());
newSubscription.setCreated(eventSubscriptionEntity.getCreated());
}
CompensateEventSubscriptionEntity eventSubscription =
eventSubscriptionEntityManager.insertCompensationEvent(
processInstanceExecutionEntity,
eventScopeExecution.getCurrentFlowElement().getId()
);
eventSubscription.setConfiguration(eventScopeExecution.getId());
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\ScopeUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String[] queryDict(String dicTable, String dicCode, String dicText) {
List<String> dictReplaces = new ArrayList<String>();
List<DictModel> dictList = null;
// step.1 如果没有字典表则使用系统字典表
if (oConvertUtils.isEmpty(dicTable)) {
dictList = commonApi.queryDictItemsByCode(dicCode);
} else {
try {
dicText = oConvertUtils.getString(dicText, dicCode);
dictList = commonApi.queryTableDictItemsByCode(dicTable, dicText, dicCode);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
for (DictModel t : dictList) { | // 代码逻辑说明: [issues/4917]excel 导出异常---
if(t!=null && t.getText()!=null && t.getValue()!=null){
// 代码逻辑说明: [issues/I4MBB3]@Excel dicText字段的值有下划线时,导入功能不能正确解析---
if(t.getValue().contains(EXCEL_SPLIT_TAG)){
String val = t.getValue().replace(EXCEL_SPLIT_TAG,TEMP_EXCEL_SPLIT_TAG);
dictReplaces.add(t.getText() + EXCEL_SPLIT_TAG + val);
}else{
dictReplaces.add(t.getText() + EXCEL_SPLIT_TAG + t.getValue());
}
}
}
if (dictReplaces != null && dictReplaces.size() != 0) {
log.info("---AutoPoi--Get_DB_Dict------"+ dictReplaces.toString());
return dictReplaces.toArray(new String[dictReplaces.size()]);
}
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\AutoPoiDictConfig.java | 2 |
请完成以下Java代码 | public void assignTradingUnitToLoadingUnit(final IHUContext huContext,
final I_M_HU loadingUnit,
final I_M_HU tradingUnit) throws NoCompatibleHUItemParentFoundException
{
//
// Services
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
// why is that?
// Check.errorIf(handlingUnitsBL.isAggregateHU(tradingUnit), "Param 'tradingUnit' can't be an aggregate HU; tradingUnit={}", tradingUnit);
//
// iterate existing items of 'lodingUnit' and see if one fits to our 'tradingUnit'
final List<I_M_HU_Item> luItems = handlingUnitsDAO.retrieveItems(loadingUnit);
for (final I_M_HU_Item luItem : luItems)
{
if (!X_M_HU_PI_Item.ITEMTYPE_HandlingUnit.equals(handlingUnitsBL.getItemType(luItem)))
{
continue; // Item type needs to be handling unit
}
if (handlingUnitsBL.isVirtual(tradingUnit))
{
// We assign virtual PI to any loading unit.
huTrxBL.setParentHU(huContext, luItem, tradingUnit);
return; // we are done
}
if (handlingUnitsBL.getPIItem(luItem).getIncluded_HU_PI_ID() != handlingUnitsBL.getPIVersion(tradingUnit).getM_HU_PI_ID()) | {
continue; // Item not supported by this handling unit
}
// Assign HU to the luItem which we just found
huTrxBL.setParentHU(huContext, luItem, tradingUnit);
return; // we are done
}
// we did not find a compatible item for 'tradingUnit' to attach.
// try if we can create one on the fly
final I_M_HU_PI_Item luPI = handlingUnitsDAO.retrieveParentPIItemForChildHUOrNull(loadingUnit, handlingUnitsBL.getPI(tradingUnit), huContext);
if (luPI != null)
{
final I_M_HU_Item newLUItem = handlingUnitsDAO.createHUItem(loadingUnit, luPI);
// Assign HU to the newLUItem which we just created
huTrxBL.setParentHU(huContext, newLUItem, tradingUnit);
return; // we are done
}
// We did not succeed; thorw an exception.
// This does not need to be translated, as it will be handled later (internal error message)
throw new NoCompatibleHUItemParentFoundException("TU could not be attached to the specified LU because no LU-PI Item supports it"
+ "\nLoading Unit (LU): " + loadingUnit
+ "\nTrading Unit (TU): " + tradingUnit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUJoinBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Demo01Producer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void syncSend(Integer id) {
// 创建 Demo01Message 消息
Demo01Message message = new Demo01Message();
message.setId(id);
// 同步发送消息
rabbitTemplate.convertAndSend(Demo01Message.EXCHANGE, Demo01Message.ROUTING_KEY, message);
}
public void syncSendDefault(Integer id) {
// 创建 Demo01Message 消息
Demo01Message message = new Demo01Message();
message.setId(id);
// 同步发送消息
rabbitTemplate.convertAndSend(Demo01Message.QUEUE, message);
} | @Async
public ListenableFuture<Void> asyncSend(Integer id) {
try {
// 发送消息
this.syncSend(id);
// 返回成功的 Future
return AsyncResult.forValue(null);
} catch (Throwable ex) {
// 返回异常的 Future
return AsyncResult.forExecutionException(ex);
}
}
} | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\producer\Demo01Producer.java | 2 |
请完成以下Java代码 | private void showError(final String title, final Object messageObj)
{
JOptionPane.showMessageDialog(this,
messageObj, // message
title,
JOptionPane.ERROR_MESSAGE);
}
/**
* Test Database connection.
*
* If the database connection is not OK, an error popup will be displayed to user.
*/
private void cmd_testDB()
{
setBusy(true);
try
{
m_cc.testDatabase(); | }
catch (Exception e)
{
log.error(e.getMessage(), e);
showError(res.getString("ConnectionError") + ": " + m_cc.getConnectionURL(), e);
}
finally
{
setBusy(false);
}
} // cmd_testDB
public boolean isCancel()
{
return isCancel;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionDialog.java | 1 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getVariableName() {
return variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public String getId() {
return id;
}
public Set<String> getTaskIds() {
return taskIds;
} | public String getExecutionId() {
return executionId;
}
public Set<String> getExecutionIds() {
return executionIds;
}
public boolean isExcludeTaskRelated() {
return excludeTaskRelated;
}
public boolean isExcludeVariableInitialization() {
return excludeVariableInitialization;
}
public QueryVariableValue getQueryVariableValue() {
return queryVariableValue;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricVariableInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private <T> T getBeanOrNull(Class<?> clazz) {
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
return (T) context.getBeanProvider(clazz).getIfUnique();
}
private static final class EitherLogoutHandler implements LogoutHandler {
private final LogoutHandler left;
private final LogoutHandler right;
EitherLogoutHandler(LogoutHandler left, LogoutHandler right) {
this.left = left;
this.right = right;
} | @Override
public void logout(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
if (request.getParameter("_spring_security_internal_logout") == null) {
this.left.logout(request, response, authentication);
}
else {
this.right.logout(request, response, authentication);
}
}
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcLogoutConfigurer.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public AllergensAsEntity getAllergens() {
return allergens;
} | public void setAllergens(AllergensAsEntity allergens) {
this.allergens = allergens;
}
public Long getId() {
return id;
}
@Override
public String toString() {
return "MealWithMultipleEntities [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", allergens=" + allergens + "]";
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\multipletables\multipleentities\MealWithMultipleEntities.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_PromotionGroup[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Promotion Group.
@param M_PromotionGroup_ID Promotion Group */
public void setM_PromotionGroup_ID (int M_PromotionGroup_ID)
{ | if (M_PromotionGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID));
}
/** Get Promotion Group.
@return Promotion Group */
public int getM_PromotionGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroup.java | 1 |
请完成以下Java代码 | public boolean isFulfilled(ActivityExecutionTuple element) {
return escalationEventDefinitionFinder.getEscalationEventDefinition() != null || element == null;
}
});
EscalationEventDefinition escalationEventDefinition = escalationEventDefinitionFinder.getEscalationEventDefinition();
if (escalationEventDefinition != null) {
executeEscalationHandler(escalationEventDefinition, activityExecutionMappingCollector, escalationCode);
}
return escalationEventDefinition;
}
protected static void executeEscalationHandler(EscalationEventDefinition escalationEventDefinition, ActivityExecutionMappingCollector activityExecutionMappingCollector, String escalationCode) {
PvmActivity escalationHandler = escalationEventDefinition.getEscalationHandler();
PvmScope escalationScope = getScopeForEscalation(escalationEventDefinition);
ActivityExecution escalationExecution = activityExecutionMappingCollector.getExecutionForScope(escalationScope);
if (escalationEventDefinition.getEscalationCodeVariable() != null) { | escalationExecution.setVariable(escalationEventDefinition.getEscalationCodeVariable(), escalationCode);
}
escalationExecution.executeActivity(escalationHandler);
}
protected static PvmScope getScopeForEscalation(EscalationEventDefinition escalationEventDefinition) {
PvmActivity escalationHandler = escalationEventDefinition.getEscalationHandler();
if (escalationEventDefinition.isCancelActivity()) {
return escalationHandler.getEventScope();
} else {
return escalationHandler.getFlowScope();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\EscalationHandler.java | 1 |
请完成以下Java代码 | public class DelegateExpressionFlowableEventListener extends BaseDelegateEventListener {
protected Expression expression;
protected boolean failOnException;
public DelegateExpressionFlowableEventListener(Expression expression, Class<?> entityClass) {
this.expression = expression;
setEntityClass(entityClass);
}
@Override
public void onEvent(FlowableEvent event) {
if (isValidEvent(event)) {
Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, new NoExecutionVariableScope());
if (delegate instanceof FlowableEventListener) {
// Cache result of isFailOnException() from delegate-instance
// until next event is received. This prevents us from having to resolve
// the expression twice when an error occurs.
failOnException = ((FlowableEventListener) delegate).isFailOnException();
// Call the delegate | ((FlowableEventListener) delegate).onEvent(event);
} else {
// Force failing, since the exception we're about to throw
// cannot be ignored, because it did not originate from the listener itself
failOnException = true;
throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + FlowableEventListener.class.getName());
}
}
}
@Override
public boolean isFailOnException() {
return failOnException;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\helper\DelegateExpressionFlowableEventListener.java | 1 |
请完成以下Java代码 | public void setAttributes(final BoilerPlateContext attributes)
{
this.attributes = attributes;
fMessage.setAttributes(attributes);
}
public BoilerPlateContext getAttributes()
{
return attributes;
}
/**
* Action Listener - Send email
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
try
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
confirmPanel.getOKButton().setEnabled(false);
//
if (m_isPrintOnOK)
{
m_isPrinted = fMessage.print();
}
}
finally
{
confirmPanel.getOKButton().setEnabled(true);
setCursor(Cursor.getDefaultCursor());
}
// m_isPrinted = true;
m_isPressedOK = true;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
} | } // actionPerformed
public void setPrintOnOK(final boolean value)
{
m_isPrintOnOK = value;
}
public boolean isPressedOK()
{
return m_isPressedOK;
}
public boolean isPrinted()
{
return m_isPrinted;
}
public File getPDF()
{
return fMessage.getPDF(getTitle());
}
public RichTextEditor getRichTextEditor()
{
return fMessage;
}
} // Letter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\LetterDialog.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyReceived()
{
Check.assumeNotNull(qtyReceived, "qtyReceived not null");
return qtyReceived;
}
public void setQtyReceived(final BigDecimal qtyReceived)
{
this.qtyReceived = qtyReceived;
}
@Override
public I_C_UOM getQtyReceivedUOM()
{
Check.assumeNotNull(qtyReceivedUOM, "qtyReceivedUOM not null");
return qtyReceivedUOM;
}
public void setQtyReceivedUOM(final I_C_UOM qtyReceivedUOM)
{
this.qtyReceivedUOM = qtyReceivedUOM;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo; | }
/**
* This method does nothing!
*/
@Override
public void add(final Object IGNORED)
{
}
/**
* This method returns the empty list.
*/
@Override
public List<Object> getModels()
{
return Collections.emptyList();
}
@Override public I_M_PriceList_Version getPLV()
{
return plv;
}
public void setPlv(I_M_PriceList_Version plv)
{
this.plv = plv;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainVendorReceipt.java | 1 |
请完成以下Java代码 | public void setIsIVTherapy (final boolean IsIVTherapy)
{
set_Value (COLUMNNAME_IsIVTherapy, IsIVTherapy);
}
@Override
public boolean isIVTherapy()
{
return get_ValueAsBoolean(COLUMNNAME_IsIVTherapy);
}
@Override
public void setIsTransferPatient (final boolean IsTransferPatient)
{
set_Value (COLUMNNAME_IsTransferPatient, IsTransferPatient);
}
@Override
public boolean isTransferPatient()
{
return get_ValueAsBoolean(COLUMNNAME_IsTransferPatient);
}
@Override
public void setNumberOfInsured (final @Nullable String NumberOfInsured)
{
set_Value (COLUMNNAME_NumberOfInsured, NumberOfInsured);
}
@Override
public String getNumberOfInsured()
{
return get_ValueAsString(COLUMNNAME_NumberOfInsured);
}
/**
* PayerType AD_Reference_ID=541319
* Reference name: PayerType_list
*/
public static final int PAYERTYPE_AD_Reference_ID=541319;
/** Unbekannt = 0 */
public static final String PAYERTYPE_Unbekannt = "0";
/** Gesetzlich = 1 */
public static final String PAYERTYPE_Gesetzlich = "1";
/** Privat = 2 */
public static final String PAYERTYPE_Privat = "2";
/** Berufsgenossenschaft = 3 */
public static final String PAYERTYPE_Berufsgenossenschaft = "3";
/** Selbstzahler = 4 */
public static final String PAYERTYPE_Selbstzahler = "4";
/** Andere = 5 */
public static final String PAYERTYPE_Andere = "5";
@Override | public void setPayerType (final @Nullable String PayerType)
{
set_Value (COLUMNNAME_PayerType, PayerType);
}
@Override
public String getPayerType()
{
return get_ValueAsString(COLUMNNAME_PayerType);
}
@Override
public void setUpdatedAt (final @Nullable java.sql.Timestamp UpdatedAt)
{
set_Value (COLUMNNAME_UpdatedAt, UpdatedAt);
}
@Override
public java.sql.Timestamp getUpdatedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_UpdatedAt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_AlbertaPatient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ForkJoinService {
private final ApplicationContext applicationContext;
public ForkJoinService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
// ForkJoinPool will start 1 thread for each available core
public static final int NUMBER_OF_LINES_TO_INSERT = 1000;
public static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
public static final ForkJoinPool forkJoinPool = new ForkJoinPool(NUMBER_OF_CORES);
private static final Logger logger = Logger.getLogger(ForkJoinService.class.getName());
public void fileToDatabase(String fileName) throws IOException {
logger.info("Reading file lines into a List<String> ...");
// fetch 200000+ lines
List<String> allLines = Files.readAllLines(Path.of(fileName));
// run on a snapshot of NUMBER_OF_LINES_TO_INSERT lines
List<String> lines = allLines.subList(0, NUMBER_OF_LINES_TO_INSERT);
logger.info(() -> "Read a total of " + allLines.size()
+ " lines, inserting " + NUMBER_OF_LINES_TO_INSERT + " lines");
logger.info("Start inserting ..."); | StopWatch watch = new StopWatch();
watch.start();
forkjoin(lines);
watch.stop();
logger.log(Level.INFO, "Stop inserting. \n Total time: {0} ms ({1} s)",
new Object[]{watch.getTotalTimeMillis(), watch.getTotalTimeSeconds()});
}
private void forkjoin(List<String> lines) {
ForkingComponent forkingComponent
= applicationContext.getBean(ForkingComponent.class, lines);
forkJoinPool.invoke(forkingComponent);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchJsonFileForkJoin\src\main\java\com\citylots\forkjoin\ForkJoinService.java | 2 |
请完成以下Java代码 | public class KafkaOperationsOutboundEventChannelAdapter implements OutboundEventChannelAdapter<Object> {
protected KafkaOperations<Object, Object> kafkaOperations;
protected KafkaPartitionProvider partitionProvider;
protected KafkaMessageKeyProvider<?> messageKeyProvider;
protected String topic;
// backwards compatibility
public KafkaOperationsOutboundEventChannelAdapter(KafkaOperations<Object, Object> kafkaOperations, KafkaPartitionProvider partitionProvider, String topic, String key) {
this(kafkaOperations, partitionProvider, topic, (ignore) -> StringUtils.defaultIfEmpty(key, null));
}
public KafkaOperationsOutboundEventChannelAdapter(KafkaOperations<Object, Object> kafkaOperations, KafkaPartitionProvider partitionProvider, String topic, KafkaMessageKeyProvider<?> messageKeyProvider) {
this.kafkaOperations = kafkaOperations;
this.partitionProvider = partitionProvider;
this.messageKeyProvider = messageKeyProvider;
this.topic = topic;
}
@Override
public void sendEvent(OutboundEvent<Object> event) {
try {
Object rawEvent = event.getBody();
Map<String, Object> headerMap = event.getHeaders();
List<Header> headers = new ArrayList<>();
for (String headerKey : headerMap.keySet()) {
Object headerValue = headerMap.get(headerKey);
if (headerValue != null) {
headers.add(new RecordHeader(headerKey, headerValue.toString().getBytes(StandardCharsets.UTF_8)));
}
}
Integer partition = partitionProvider == null ? null : partitionProvider.determinePartition(event);
Object key = messageKeyProvider == null ? null : messageKeyProvider.determineMessageKey(event);
ProducerRecord<Object, Object> producerRecord = new ProducerRecord<>(topic, partition, key, rawEvent, headers); | kafkaOperations.send(producerRecord).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new FlowableException("Sending the event was interrupted", e);
} catch (ExecutionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else {
throw new FlowableException("failed to send event", e.getCause());
}
}
}
@Override
public void sendEvent(Object rawEvent, Map<String, Object> headerMap) {
throw new UnsupportedOperationException("Outbound processor should never call this");
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\KafkaOperationsOutboundEventChannelAdapter.java | 1 |
请完成以下Java代码 | class PerfectNumber {
public static boolean isPerfectBruteForce(int number) {
int sum = 0;
for (int i = 1; i <= number / 2; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}
public static boolean isPerfectStream(int number) {
int sum = IntStream.rangeClosed(2, (int) Math.sqrt(number))
.filter(test -> number % test == 0)
.reduce(1, (s, test) -> s + test + (number / test));
return sum == number;
}
public static boolean isPerfectEuclidEuler(int number) {
int p = 2;
int perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
while (perfectNumber <= number) {
if (perfectNumber == number) {
return true;
}
p++;
perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
}
return false; | }
public static boolean isPerfectEuclidEulerUsingShift(int number) {
int p = 2;
int perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
while (perfectNumber <= number) {
if (perfectNumber == number) {
return true;
}
p++;
perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
}
return false;
}
} | repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\perfectnumber\PerfectNumber.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<ExternalWorkerJobEntity> findExternalJobsToExecute(ExternalWorkerJobAcquireBuilderImpl builder, int numberOfJobs) {
return getDbSqlSession().selectList("selectExternalWorkerJobsToExecute", builder, new Page(0, numberOfJobs));
}
@Override
public List<ExternalWorkerJobEntity> findJobsByScopeIdAndSubScopeId(String scopeId, String subScopeId) {
Map<String, String> paramMap = new HashMap<>();
paramMap.put("scopeId", scopeId);
paramMap.put("subScopeId", subScopeId);
return getList(getDbSqlSession(), "selectExternalWorkerJobsByScopeIdAndSubScopeId", paramMap, externalWorkerJobsByScopeIdAndSubScopeIdMatcher, true);
}
@Override
public List<ExternalWorkerJobEntity> findJobsByWorkerId(String workerId) {
return getList("selectExternalWorkerJobsByWorkerId", workerId); | }
@Override
public List<ExternalWorkerJobEntity> findJobsByWorkerIdAndTenantId(String workerId, String tenantId) {
Map<String, String> paramMap = new HashMap<>();
paramMap.put("workerId", workerId);
paramMap.put("tenantId", tenantId);
return getList("selectExternalWorkerJobsByWorkerIdAndTenantId", paramMap);
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisExternalWorkerJobDataManager.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FileSyncConfiguration {
@Resource
SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory;
@Resource
private SftpProperties properties;
@Bean
public SftpInboundFileSynchronizer sftpInboundFileSynchronizer(SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory) {
SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory);
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setRemoteDirectory(properties.getRemoteDir());
fileSynchronizer.setFilter(new SftpSimplePatternFileListFilter("*.*"));
return fileSynchronizer;
}
/**
* @return MessageSource
* @create by: qiushicai
* @description: 配置Inbound Channel Adapter,监控sftp服务器文件的状态。一旦由符合条件的文件生成,就将其同步到本地服务器。
* 需要条件:inboundFileChannel的bean;轮询的机制;文件同步bean,SftpInboundFileSynchronizer;
* @create time: 2020/11/20 10:06
* @Param: sftpInboundFileSynchronizer
*/
@Bean
@InboundChannelAdapter(channel = "fileSynchronizerChannel",
poller = @Poller(cron = "0/5 * * * * *",
//fixedDelay = "5000",
maxMessagesPerPoll = "1")) | public MessageSource<File> sftpMessageSource(SftpInboundFileSynchronizer sftpInboundFileSynchronizer) {
SftpInboundFileSynchronizingMessageSource source =
new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer);
source.setLocalDirectory(new File(properties.getLocalDir()));
source.setAutoCreateLocalDirectory(true);
source.setLocalFilter(new AcceptOnceFileListFilter<>());
source.setMaxFetchSize(-1);
return source;
}
/**
* create by: qiushicai
* description: TODO
* create time: 2020/11/20
*
* @return MessageHandler
*/
@Bean
@ServiceActivator(inputChannel = "fileSynchronizerChannel")
public MessageHandler handler() {
// 同步时打印文件信息
return (m) -> {
System.out.println(m.getPayload());
m.getHeaders()
.forEach((key, value) -> System.out.println("\t\t|---" + key + "=" + value));
};
}
} | repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\config\file\sync\FileSyncConfiguration.java | 2 |
请完成以下Java代码 | public static class ExecutionPlan {
private final Map<String, Boolean> testPlan = testPlan();
void validate(Function<String, Boolean> functionUnderTest) {
testPlan.forEach((key, value) -> {
Boolean result = functionUnderTest.apply(key);
assertEquals(value, result, key);
});
}
private void assertEquals(Boolean expectedResult, Boolean result, String input) {
if (result != expectedResult) {
throw new IllegalStateException("The output does not match the expected output, for input: " + input);
}
}
private Map<String, Boolean> testPlan() {
HashMap<String, Boolean> plan = new HashMap<>();
plan.put(Integer.toString(Integer.MAX_VALUE), true);
if (MODE == TestMode.SIMPLE) {
return plan;
}
plan.put("x0", false);
plan.put("0..005", false);
plan.put("--11", false);
plan.put("test", false);
plan.put(null, false);
for (int i = 0; i < 94; i++) {
plan.put(Integer.toString(i), true);
}
return plan;
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingCoreJava(ExecutionPlan plan) {
plan.validate(subject::usingCoreJava);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingRegularExpressions(ExecutionPlan plan) {
plan.validate(subject::usingPreCompiledRegularExpressions);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
plan.validate(subject::usingNumberUtils_isCreatable);
} | @Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
plan.validate(subject::usingNumberUtils_isParsable);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
plan.validate(subject::usingStringUtils_isNumeric);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
plan.validate(subject::usingStringUtils_isNumericSpace);
}
private enum TestMode {
SIMPLE, DIVERS
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\isnumeric\Benchmarking.java | 1 |
请完成以下Java代码 | public final void setRealmName(String realmName) {
this.realmName = realmName;
}
private static Map<String, String> errorMessageParameters(Map<String, String> parameters) {
parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
parameters.put("error_description",
"The request requires higher privileges than provided by the access token.");
parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1");
return parameters;
}
private static Mono<Void> respond(ServerWebExchange exchange, Map<String, String> parameters) {
String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters);
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
exchange.getResponse().getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate);
return exchange.getResponse().setComplete();
} | private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) {
StringBuilder wwwAuthenticate = new StringBuilder();
wwwAuthenticate.append("Bearer");
if (!parameters.isEmpty()) {
wwwAuthenticate.append(" ");
int i = 0;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
if (i != parameters.size() - 1) {
wwwAuthenticate.append(", ");
}
i++;
}
}
return wwwAuthenticate.toString();
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\access\server\BearerTokenServerAccessDeniedHandler.java | 1 |
请完成以下Java代码 | public void setAPI_Request_Audit_ID (final int API_Request_Audit_ID)
{
if (API_Request_Audit_ID < 1)
set_Value (COLUMNNAME_API_Request_Audit_ID, null);
else
set_Value (COLUMNNAME_API_Request_Audit_ID, API_Request_Audit_ID);
}
@Override
public int getAPI_Request_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID);
}
@Override
public void setAPI_Request_Audit_Log_ID (final int API_Request_Audit_Log_ID)
{
if (API_Request_Audit_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_API_Request_Audit_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_API_Request_Audit_Log_ID, API_Request_Audit_Log_ID);
}
@Override
public int getAPI_Request_Audit_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_Log_ID);
}
@Override
public void setLogmessage (final @Nullable java.lang.String Logmessage)
{
set_Value (COLUMNNAME_Logmessage, Logmessage);
}
@Override
public java.lang.String getLogmessage()
{
return get_ValueAsString(COLUMNNAME_Logmessage);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null); | else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTrxName (final @Nullable java.lang.String TrxName)
{
set_Value (COLUMNNAME_TrxName, TrxName);
}
@Override
public java.lang.String getTrxName()
{
return get_ValueAsString(COLUMNNAME_TrxName);
}
/**
* Type AD_Reference_ID=541329
* Reference name: TypeList
*/
public static final int TYPE_AD_Reference_ID=541329;
/** Created = Created */
public static final String TYPE_Created = "Created";
/** Updated = Updated */
public static final String TYPE_Updated = "Updated";
/** Deleted = Deleted */
public static final String TYPE_Deleted = "Deleted";
@Override
public void setType (final @Nullable java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit_Log.java | 1 |
请完成以下Java代码 | public static RemoteToLocalSyncResult obtainedEmailBounceInfo(@NonNull final ContactPerson datarecord)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(datarecord)
.remoteToLocalStatus(RemoteToLocalStatus.OBTAINED_EMAIL_BOUNCE_INFO)
.build();
}
/** email doesn't exist remotely but we do have a remoteId */
public static RemoteToLocalSyncResult deletedOnRemotePlatform(@NonNull final DataRecord datarecord)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(datarecord)
.remoteToLocalStatus(RemoteToLocalStatus.DELETED_ON_REMOTE_PLATFORM)
.build();
}
/** email doesn't exist remotely and we don't have a remoteId */
public static RemoteToLocalSyncResult notYetAddedToRemotePlatform(@NonNull final DataRecord datarecord)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(datarecord)
.remoteToLocalStatus(RemoteToLocalStatus.NOT_YET_ADDED_TO_REMOTE_PLATFORM)
.build();
}
/** contact or campaign that doesn't yet exist locally */
public static RemoteToLocalSyncResult obtainedNewDataRecord(@NonNull final DataRecord datarecord)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(datarecord)
.remoteToLocalStatus(RemoteToLocalStatus.OBTAINED_NEW_CONTACT_PERSON)
.build();
}
public static RemoteToLocalSyncResult noChanges(@NonNull final DataRecord dataRecord)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(dataRecord)
.remoteToLocalStatus(RemoteToLocalStatus.NO_CHANGES)
.build();
}
public static RemoteToLocalSyncResult error(@NonNull final DataRecord datarecord, String errorMessage)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(datarecord)
.remoteToLocalStatus(RemoteToLocalStatus.ERROR)
.errorMessage(errorMessage)
.build();
}
public enum RemoteToLocalStatus
{
/** See {@link RemoteToLocalSyncResult#deletedOnRemotePlatform(DataRecord)}. */
DELETED_ON_REMOTE_PLATFORM, | /** See {@link RemoteToLocalSyncResult#notYetAddedToRemotePlatform(DataRecord)}. */
NOT_YET_ADDED_TO_REMOTE_PLATFORM,
/** See {@link RemoteToLocalSyncResult#obtainedRemoteId(DataRecord)}. */
OBTAINED_REMOTE_ID,
/** See {@link RemoteToLocalSyncResult#obtainedRemoteEmail(DataRecord)}. */
OBTAINED_REMOTE_EMAIL,
/** See {@link RemoteToLocalSyncResult#obtainedEmailBounceInfo(DataRecord)}. */
OBTAINED_EMAIL_BOUNCE_INFO,
OBTAINED_NEW_CONTACT_PERSON, NO_CHANGES, OBTAINED_OTHER_REMOTE_DATA, ERROR;
}
RemoteToLocalStatus remoteToLocalStatus;
String errorMessage;
DataRecord synchedDataRecord;
@Builder
private RemoteToLocalSyncResult(
@NonNull final DataRecord synchedDataRecord,
@Nullable final RemoteToLocalStatus remoteToLocalStatus,
@Nullable final String errorMessage)
{
this.synchedDataRecord = synchedDataRecord;
this.remoteToLocalStatus = remoteToLocalStatus;
this.errorMessage = errorMessage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\RemoteToLocalSyncResult.java | 1 |
请完成以下Java代码 | public boolean isPrepay(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType docType = docTypesRepo.getById(docTypeId);
return isPrepay(docType);
}
@Override
public boolean isPrepay(final I_C_DocType dt)
{
return X_C_DocType.DOCSUBTYPE_PrepayOrder.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType());
}
@Override
public boolean hasRequestType(@NonNull final DocTypeId docTypeId)
{
return docTypesRepo.getById(docTypeId).getR_RequestType_ID() > 0;
}
@Override
public boolean isRequisition(final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return X_C_DocType.DOCSUBTYPE_Requisition.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType());
}
@Override
public boolean isMediated(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return X_C_DocType.DOCSUBTYPE_Mediated.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType());
}
@Override
public boolean isCallOrder(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return (X_C_DocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType()) || X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType()))
&& X_C_DocType.DOCSUBTYPE_CallOrder.equals(dt.getDocSubType());
}
@Override
public void save(@NonNull final I_C_DocType dt)
{
docTypesRepo.save(dt);
} | @NonNull
public ImmutableList<I_C_DocType> retrieveForSelection(@NonNull final PInstanceId pinstanceId)
{
return docTypesRepo.retrieveForSelection(pinstanceId);
}
public DocTypeId cloneToOrg(@NonNull final I_C_DocType fromDocType, @NonNull final OrgId toOrgId)
{
final String newName = fromDocType.getName() + "_cloned";
final I_C_DocType newDocType = InterfaceWrapperHelper.copy()
.setFrom(fromDocType)
.setSkipCalculatedColumns(true)
.copyToNew(I_C_DocType.class);
newDocType.setAD_Org_ID(toOrgId.getRepoId());
// dev-note: unique index (ad_client_id, name)
newDocType.setName(newName);
final DocSequenceId fromDocSequenceId = DocSequenceId.ofRepoIdOrNull(fromDocType.getDocNoSequence_ID());
if (fromDocType.isDocNoControlled() && fromDocSequenceId != null)
{
final DocSequenceId clonedDocSequenceId = sequenceDAO.cloneToOrg(fromDocSequenceId, toOrgId);
newDocType.setDocNoSequence_ID(clonedDocSequenceId.getRepoId());
newDocType.setIsDocNoControlled(true);
}
save(newDocType);
return DocTypeId.ofRepoId(newDocType.getC_DocType_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeBL.java | 1 |
请完成以下Java代码 | private ProcessingMod createProcessingMod()
{
return ProcessingMod.builder()
.transportMod(createTransportMod())
.build();
}
private TransportMod createTransportMod()
{
if (Check.isEmpty(exportFileFromEAN, true))
{
return null;
}
return TransportMod.builder()
.from(exportFileFromEAN)
.replacementViaEAN(exportFileViaEAN)
.build();
}
private PayloadMod createPayloadMod(
@NonNull final DunningToExport dunning,
@NonNull final XmlPayload xPayLoad)
{
return PayloadMod.builder()
.type(RequestType.REMINDER.getValue())
.reminder(createReminder(dunning))
.bodyMod(createBodyMod(dunning))
.build();
}
private XmlReminder createReminder(@NonNull final DunningToExport dunning)
{
final XmlReminder createReminder = XmlReminder.builder()
.requestDate(asXmlCalendar(dunning.getDunningDate()))
.requestTimestamp(BigInteger.valueOf(dunning.getDunningTimestamp().getEpochSecond()))
.requestId(dunning.getDocumentNumber())
.reminderText(dunning.getDunningText())
.reminderLevel("1")
.build();
return createReminder;
}
private BodyMod createBodyMod(
@NonNull final DunningToExport dunning)
{
return BodyMod
.builder()
.prologMod(createPrologMod(dunning.getMetasfreshVersion()))
.balanceMod(createBalanceMod(dunning))
.build();
}
private PrologMod createPrologMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final SoftwareMod softwareMod = createSoftwareMod(metasfreshVersion);
return PrologMod.builder()
.pkgMod(softwareMod)
.generatorMod(createSoftwareMod(metasfreshVersion))
.build();
}
private XMLGregorianCalendar asXmlCalendar(@NonNull final Calendar cal)
{
try
{
final GregorianCalendar gregorianCal = new GregorianCalendar(cal.getTimeZone());
gregorianCal.setTime(cal.getTime());
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCal);
} | catch (final DatatypeConfigurationException e)
{
throw new AdempiereException(e).appendParametersToMessage()
.setParameter("cal", cal);
}
}
private SoftwareMod createSoftwareMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final long versionNumber = metasfreshVersion.getMajor() * 100 + metasfreshVersion.getMinor(); // .. as advised in the documentation
return SoftwareMod
.builder()
.name("metasfresh")
.version(versionNumber)
.description(metasfreshVersion.getFullVersion())
.id(0L)
.copyright("Copyright (C) 2018 metas GmbH")
.build();
}
private BalanceMod createBalanceMod(@NonNull final DunningToExport dunning)
{
final Money amount = dunning.getAmount();
final Money alreadyPaidAmount = dunning.getAlreadyPaidAmount();
final BigDecimal amountDue = amount.getAmount().subtract(alreadyPaidAmount.getAmount());
return BalanceMod.builder()
.currency(amount.getCurrency())
.amount(amount.getAmount())
.amountDue(amountDue)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientImpl.java | 1 |
请完成以下Java代码 | public void setPP_Product_BOM_ID (int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_Value (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_Value (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID));
}
/** Get BOM & Formula.
@return BOM & Formula
*/
public int getPP_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Group.
@param R_Group_ID | Request Group
*/
public void setR_Group_ID (int R_Group_ID)
{
if (R_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID));
}
/** Get Group.
@return Request Group
*/
public int getR_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Group.java | 1 |
请完成以下Java代码 | public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getStock() { | return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
} | repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\model\Product.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.