instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public ItemReader<Transaction> itemReader(Resource inputData) { DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); tokenizer.setNames(tokens); DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>(); reader.setResource(inputData); reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } @Bean public CloseableHttpClient closeableHttpClient() { final RequestConfig config = RequestConfig.custom() .setConnectTimeout(TWO_SECONDS) .build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } @Bean public ItemProcessor<Transaction, Transaction> retryItemProcessor() { return new RetryItemProcessor(); } @Bean public ItemWriter<Transaction> itemWriter(Marshaller marshaller) { StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); itemWriter.setResource(outputXml); return itemWriter; }
@Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean public Step retryStep( JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("retryItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) { return new StepBuilder("retryStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(inputCsv)) .processor(processor) .writer(writer) .faultTolerant() .retryLimit(3) .retry(ConnectTimeoutException.class) .retry(DeadlockLoserDataAccessException.class) .build(); } @Bean(name = "retryBatchJob") public Job retryJob(JobRepository jobRepository, @Qualifier("retryStep") Step retryStep) { return new JobBuilder("retryBatchJob", jobRepository) .start(retryStep) .build(); } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\SpringBatchRetryConfig.java
1
请完成以下Java代码
public void setPriority (int Priority) { set_Value (COLUMNNAME_Priority, Integer.valueOf(Priority)); } /** Get Priority. @return Indicates if this request is of a high, medium or low priority. */ public int getPriority () { Integer ii = (Integer)get_Value(COLUMNNAME_Priority); if (ii == null) return 0; return ii.intValue(); } /** Set Relative URL. @param RelativeURL Contains the relative URL for the container */ public void setRelativeURL (String RelativeURL) { set_Value (COLUMNNAME_RelativeURL, RelativeURL); } /** Get Relative URL. @return Contains the relative URL for the container */ public String getRelativeURL () { return (String)get_Value(COLUMNNAME_RelativeURL); } /** Set StructureXML. @param StructureXML Autogenerated Containerdefinition as XML Code */ public void setStructureXML (String StructureXML) { set_Value (COLUMNNAME_StructureXML, StructureXML); }
/** Get StructureXML. @return Autogenerated Containerdefinition as XML Code */ public String getStructureXML () { return (String)get_Value(COLUMNNAME_StructureXML); } /** Set Title. @param Title Name this entity is referred to as */ public void setTitle (String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Title. @return Name this entity is referred to as */ public String getTitle () { return (String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container.java
1
请在Spring Boot框架中完成以下Java代码
public class TokenToUserMethodArgumentResolver implements HandlerMethodArgumentResolver { @Autowired private AdminUserService adminUserService; public TokenToUserMethodArgumentResolver() { } public boolean supportsParameter(MethodParameter parameter) { if (parameter.hasParameterAnnotation(TokenToUser.class)) { return true; } return false; } public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { if (parameter.getParameterAnnotation(TokenToUser.class) instanceof TokenToUser) { AdminUser adminUser = null; String token = webRequest.getHeader("token"); if (null != token && !"".equals(token) && token.length() == 32) { adminUser = adminUserService.getAdminUserByToken(token); } return adminUser;
} return null; } public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if (contentLength < 0) { return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength; ) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\config\handler\TokenToUserMethodArgumentResolver.java
2
请完成以下Java代码
private void presetRejectWithInternalReason(final String errorMessage, final Throwable ex) { logger.warn("Marked checker as not applicable: {} because {}", this, errorMessage, ex); _presetResolution = ProcessPreconditionsResolution.rejectWithInternalReason(errorMessage); } private ProcessPreconditionsResolution getPresetResolution() { return _presetResolution; } private boolean hasPresetResolution() { return _presetResolution != null; } private Class<? extends IProcessPrecondition> getPreconditionsClass() { return _preconditionsClass; } private ProcessClassInfo getProcessClassInfo() { if (_processClassInfo == null) { _processClassInfo = ProcessClassInfo.of(_processClass); } return _processClassInfo; } public ProcessPreconditionChecker setPreconditionsContext(final IProcessPreconditionsContext preconditionsContext)
{ setPreconditionsContext(() -> preconditionsContext); return this; } public ProcessPreconditionChecker setPreconditionsContext(final Supplier<IProcessPreconditionsContext> preconditionsContextSupplier) { _preconditionsContextSupplier = preconditionsContextSupplier; return this; } private IProcessPreconditionsContext getPreconditionsContext() { Check.assumeNotNull(_preconditionsContextSupplier, "Parameter preconditionsContextSupplier is not null"); final IProcessPreconditionsContext preconditionsContext = _preconditionsContextSupplier.get(); Check.assumeNotNull(preconditionsContext, "Parameter preconditionsContext is not null"); return preconditionsContext; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionChecker.java
1
请完成以下Java代码
public Date getInProgressStartDueDate() { return null; } @Override public String getTaskDefinitionKey() { return activiti5Task.getTaskDefinitionKey(); } @Override public Date getDueDate() { return activiti5Task.getDueDate(); } @Override public String getCategory() { return activiti5Task.getCategory(); } @Override public String getParentTaskId() { return activiti5Task.getParentTaskId(); } @Override public String getTenantId() { return activiti5Task.getTenantId(); } @Override public String getFormKey() { return activiti5Task.getFormKey(); } @Override public Map<String, Object> getTaskLocalVariables() { return activiti5Task.getTaskLocalVariables(); } @Override public Map<String, Object> getProcessVariables() { return activiti5Task.getProcessVariables(); } @Override public Map<String, Object> getCaseVariables() { return null; } @Override public List<? extends IdentityLinkInfo> getIdentityLinks() { return null; } @Override public Date getClaimTime() { return null; } @Override public void setName(String name) { activiti5Task.setName(name); } @Override public void setLocalizedName(String name) { activiti5Task.setLocalizedName(name); } @Override public void setDescription(String description) { activiti5Task.setDescription(description); } @Override public void setLocalizedDescription(String description) { activiti5Task.setLocalizedDescription(description); } @Override public void setPriority(int priority) { activiti5Task.setPriority(priority);
} @Override public void setOwner(String owner) { activiti5Task.setOwner(owner); } @Override public void setAssignee(String assignee) { activiti5Task.setAssignee(assignee); } @Override public DelegationState getDelegationState() { return activiti5Task.getDelegationState(); } @Override public void setDelegationState(DelegationState delegationState) { activiti5Task.setDelegationState(delegationState); } @Override public void setDueDate(Date dueDate) { activiti5Task.setDueDate(dueDate); } @Override public void setCategory(String category) { activiti5Task.setCategory(category); } @Override public void setParentTaskId(String parentTaskId) { activiti5Task.setParentTaskId(parentTaskId); } @Override public void setTenantId(String tenantId) { activiti5Task.setTenantId(tenantId); } @Override public void setFormKey(String formKey) { activiti5Task.setFormKey(formKey); } @Override public boolean isSuspended() { return activiti5Task.isSuspended(); } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java
1
请完成以下Java代码
public void setPolicy(CrossOriginOpenerPolicy openerPolicy) { Assert.notNull(openerPolicy, "openerPolicy cannot be null"); this.policy = openerPolicy; } @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (this.policy != null && !response.containsHeader(OPENER_POLICY)) { response.addHeader(OPENER_POLICY, this.policy.getPolicy()); } } public enum CrossOriginOpenerPolicy { UNSAFE_NONE("unsafe-none"), SAME_ORIGIN_ALLOW_POPUPS("same-origin-allow-popups"), SAME_ORIGIN("same-origin"); private final String policy;
CrossOriginOpenerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } public static @Nullable CrossOriginOpenerPolicy from(String openerPolicy) { for (CrossOriginOpenerPolicy policy : values()) { if (policy.getPolicy().equals(openerPolicy)) { return policy; } } return null; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\CrossOriginOpenerPolicyHeaderWriter.java
1
请完成以下Java代码
/* package */class ReceiptScheduleHUDocument extends AbstractHUDocument { private final String displayName; private final List<IHUDocumentLine> lines; public ReceiptScheduleHUDocument(final String displayName, final List<IHUDocumentLine> lines) { super(); Check.assumeNotNull(displayName, "displayName not null"); this.displayName = displayName; Check.assumeNotNull(lines, "lines not null"); this.lines = Collections.unmodifiableList(new ArrayList<IHUDocumentLine>(lines)); } @Override public IHUDocument getReversal() { return new ReceiptScheduleHUDocument(getDisplayName(), getReversalLines());
} @Override public String getDisplayName() { return displayName; } @Override public List<IHUDocumentLine> getLines() { return lines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUDocument.java
1
请完成以下Java代码
public class MTab extends X_AD_Tab { public MTab (final Properties ctx, final int AD_Tab_ID, final String trxName) { super (ctx, AD_Tab_ID, trxName); if (is_new()) { setEntityType (ENTITYTYPE_UserMaintained); // U setHasTree (false); setIsReadOnly (false); setIsSingleRow (false); setIsSortTab (false); // N setIsTranslationTab (false); setSeqNo (0); setTabLevel (0); setIsInsertRecord(true); setIsAdvancedTab(false); } } public MTab (final Properties ctx, final ResultSet rs, final String trxName) { super(ctx, rs, trxName); }
@Override protected boolean beforeSave (final boolean newRecord) { // UPDATE AD_Tab SET IsInsertRecord='N' WHERE IsInsertRecord='Y' AND IsReadOnly='Y' if (isReadOnly() && isInsertRecord()) setIsInsertRecord(false); //RF[2826384] if(isSortTab()) { if(getAD_ColumnSortOrder_ID() == 0) { throw new FillMandatoryException("AD_ColumnSortOrder_ID"); } } // Prevent adding more wrong cases. if(is_ValueChanged(COLUMNNAME_OrderByClause) && !Check.isEmpty(getOrderByClause(), true)) { throw new AdempiereException("OrderByClause shall be empty. See https://github.com/metasfresh/metasfresh/issues/412"); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTab.java
1
请完成以下Java代码
public String getTxCtgy() { return txCtgy; } /** * Sets the value of the txCtgy property. * * @param value * allowed object is * {@link String } * */ public void setTxCtgy(String value) { this.txCtgy = value; } /** * Gets the value of the saleRcncltnId property. * * @return * possible object is * {@link String } * */ public String getSaleRcncltnId() { return saleRcncltnId; } /** * Sets the value of the saleRcncltnId property. * * @param value * allowed object is * {@link String } * */ public void setSaleRcncltnId(String value) { this.saleRcncltnId = value; } /** * Gets the value of the seqNbRg property. * * @return * possible object is * {@link CardSequenceNumberRange1 } * */ public CardSequenceNumberRange1 getSeqNbRg() { return seqNbRg; } /** * Sets the value of the seqNbRg property.
* * @param value * allowed object is * {@link CardSequenceNumberRange1 } * */ public void setSeqNbRg(CardSequenceNumberRange1 value) { this.seqNbRg = value; } /** * Gets the value of the txDtRg property. * * @return * possible object is * {@link DateOrDateTimePeriodChoice } * */ public DateOrDateTimePeriodChoice getTxDtRg() { return txDtRg; } /** * Sets the value of the txDtRg property. * * @param value * allowed object is * {@link DateOrDateTimePeriodChoice } * */ public void setTxDtRg(DateOrDateTimePeriodChoice value) { this.txDtRg = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardAggregated1.java
1
请完成以下Java代码
private void commitChunkTrx() throws DBException { Check.assumeNotNull(chunkTrx, "chunkTrx shall NOT be null; this=", this); // // Case: Locally created transaction => commit it if (chunkTrxIsLocal) { try { chunkTrx.commit(true); } catch (final Throwable e) { throw DBException.wrapIfNeeded(e); } chunkTrx.close(); } // // Case: Savepoint on inherited transaction => release the savepoint else if (chunkTrxSavepoint != null) { chunkTrx.releaseSavepoint(chunkTrxSavepoint); chunkTrxSavepoint = null; } // // Case: Inherited transaction without any savepoint => do nothing else { // nothing } chunkTrx = null; // NOTE: no need to restore/reset thread transaction because "execute" method will retore it anyways at the end // trxManager.setThreadInheritedTrxName(null); } /** * Rollback current chunk's transaction if there is a savepoint (see {@link #setUseTrxSavepoints(boolean)}) or if we have a local transaction.
* * If something went wrong this method will throw an exception right away, exception which will stop entire batch processing. */ private void rollbackChunkTrx() { Check.assumeNotNull(chunkTrx, "chunkTrx shall NOT be null"); // // Case: Locally created transaction => rollback it if (chunkTrxIsLocal) { chunkTrx.rollback(); chunkTrx.close(); } // // Case: Savepoint on inherited transaction => rollback to savepoint else if (chunkTrxSavepoint != null) { chunkTrx.rollback(chunkTrxSavepoint); chunkTrxSavepoint = null; } // // Case: Inherited transaction without any savepoint => do nothing else { // nothing } chunkTrx = null; // NOTE: no need to restore/reset thread transaction because the "execute" method will restore it anyways at the end // trxManager.setThreadInheritedTrxName(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemChunkProcessorExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeService { @Autowired private EmployeeRepository employeeRepository; public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } public Optional<Employee> getEmployeeById(Long employeeId) throws ResourceNotFoundException { return employeeRepository.findById(employeeId); } public Employee addEmployee(Employee employee) { return employeeRepository.save(employee); } public Employee updateEmployee(Long employeeId, Employee employeeDetails) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName()); employee.setFirstName(employeeDetails.getFirstName()); final Employee updatedEmployee = employeeRepository.save(employee); return updatedEmployee; } public Map<String, Boolean> deleteEmployee(Long employeeId) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employeeRepository.delete(employee); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } }
repos\Spring-Boot-Advanced-Projects-main\spring-aop-advice-examples\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\service\EmployeeService.java
2
请完成以下Java代码
public class ClientLoggerUtil extends LoggerUtil { public void beanCreationSkipped(String className, String beanName) { logDebug("001", "Skipping creation of bean '{}' for factory '{}'. " + "A bean of type '{}' already exists", beanName, className, ExternalTaskClient.class); } public void registered(String beanName) { logDebug("002", "Registered external task client with beanName '{}'", beanName); } public void bootstrapped() { logDebug("003", "Client successfully bootstrapped"); } public void requestInterceptorsFound(int requestInterceptorCount) { logDebug("004", "Found '{}' client request interceptors", requestInterceptorCount); }
public void backoffStrategyFound() { logDebug("005", "Client backoff strategy found"); } public SpringExternalTaskClientException noUniqueClientException() { return new SpringExternalTaskClientException(exceptionMessage( "006", "Multiple matching client bean candidates have been found " + "when only one matching client bean was expected.")); } public SpringExternalTaskClientException noUniqueAnnotation() { return new SpringExternalTaskClientException(exceptionMessage( "007", "Multiple matching client annotation candidates have been found " + "when only one matching client annotation was expected.")); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\util\ClientLoggerUtil.java
1
请完成以下Java代码
public Object getCredentials() { return null; } @Override public Object getDetails() { return null; } @Override public Object getPrincipal() { return this; } @Override public boolean isAuthenticated() { return false; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { } @Override public String getName() { return clientRegistration.getClientId(); } };
} public String getAccessToken() { try { OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(clientRegistration.getRegistrationId()) .principal(principal) .build(); OAuth2AuthorizedClient client = manager.authorize(oAuth2AuthorizeRequest); if (isNull(client)) { throw new IllegalStateException("client credentials flow on " + clientRegistration.getRegistrationId() + " failed, client is null"); } return client.getAccessToken().getTokenValue(); } catch (Exception exp) { logger.error("client credentials error " + exp.getMessage()); } return null; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign\src\main\java\com\baeldung\cloud\openfeign\oauthfeign\OAuthClientCredentialsFeignManager.java
1
请完成以下Java代码
public Class<I_I_GLJournal> getImportModelClass() { return I_I_GLJournal.class; } @Override public String getImportTableName() { return I_I_GLJournal.Table_Name; } @Override protected String getTargetTableName() { return I_GL_Journal.Table_Name; }
@Override protected String getImportOrderBySql() { return "COALESCE(BatchDocumentNo, I_GLJournal_ID ||' '), COALESCE(JournalDocumentNo, " + "I_GLJournal_ID ||' '), C_AcctSchema_ID, PostingType, C_DocType_ID, GL_Category_ID, " + "C_Currency_ID, TRUNC(DateAcct), Line, I_GLJournal_ID"; } @Override public I_I_GLJournal retrieveImportRecord(Properties ctx, ResultSet rs) { return new X_I_GLJournal(ctx, rs, ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\impexp\GLJournalImportProcess.java
1
请完成以下Java代码
public void setQtyBOM (final @Nullable BigDecimal QtyBOM) { set_ValueNoCheck (COLUMNNAME_QtyBOM, QtyBOM); } @Override public BigDecimal getQtyBOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyRequiered (final @Nullable BigDecimal QtyRequiered)
{ set_ValueNoCheck (COLUMNNAME_QtyRequiered, QtyRequiered); } @Override public BigDecimal getQtyRequiered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRequiered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Order_BOMLine.java
1
请完成以下Java代码
public DocumentPrintOptionDescriptorsList getPrintingOptionDescriptors(@NonNull final AdProcessId reportProcessId) { return cache.getOrLoad(reportProcessId, this::retrievePrintingOptionDescriptors); } private DocumentPrintOptionDescriptorsList retrievePrintingOptionDescriptors(@NonNull final AdProcessId reportProcessId) { final ImmutableList<DocumentPrintOptionDescriptor> options = adProcessDAO.retrieveProcessParameters(reportProcessId) .stream() .map(DocumentPrintOptionDescriptorsRepository::extractDescriptorOrNull) .collect(ImmutableList.toImmutableList()); return DocumentPrintOptionDescriptorsList.of(options); } @Nullable private static DocumentPrintOptionDescriptor extractDescriptorOrNull(final I_AD_Process_Para processPara) {
final String parameterName = processPara.getColumnName(); if (!parameterName.startsWith(DocumentPrintOptionDescriptor.PROCESS_PARAM_PRINTER_OPTIONS_PREFIX)) { return null; } final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(processPara); return DocumentPrintOptionDescriptor.builder() .internalName(parameterName) .name(trls.getColumnTrl(I_AD_Process_Para.COLUMNNAME_Name, processPara.getName())) .description(trls.getColumnTrl(I_AD_Process_Para.COLUMNNAME_Description, processPara.getDescription())) .defaultValue(StringUtils.toBoolean(processPara.getDefaultValue())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptionDescriptorsRepository.java
1
请完成以下Java代码
public int getC_Activity_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getC_Activity_ID(); } public int getC_Order_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getC_Order_ID(); } /** * Get Campaign * * @return campaign if based on shipment line and 0 for charge based */ public int getC_Campaign_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getC_Campaign_ID(); } /** * Get Org Trx * * @return Org Trx if based on shipment line and 0 for charge based */ public int getAD_OrgTrx_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getAD_OrgTrx_ID(); } /** * Get User1 * * @return user1 if based on shipment line and 0 for charge based */ public int getUser1_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getUser1_ID(); } /** * Get User2 * * @return user2 if based on shipment line and 0 for charge based */
public int getUser2_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getUser2_ID(); } /** * Get Attribute Set Instance * * @return ASI if based on shipment line and 0 for charge based */ public int getM_AttributeSetInstance_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getM_AttributeSetInstance_ID(); } /** * Get Locator * * @return locator if based on shipment line and 0 for charge based */ public int getM_Locator_ID() { if (m_ioLine == null) { return 0; } return m_ioLine.getM_Locator_ID(); } /** * Get Tax * * @return Tax based on Invoice/Order line and Tax exempt for charge based */ public int getC_Tax_ID() { return taxId; } } // MRMALine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMALine.java
1
请完成以下Java代码
private static LocalDate parseLocalDate(final String dateStr) { return !Check.isEmpty(dateStr, true) ? LocalDate.parse(dateStr, dateFormatter) : null; } private static LocalTime parseLocalTime(final String timeStr) { return !Check.isEmpty(timeStr, true) ? LocalTime.parse(timeStr, timeFormatter) : null; } private List<PackageLabels> createDeliveryPackageLabels(final Label goLabels) { return goLabels.getSendung() .stream() .map(goPackageLabels -> createPackageLabels(goPackageLabels)) .collect(ImmutableList.toImmutableList()); } private PackageLabels createPackageLabels(final Label.Sendung goPackageLabels) { final Label.Sendung.PDFs pdfs = goPackageLabels.getPDFs(); return PackageLabels.builder() .orderId(GOUtils.createOrderId(goPackageLabels.getSendungsnummerAX4())) .defaultLabelType(GOPackageLabelType.DIN_A6_ROUTER_LABEL) .label(PackageLabel.builder() .type(GOPackageLabelType.DIN_A4_HWB) .fileName(GOPackageLabelType.DIN_A4_HWB.toString()) .contentType(PackageLabel.CONTENTTYPE_PDF) .labelData(pdfs.getFrachtbrief()) .build()) .label(PackageLabel.builder()
.type(GOPackageLabelType.DIN_A6_ROUTER_LABEL) .fileName(GOPackageLabelType.DIN_A6_ROUTER_LABEL.toString()) .contentType(PackageLabel.CONTENTTYPE_PDF) .labelData(pdfs.getRouterlabel()) .build()) .label(PackageLabel.builder() .type(GOPackageLabelType.DIN_A6_ROUTER_LABEL_ZEBRA) .fileName(GOPackageLabelType.DIN_A6_ROUTER_LABEL_ZEBRA.toString()) .contentType(PackageLabel.CONTENTTYPE_PDF) .labelData(pdfs.getRouterlabelZebra()) .build()) .build(); } @Override public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request) { return JsonDeliveryAdvisorResponse.builder() .requestId(request.getId()) .shipperProduct(JsonShipperProduct.builder() .code(GOShipperProduct.Overnight.getCode()) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GOClient.java
1
请在Spring Boot框架中完成以下Java代码
private MediatedCommissionSettings toMediatedCommissionSettings(@NonNull final I_C_MediatedCommissionSettings record) { final ImmutableList<MediatedCommissionSettingsLine> lines = queryBL.createQueryBuilder(I_C_MediatedCommissionSettingsLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_MediatedCommissionSettings.COLUMNNAME_C_MediatedCommissionSettings_ID, record.getC_MediatedCommissionSettings_ID()) .create() .stream() .map(this::toMediatedCommissionLine) .collect(ImmutableList.toImmutableList()); return MediatedCommissionSettings.builder() .commissionSettingsId(MediatedCommissionSettingsId.ofRepoId(record.getC_MediatedCommissionSettings_ID())) .commissionProductId(ProductId.ofRepoId(record.getCommission_Product_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .pointsPrecision(record.getPointsPrecision()) .lines(lines)
.build(); } @NonNull private MediatedCommissionSettingsLine toMediatedCommissionLine(@NonNull final I_C_MediatedCommissionSettingsLine record) { final MediatedCommissionSettingsId settingsId = MediatedCommissionSettingsId.ofRepoId(record.getC_MediatedCommissionSettings_ID()); return MediatedCommissionSettingsLine.builder() .mediatedCommissionSettingsLineId(MediatedCommissionSettingsLineId.ofRepoId(record.getC_MediatedCommissionSettingsLine_ID(), settingsId)) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .percentOfBasedPoints(Percent.of(record.getPercentOfBasePoints())) .seqNo(record.getSeqNo()) .productCategoryId(ProductCategoryId.ofRepoIdOrNull(record.getM_Product_Category_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\mediated\repository\MediatedCommissionSettingsRepo.java
2
请完成以下Java代码
public void setAD_Org_From_ID (final int AD_Org_From_ID) { if (AD_Org_From_ID < 1) set_Value (COLUMNNAME_AD_Org_From_ID, null); else set_Value (COLUMNNAME_AD_Org_From_ID, AD_Org_From_ID); } @Override public int getAD_Org_From_ID() { return get_ValueAsInt(COLUMNNAME_AD_Org_From_ID); } @Override public org.compiere.model.I_AD_Org_Mapping getAD_Org_Mapping() { return get_ValueAsPO(COLUMNNAME_AD_Org_Mapping_ID, org.compiere.model.I_AD_Org_Mapping.class); } @Override public void setAD_Org_Mapping(final org.compiere.model.I_AD_Org_Mapping AD_Org_Mapping) { set_ValueFromPO(COLUMNNAME_AD_Org_Mapping_ID, org.compiere.model.I_AD_Org_Mapping.class, AD_Org_Mapping); } @Override public void setAD_Org_Mapping_ID (final int AD_Org_Mapping_ID) { if (AD_Org_Mapping_ID < 1) set_Value (COLUMNNAME_AD_Org_Mapping_ID, null); else set_Value (COLUMNNAME_AD_Org_Mapping_ID, AD_Org_Mapping_ID); } @Override public int getAD_Org_Mapping_ID() { return get_ValueAsInt(COLUMNNAME_AD_Org_Mapping_ID); } @Override public void setAD_OrgTo_ID (final int AD_OrgTo_ID) { if (AD_OrgTo_ID < 1) set_Value (COLUMNNAME_AD_OrgTo_ID, null); else set_Value (COLUMNNAME_AD_OrgTo_ID, AD_OrgTo_ID); } @Override public int getAD_OrgTo_ID() { return get_ValueAsInt(COLUMNNAME_AD_OrgTo_ID); }
@Override public void setC_BPartner_From_ID (final int C_BPartner_From_ID) { if (C_BPartner_From_ID < 1) set_Value (COLUMNNAME_C_BPartner_From_ID, null); else set_Value (COLUMNNAME_C_BPartner_From_ID, C_BPartner_From_ID); } @Override public int getC_BPartner_From_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_From_ID); } @Override public void setC_BPartner_To_ID (final int C_BPartner_To_ID) { if (C_BPartner_To_ID < 1) set_Value (COLUMNNAME_C_BPartner_To_ID, null); else set_Value (COLUMNNAME_C_BPartner_To_ID, C_BPartner_To_ID); } @Override public int getC_BPartner_To_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_To_ID); } @Override public void setDate_OrgChange (final java.sql.Timestamp Date_OrgChange) { set_Value (COLUMNNAME_Date_OrgChange, Date_OrgChange); } @Override public java.sql.Timestamp getDate_OrgChange() { return get_ValueAsTimestamp(COLUMNNAME_Date_OrgChange); } @Override public void setIsCloseInvoiceCandidate (final boolean IsCloseInvoiceCandidate) { set_Value (COLUMNNAME_IsCloseInvoiceCandidate, IsCloseInvoiceCandidate); } @Override public boolean isCloseInvoiceCandidate() { return get_ValueAsBoolean(COLUMNNAME_IsCloseInvoiceCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgChange_History.java
1
请完成以下Java代码
public Edge getEdge(Node from, Node to) { // 首先尝试词+词 Attribute attribute = get(from.compiledWord, to.compiledWord); if (attribute == null) attribute = get(from.compiledWord, WordNatureWeightModelMaker.wrapTag(to.label)); if (attribute == null) attribute = get(WordNatureWeightModelMaker.wrapTag(from.label), to.compiledWord); if (attribute == null) attribute = get(WordNatureWeightModelMaker.wrapTag(from.label), WordNatureWeightModelMaker.wrapTag(to.label)); if (attribute == null) { attribute = Attribute.NULL; } if (HanLP.Config.DEBUG) { System.out.println(from + " 到 " + to + " : " + attribute); } return new Edge(from.id, to.id, attribute.dependencyRelation[0], attribute.p[0]); } public Attribute get(String from, String to) { return get(from + "@" + to); } static class Attribute { final static Attribute NULL = new Attribute("未知", 10000.0f); /** * 依存关系 */ public String[] dependencyRelation; /** * 概率 */ public float[] p; public Attribute(int size)
{ dependencyRelation = new String[size]; p = new float[size]; } Attribute(String dr, float p) { dependencyRelation = new String[]{dr}; this.p = new float[]{p}; } /** * 加权 * @param boost */ public void setBoost(float boost) { for (int i = 0; i < p.length; ++i) { p[i] *= boost; } } @Override public String toString() { final StringBuilder sb = new StringBuilder(dependencyRelation.length * 10); for (int i = 0; i < dependencyRelation.length; ++i) { sb.append(dependencyRelation[i]).append(' ').append(p[i]).append(' '); } return sb.toString(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\WordNatureDependencyModel.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public FileInfo uploadedDate(String uploadedDate) { this.uploadedDate = uploadedDate; return this; } /** * The timestamp in this field shows the date/time when the seller uploaded the evidential document to eBay. The timestamps returned here use the ISO-8601 24-hour date and time format, and the time zone used is Universal Coordinated Time (UTC), also known as Greenwich Mean Time (GMT), or Zulu. The ISO-8601 format looks like this: yyyy-MM-ddThh:mm.ss.sssZ. An example would be * 2019-08-04T19:09:02.768Z. * * @return uploadedDate **/ @javax.annotation.Nullable @ApiModelProperty(value = "The timestamp in this field shows the date/time when the seller uploaded the evidential document to eBay. The timestamps returned here use the ISO-8601 24-hour date and time format, and the time zone used is Universal Coordinated Time (UTC), also known as Greenwich Mean Time (GMT), or Zulu. The ISO-8601 format looks like this: yyyy-MM-ddThh:mm.ss.sssZ. An example would be 2019-08-04T19:09:02.768Z.") public String getUploadedDate() { return uploadedDate; } public void setUploadedDate(String uploadedDate) { this.uploadedDate = uploadedDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FileInfo fileInfo = (FileInfo)o; return Objects.equals(this.fileId, fileInfo.fileId) && Objects.equals(this.fileType, fileInfo.fileType) && Objects.equals(this.name, fileInfo.name) &&
Objects.equals(this.uploadedDate, fileInfo.uploadedDate); } @Override public int hashCode() { return Objects.hash(fileId, fileType, name, uploadedDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class FileInfo {\n"); sb.append(" fileId: ").append(toIndentedString(fileId)).append("\n"); sb.append(" fileType: ").append(toIndentedString(fileType)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" uploadedDate: ").append(toIndentedString(uploadedDate)).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\FileInfo.java
2
请完成以下Java代码
public class Calculator { public int calculate(int a, int b, String operator) { int result = Integer.MIN_VALUE; if ("add".equals(operator)) { result = a + b; } else if ("multiply".equals(operator)) { result = a * b; } else if ("divide".equals(operator)) { result = a / b; } else if ("subtract".equals(operator)) { result = a - b; } else if ("modulo".equals(operator)) { result = a % b; } return result; } public int calculateUsingSwitch(int a, int b, String operator) { int result = 0; switch (operator) { case "add": result = a + b; break; case "multiply": result = a * b; break; case "divide": result = a / b; break; case "subtract": result = a - b; break; case "modulo": result = a % b; break; default: result = Integer.MIN_VALUE; } return result; } public int calculateUsingSwitch(int a, int b, Operator operator) { int result = 0; switch (operator) { case ADD: result = a + b; break;
case MULTIPLY: result = a * b; break; case DIVIDE: result = a / b; break; case SUBTRACT: result = a - b; break; case MODULO: result = a % b; break; default: result = Integer.MIN_VALUE; } return result; } public int calculate(int a, int b, Operator operator) { return operator.apply(a, b); } public int calculateUsingFactory(int a, int b, String operation) { Operation targetOperation = OperatorFactory.getOperation(operation) .orElseThrow(() -> new IllegalArgumentException("Invalid Operator")); return targetOperation.apply(a, b); } public int calculate(Command command) { return command.execute(); } }
repos\tutorials-master\patterns-modules\design-patterns-creational\src\main\java\com\baeldung\reducingIfElse\Calculator.java
1
请完成以下Java代码
public void setPhase(int phase) { this.phase = phase; } @Override public synchronized void onApplicationEvent(ListenerContainerIdleEvent event) { LOGGER.debug(() -> event.toString()); MessageListenerContainer parent = event.getContainer(MessageListenerContainer.class); MessageListenerContainer container = (MessageListenerContainer) event.getSource(); boolean inCurrentGroup = this.currentGroup != null && this.currentGroup.contains(parent); if (this.running && inCurrentGroup && (Objects.requireNonNull(this.iterator).hasNext() || this.stopLastGroupWhenIdle)) { this.executor.execute(() -> { LOGGER.debug(() -> "Stopping: " + container); container.stop(() -> { synchronized (this) { if (!parent.isChildRunning()) { this.executor.execute(() -> { stopParentAndCheckGroup(parent); }); } } }); }); } } private synchronized void stopParentAndCheckGroup(MessageListenerContainer parent) { if (parent.isRunning()) { LOGGER.debug(() -> "Stopping: " + parent); parent.stop(() -> { if (this.currentGroup != null) { LOGGER.debug(() -> { if (this.currentGroup != null) { return "Checking group: " + this.currentGroup.toString(); } else { return "Current group is null"; } }); if (this.currentGroup.allStopped()) { if (Objects.requireNonNull(this.iterator).hasNext()) { this.currentGroup = this.iterator.next(); LOGGER.debug(() -> "Starting next group: " + this.currentGroup); this.currentGroup.start(); } else { this.currentGroup = null; } } } }); } } @Override public synchronized void start() { if (this.currentGroup != null) { LOGGER.debug(() -> "Starting first group: " + this.currentGroup); this.currentGroup.start();
} this.running = true; } public void initialize() { this.groups.clear(); for (String group : this.groupNames) { this.groups.add(Objects.requireNonNull(this.applicationContext).getBean(group + ".group", ContainerGroup.class)); } if (!this.groups.isEmpty()) { this.iterator = this.groups.iterator(); this.currentGroup = this.iterator.next(); this.groups.forEach(grp -> { Collection<String> ids = grp.getListenerIds(); ids.forEach(id -> { MessageListenerContainer container = this.registry.getListenerContainer(id); if (Objects.requireNonNull(container).getContainerProperties().getIdleEventInterval() == null) { container.getContainerProperties().setIdleEventInterval(this.defaultIdleEventInterval); container.setAutoStartup(false); } }); }); } LOGGER.debug(() -> "Found: " + this.groups); } @Override public synchronized void stop() { this.running = false; if (this.currentGroup != null) { this.currentGroup.stop(); this.currentGroup = null; } } @Override public synchronized boolean isRunning() { return this.running; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerGroupSequencer.java
1
请完成以下Java代码
public void schemaDrop() { try { executeMandatorySchemaResource("drop", schemaComponent); } catch (Exception e) { logger.info("Error dropping {} tables", schemaComponent, e); } } @Override public String schemaUpdate() { return schemaUpdate(null); } @Override public String schemaUpdate(String engineDbVersion) { String feedback = null; if (isUpdateNeeded()) { String dbVersion = getSchemaVersion(); String compareWithVersion = null; if (dbVersion == null) { compareWithVersion = "6.1.2.0"; // last version before services were separated. Start upgrading from this point. } else { compareWithVersion = dbVersion; } int matchingVersionIndex = FlowableVersions.getFlowableVersionIndexForDbVersion(compareWithVersion); boolean isUpgradeNeeded = (matchingVersionIndex != (FlowableVersions.FLOWABLE_VERSIONS.size() - 1)); if (isUpgradeNeeded) { dbSchemaUpgrade(schemaComponent, matchingVersionIndex, engineDbVersion); } feedback = "upgraded from " + compareWithVersion + " to " + FlowableVersions.CURRENT_VERSION; } else { schemaCreate(); } return feedback; } @Override
public void schemaCheckVersion() { String dbVersion = getSchemaVersion(); if (!FlowableVersions.CURRENT_VERSION.equals(dbVersion)) { throw new FlowableWrongDbException(FlowableVersions.CURRENT_VERSION, dbVersion); } } protected boolean isUpdateNeeded() { return isTablePresent(table); } protected String getSchemaVersion() { if (schemaVersionProperty == null) { throw new FlowableException("Schema version property is not set"); } String dbVersion = getProperty(schemaVersionProperty); if (dbVersion == null) { return getUpgradeStartVersion(); } return dbVersion; } protected String getUpgradeStartVersion() { return "6.1.2.0"; // last version before most services were separated. Start upgrading from this point. } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\ServiceSqlScriptBasedDbSchemaManager.java
1
请完成以下Java代码
public class X_C_User_Role extends org.compiere.model.PO implements I_C_User_Role, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1464548893L; /** Standard Constructor */ public X_C_User_Role (final Properties ctx, final int C_User_Role_ID, @Nullable final String trxName) { super (ctx, C_User_Role_ID, trxName); } /** Load Constructor */ public X_C_User_Role (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_User_Role_ID (final int C_User_Role_ID) { if (C_User_Role_ID < 1) set_ValueNoCheck (COLUMNNAME_C_User_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_C_User_Role_ID, C_User_Role_ID); } @Override
public int getC_User_Role_ID() { return get_ValueAsInt(COLUMNNAME_C_User_Role_ID); } @Override public void setIsUniqueForBPartner (final boolean IsUniqueForBPartner) { set_Value (COLUMNNAME_IsUniqueForBPartner, IsUniqueForBPartner); } @Override public boolean isUniqueForBPartner() { return get_ValueAsBoolean(COLUMNNAME_IsUniqueForBPartner); } @Override public void setName (final @Nullable 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_User_Role.java
1
请完成以下Java代码
public class MKTG_ContactPerson_CreateFrom_C_BPartner extends JavaProcess { @Param(mandatory = true, parameterName = I_MKTG_Campaign.COLUMNNAME_MKTG_Campaign_ID) private int campaignRecordId; @Param(mandatory = true, parameterName = "IsRemoveAllExistingContactsFromCampaign") private boolean removeAllExistingContactsFromCampaign; @Override protected String doIt() throws Exception { // note: if the queryFilter is empty, then do not return everything final IQueryFilter<I_C_BPartner> currentSelectionFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final CampaignId campaignId = CampaignId.ofRepoId(campaignRecordId); final MKTG_ContactPerson_ProcessBase contactPersonProcessBase = SpringContextHolder.instance.getBean(MKTG_ContactPerson_ProcessBase.class); final MKTG_ContactPerson_ProcessParams params = MKTG_ContactPerson_ProcessParams.builder() .selectionFilter(currentSelectionFilter) .campaignId(campaignId) .addresType(null) .removeAllExistingContactsFromCampaign(removeAllExistingContactsFromCampaign) .build(); contactPersonProcessBase.createContactPersonsForPartner(params); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\process\MKTG_ContactPerson_CreateFrom_C_BPartner.java
1
请在Spring Boot框架中完成以下Java代码
public void evict(TenantId tenantId, DeviceId deviceId) { DeviceProfileId old = devicesMap.remove(deviceId); if (old != null) { DeviceProfile newProfile = get(tenantId, deviceId); if (newProfile == null || !old.equals(newProfile.getId())) { notifyDeviceListeners(tenantId, deviceId, newProfile); } } } @Override public void addListener(TenantId tenantId, EntityId listenerId, Consumer<DeviceProfile> profileListener, BiConsumer<DeviceId, DeviceProfile> deviceListener) { if (profileListener != null) { profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener); } if (deviceListener != null) { deviceProfileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, deviceListener); } } @Override public DeviceProfile find(DeviceProfileId deviceProfileId) { return deviceProfileService.findDeviceProfileById(TenantId.SYS_TENANT_ID, deviceProfileId); } @Override public DeviceProfile findOrCreateDeviceProfile(TenantId tenantId, String profileName) { return deviceProfileService.findOrCreateDeviceProfile(tenantId, profileName); } @Override public void removeListener(TenantId tenantId, EntityId listenerId) { ConcurrentMap<EntityId, Consumer<DeviceProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.remove(listenerId); } ConcurrentMap<EntityId, BiConsumer<DeviceId, DeviceProfile>> deviceListeners = deviceProfileListeners.get(tenantId); if (deviceListeners != null) {
deviceListeners.remove(listenerId); } } private void notifyProfileListeners(DeviceProfile profile) { ConcurrentMap<EntityId, Consumer<DeviceProfile>> tenantListeners = profileListeners.get(profile.getTenantId()); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(profile)); } } private void notifyDeviceListeners(TenantId tenantId, DeviceId deviceId, DeviceProfile profile) { if (profile != null) { ConcurrentMap<EntityId, BiConsumer<DeviceId, DeviceProfile>> tenantListeners = deviceProfileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(deviceId, profile)); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbDeviceProfileCache.java
2
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public boolean isDoNotIncludeVariables() { return doNotIncludeVariables; } public void setDoNotIncludeVariables(boolean doNotIncludeVariables) { this.doNotIncludeVariables = doNotIncludeVariables; } @Override public List<IOParameter> getInParameters() { return inParameters; } @Override public void addInParameter(IOParameter inParameter) { inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public List<IOParameter> getOutParameters() { return outParameters;
} @Override public void addOutParameter(IOParameter outParameter) { outParameters.add(outParameter); } @Override public void setOutParameters(List<IOParameter> outParameters) { this.outParameters = outParameters; } @Override public ExternalWorkerServiceTask clone() { ExternalWorkerServiceTask clone = new ExternalWorkerServiceTask(); clone.setValues(this); return clone; } public void setValues(ExternalWorkerServiceTask otherElement) { super.setValues(otherElement); setType(otherElement.getType()); setTopic(otherElement.getTopic()); setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables()); setInParameters(new ArrayList<>(otherElement.getInParameters())); setOutParameters(new ArrayList<>(otherElement.getInParameters())); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ExternalWorkerServiceTask.java
1
请完成以下Java代码
private void setDefaultButton() { setDefaultButton(confirmPanel.getOKButton()); } private void setDefaultButton(final JButton button) { final Window frame = AEnv.getWindow(this); if (frame instanceof RootPaneContainer) { final RootPaneContainer c = (RootPaneContainer)frame; c.getRootPane().setDefaultButton(button); } } /** * Get Icon with name action * * @param name name * @param small small * @return Icon */ private final ImageIcon getIcon(String name) { final String fullName = name + (drawSmallButtons ? "16" : "24"); return Images.getImageIcon2(fullName); } /** * @return true if the panel is visible and it has at least one field in simple search mode */ @Override public boolean isFocusable() { if (!isVisible()) { return false; } if (isSimpleSearchPanelActive()) { return m_editorFirst != null; } return false;
} @Override public void setFocusable(final boolean focusable) { // ignore it } @Override public void requestFocus() { if (isSimpleSearchPanelActive()) { if (m_editorFirst != null) { m_editorFirst.requestFocus(); } } } @Override public boolean requestFocusInWindow() { if (isSimpleSearchPanelActive()) { if (m_editorFirst != null) { return m_editorFirst.requestFocusInWindow(); } } return false; } private boolean disposed = false; boolean isDisposed() { return disposed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanel.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentCandidatesView_Launcher extends ViewBasedProcessTemplate implements IProcessPrecondition { @Autowired private IViewsRepository viewsFactory; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds = getSelectedShipmentScheduleIds(); if (shipmentScheduleIds.isEmpty()) { throw new AdempiereException("@NoSelection@"); } final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(ShipmentCandidatesViewFactory.WINDOWID) .setFilterOnlyIds(ShipmentScheduleId.toIntSet(shipmentScheduleIds)) .build()) .getViewId(); getResult().setWebuiViewToOpen(WebuiViewToOpen.builder() .viewId(viewId.getViewId())
.target(ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } private ImmutableSet<ShipmentScheduleId> getSelectedShipmentScheduleIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ImmutableSet.of(); } else if (selectedRowIds.isAll()) { return getView().streamByIds(DocumentIdsSelection.ALL) .map(IViewRow::getId) .map(rowId -> ShipmentScheduleId.ofRepoId(rowId.toInt())) .collect(ImmutableSet.toImmutableSet()); } else { return selectedRowIds .stream() .map(rowId -> ShipmentScheduleId.ofRepoId(rowId.toInt())) .collect(ImmutableSet.toImmutableSet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\process\ShipmentCandidatesView_Launcher.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityPubSubChannel { @Bean(name = "startPSChannel") @SecuredChannel(interceptor = "channelSecurityInterceptor", sendAccess = "ROLE_VIEWER") public PublishSubscribeChannel startChannel() { return new PublishSubscribeChannel(executor()); } @ServiceActivator(inputChannel = "startPSChannel", outputChannel = "finalPSResult") @PreAuthorize("hasRole('ROLE_LOGGER')") public Message<?> changeMessageToRole(Message<?> message) { return buildNewMessage(getRoles(), message); } @ServiceActivator(inputChannel = "startPSChannel", outputChannel = "finalPSResult") @PreAuthorize("hasRole('ROLE_VIEWER')") public Message<?> changeMessageToUserName(Message<?> message) { return buildNewMessage(getUsername(), message); } @Bean(name = "finalPSResult") public DirectChannel finalPSResult() { return new DirectChannel(); } @Bean @GlobalChannelInterceptor(patterns = { "startPSChannel", "endDirectChannel" }) public ChannelInterceptor securityContextPropagationInterceptor() { return new SecurityContextPropagationChannelInterceptor(); } @Bean public ThreadPoolTaskExecutor executor() { ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); pool.setCorePoolSize(10); pool.setMaxPoolSize(10); pool.setWaitForTasksToCompleteOnShutdown(true); return pool; }
public String getRoles() { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(",")); } public String getUsername() { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getName(); } public Message<String> buildNewMessage(String content, Message<?> message) { DefaultMessageBuilderFactory builderFactory = new DefaultMessageBuilderFactory(); MessageBuilder<String> messageBuilder = builderFactory.withPayload(content); messageBuilder.copyHeaders(message.getHeaders()); return messageBuilder.build(); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\si\security\SecurityPubSubChannel.java
2
请完成以下Java代码
public ICalloutField asCalloutField() { if (_calloutField == null) { _calloutField = new DocumentFieldAsCalloutField(this); } return _calloutField; } private void updateValid(final IDocumentChangesCollector changesCollector) { final DocumentValidStatus validStatusOld = _validStatus; final DocumentValidStatus validStatusNew = computeValidStatus(); _validStatus = validStatusNew; // Collect validStatus changed event if (!NullDocumentChangesCollector.isNull(changesCollector) && !Objects.equals(validStatusOld, validStatusNew)) { // logger.debug("updateValid: {}: {} <- {}", getFieldName(), validNew, validOld); changesCollector.collectValidStatus(this); } } /** * Computes field's validStatus. * IMPORTANT: this method is not updating the status, it's only computing it. */ private DocumentValidStatus computeValidStatus() { // Consider virtual fields as valid because there is nothing we can do about them if (isReadonlyVirtualField()) { return DocumentValidStatus.validField(getFieldName(), isInitialValue()); } // Check mandatory constraint if (isMandatory() && getValue() == null) { return DocumentValidStatus.invalidFieldMandatoryNotFilled(getFieldName(), isInitialValue()); } return DocumentValidStatus.validField(getFieldName(), isInitialValue()); } @Override public DocumentValidStatus getValidStatus() {
return _validStatus; } @Override public DocumentValidStatus updateStatusIfInitialInvalidAndGet(final IDocumentChangesCollector changesCollector) { if (_validStatus.isInitialInvalid()) { updateValid(changesCollector); } return _validStatus; } @Override public boolean hasChangesToSave() { if (isReadonlyVirtualField()) { return false; } return !isInitialValue(); } private boolean isInitialValue() { return DataTypes.equals(_value, _initialValue); } @Override public Optional<WindowId> getZoomIntoWindowId() { final LookupDataSource lookupDataSource = getLookupDataSourceOrNull(); if (lookupDataSource == null) { return Optional.empty(); } return lookupDataSource.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentField.java
1
请完成以下Spring Boot application配置
# dubbo 配置项,对应 DubboConfigurationProperties 配置类 dubbo: # Dubbo 应用配置 application: name: user-service-provider # 应用名 # Dubbo 注册中心配 registry: address: nacos://127.0.0.1:8848 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。 # Dubbo 服务提供者协议配置 protocol: port: -1 # 协议端口。使用 -1 表示随机端口。 name: dubbo # 使用 `dubbo://` 协议。更多协议,可见 http://dubbo.apache.org/zh-cn/docs/user/references/protocol/introduction.html 文档 # Dubbo 服务提供者配置 provider:
timeout: 1000 # 【重要】远程服务调用超时时间,单位:毫秒。默认为 1000 毫秒,胖友可以根据自己业务修改 UserRpcService: version: 1.0.0 # 配置扫描 Dubbo 自定义的 @Service 注解,暴露成 Dubbo 服务提供者 scan: base-packages: cn.iocoder.springboot.lab30.rpc.service
repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-annotations-nacos\user-rpc-service-provider-03\src\main\resources\application.yaml
2
请完成以下Java代码
protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("C_Order_ID")) p_C_Order_ID = para[i].getParameterAsInt(); else log.error("prepare - Unknown Parameter: " + name); } } // prepare /** * Perform process. * @return Message * @throws Exception if not successful
*/ protected String doIt() throws AdempiereSystemError { log.info("doIt - Open C_Order_ID=" + p_C_Order_ID); if (p_C_Order_ID == 0) return ""; // MOrder order = new MOrder (getCtx(), p_C_Order_ID, get_TrxName()); String msg = order.reopenIt(); if ( msg.length() != 0 ) { throw new AdempiereSystemError(msg); } return order.save() ? "@OK@" : "@Error@"; } // doIt } // OrderOpen
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\OrderOpen.java
1
请完成以下Java代码
private boolean isMatch(String url, List<Pattern> patterns) { for (Pattern pattern : patterns) { if (pattern.matcher(url).find()) { return true; } } return false; } public static DevToolsSettings get() { if (settings == null) { settings = load(); } return settings; } static DevToolsSettings load() { return load(SETTINGS_RESOURCE_LOCATION); } static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(location);
while (urls.hasMoreElements()) { settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { throw new IllegalStateException("Unable to load devtools settings from location [" + location + "]", ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\settings\DevToolsSettings.java
1
请完成以下Java代码
public @Nullable String get(String key) { return this.entries.getProperty(key); } /** * Return the value of the specified property as an {@link Instant} or {@code null} if * the value is not a valid {@link Long} representation of an epoch time. * @param key the key of the property * @return the property value */ public @Nullable Instant getInstant(String key) { String s = get(key); if (s != null) { try { return Instant.ofEpochMilli(Long.parseLong(s)); } catch (NumberFormatException ex) { // Not valid epoch time } } return null; } @Override public Iterator<Entry> iterator() { return new PropertiesIterator(this.entries); } /** * Return a {@link PropertySource} of this instance. * @return a {@link PropertySource} */ public PropertySource<?> toPropertySource() { return new PropertiesPropertySource(getClass().getSimpleName(), copy(this.entries)); } private Properties copy(Properties properties) { Properties copy = new Properties(); copy.putAll(properties); return copy; } private static final class PropertiesIterator implements Iterator<Entry> { private final Iterator<Map.Entry<Object, Object>> iterator; private PropertiesIterator(Properties properties) {
this.iterator = properties.entrySet().iterator(); } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public Entry next() { Map.Entry<Object, Object> entry = this.iterator.next(); return new Entry((String) entry.getKey(), (String) entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException("InfoProperties are immutable."); } } /** * Property entry. */ public static final class Entry { private final String key; private final String value; private Entry(String key, String value) { this.key = key; this.value = value; } public String getKey() { return this.key; } public String getValue() { return this.value; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\InfoProperties.java
1
请完成以下Java代码
public int getM_Movement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ 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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementConfirm.java
1
请完成以下Java代码
public void sendMessageToPartition(String message, int partition) { kafkaTemplate.send(partitionedTopicName, partition, null, message); } public void sendMessageToFiltered(String message) { kafkaTemplate.send(filteredTopicName, message); } public void sendGreetingMessage(Greeting greeting) { greetingKafkaTemplate.send(greetingTopicName, greeting); } } public static class MessageListener { private CountDownLatch latch = new CountDownLatch(3); private CountDownLatch partitionLatch = new CountDownLatch(2); private CountDownLatch filterLatch = new CountDownLatch(2); private CountDownLatch greetingLatch = new CountDownLatch(1); @KafkaListener(topics = "${message.topic.name}", groupId = "foo", containerFactory = "fooKafkaListenerContainerFactory") public void listenGroupFoo(String message) { System.out.println("Received Message in group 'foo': " + message); latch.countDown(); } @KafkaListener(topics = "${message.topic.name}", groupId = "bar", containerFactory = "barKafkaListenerContainerFactory") public void listenGroupBar(String message) { System.out.println("Received Message in group 'bar': " + message); latch.countDown(); }
@KafkaListener(topics = "${message.topic.name}", containerFactory = "headersKafkaListenerContainerFactory") public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); latch.countDown(); } @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" }), containerFactory = "partitionsKafkaListenerContainerFactory") public void listenToPartition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); this.partitionLatch.countDown(); } @KafkaListener(topics = "${filtered.topic.name}", containerFactory = "filterKafkaListenerContainerFactory") public void listenWithFilter(String message) { System.out.println("Received Message in filtered listener: " + message); this.filterLatch.countDown(); } @KafkaListener(topics = "${greeting.topic.name}", containerFactory = "greetingKafkaListenerContainerFactory") public void greetingListener(Greeting greeting) { System.out.println("Received greeting message: " + greeting); this.greetingLatch.countDown(); } } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\spring\kafka\KafkaApplication.java
1
请完成以下Java代码
private void updateMDCandidatesFromDDOrderCandidate(final DDOrderCandidate ddOrderCandidate) { final DDOrderCandidateId ddOrderCandidateId = ddOrderCandidate.getIdNotNull(); if (ddOrderCandidate.getMaterialDispoGroupId() != null) { candidateRepositoryWriteService.updateCandidatesByQuery( CandidatesQuery.builder() .groupId(ddOrderCandidate.getMaterialDispoGroupId()) .businessCase(CandidateBusinessCase.DISTRIBUTION) .build(), candidate -> candidate.withBusinessCaseDetail(DistributionDetail.class, dispoDetail -> dispoDetail.withDdOrderCandidateId(ddOrderCandidateId.getRepoId())) ); } } private DDOrderCandidate createAndSaveDDOrderCandidate(@NonNull final DDOrderCandidateRequestedEvent event) { final DDOrderCandidate ddOrderCandidate = toDDOrderCandidate(event); ddOrderCandidateService.save(ddOrderCandidate); Loggables.withLogger(logger, Level.DEBUG).addLog("Created DD Order candidate: {}", ddOrderCandidate); return ddOrderCandidate; } private DDOrderCandidate toDDOrderCandidate(@NonNull final DDOrderCandidateRequestedEvent event) { final PPOrderId forwardPPOrderId = findForwardPPOrderId(event); final DDOrderCandidateData ddOrderCandidateData = event.getDdOrderCandidateData().withPPOrderId(forwardPPOrderId); return DDOrderCandidate.from(ddOrderCandidateData) .dateOrdered(event.getDateOrdered()) .traceId(event.getTraceId())
.build(); } @Nullable private PPOrderId findForwardPPOrderId(@NonNull final DDOrderCandidateRequestedEvent event) { return findForwardPPOrderId(event.getDdOrderCandidateData().getForwardPPOrderRef()); } @Nullable private PPOrderId findForwardPPOrderId(@Nullable final PPOrderRef forwardPPOrderRef) { if (forwardPPOrderRef == null) { return null; } if (forwardPPOrderRef.getPpOrderId() != null) { return forwardPPOrderRef.getPpOrderId(); } if (forwardPPOrderRef.getPpOrderCandidateId() != null) { final PPOrderCandidateId ppOrderCandidateId = forwardPPOrderRef.getPpOrderCandidateId(); final ImmutableSet<PPOrderId> forwardPPOrderIds = ppOrderCandidateDAO.getPPOrderIds(ppOrderCandidateId); return forwardPPOrderIds.size() == 1 ? forwardPPOrderIds.iterator().next() : null; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\DDOrderCandidateRequestedEventHandler.java
1
请完成以下Java代码
public I_MSV3_Verfuegbarkeit_Transaction store() { final I_MSV3_Verfuegbarkeit_Transaction transactionRecord = newInstance(I_MSV3_Verfuegbarkeit_Transaction.class); transactionRecord.setAD_Org_ID(orgId.getRepoId()); final I_MSV3_VerfuegbarkeitsanfrageEinzelne verfuegbarkeitsanfrageEinzelneRecord = // availabilityDataPersister.storeAvailabilityRequest( query, ImmutableMap.copyOf(contextInfosByQueryItem)); transactionRecord.setMSV3_VerfuegbarkeitsanfrageEinzelne(verfuegbarkeitsanfrageEinzelneRecord); if (response != null) { final I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort verfuegbarkeitsanfrageEinzelneAntwortRecord = // availabilityDataPersister.storeAvailabilityResponse( response, ImmutableMap.copyOf(contextInfosByResponse)); transactionRecord.setMSV3_VerfuegbarkeitsanfrageEinzelneAntwort(verfuegbarkeitsanfrageEinzelneAntwortRecord); } if (faultInfo != null) { final I_MSV3_FaultInfo faultInfoRecord = Msv3FaultInfoDataPersister .newInstanceWithOrgId(orgId) .storeMsv3FaultInfoOrNull(faultInfo); transactionRecord.setMSV3_FaultInfo(faultInfoRecord); } if (otherException != null) { final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(otherException); transactionRecord.setAD_Issue_ID(issueId.getRepoId()); }
save(transactionRecord); return transactionRecord; } public RuntimeException getExceptionOrNull() { if (faultInfo == null && otherException == null) { return null; } return Msv3ClientException.builder().msv3FaultInfo(faultInfo) .cause(otherException).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\availability\MSV3AvailabilityTransaction.java
1
请完成以下Java代码
public Object getLineAggregationKey() { return Util.mkKey( getM_Product_ID(), getAttributeSetInstanceId().getRepoId(), getC_UOM_ID(), getM_HU_PI_Item_Product_ID(), getPrice()); } /** * Creates and {@link I_PMM_PurchaseCandidate} to {@link I_C_OrderLine} line allocation using the whole candidate's QtyToOrder. * * @param orderLine */ /* package */void createAllocation(final I_C_OrderLine orderLine) { Check.assumeNotNull(orderLine, "orderLine not null");
final BigDecimal qtyToOrder = getQtyToOrder(); final BigDecimal qtyToOrderTU = getQtyToOrder_TU(); // // Create allocation final I_PMM_PurchaseCandidate_OrderLine alloc = InterfaceWrapperHelper.newInstance(I_PMM_PurchaseCandidate_OrderLine.class, orderLine); alloc.setC_OrderLine(orderLine); alloc.setPMM_PurchaseCandidate(model); alloc.setQtyOrdered(qtyToOrder); alloc.setQtyOrdered_TU(qtyToOrderTU); InterfaceWrapperHelper.save(alloc); // NOTE: on alloc's save we expect the model's quantities to be updated InterfaceWrapperHelper.markStaled(model); // FIXME: workaround because we are modifying the model from alloc's model interceptor } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PurchaseCandidate.java
1
请在Spring Boot框架中完成以下Java代码
GitInfoContributor gitInfoContributor(GitProperties gitProperties, InfoContributorProperties infoContributorProperties) { return new GitInfoContributor(gitProperties, infoContributorProperties.getGit().getMode()); } @Bean @ConditionalOnEnabledInfoContributor("build") @ConditionalOnSingleCandidate(BuildProperties.class) @Order(DEFAULT_ORDER) InfoContributor buildInfoContributor(BuildProperties buildProperties) { return new BuildInfoContributor(buildProperties); } @Bean @ConditionalOnEnabledInfoContributor(value = "java", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) JavaInfoContributor javaInfoContributor() { return new JavaInfoContributor(); } @Bean @ConditionalOnEnabledInfoContributor(value = "os", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) OsInfoContributor osInfoContributor() { return new OsInfoContributor();
} @Bean @ConditionalOnEnabledInfoContributor(value = "process", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) ProcessInfoContributor processInfoContributor() { return new ProcessInfoContributor(); } @Bean @ConditionalOnEnabledInfoContributor(value = "ssl", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) SslInfoContributor sslInfoContributor(SslInfo sslInfo) { return new SslInfoContributor(sslInfo); } @Bean @ConditionalOnMissingBean @ConditionalOnEnabledInfoContributor(value = "ssl", fallback = InfoContributorFallback.DISABLE) SslInfo sslInfo(SslBundles sslBundles) { return new SslInfo(sslBundles); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\info\InfoContributorAutoConfiguration.java
2
请完成以下Java代码
public Integer getPrecedence() { return ProcessApplicationElResolver.SPRING_RESOLVER; } @Override public ELResolver getElResolver(AbstractProcessApplication processApplication) { if (processApplication instanceof SpringProcessApplication) { SpringProcessApplication springProcessApplication = (SpringProcessApplication) processApplication; return new ApplicationContextElResolver(springProcessApplication.getApplicationContext()); } else if (processApplication instanceof org.camunda.bpm.application.impl.ServletProcessApplication) { // Using fully-qualified class name instead of import statement to allow for automatic transformation org.camunda.bpm.application.impl.ServletProcessApplication servletProcessApplication = (org.camunda.bpm.application.impl.ServletProcessApplication) processApplication; if(!ClassUtils.isPresent("org.springframework.web.context.support.WebApplicationContextUtils", processApplication.getProcessApplicationClassloader())) { LOGGER.log(Level.FINE, "WebApplicationContextUtils must be present for SpringProcessApplicationElResolver to work");
return null; } ServletContext servletContext = servletProcessApplication.getServletContext(); WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); if(applicationContext != null) { return new ApplicationContextElResolver(applicationContext); } } LOGGER.log(Level.FINE, "Process application class {0} unsupported by SpringProcessApplicationElResolver", processApplication); return null; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\application\SpringProcessApplicationElResolver.java
1
请在Spring Boot框架中完成以下Java代码
public void addQtyToAllMatchingGroups(@NonNull final AddToResultGroupRequest request) { // note that we might select more quantities than we actually wanted (bc of the way we match attributes in the query using LIKE) // for that reason, we need to be lenient in case not all quantities can be added to a bucked buckets.forEach(bucket -> bucket.addQtyToAllMatchingGroups(request)); } public void addToNewGroupIfFeasible(@NonNull final AddToResultGroupRequest request) { boolean addedToAtLeastOneGroup = false; for (final AvailableToPromiseResultBucket bucket : buckets) { if (bucket.addToNewGroupIfFeasible(request)) { addedToAtLeastOneGroup = true; break; } } if (!addedToAtLeastOneGroup) { final AvailableToPromiseResultBucket bucket = newBucket(request); if (!bucket.addToNewGroupIfFeasible(request)) { throw new AdempiereException("Internal error: cannot add " + request + " to newly created bucket: " + bucket); } } } private AvailableToPromiseResultBucket newBucket(final AddToResultGroupRequest request) { final AvailableToPromiseResultBucket bucket = AvailableToPromiseResultBucket.builder() .warehouse(WarehouseClassifier.specificOrAny(request.getWarehouseId())) .bpartner(request.getBpartner())
.product(ProductClassifier.specific(request.getProductId().getRepoId())) .storageAttributesKeyMatcher(AttributesKeyPatternsUtil.matching(request.getStorageAttributesKey())) .build(); buckets.add(bucket); return bucket; } @VisibleForTesting ImmutableList<AvailableToPromiseResultBucket> getBuckets() { return ImmutableList.copyOf(buckets); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultBuilder.java
2
请完成以下Java代码
public class SqlBatch { @Getter private final String sqlCommand; private final ArrayList<SqlParams> rows = new ArrayList<>(); private SqlBatch(final String sqlCommand) { this.sqlCommand = sqlCommand; } public static SqlBatch ofSql(@NonNull final String sqlCommand) { return new SqlBatch(sqlCommand); } public void addRow(@Nullable final Map<Integer, Object> row) { addRow(SqlParams.ofMap(row));
} public void addRow(@NonNull SqlParams row) { rows.add(row); } public Stream<Sql> streamSqls() {return rows.stream().map(this::toSql);} private Sql toSql(final SqlParams sqlParams) { return Sql.ofSql(sqlCommand, sqlParams); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\SqlBatch.java
1
请完成以下Java代码
public static void readEmails(Store store) throws MessagingException, IOException { Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); if (messages.length > 0) { Message message = messages[0]; LOGGER.info("Subject: " + message.getSubject()); LOGGER.info("From: " + Arrays.toString(message.getFrom())); LOGGER.info("Text: " + message.getContent()); } inbox.close(true); } public static void searchEmails(Store store, String from) throws MessagingException { Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_ONLY); SearchTerm senderTerm = new FromStringTerm(from); Message[] messages = inbox.search(senderTerm); Message[] getFirstFiveEmails = Arrays.copyOfRange(messages, 0, 5); for (Message message : getFirstFiveEmails) { LOGGER.info("Subject: " + message.getSubject()); LOGGER.info("From: " + Arrays.toString(message.getFrom())); } inbox.close(true); } public static void deleteEmail(Store store) throws MessagingException { Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); if (messages.length >= 7) { Message seventhLatestMessage = messages[messages.length - 7]; seventhLatestMessage.setFlag(Flags.Flag.DELETED, true);
LOGGER.info("Delete the seventh message: " + seventhLatestMessage.getSubject()); } else { LOGGER.info("There are less than seven messages in the inbox."); } inbox.close(true); } public static void markLatestUnreadAsRead(Store store) throws MessagingException { Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); if (messages.length > 0) { Message latestUnreadMessage = messages[messages.length - 1]; latestUnreadMessage.setFlag(Flags.Flag.SEEN, true); } inbox.close(true); } public static void moveToFolder(Store store, Message message, String folderName) throws MessagingException { Folder destinationFolder = store.getFolder(folderName); if (!destinationFolder.exists()) { destinationFolder.create(Folder.HOLDS_MESSAGES); } Message[] messagesToMove = new Message[] { message }; message.getFolder() .copyMessages(messagesToMove, destinationFolder); message.setFlag(Flags.Flag.DELETED, true); } }
repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\accessemailwithimap\GmailApp.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getRoleLevel() { return roleLevel; } public void setRoleLevel(Integer roleLevel) { this.roleLevel = roleLevel; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMenuItems() { return menuItems; } public void setMenuItems(String menuItems) { this.menuItems = menuItems; } @Override
public int compareTo(Role o) { if(id == o.getId()){ return 0; }else if(id > o.getId()){ return 1; }else{ return -1; } } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(obj instanceof Role){ if(this.id == ((Role)obj).getId()){ return true; } } return false; } @Override public String toString() { return "Role{" + "id=" + id + ", name=" + name + ", roleLevel=" + roleLevel + ", description=" + description + '}'; } }
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\Role.java
1
请完成以下Java代码
private boolean isInstall() { return environment.acceptsProfiles(Profiles.of("install")); } private void initSession() { if (this.keyspaceName != null) { this.sessionBuilder.withKeyspace(this.keyspaceName); } this.sessionBuilder.withLocalDatacenter(localDatacenter); if (StringUtils.isNotBlank(cloudSecureConnectBundlePath)) { this.sessionBuilder.withCloudSecureConnectBundle(Paths.get(cloudSecureConnectBundlePath)); this.sessionBuilder.withAuthCredentials(cloudClientId, cloudClientSecret); } session = sessionBuilder.build(); if (this.metrics && this.jmx) { MetricRegistry registry = session.getMetrics().orElseThrow( () -> new IllegalStateException("Metrics are disabled")) .getRegistry(); this.reporter = JmxReporter.forRegistry(registry) .inDomain("com.datastax.oss.driver") .build(); this.reporter.start(); } } @PreDestroy
public void close() { if (reporter != null) { reporter.stop(); } if (session != null) { session.close(); } } public ConsistencyLevel getDefaultReadConsistencyLevel() { return driverOptions.getDefaultReadConsistencyLevel(); } public ConsistencyLevel getDefaultWriteConsistencyLevel() { return driverOptions.getDefaultWriteConsistencyLevel(); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\AbstractCassandraCluster.java
1
请完成以下Java代码
public class UserWithView { @JsonView(InternalView.class) private Long id; @JsonView(PublicView.class) private String name; public UserWithView(Long id, String name) { this.id = id; this.name = name; } public UserWithView() { } public String getName() { return name; } public Long getId() { return id; }
/** * View that is used to hide sensitive information */ public interface PublicView { } /** * View that is used to show all information */ public interface InternalView extends PublicView { } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\dynamicignore\UserWithView.java
1
请完成以下Java代码
public @Nullable Object invoke(MethodInvocation mi) throws Throwable { Object result = mi.proceed(); if (result == null) { return null; } Assert.notNull(this.authorizationProxyFactory, "authorizationProxyFactory cannot be null"); return this.authorizationProxyFactory.proxy(result); } /** * Use this {@link AuthorizationProxyFactory} * @param authorizationProxyFactory the proxy factory to use * @since 6.5 */ public void setAuthorizationProxyFactory(AuthorizationProxyFactory authorizationProxyFactory) { Assert.notNull(authorizationProxyFactory, "authorizationProxyFactory cannot be null"); this.authorizationProxyFactory = authorizationProxyFactory; } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } /** * {@inheritDoc} */ @Override public Pointcut getPointcut() {
return this.pointcut; } public void setPointcut(Pointcut pointcut) { this.pointcut = pointcut; } @Override public Advice getAdvice() { return this; } @Override public boolean isPerInstance() { return true; } static final class MethodReturnTypePointcut extends StaticMethodMatcherPointcut { private final Predicate<Class<?>> returnTypeMatches; MethodReturnTypePointcut(Predicate<Class<?>> returnTypeMatches) { this.returnTypeMatches = returnTypeMatches; } @Override public boolean matches(Method method, Class<?> targetClass) { return this.returnTypeMatches.test(method.getReturnType()); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\AuthorizeReturnObjectMethodInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public InMemoryUserDetailsManager userDetailsService() { UserDetails user1 = User.withUsername("user1") .password(passwordEncoder().encode("user1Pass")) .roles("USER") .build(); UserDetails admin1 = User.withUsername("admin1") .password(passwordEncoder().encode("admin1Pass")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user1, admin1); } @Bean public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry .requestMatchers(mvc.pattern("/anonymous*")).anonymous() .requestMatchers(mvc.pattern("/login*"), mvc.pattern("/invalidSession*"), mvc.pattern("/sessionExpired*"), mvc.pattern("/foo/**")).permitAll() .anyRequest().authenticated()) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login") .loginProcessingUrl("/login") .successHandler(successHandler()) .failureUrl("/login?error=true")) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.deleteCookies("JSESSIONID")) .rememberMe(httpSecurityRememberMeConfigurer -> httpSecurityRememberMeConfigurer.key("uniqueAndSecret") .tokenValiditySeconds(86400)) .sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionFixation() .migrateSession().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .invalidSessionUrl("/invalidSession") .maximumSessions(2) .expiredUrl("/sessionExpired")); return http.build(); } private AuthenticationSuccessHandler successHandler() {
return new MySimpleUrlAuthenticationSuccessHandler(); } @Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) { return new MvcRequestMatcher.Builder(introspector); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\session\security\config\SecSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public T pathMatchers(HttpMethod method, String... antPatterns) { List<PathPattern> pathPatterns = parsePatterns(antPatterns); return matcher(ServerWebExchangeMatchers.pathMatchers(method, pathPatterns.toArray(new PathPattern[0]))); } /** * Maps a {@link List} of {@link PathPatternParserServerWebExchangeMatcher} instances * that do not care which {@link HttpMethod} is used. * @param antPatterns the ant patterns to create * {@link PathPatternParserServerWebExchangeMatcher} from * @return the object that is chained after creating the * {@link ServerWebExchangeMatcher} */ public T pathMatchers(String... antPatterns) { List<PathPattern> pathPatterns = parsePatterns(antPatterns); return matcher(ServerWebExchangeMatchers.pathMatchers(pathPatterns.toArray(new PathPattern[0]))); } private List<PathPattern> parsePatterns(String[] antPatterns) { PathPatternParser parser = getPathPatternParser(); List<PathPattern> pathPatterns = new ArrayList<>(antPatterns.length); for (String pattern : antPatterns) { pattern = parser.initFullPathPattern(pattern); PathPattern pathPattern = parser.parse(pattern); pathPatterns.add(pathPattern); } return pathPatterns; } /** * Associates a list of {@link ServerWebExchangeMatcher} instances * @param matchers the {@link ServerWebExchangeMatcher} instances * @return the object that is chained after creating the * {@link ServerWebExchangeMatcher} */
public T matchers(ServerWebExchangeMatcher... matchers) { return registerMatcher(new OrServerWebExchangeMatcher(matchers)); } /** * Subclasses should implement this method for returning the object that is chained to * the creation of the {@link ServerWebExchangeMatcher} instances. * @param matcher the {@link ServerWebExchangeMatcher} instances that were created * @return the chained Object for the subclass which allows association of something * else to the {@link ServerWebExchangeMatcher} */ protected abstract T registerMatcher(ServerWebExchangeMatcher matcher); protected PathPatternParser getPathPatternParser() { return PathPatternParser.defaultInstance; } /** * Associates a {@link ServerWebExchangeMatcher} instances * @param matcher the {@link ServerWebExchangeMatcher} instance * @return the object that is chained after creating the * {@link ServerWebExchangeMatcher} */ private T matcher(ServerWebExchangeMatcher matcher) { return registerMatcher(matcher); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\web\server\AbstractServerWebExchangeMatcherRegistry.java
2
请完成以下Java代码
public static ExecutableScript getScriptFromResourceExpression(String language, Expression resourceExpression, ScriptFactory scriptFactory) { ensureNotEmpty(NotValidException.class, "Script language", language); ensureNotNull(NotValidException.class, "Script resource expression", resourceExpression); return scriptFactory.createScriptFromResource(language, resourceExpression); } /** * Checks if the value is an expression for a dynamic script source or resource. * * @param language the language of the script * @param value the value to check * @return true if the value is an expression for a dynamic script source/resource, otherwise false */ public static boolean isDynamicScriptExpression(String language, String value) { return StringUtil.isExpression(value) && (language != null && !JuelScriptEngineFactory.names.contains(language.toLowerCase()));
} /** * Returns the configured script factory in the context or a new one. */ public static ScriptFactory getScriptFactory() { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); if (processEngineConfiguration != null) { return processEngineConfiguration.getScriptFactory(); } else { return new ScriptFactory(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ScriptUtil.java
1
请完成以下Java代码
/* package */ void validateBbanLength(final String iban, final BBANStructure structure) { final int expectedBbanLength = structure.getBbanLength(); final String bban = getBBAN(iban); final int bbanLength = bban.length(); Check.assume(expectedBbanLength == bbanLength, msgBL.getMsg(Env.getCtx(), "BBAN_Length", new Object[] { bbanLength, expectedBbanLength })); } /* package */ void validateBbanEntries(final String iban, final BBANStructure code) { final String bban = getBBAN(iban); int bbanEntryOffset = 0; for (final BBANStructureEntry entry : code.getEntries()) { final int entryLength = entry.getLength(); final String entryValue = bban.substring(bbanEntryOffset, bbanEntryOffset + entryLength); bbanEntryOffset = bbanEntryOffset + entryLength; // validate character type validateBbanEntryCharacterType(entry, entryValue); } } /* package */ void validateBbanEntryCharacterType(final BBANStructureEntry entry, final String entryValue) { switch (entry.getCharacterType()) { case a: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isUpperCase(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Upper_Letters", new Object[] { entryValue })); } break; case c: for (char ch : entryValue.toCharArray()) {
Check.assume(Character.isLetterOrDigit(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Letters_Digits", new Object[] { entryValue })); } break; case n: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isDigit(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Digits", new Object[] { entryValue })); } break; } } /* package */ BBANStructure getBBANCode(final String iban) { final String countryCode = getCountryCode(iban); return Services.get(IBBANStructureBL.class).getBBANStructureForCountry(countryCode); } private String fromCharCode(int... codePoints) { return new String(codePoints, 0, codePoints.length); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\IBANValidationBL.java
1
请完成以下Java代码
private AdColumnId getAD_Column_ID() { return adColumnId; } public C_AggregationItem_Builder setIncluded_Aggregation(final I_C_Aggregation includedAggregation) { this.includedAggregation = includedAggregation; return this; } private I_C_Aggregation getIncluded_Aggregation() { return includedAggregation; } public C_AggregationItem_Builder setIncludeLogic(final String includeLogic) { this.includeLogic = includeLogic; return this;
} private String getIncludeLogic() { return includeLogic; } public C_AggregationItem_Builder setC_Aggregation_Attribute(I_C_Aggregation_Attribute attribute) { this.attribute = attribute; return this; } private I_C_Aggregation_Attribute getC_Aggregation_Attribute() { return this.attribute; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_AggregationItem_Builder.java
1
请完成以下Java代码
public InputStream connectNext(final boolean lastWasSuccess) { if (currentStream != null) { try { // note: close alone didn't suffice (at least in WinXP when // running in eclipse debug session) currentStream.getFD().sync(); currentStream.close(); } catch (IOException e) { throw new AdempiereException(e); } } if (lastWasSuccess && currentFile != null) { final String archiveFolder = (String)getCurrentParams().get( IInboundProcessorBL.ARCHIVE_FOLDER).getValue(); inboundProcessorBL.moveToArchive(currentFile, archiveFolder); } if (currentFiles.hasNext()) { currentFile = currentFiles.next(); try { currentStream = new FileInputStream(currentFile); return currentStream; } catch (FileNotFoundException e)
{ ConfigException.throwNew(ConfigException.FILE_ACCESS_FAILED_2P, currentFile.getAbsolutePath(), e.getMessage()); } } return null; } @Override public List<Parameter> getParameters() { final List<Parameter> result = new ArrayList<Parameter>(); result.add(new Parameter(IInboundProcessorBL.LOCAL_FOLDER, "Import-Ordner", "Name of the folder to import from", DisplayType.FilePath, 1)); result.add(new Parameter(IInboundProcessorBL.ARCHIVE_FOLDER, "Archiv-Ordner", "Name of the folder to move files to after import", DisplayType.FilePath, 2)); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\spi\impl\FileImporter.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Country Area. @param C_CountryArea_ID Country Area */ @Override public void setC_CountryArea_ID (int C_CountryArea_ID) { if (C_CountryArea_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, Integer.valueOf(C_CountryArea_ID)); } /** Get Country Area. @return Country Area */ @Override public int getC_CountryArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CountryArea.java
1
请完成以下Java代码
public static String convertJpg2Pdf(String strJpgFile, String strPdfFile) throws Exception { Document document = new Document(); RandomAccessFileOrArray rafa = null; FileOutputStream outputStream = null; try { RandomAccessFile aFile = new RandomAccessFile(strJpgFile, "r"); FileChannel inChannel = aFile.getChannel(); FileChannelRandomAccessSource fcra = new FileChannelRandomAccessSource(inChannel); rafa = new RandomAccessFileOrArray(fcra); int pages = TiffImage.getNumberOfPages(rafa); outputStream = new FileOutputStream(strPdfFile); PdfWriter.getInstance(document, outputStream); document.open(); Image image; for (int i = 1; i <= pages; i++) { image = TiffImage.getTiffImage(rafa, i); image.scaleToFit(FIT_WIDTH, FIT_HEIGHT); document.add(image); } } catch (IOException e) { if (!e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) { logger.error("TIF转JPG异常,文件路径:" + strPdfFile, e); }
throw new Exception(e); } finally { if (document != null) { document.close(); } if (rafa != null) { rafa.close(); } if (outputStream != null) { outputStream.close(); } } return strPdfFile; } }
repos\kkFileView-master\server\src\main\java\cn\keking\utils\ConvertPicUtil.java
1
请完成以下Java代码
public synchronized void reload(final InboundEMailConfig config) { final InboundEMailConfigId configId = config.getId(); final InboundEMailConfig loadedConfig = loadedConfigs.get(configId); if (loadedConfig != null && loadedConfig.equals(config)) { logger.info("Skip reloading {} because it's already loaded and not changed", config); } unloadById(configId); load(config); } public synchronized void unloadById(final InboundEMailConfigId configId) { final InboundEMailConfig loadedConfig = loadedConfigs.remove(configId); if (loadedConfig == null) { logger.info("Skip unloading inbound mail for {} because it's not loaded", configId); return; } try { flowContext.remove(toFlowId(configId)); logger.info("Unloaded inbound mail for {}", configId); } catch (final Exception ex) { logger.warn("Unloading inbound mail for {} failed. Ignored.", configId, ex); } } private synchronized void load(final InboundEMailConfig config) { final IntegrationFlow flow = createIntegrationFlow(config); flowContext.registration(flow) .id(toFlowId(config.getId()))
.register(); loadedConfigs.put(config.getId(), config); logger.info("Loaded inbound mail for {}", config); } private IntegrationFlow createIntegrationFlow(final InboundEMailConfig config) { return IntegrationFlows .from(Mail.imapIdleAdapter(config.getUrl()) .javaMailProperties(p -> p.put("mail.debug", Boolean.toString(config.isDebugProtocol()))) .userFlag(IMAP_USER_FLAG) .shouldMarkMessagesAsRead(false) .shouldDeleteMessages(false) .shouldReconnectAutomatically(true) .embeddedPartsAsBytes(false) .headerMapper(InboundEMailHeaderAndContentMapper.newInstance())) .handle(InboundEMailMessageHandler.builder() .config(config) .emailService(emailService) .build()) .get(); } @Override public void onInboundEMailConfigChanged(final Set<InboundEMailConfigId> changedConfigIds) { final List<InboundEMailConfig> newOrChangedConfigs = configsRepo.getByIds(changedConfigIds); final Set<InboundEMailConfigId> newOrChangedConfigIds = newOrChangedConfigs.stream() .map(InboundEMailConfig::getId) .collect(ImmutableSet.toImmutableSet()); final Set<InboundEMailConfigId> deletedConfigIds = Sets.difference(changedConfigIds, newOrChangedConfigIds); deletedConfigIds.forEach(this::unloadById); reload(newOrChangedConfigs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailServer.java
1
请完成以下Java代码
public void setStorno(Boolean value) { this.storno = value; } /** * Gets the value of the copy property. * * @return * possible object is * {@link Boolean } * */ public boolean isCopy() { if (copy == null) { return false; } else { return copy; } } /** * Sets the value of the copy property. * * @param value * allowed object is * {@link Boolean } * */ public void setCopy(Boolean value) { this.copy = value; }
/** * Gets the value of the responseTimestamp property. * */ public int getResponseTimestamp() { return responseTimestamp; } /** * Sets the value of the responseTimestamp property. * */ public void setResponseTimestamp(int value) { this.responseTimestamp = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\PayloadType.java
1
请完成以下Java代码
public class ContractChangeDAO extends AbstractContractChangeDAO { @Override public I_C_Contract_Change retrieveChangeConditions( final I_C_Flatrate_Term term, final int newSubscriptionId, final Timestamp changeDate) { final String where = X_C_Contract_Change.COLUMNNAME_Action + "='" + X_C_Contract_Change.ACTION_Abowechsel + "' AND " + X_C_Contract_Change.COLUMNNAME_C_Flatrate_Transition_ID + "=? AND " + "COALESCE(" + X_C_Contract_Change.COLUMNNAME_C_Flatrate_Conditions_ID + ",0) IN (0,?) AND " + X_C_Contract_Change.COLUMNNAME_C_Flatrate_Conditions_Next_ID + "=?"; final Properties ctx = InterfaceWrapperHelper.getCtx(term); final String trxName = InterfaceWrapperHelper.getTrxName(term);
final List<I_C_Contract_Change> entries = new Query(ctx, I_C_Contract_Change.Table_Name, where, trxName) .setParameters(term.getC_Flatrate_Transition_ID(), term.getC_Flatrate_Conditions_ID(), newSubscriptionId) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Contract_Change.COLUMNNAME_C_Contract_Change_ID) .list(I_C_Contract_Change.class); final I_C_Contract_Change earliestEntryForRefDate = getEarliestEntryForRefDate(entries, changeDate, term.getEndDate()); if (earliestEntryForRefDate == null) { throw new SubscriptionChangeException(term.getC_Flatrate_Conditions_ID(), newSubscriptionId, changeDate); } return earliestEntryForRefDate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractChangeDAO.java
1
请完成以下Spring Boot application配置
#primary spring.primary.datasource.url=jdbc:mysql://localhost:3306/test1 spring.primary.datasource.username=root spring.primary.datasource.password=root spring.primary.datasource.driver-class-name=com.mysql.jdbc.Driver #secondary spring.secondary.datasource.url=jdbc:mysql://localhost:3306/test2 spring.secondary.datasource.username=root spring.secondary.datasource.password=root spring.secondary.datasource.driver-class-name=com.mysql.jd
bc.Driver #multiple Setting spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= true
repos\spring-boot-leaning-master\1.x\第04课:Spring Data Jpa 的使用\spring-boot-multi-Jpa\src\main\resources\application.properties
2
请完成以下Java代码
public Tags apply(ServerWebExchange exchange) { String outcome = "CUSTOM"; String status = "CUSTOM"; String httpStatusCodeStr = "NA"; String httpMethod = exchange.getRequest().getMethod().name(); // a non standard HTTPS status could be used. Let's be defensive here // it needs to be checked for first, otherwise the delegate response // who's status DIDN'T change, will be used Integer statusInt = null; HttpStatusCode statusCode = exchange.getResponse().getStatusCode(); if (statusCode != null) { statusInt = statusCode.value(); if (statusInt != null) { status = String.valueOf(statusInt);
httpStatusCodeStr = status; HttpStatus resolved = HttpStatus.resolve(statusInt); if (resolved != null) { // this is not a CUSTOM status, so use series here. outcome = resolved.series().name(); status = resolved.name(); } } } return Tags.of("outcome", outcome, "status", status, "httpStatusCode", httpStatusCodeStr, "httpMethod", httpMethod); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\tagsprovider\GatewayHttpTagsProvider.java
1
请完成以下Java代码
public class StartCreatedProcessInstanceCmd<T> implements Command<ProcessInstance>, Serializable { private static final long serialVersionUID = 1L; private ProcessInstance internalProcessInstance; private Map<String, Object> variables; public StartCreatedProcessInstanceCmd(ProcessInstance internalProcessInstance, Map<String, Object> variables) { this.internalProcessInstance = internalProcessInstance; this.variables = variables; } @Override public ProcessInstance execute(CommandContext commandContext) { if (this.internalProcessInstance.getStartTime() != null) { throw new ActivitiIllegalArgumentException( "Process instance " + this.internalProcessInstance.getProcessInstanceId() + " has already been started" ); }
ExecutionEntity processExecution = (ExecutionEntity) internalProcessInstance; ProcessInstanceHelper processInstanceHelper = commandContext .getProcessEngineConfiguration() .getProcessInstanceHelper(); Process process = ProcessDefinitionUtil.getProcess(internalProcessInstance.getProcessDefinitionId()); processInstanceHelper.startProcessInstance( processExecution, commandContext, variables, process.getInitialFlowElement(), Collections.emptyMap(), null, null ); return processExecution; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\StartCreatedProcessInstanceCmd.java
1
请完成以下Java代码
public static boolean set(String key, Object val, long cacheTime){ // clean timeout cache, before set new cache (avoid cache too much) cleanTimeoutCache(); // set new cache if (key==null || key.trim().length()==0) { return false; } if (val == null) { remove(key); } if (cacheTime <= 0) { remove(key); } long timeoutTime = System.currentTimeMillis() + cacheTime; LocalCacheData localCacheData = new LocalCacheData(key, val, timeoutTime); cacheRepository.put(localCacheData.getKey(), localCacheData); return true; } /** * remove cache * * @param key * @return */ public static boolean remove(String key){ if (key==null || key.trim().length()==0) { return false; } cacheRepository.remove(key); return true; } /**
* get cache * * @param key * @return */ public static Object get(String key){ if (key==null || key.trim().length()==0) { return null; } LocalCacheData localCacheData = cacheRepository.get(key); if (localCacheData!=null && System.currentTimeMillis()<localCacheData.getTimeoutTime()) { return localCacheData.getVal(); } else { remove(key); return null; } } /** * clean timeout cache * * @return */ public static boolean cleanTimeoutCache(){ if (!cacheRepository.keySet().isEmpty()) { for (String key: cacheRepository.keySet()) { LocalCacheData localCacheData = cacheRepository.get(key); if (localCacheData!=null && System.currentTimeMillis()>=localCacheData.getTimeoutTime()) { cacheRepository.remove(key); } } } return true; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\LocalCacheUtil.java
1
请完成以下Java代码
static class PostgresDbR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements R2dbcConnectionDetails { private static final Option<String> APPLICATION_NAME = Option.valueOf("applicationName"); private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder( "postgresql", 5432); private final ConnectionFactoryOptions connectionFactoryOptions; PostgresDbR2dbcDockerComposeConnectionDetails(RunningService service, Environment environment) { super(service); this.connectionFactoryOptions = getConnectionFactoryOptions(service, environment); } @Override public ConnectionFactoryOptions getConnectionFactoryOptions() { return this.connectionFactoryOptions; } private static ConnectionFactoryOptions getConnectionFactoryOptions(RunningService service, Environment environment) { PostgresEnvironment env = new PostgresEnvironment(service.env());
ConnectionFactoryOptions connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, env.getDatabase(), env.getUsername(), env.getPassword()); return addApplicationNameIfNecessary(connectionFactoryOptions, environment); } private static ConnectionFactoryOptions addApplicationNameIfNecessary( ConnectionFactoryOptions connectionFactoryOptions, Environment environment) { if (connectionFactoryOptions.hasOption(APPLICATION_NAME)) { return connectionFactoryOptions; } String applicationName = environment.getProperty("spring.application.name"); if (!StringUtils.hasText(applicationName)) { return connectionFactoryOptions; } return connectionFactoryOptions.mutate().option(APPLICATION_NAME, applicationName).build(); } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\PostgresR2dbcDockerComposeConnectionDetailsFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void doSignatureValidation(JoinPoint point) throws Exception { // 获取方法上的注解 MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); SignatureCheck signatureCheck = method.getAnnotation(SignatureCheck.class); log.info("AOP签名验证: {}.{}", method.getDeclaringClass().getSimpleName(), method.getName()); // 如果注解被禁用,直接返回 if (!signatureCheck.enabled()) { log.info("签名验证已禁用,跳过"); return; } ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes == null) { log.error("无法获取请求上下文"); throw new IllegalArgumentException("无法获取请求上下文"); } HttpServletRequest request = attributes.getRequest(); log.info("X-SIGN: {}, X-TIMESTAMP: {}", request.getHeader("X-SIGN"), request.getHeader("X-TIMESTAMP")); try { // 直接调用SignAuthInterceptor的验证逻辑 signAuthInterceptor.validateSignature(request); log.info("AOP签名验证通过"); } catch (IllegalArgumentException e) { // 使用注解中配置的错误消息,或者保留原始错误消息 String errorMessage = signatureCheck.errorMessage(); log.error("AOP签名验证失败: {}", e.getMessage());
if ("Sign签名校验失败!".equals(errorMessage)) { // 如果是默认错误消息,使用原始的详细错误信息 throw e; } else { // 如果是自定义错误消息,使用自定义消息 throw new IllegalArgumentException(errorMessage, e); } } catch (Exception e) { // 包装其他异常 String errorMessage = signatureCheck.errorMessage(); log.error("AOP签名验证异常: {}", e.getMessage()); throw new IllegalArgumentException(errorMessage, e); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\aspect\SignatureCheckAspect.java
2
请完成以下Java代码
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 void onMessage(MapRecord<String, String, String> record) { counter.incrementAndGet(); deque.add(record); } /** * @return new instance of {@link CapturingStreamListener}. */ public static CapturingStreamListener create() { return new CapturingStreamListener(); } /** * @return the total number or records captured so far.
*/ public int recordsReceived() { return counter.get(); } /** * Retrieves and removes the head of the queue waiting if * necessary until an element becomes available. * * @return * @throws InterruptedException if interrupted while waiting */ public MapRecord<String, String, String> take() throws InterruptedException { return deque.take(); } }
repos\spring-data-examples-main\redis\streams\src\main\java\example\springdata\redis\sync\CapturingStreamListener.java
1
请完成以下Java代码
public Builder setIdFieldName(final String idFieldName) { this.idFieldName = idFieldName; return this; } private String getIdFieldName() { return idFieldName; } public Builder setHasAttributesSupport(final boolean hasAttributesSupport) { this.hasAttributesSupport = hasAttributesSupport; return this; } public Builder setIncludedViewLayout(final IncludedViewLayout includedViewLayout) { this.includedViewLayout = includedViewLayout; return this; } public Builder clearViewCloseActions() { allowedViewCloseActions = new LinkedHashSet<>(); return this; } public Builder allowViewCloseAction(@NonNull final ViewCloseAction viewCloseAction) { if (allowedViewCloseActions == null) { allowedViewCloseActions = new LinkedHashSet<>(); } allowedViewCloseActions.add(viewCloseAction); return this; } private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions() { return allowedViewCloseActions != null ? ImmutableSet.copyOf(allowedViewCloseActions) : DEFAULT_allowedViewCloseActions; } public Builder setHasTreeSupport(final boolean hasTreeSupport) { this.hasTreeSupport = hasTreeSupport;
return this; } public Builder setTreeCollapsible(final boolean treeCollapsible) { this.treeCollapsible = treeCollapsible; return this; } public Builder setTreeExpandedDepth(final int treeExpandedDepth) { this.treeExpandedDepth = treeExpandedDepth; return this; } public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails) { this.allowOpeningRowDetails = allowOpeningRowDetails; return this; } public Builder setFocusOnFieldName(final String focusOnFieldName) { this.focusOnFieldName = focusOnFieldName; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java
1
请在Spring Boot框架中完成以下Java代码
public List<Menu> getMenus() { return menus; } public void setMenus(List<Menu> menus) { this.menus = menus; } public Theme getThemes() { return themes; } public void setThemes(Theme themes) { this.themes = themes; } public List<Server> getServers() {
return servers; } public void setServers(List<Server> servers) { this.servers = servers; } @Override public String toString() { return "WordpressProperties{" + "menus=" + menus + ", themes=" + themes + ", servers=" + servers + '}'; } }
repos\spring-boot-master\yaml-simple\src\main\java\com\mkyong\config\WordpressProperties.java
2
请完成以下Java代码
public void run(){ if (graph.size() > 0){ graph.get(0).setVisited(true); } while (isDisconnected()){ Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = graph.get(0); for (Vertex vertex : graph){ if (vertex.isVisited()){ Pair<Vertex, Edge> candidate = vertex.nextMinimum(); if (candidate.getValue().getWeight() < nextMinimum.getWeight()){ nextMinimum = candidate.getValue(); nextVertex = candidate.getKey(); } } } nextMinimum.setIncluded(true); nextVertex.setVisited(true); } } private boolean isDisconnected(){ for (Vertex vertex : graph){ if (!vertex.isVisited()){ return true; } } return false; }
public String originalGraphToString(){ StringBuilder sb = new StringBuilder(); for (Vertex vertex : graph){ sb.append(vertex.originalToString()); } return sb.toString(); } public void resetPrintHistory(){ for (Vertex vertex : graph){ Iterator<Map.Entry<Vertex,Edge>> it = vertex.getEdges().entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); pair.getValue().setPrinted(false); } } } public String minimumSpanningTreeToString(){ StringBuilder sb = new StringBuilder(); for (Vertex vertex : graph){ sb.append(vertex.includedToString()); } return sb.toString(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\prim\Prim.java
1
请完成以下Java代码
public Integer getUsePointLimitNew() { return usePointLimitNew; } public void setUsePointLimitNew(Integer usePointLimitNew) { this.usePointLimitNew = usePointLimitNew; } public String getOperateMan() { return operateMan; } public void setOperateMan(String operateMan) { this.operateMan = operateMan; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", priceOld=").append(priceOld); sb.append(", priceNew=").append(priceNew); sb.append(", salePriceOld=").append(salePriceOld); sb.append(", salePriceNew=").append(salePriceNew); sb.append(", giftPointOld=").append(giftPointOld); sb.append(", giftPointNew=").append(giftPointNew); sb.append(", usePointLimitOld=").append(usePointLimitOld); sb.append(", usePointLimitNew=").append(usePointLimitNew); sb.append(", operateMan=").append(operateMan); sb.append(", createTime=").append(createTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductOperateLog.java
1
请完成以下Java代码
public boolean isConstant() { return constantValue != null; } @Override public boolean constantValue() { if (constantValue == null) { throw ExpressionEvaluationException.newWithTranslatableMessage("Not a constant expression: " + this); } return constantValue; } @Override public ILogicExpression toConstantExpression(final boolean constantValue) { if (this.constantValue != null && this.constantValue == constantValue) { return this; } return new LogicTuple(constantValue, this); } @Override public String getExpressionString() { return expressionStr; } @Override public Set<CtxName> getParameters() { if (_parameters == null) { if (isConstant()) { _parameters = ImmutableSet.of(); } else { final Set<CtxName> result = new LinkedHashSet<>(); if (operand1 instanceof CtxName) { result.add((CtxName)operand1); } if (operand2 instanceof CtxName) { result.add((CtxName)operand2); } _parameters = ImmutableSet.copyOf(result); } }
return _parameters; } /** * @return {@link CtxName} or {@link String}; never returns null */ public Object getOperand1() { return operand1; } /** * @return {@link CtxName} or {@link String}; never returns null */ public Object getOperand2() { return operand2; } /** * @return operator; never returns null */ public String getOperator() { return operator; } @Override public String toString() { return getExpressionString(); } @Override public String getFormatedExpressionString() { return getExpressionString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicTuple.java
1
请完成以下Java代码
public void setHtmlText(String htmlText) { editor.setText(htmlText); } public String getHtmlText() { try { StringWriter sw = new StringWriter(); new AltHTMLWriter(sw, editor.getDocument()).write(); // new HTMLWriter(sw, editor.document).write(); String html = sw.toString(); return html; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Compatible with CTextArea * * @param text * @see #setHtmlText(String) */ public void setText(String text) { if (!isHtml(text)) { setHtmlText(convertToHtml(text)); } else { setHtmlText(text); } } /** * Compatible with CTextArea * * @return html text * @see #getHtmlText() */ public String getText() { return getHtmlText(); } /** * Compatible with CTextArea * * @param position */ public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public BoilerPlateContext getAttributes() { return boilerPlateMenu.getAttributes(); } public void setAttributes(final BoilerPlateContext attributes) { boilerPlateMenu.setAttributes(attributes); } public File getPDF(String fileNamePrefix) { throw new UnsupportedOperationException(); } private void actionPreview() { // final ReportEngine re = getReportEngine(); // ReportCtl.preview(re); File pdf = getPDF(null); if (pdf != null) { Env.startBrowser(pdf.toURI().toString()); } } private Dialog getParentDialog() { Dialog parent = null; Container e = getParent(); while (e != null)
{ if (e instanceof Dialog) { parent = (Dialog)e; break; } e = e.getParent(); } return parent; } public boolean print() { throw new UnsupportedOperationException(); } public static boolean isHtml(String s) { if (s == null) return false; String s2 = s.trim().toUpperCase(); return s2.startsWith("<HTML>"); } public static String convertToHtml(String plainText) { if (plainText == null) return null; return plainText.replaceAll("[\r]*\n", "<br/>\n"); } public boolean isResolveVariables() { return boilerPlateMenu.isResolveVariables(); } public void setResolveVariables(boolean isResolveVariables) { boilerPlateMenu.setResolveVariables(isResolveVariables); } public void setEnablePrint(boolean enabled) { butPrint.setEnabled(enabled); butPrint.setVisible(enabled); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
1
请完成以下Java代码
protected String doIt() throws Exception { final I_ESR_Import esrImport = retrieveESR_Import(); ESRImportEnqueuer.newInstance() .esrImport(esrImport) .fromDataSource(ESRImportEnqueuerDataSource.ofFile(p_FileName)) // .asyncBatchName(p_AsyncBatchName) .asyncBatchDesc(p_AsyncBatchDesc) .pinstanceId(getPinstanceId()) // .loggable(this) // .execute(); getResult().setRecordToRefreshAfterExecution(TableRecordReference.of(esrImport)); return MSG_OK; } private final I_ESR_Import retrieveESR_Import() {
if (p_ESR_Import_ID <= 0) { if (I_ESR_Import.Table_Name.equals(getTableName())) { p_ESR_Import_ID = getRecord_ID(); } if (p_ESR_Import_ID <= 0) { throw new FillMandatoryException(I_ESR_Import.COLUMNNAME_ESR_Import_ID); } } final I_ESR_Import esrImport = InterfaceWrapperHelper.create(getCtx(), p_ESR_Import_ID, I_ESR_Import.class, get_TrxName()); if (esrImport == null) { throw new AdempiereException("@NotFound@ @ESR_Import_ID@"); } return esrImport; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\process\ESR_Import_LoadFromFile.java
1
请完成以下Java代码
public HistoricActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } // getters and setters // ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public String getAssignee() { return assignee; }
public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected static final <T extends AbstractTranslationEntity<?>> Map<String, T> mapByLanguage(final List<T> list) { if (list.isEmpty()) { return new HashMap<>(); } final Map<String, T> map = new HashMap<>(list.size()); for (final T e : list) { map.put(e.getLanguage(), e); } return map; } /** * Throws an {@link IllegalDeleteRequestException} if the given <code>syncModel</code> has <code>isDeleted</code>. */ protected void assertNotDeleteRequest(final IConfirmableDTO syncModel, final String reason) { if (syncModel.isDeleted()) { throw new IllegalDeleteRequestException("Setting Deleted flag to " + syncModel + " is not allowed while: " + reason); } }
protected <T extends IConfirmableDTO> T assertNotDeleteRequest_WarnAndFix(@NonNull final T syncModel, final String reason) { if (syncModel.isDeleted()) { logger.warn("Setting Deleted flag to " + syncModel + " is not allowed while: " + reason + ". Unsetting the flag and going forward."); return (T)syncModel.withNotDeleted(); } return syncModel; } private static class IllegalDeleteRequestException extends RuntimeException { private static final long serialVersionUID = 8217968386550762496L; IllegalDeleteRequestException(final String message) { super(message); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\AbstractSyncImportService.java
2
请在Spring Boot框架中完成以下Java代码
public class AppController { @Autowired private AppManagement appManagement; @GetMapping("/names.json") public Result<List<String>> queryApps(HttpServletRequest request) { return Result.ofSuccess(appManagement.getAppNames()); } @GetMapping("/briefinfos.json") public Result<List<AppInfo>> queryAppInfos(HttpServletRequest request) { List<AppInfo> list = new ArrayList<>(appManagement.getBriefApps()); Collections.sort(list, Comparator.comparing(AppInfo::getApp)); return Result.ofSuccess(list); } @GetMapping(value = "/{app}/machines.json") public Result<List<MachineInfoVo>> getMachinesByApp(@PathVariable("app") String app) { AppInfo appInfo = appManagement.getDetailApp(app); if (appInfo == null) { return Result.ofSuccess(null); } List<MachineInfo> list = new ArrayList<>(appInfo.getMachines());
Collections.sort(list, Comparator.comparing(MachineInfo::getApp).thenComparing(MachineInfo::getIp).thenComparingInt(MachineInfo::getPort)); return Result.ofSuccess(MachineInfoVo.fromMachineInfoList(list)); } @RequestMapping(value = "/{app}/machine/remove.json") public Result<String> removeMachineById( @PathVariable("app") String app, @RequestParam(name = "ip") String ip, @RequestParam(name = "port") int port) { AppInfo appInfo = appManagement.getDetailApp(app); if (appInfo == null) { return Result.ofSuccess(null); } if (appManagement.removeMachine(app, ip, port)) { return Result.ofSuccessMsg("success"); } else { return Result.ofFail(1, "remove failed"); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\AppController.java
2
请完成以下Java代码
public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Field Value. @param FieldValue Field Value */ public void setFieldValue (String FieldValue) { set_Value (COLUMNNAME_FieldValue, FieldValue); } /** Get Field Value. @return Field Value */ public String getFieldValue () { return (String)get_Value(COLUMNNAME_FieldValue); } /** Set Value Format. @param FieldValueFormat Value Format */ public void setFieldValueFormat (String FieldValueFormat) { set_Value (COLUMNNAME_FieldValueFormat, FieldValueFormat); } /** Get Value Format. @return Value Format */ public String getFieldValueFormat () { return (String)get_Value(COLUMNNAME_FieldValueFormat); } /** Set Null Value. @param IsNullFieldValue Null Value */ public void setIsNullFieldValue (boolean IsNullFieldValue) { set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue)); } /** Get Null Value. @return Null Value */ public boolean isNullFieldValue () { Object oo = get_Value(COLUMNNAME_IsNullFieldValue); 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 Eintraege; die kleinste Zahl kommt zuerst */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); }
/** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Type AD_Reference_ID=540203 */ public static final int TYPE_AD_Reference_ID=540203; /** Set Field Value = SV */ public static final String TYPE_SetFieldValue = "SV"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Action.java
1
请完成以下Java代码
static ZonedDateTime computeOrderLineDeliveryDate( @NonNull final I_C_OrderLine orderLine, @NonNull final I_C_Order order) { final ZonedDateTime presetDateShipped = TimeUtil.asZonedDateTime(orderLine.getPresetDateShipped()); if (presetDateShipped != null) { return presetDateShipped; } // Fetch it from order line if possible final ZonedDateTime datePromised = TimeUtil.asZonedDateTime(orderLine.getDatePromised()); if (datePromised != null) { return datePromised; } // Fetch it from order header if possible final ZonedDateTime datePromisedFromOrder = TimeUtil.asZonedDateTime(order.getDatePromised()); if (datePromisedFromOrder != null) { return datePromisedFromOrder; }
// Fail miserably... throw new AdempiereException("@NotFound@ @DeliveryDate@") .appendParametersToMessage() .setParameter("oderLine", orderLine) .setParameter("order", order); } private static DocumentLineDescriptor createDocumentLineDescriptor( @NonNull final OrderAndLineId orderAndLineId, @NonNull final I_C_Order order) { return OrderLineDescriptor.builder() .orderId(orderAndLineId.getOrderRepoId()) .orderLineId(orderAndLineId.getOrderLineRepoId()) .orderBPartnerId(order.getC_BPartner_ID()) .docTypeId(order.getC_DocType_ID()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\ShipmentScheduleOrderReferenceProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private final Log logger = LogFactory.getLog(this.getClass()); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); protected MySimpleUrlAuthenticationSuccessHandler() { super(); } // API @Override public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { handle(request, response, authentication); clearAuthenticationAttributes(request); } // IMPL protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { final String targetUrl = determineTargetUrl(authentication); if (response.isCommitted()) { logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); return; } redirectStrategy.sendRedirect(request, response, targetUrl); } protected String determineTargetUrl(final Authentication authentication) { boolean isUser = false; boolean isAdmin = false; final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_USER.toString())) { isUser = true; break; } else if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_ADMIN.toString())) { isAdmin = true; break; } } if (isUser) { return "/homepage.html"; } else if (isAdmin) { return "/console.html";
} else { throw new IllegalStateException(); } } /** * Removes temporary authentication-related data which may have been stored in the session * during the authentication process. */ protected final void clearAuthenticationAttributes(final HttpServletRequest request) { final HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return redirectStrategy; } }
repos\tutorials-master\spring-security-modules\spring-security-web-persistent-login\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
2
请在Spring Boot框架中完成以下Java代码
public WebSecurityCustomizer debugSecurity() { return (web) -> web.debug(true); } @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("user") .password(encoder().encode("userPass")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user); } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder();
} @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/admin/**") .hasRole("ADMIN") .anyRequest() .permitAll()) .httpBasic(withDefaults()) .formLogin(withDefaults()) .csrf(AbstractHttpConfigurer::disable); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\httpsecurityvswebsecurity\SecurityConfiguration.java
2
请完成以下Java代码
public HistoricDetailQueryImpl orderByVariableRevision() { orderBy(HistoricDetailQueryProperty.VARIABLE_REVISION); return this; } public HistoricDetailQueryImpl orderByVariableType() { orderBy(HistoricDetailQueryProperty.VARIABLE_TYPE); return this; } // getters and setters // ////////////////////////////////////////////////////// public String getId() { return id; } public String getProcessInstanceId() { return processInstanceId; } public String getTaskId() { return taskId; } public String getActivityId() { return activityId; }
public String getType() { return type; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getExecutionId() { return executionId; } public String getActivityInstanceId() { return activityInstanceId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricDetailQueryImpl.java
1
请完成以下Java代码
public Flux<ZipCode> postZipCode(@RequestParam String city) { return zipRepo.findByCity(city); } @PostMapping public Mono<ZipCode> create(@RequestBody ZipCode zipCode) { return getById(zipCode.getZip()) .switchIfEmpty(Mono.defer(createZipCode(zipCode))) .onErrorResume(this::isKeyDuplicated, this.recoverWith(zipCode)); } private Mono<ZipCode> getById(String zipCode) { return zipRepo.findById(zipCode); }
private boolean isKeyDuplicated(Throwable ex) { return ex instanceof DataIntegrityViolationException || ex instanceof UncategorizedR2dbcException; } private Function<? super Throwable, ? extends Mono<ZipCode>> recoverWith(ZipCode zipCode) { return throwable -> zipRepo.findById(zipCode.getZip()); } private Supplier<Mono<? extends ZipCode>> createZipCode(ZipCode zipCode) { return () -> { zipCode.setId(zipCode.getZip()); return zipRepo.save(zipCode); }; } }
repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\ZipCodeApi.java
1
请完成以下Java代码
public List<Coordinate> solve(Maze maze) { LinkedList<Coordinate> nextToVisit = new LinkedList<>(); Coordinate start = maze.getEntry(); nextToVisit.add(start); while (!nextToVisit.isEmpty()) { Coordinate cur = nextToVisit.remove(); if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) { continue; } if (maze.isWall(cur.getX(), cur.getY())) { maze.setVisited(cur.getX(), cur.getY(), true); continue; } if (maze.isExit(cur.getX(), cur.getY())) { return backtrackPath(cur); } for (int[] direction : DIRECTIONS) { Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur); nextToVisit.add(coordinate); maze.setVisited(cur.getX(), cur.getY(), true); }
} return Collections.emptyList(); } private List<Coordinate> backtrackPath(Coordinate cur) { List<Coordinate> path = new ArrayList<>(); Coordinate iter = cur; while (iter != null) { path.add(iter); iter = iter.parent; } return path; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\maze\solver\BFSMazeSolver.java
1
请完成以下Java代码
public static String processPattern(String pattern, TbMsg tbMsg) { try { String result = processPattern(pattern, tbMsg.getMetaData()); JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData()); result = result.replace(ALL_DATA_TEMPLATE, JacksonUtil.toString(json)); if (json.isObject()) { Matcher matcher = DATA_PATTERN.matcher(result); while (matcher.find()) { String group = matcher.group(2); String[] keys = group.split("\\."); JsonNode jsonNode = json; for (String key : keys) { if (StringUtils.isNotEmpty(key) && jsonNode != null) { jsonNode = jsonNode.get(key); } else { jsonNode = null; break; } } if (jsonNode != null && jsonNode.isValueNode()) { result = result.replace(formatDataVarTemplate(group), jsonNode.asText()); } } } return result; } catch (Exception e) { throw new RuntimeException("Failed to process pattern!", e); } } private static String processPattern(String pattern, TbMsgMetaData metaData) { String replacement = metaData.isEmpty() ? "{}" : JacksonUtil.toString(metaData.getData()); pattern = pattern.replace(ALL_METADATA_TEMPLATE, replacement); return processTemplate(pattern, metaData.values()); } public static String processTemplate(String template, Map<String, String> data) {
String result = template; for (Map.Entry<String, String> kv : data.entrySet()) { result = processVar(result, kv.getKey(), kv.getValue()); } return result; } private static String processVar(String pattern, String key, String val) { return pattern.replace(formatMetadataVarTemplate(key), val); } static String formatDataVarTemplate(String key) { return "$[" + key + "]"; } static String formatMetadataVarTemplate(String key) { return "${" + key + "}"; } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\util\TbNodeUtils.java
1
请在Spring Boot框架中完成以下Java代码
public String getPlatform() { return this.platform; } public void setPlatform(String platform) { this.platform = platform; } public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public boolean isContinueOnError() { return this.continueOnError; }
public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } public String getSeparator() { return this.separator; } public void setSeparator(String separator) { this.separator = separator; } public @Nullable Charset getEncoding() { return this.encoding; } public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; } public DatabaseInitializationMode getMode() { return this.mode; } public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\autoconfigure\init\SqlInitializationProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Money toMoney() {return relativeValue;} public @NonNull BigDecimal toBigDecimal() {return toMoney().toBigDecimal();} public Money toRealValueAsMoney() {return multiplier.convertToRealValue(relativeValue);} public BigDecimal toRealValueAsBigDecimal() {return toRealValueAsMoney().toBigDecimal();} public boolean isAP() {return multiplier.isAP();} public boolean isAPAdjusted() {return multiplier.isAPAdjusted();} public boolean isCreditMemo() {return multiplier.isCreditMemo();} public boolean isCMAdjusted() {return multiplier.isCreditMemoAdjusted();} public InvoiceTotal withAPAdjusted(final boolean isAPAdjusted) { return isAPAdjusted ? withAPAdjusted() : withoutAPAdjusted(); } public InvoiceTotal withAPAdjusted() { if (multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(true)); } } public InvoiceTotal withoutAPAdjusted() { if (!multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(false)); } } public InvoiceTotal withCMAdjusted(final boolean isCMAdjusted) { return isCMAdjusted ? withCMAdjusted() : withoutCMAdjusted();
} public InvoiceTotal withCMAdjusted() { if (multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(true)); } } public InvoiceTotal withoutCMAdjusted() { if (!multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(false)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceTotal.java
2
请完成以下Java代码
public org.compiere.model.I_M_AttributeSearch getM_AttributeSearch() { return get_ValueAsPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class); } @Override public void setM_AttributeSearch(final org.compiere.model.I_M_AttributeSearch M_AttributeSearch) { set_ValueFromPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class, M_AttributeSearch); } @Override public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_Value (COLUMNNAME_M_AttributeSearch_ID, null); else set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID); } @Override public int getM_AttributeSearch_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_ID); } @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); } @Override public void setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override) { set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override); } @Override public java.lang.String getPrintValue_Override() { return get_ValueAsString(COLUMNNAME_PrintValue_Override); } @Override public void setValue (final java.lang.String Value) {
set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueMax (final @Nullable BigDecimal ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public BigDecimal getValueMax() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueMin (final @Nullable BigDecimal ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public BigDecimal getValueMin() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
1
请完成以下Java代码
static Money extractLineNetAmt(final I_C_OrderLine orderLine) { return Money.of(orderLine.getLineNetAmt(), CurrencyId.ofRepoId(orderLine.getC_Currency_ID())); } static Quantity extractQtyEntered(final I_C_OrderLine orderLine) { final UomId uomId = UomId.ofRepoId(orderLine.getC_UOM_ID()); return Quantitys.of(orderLine.getQtyEntered(), uomId); } default boolean isCompleted(@NonNull final I_C_Order order) { return DocStatus.ofCode(order.getDocStatus()).isCompleted(); } DocStatus getDocStatus(OrderId orderId); void save(I_C_OrderLine orderLine); de.metas.interfaces.I_C_OrderLine createOrderLine(I_C_Order order); void setProductId( @NonNull I_C_OrderLine orderLine, @NonNull ProductId productId, boolean setUOM); CurrencyConversionContext getCurrencyConversionContext(I_C_Order order); void deleteLineById(final OrderAndLineId orderAndLineId);
String getDescriptionBottomById(@NonNull OrderId orderId); String getDescriptionById(@NonNull OrderId orderId); void setShipperId(@NonNull I_C_Order order); default boolean isLUQtySet(final @NonNull de.metas.interfaces.I_C_OrderLine orderLine) { final BigDecimal luQty = orderLine.getQtyLU(); return luQty != null && luQty.signum() > 0; } PaymentTermId getPaymentTermId(@NonNull I_C_Order orderRecord); Money getGrandTotal(@NonNull I_C_Order order); void save(I_C_Order order); void syncDatesFromTransportOrder(@NonNull OrderId orderId, @NonNull I_M_ShipperTransportation transportOrder); void syncDateInvoicedFromInvoice(@NonNull OrderId orderId, @NonNull I_C_Invoice invoice); List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\IOrderBL.java
1
请完成以下Java代码
protected Date calculateRemovalTime(HistoricDecisionInstanceEntity historicDecisionInstance, DecisionDefinition decisionDefinition) { return Context.getProcessEngineConfiguration() .getHistoryRemovalTimeProvider() .calculateRemovalTime(historicDecisionInstance, decisionDefinition); } protected void provideRemovalTime(HistoryEvent historyEvent) { String rootProcessInstanceId = historyEvent.getRootProcessInstanceId(); if (rootProcessInstanceId != null) { HistoricProcessInstanceEventEntity historicRootProcessInstance = getHistoricRootProcessInstance(rootProcessInstanceId); if (historicRootProcessInstance != null) { Date removalTime = historicRootProcessInstance.getRemovalTime(); historyEvent.setRemovalTime(removalTime); } } }
protected boolean isHistoryRemovalTimeStrategyStart() { return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy()); } protected String getHistoryRemovalTimeStrategy() { return Context.getProcessEngineConfiguration() .getHistoryRemovalTimeStrategy(); } protected HistoricProcessInstanceEventEntity getHistoricRootProcessInstance(String rootProcessInstanceId) { return Context.getCommandContext().getDbEntityManager() .selectById(HistoricProcessInstanceEventEntity.class, rootProcessInstanceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultDmnHistoryEventProducer.java
1
请完成以下Java代码
public BatchStatisticsQuery withoutTenantId() { this.tenantIds = null; isTenantIdSet = true; return this; } public BatchStatisticsQuery active() { this.suspensionState = SuspensionState.ACTIVE; return this; } public BatchStatisticsQuery suspended() { this.suspensionState = SuspensionState.SUSPENDED; return this; } @Override public BatchStatisticsQuery createdBy(final String userId) { this.userId = userId; return this; } @Override public BatchStatisticsQuery startedBefore(final Date date) { this.startedBefore = date; return this; } @Override public BatchStatisticsQuery startedAfter(final Date date) { this.startedAfter = date; return this; } @Override public BatchStatisticsQuery withFailures() { this.hasFailure = true; return this; } @Override public BatchStatisticsQuery withoutFailures() { this.hasFailure = false; return this; }
public SuspensionState getSuspensionState() { return suspensionState; } public BatchStatisticsQuery orderById() { return orderBy(BatchQueryProperty.ID); } @Override public BatchStatisticsQuery orderByTenantId() { return orderBy(BatchQueryProperty.TENANT_ID); } @Override public BatchStatisticsQuery orderByStartTime() { return orderBy(BatchQueryProperty.START_TIME); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsCountGroupedByBatch(this); } public List<BatchStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsGroupedByBatch(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchStatisticsQueryImpl.java
1
请完成以下Java代码
public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getExternalTaskId() { return externalTaskId; } public void setExternalTaskId(String externalTaskId) { this.externalTaskId = externalTaskId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override
public String toString() { return this.getClass().getSimpleName() + "[taskId=" + taskId + ", deploymentId=" + deploymentId + ", processDefinitionKey=" + processDefinitionKey + ", jobId=" + jobId + ", jobDefinitionId=" + jobDefinitionId + ", batchId=" + batchId + ", operationId=" + operationId + ", operationType=" + operationType + ", userId=" + userId + ", timestamp=" + timestamp + ", property=" + property + ", orgValue=" + orgValue + ", newValue=" + newValue + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", externalTaskId=" + externalTaskId + ", tenantId=" + tenantId + ", entityType=" + entityType + ", category=" + category + ", annotation=" + annotation + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public int getLockTimeInMillis() { return jobExecutor.getLockTimeInMillis(); } public void setLockTimeInMillis(int lockTimeInMillis) { jobExecutor.setLockTimeInMillis(lockTimeInMillis); } public String getLockOwner() { return jobExecutor.getLockOwner(); } public void setLockOwner(String lockOwner) { jobExecutor.setLockOwner(lockOwner); } public int getMaxJobsPerAcquisition() { return jobExecutor.getMaxJobsPerAcquisition(); } public void setMaxJobsPerAcquisition(int maxJobsPerAcquisition) {
jobExecutor.setMaxJobsPerAcquisition(maxJobsPerAcquisition); } public String getName() { return jobExecutor.getName(); } public JobExecutor getValue() { return jobExecutor; } public boolean isActive() { return jobExecutor.isActive(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedJobExecutor.java
2
请完成以下Java代码
public final class RedisSessionMapper implements BiFunction<String, Map<String, Object>, MapSession> { /** * The key in the hash representing {@link Session#getCreationTime()}. */ static final String CREATION_TIME_KEY = "creationTime"; /** * The key in the hash representing {@link Session#getLastAccessedTime()}. */ static final String LAST_ACCESSED_TIME_KEY = "lastAccessedTime"; /** * The key in the hash representing {@link Session#getMaxInactiveInterval()}. */ static final String MAX_INACTIVE_INTERVAL_KEY = "maxInactiveInterval"; /** * The prefix of the key in the hash used for session attributes. For example, if the * session contained an attribute named {@code attributeName}, then there would be an * entry in the hash named {@code sessionAttr:attributeName} that mapped to its value. */ static final String ATTRIBUTE_PREFIX = "sessionAttr:"; private static void handleMissingKey(String key) { throw new IllegalStateException(key + " key must not be null"); } @Override public MapSession apply(String sessionId, Map<String, Object> map) { Assert.hasText(sessionId, "sessionId must not be empty"); Assert.notEmpty(map, "map must not be empty"); MapSession session = new MapSession(sessionId); Long creationTime = (Long) map.get(CREATION_TIME_KEY);
if (creationTime == null) { handleMissingKey(CREATION_TIME_KEY); } session.setCreationTime(Instant.ofEpochMilli(creationTime)); Long lastAccessedTime = (Long) map.get(LAST_ACCESSED_TIME_KEY); if (lastAccessedTime == null) { handleMissingKey(LAST_ACCESSED_TIME_KEY); } session.setLastAccessedTime(Instant.ofEpochMilli(lastAccessedTime)); Integer maxInactiveInterval = (Integer) map.get(MAX_INACTIVE_INTERVAL_KEY); if (maxInactiveInterval == null) { handleMissingKey(MAX_INACTIVE_INTERVAL_KEY); } session.setMaxInactiveInterval(Duration.ofSeconds(maxInactiveInterval)); map.forEach((name, value) -> { if (name.startsWith(ATTRIBUTE_PREFIX)) { session.setAttribute(name.substring(ATTRIBUTE_PREFIX.length()), value); } }); return session; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionMapper.java
1
请在Spring Boot框架中完成以下Java代码
private JsonResponseBPartnerCompositeUpsertItem getResponseItemBySourceBPIdentifier( @NonNull final String sourceBPIdentifier, @NonNull final List<JsonResponseBPartnerCompositeUpsertItem> responseItems) { return responseItems .stream() .filter(upsertItem -> upsertItem.getResponseBPartnerItem() != null && sourceBPIdentifier.equals(upsertItem.getResponseBPartnerItem().getIdentifier())) .findFirst() .orElseThrow(() -> new RuntimeCamelException("No JsonResponseBPartnerCompositeUpsertItem found for sourceBPIdentifier:" + sourceBPIdentifier)); } @NonNull private JsonMetasfreshId getSourceLocationMFIdByIdentifier( @NonNull final String locationIdentifier, @NonNull final JsonResponseBPartnerCompositeUpsertItem bpartnerUpsertResponseItem) { if (bpartnerUpsertResponseItem.getResponseLocationItems() == null || bpartnerUpsertResponseItem.getResponseLocationItems().isEmpty()) { throw new RuntimeCamelException("Empty JsonResponseBPartnerCompositeUpsertItem.getResponseLocationItems! Location identifier: " + locationIdentifier); } return bpartnerUpsertResponseItem.getResponseLocationItems() .stream() .filter(locationRespItem -> locationIdentifier.equals(locationRespItem.getIdentifier())) .map(JsonResponseUpsertItem::getMetasfreshId) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new RuntimeCamelException("No JsonMetasfreshId found for locationIdentifier: " + locationIdentifier));
} @NonNull private JsonMetasfreshId getFirstLocationMFId(@NonNull final JsonResponseBPartnerCompositeUpsertItem bpartnerUpsertResponseItem) { if (bpartnerUpsertResponseItem.getResponseLocationItems() == null || bpartnerUpsertResponseItem.getResponseLocationItems().isEmpty()) { throw new RuntimeCamelException("The given JsonResponseBPartnerCompositeUpsertItem has no responseLocationItems!; bpartnerUpsertResponseItem=" + bpartnerUpsertResponseItem); } return bpartnerUpsertResponseItem.getResponseLocationItems() .stream() .map(JsonResponseUpsertItem::getMetasfreshId) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new RuntimeCamelException("No location JsonResponseUpsertItem found!")); } @NonNull private JsonMetasfreshId getBPartnerMetasfreshId(@NonNull final JsonResponseBPartnerCompositeUpsertItem bpUpsertItem) { if (bpUpsertItem.getResponseBPartnerItem() == null || bpUpsertItem.getResponseBPartnerItem().getMetasfreshId() == null) { throw new RuntimeCamelException("ResponseBPartnerItem.JsonMetasfreshId is missing for bpUpsertItem: " + bpUpsertItem); } return bpUpsertItem.getResponseBPartnerItem().getMetasfreshId(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\processor\CreateBPRelationReqProcessor.java
2
请完成以下Java代码
public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set AD_Window_Access. @param AD_Window_Access_ID AD_Window_Access */ @Override public void setAD_Window_Access_ID (int AD_Window_Access_ID) { if (AD_Window_Access_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Window_Access_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Window_Access_ID, Integer.valueOf(AD_Window_Access_ID)); } /** Get AD_Window_Access. @return AD_Window_Access */ @Override public int getAD_Window_Access_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_Access_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class); } @Override public void setAD_Window(org.compiere.model.I_AD_Window AD_Window) { set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window); } /** Set Fenster. @param AD_Window_ID Data entry or display window */ @Override public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null);
else set_ValueNoCheck (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Fenster. @return Data entry or display window */ @Override public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); } /** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window_Access.java
1
请在Spring Boot框架中完成以下Java代码
public TimeUnit getBaseTimeUnit() { return this.baseTimeUnit; } public void setBaseTimeUnit(TimeUnit baseTimeUnit) { this.baseTimeUnit = baseTimeUnit; } public Map<String, Meter> getMeter() { return this.meter; } /** * Per-meter settings. */ public static class Meter { /** * Maximum number of buckets to be used for exponential histograms, if configured. * This has no effect on explicit bucket histograms. */ private @Nullable Integer maxBucketCount; /** * Histogram type when histogram publishing is enabled. */ private @Nullable HistogramFlavor histogramFlavor; public @Nullable Integer getMaxBucketCount() { return this.maxBucketCount; }
public void setMaxBucketCount(@Nullable Integer maxBucketCount) { this.maxBucketCount = maxBucketCount; } public @Nullable HistogramFlavor getHistogramFlavor() { return this.histogramFlavor; } public void setHistogramFlavor(@Nullable HistogramFlavor histogramFlavor) { this.histogramFlavor = histogramFlavor; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsProperties.java
2