instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class DocOutboundUtils { public I_C_Doc_Outbound_Log_Line createOutboundLogLineRecord(@NonNull final I_C_Doc_Outbound_Log docOutboundLog) { Check.assume(!isNew(docOutboundLog), "The given docOutboundLog needs to be saved; docOutboundLog={}", docOutboundLog); final Properties ctx = getCtx(docOutboundLog); final I_C_Doc_Outbound_Log_Line docOutboundLogLineRecord = newInstance(I_C_Doc_Outbound_Log_Line.class); docOutboundLogLineRecord.setC_Doc_Outbound_Log_ID(docOutboundLog.getC_Doc_Outbound_Log_ID()); docOutboundLogLineRecord.setAD_Org_ID(docOutboundLog.getAD_Org_ID()); docOutboundLogLineRecord.setAD_Table_ID(docOutboundLog.getAD_Table_ID()); docOutboundLogLineRecord.setRecord_ID(docOutboundLog.getRecord_ID());
final IDocumentBL documentBL = Services.get(IDocumentBL.class); final String documentNo = documentBL.getDocumentNo(ctx, docOutboundLog.getAD_Table_ID(), docOutboundLog.getRecord_ID()); docOutboundLogLineRecord.setDocumentNo(documentNo); final TableRecordReference reference = TableRecordReference.ofReferenced(docOutboundLog); final DocStatus docStatus = documentBL.getDocStatusOrNull(reference); docOutboundLogLineRecord.setDocStatus(DocStatus.toCodeOrNull(docStatus)); final int doctypeID = documentBL.getC_DocType_ID(ctx, docOutboundLog.getAD_Table_ID(), docOutboundLog.getRecord_ID()); docOutboundLogLineRecord.setC_DocType_ID(doctypeID); return docOutboundLogLineRecord; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\DocOutboundUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class DataEntry_Field { public DataEntry_Field() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteChildRecords(@NonNull final I_DataEntry_Field dataEntryFieldRecord) { Services.get(IQueryBL.class) .createQueryBuilder(I_DataEntry_ListValue.class) .addEqualsFilter(I_DataEntry_ListValue.COLUMN_DataEntry_Field_ID, dataEntryFieldRecord.getDataEntry_Field_ID()) .create() .delete(); } @CalloutMethod(columnNames = I_DataEntry_Field.COLUMNNAME_DataEntry_Line_ID) public void setSeqNo(@NonNull final I_DataEntry_Field dataEntryFieldRecord)
{ if (dataEntryFieldRecord.getDataEntry_Line_ID() <= 0) { return; } dataEntryFieldRecord.setSeqNo(maxSeqNo(dataEntryFieldRecord) + 10); } private int maxSeqNo(@NonNull final I_DataEntry_Field dataEntryFieldRecord) { return Services .get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Field.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DataEntry_Field.COLUMN_DataEntry_Line_ID, dataEntryFieldRecord.getDataEntry_Line_ID()) .create() .maxInt(I_DataEntry_Tab.COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\interceptor\DataEntry_Field.java
2
请完成以下Java代码
public class MyBatisUtil { public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver"; public static final String URL = "jdbc:derby:testdb1;create=true"; public static final String USERNAME = "sa"; public static final String PASSWORD = "pass123"; private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory buildqlSessionFactory() { DataSource dataSource = new PooledDataSource(DRIVER, URL, USERNAME, PASSWORD); Environment environment = new Environment("Development", new JdbcTransactionFactory(), dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(PersonMapper.class); configuration.addMapper(AddressMapper.class); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(configuration); return factory;
} public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public String getPersonByName(String name) { return new SQL() { { SELECT("*"); FROM("person"); WHERE("name like #{name} || '%'"); } }.toString(); } }
repos\tutorials-master\mybatis\src\main\java\com\baeldung\mybatis\utils\MyBatisUtil.java
1
请完成以下Java代码
public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic) { set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic); } @Override public java.lang.String getReadOnlyLogic() { return get_ValueAsString(COLUMNNAME_ReadOnlyLogic); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTabLevel (final int TabLevel) { set_Value (COLUMNNAME_TabLevel, TabLevel); } @Override public int getTabLevel() { return get_ValueAsInt(COLUMNNAME_TabLevel); } @Override public org.compiere.model.I_AD_Tab getTemplate_Tab() { return get_ValueAsPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class);
} @Override public void setTemplate_Tab(final org.compiere.model.I_AD_Tab Template_Tab) { set_ValueFromPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class, Template_Tab); } @Override public void setTemplate_Tab_ID (final int Template_Tab_ID) { if (Template_Tab_ID < 1) set_Value (COLUMNNAME_Template_Tab_ID, null); else set_Value (COLUMNNAME_Template_Tab_ID, Template_Tab_ID); } @Override public int getTemplate_Tab_ID() { return get_ValueAsInt(COLUMNNAME_Template_Tab_ID); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tab.java
1
请完成以下Java代码
protected final LocalDate getDocumentDate(@Nullable final Object model) { if (model == null) { return null; } if (model instanceof I_C_OrderLine) { return TimeUtil.asLocalDate(((I_C_OrderLine)model).getDateOrdered()); } final IDocument doc = getDocumentOrNull(model); if (doc != null) { return doc.getDocumentDate(); } // in case the log is not made for one of these tables leave the dateDoc empty return null; } @Override public final String getSummary(@NonNull final Object model) { final IDocument doc = getDocumentOrNull(model); if (doc != null) { return doc.getSummary(); } // Fallback: use toString() return String.valueOf(model); } @Override public boolean isReversalDocument(@NonNull final Object model) { // Try Reversal_ID column if available final Integer original_ID = InterfaceWrapperHelper.getValueOrNull(model, IDocument.Reversal_ID); if (original_ID != null && original_ID > 0) { final int reversal_id = InterfaceWrapperHelper.getId(model); return reversal_id > original_ID; } return false; } @Override public final Map<String, IDocActionItem> retrieveDocActionItemsIndexedByValue() { final ADReferenceService adReferenceService = ADReferenceService.get(); final Properties ctx = Env.getCtx(); final String adLanguage = Env.getAD_Language(ctx); return adReferenceService.retrieveListItems(X_C_Order.DOCACTION_AD_Reference_ID) // 135 .stream() .map(adRefListItem -> new DocActionItem(adRefListItem, adLanguage)) .sorted(Comparator.comparing(DocActionItem::toString))
.collect(GuavaCollectors.toImmutableMapByKey(IDocActionItem::getValue)); } private static final class DocActionItem implements IDocActionItem { private final String value; private final String caption; private final String description; private DocActionItem(final ADRefListItem adRefListItem, final String adLanguage) { this.value = adRefListItem.getValue(); this.caption = adRefListItem.getName().translate(adLanguage); this.description = adRefListItem.getDescription().translate(adLanguage); } @Override public String toString() { // IMPORTANT: this is how it will be displayed to user return caption; } @Override public int hashCode() { return Objects.hashCode(value); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof DocActionItem) { final DocActionItem other = (DocActionItem)obj; return Objects.equal(value, other.value); } else { return false; } } @Override public String getValue() { return value; } @Override public String getDescription() { return description; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\AbstractDocumentBL.java
1
请完成以下Java代码
public int getLastDeleted () { Integer ii = (Integer)get_Value(COLUMNNAME_LastDeleted); if (ii == null) return 0; return ii.intValue(); } /** Set Last Run. @param LastRun Last Run */ public void setLastRun (Timestamp LastRun) { set_Value (COLUMNNAME_LastRun, LastRun); } /** Get Last Run. @return Last Run */ public Timestamp getLastRun () { return (Timestamp)get_Value(COLUMNNAME_LastRun); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** 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; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_HouseKeeping.java
1
请完成以下Java代码
public Price2 getDealPric() { return dealPric; } /** * Sets the value of the dealPric property. * * @param value * allowed object is * {@link Price2 } * */ public void setDealPric(Price2 value) { this.dealPric = value; } /** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryPrice2 } * * */ public List<ProprietaryPrice2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryPrice2>(); } return this.prtry; } }
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\TransactionPrice3Choice.java
1
请完成以下Java代码
public class C_Project_UnClose extends JavaProcess implements IProcessPrecondition { private final ProjectService projectService = SpringContextHolder.instance.getBean(ProjectService.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a single selection"); } final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (projectId == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("no project selected"); }
if (!projectService.isClosed(projectId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("projectis not closed"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final ProjectId projectId = ProjectId.ofRepoId(getRecord_ID()); projectService.uncloseProject(projectId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\process\C_Project_UnClose.java
1
请完成以下Java代码
public Mono<Void> deleteById(String id) { return Mono.fromRunnable(() -> this.sessions.remove(id)); } @Override public Mono<MapSession> createSession() { // @formatter:off return Mono.fromSupplier(() -> this.sessionIdGenerator.generate()) .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) .map((sessionId) -> { MapSession result = new MapSession(sessionId); result.setMaxInactiveInterval(this.defaultMaxInactiveInterval); result.setSessionIdGenerator(this.sessionIdGenerator); return result;
}); // @formatter:on } /** * Sets the {@link SessionIdGenerator} to use. * @param sessionIdGenerator the non-null {@link SessionIdGenerator} to use * @since 3.2 */ public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { Assert.notNull(sessionIdGenerator, "sessionIdGenerator cannot be null"); this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\ReactiveMapSessionRepository.java
1
请完成以下Java代码
public static class KeyValuePair { private String key; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = String.class, name = "string"), @JsonSubTypes.Type(value = Long.class, name = "long"), @JsonSubTypes.Type(value = Integer.class, name = "int") }) private Object value; public KeyValuePair() { } public KeyValuePair(String key, Object value) { this.key = key; this.value = value; } public String getKey() {
return key; } public void setKey(String key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } }
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\specifictype\dtos\PersonDTOWithType.java
1
请完成以下Java代码
public List<CaseDefinitionDto> getCaseDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { CaseDefinitionQueryDto queryDto = new CaseDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); List<CaseDefinitionDto> definitions = new ArrayList<CaseDefinitionDto>(); ProcessEngine engine = getProcessEngine(); CaseDefinitionQuery query = queryDto.toQuery(engine); List<CaseDefinition> matchingDefinitions = QueryUtil.list(query, firstResult, maxResults); for (CaseDefinition definition : matchingDefinitions) { CaseDefinitionDto def = CaseDefinitionDto.fromCaseDefinition(definition); definitions.add(def); } return definitions; }
@Override public CountResultDto getCaseDefinitionsCount(UriInfo uriInfo) { CaseDefinitionQueryDto queryDto = new CaseDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); ProcessEngine engine = getProcessEngine(); CaseDefinitionQuery query = queryDto.toQuery(engine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseDefinitionRestServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class RpUserBankAuth extends BaseEntity implements Serializable { private static final long serialVersionUID = 6173089060762552675L; /** * 商户号 */ private String merchantNo; /** * 支付订单号 */ private String payOrderNo; /** * 用户名称 */ private String userName; /** * 手机号 */ private String phone; /** * 身份证号 */ private String idNo; /** * 银行卡号 */ private String bankAccountNo; public String getMerchantNo() { return merchantNo; } public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo; } public String getPayOrderNo() { return payOrderNo; } public void setPayOrderNo(String payOrderNo) { this.payOrderNo = payOrderNo; } public String getUserName() {
return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpUserBankAuth.java
2
请完成以下Java代码
String run(@Nullable Consumer<String> outputConsumer, String... command) { logger.trace(LogMessage.of(() -> "Running '%s'".formatted(String.join(" ", command)))); Process process = startProcess(command); ReaderThread stdOutReader = new ReaderThread(process.getInputStream(), "stdout", outputConsumer); ReaderThread stdErrReader = new ReaderThread(process.getErrorStream(), "stderr", outputConsumer); logger.trace("Waiting for process exit"); int exitCode = waitForProcess(process); logger.trace(LogMessage.format("Process exited with exit code %d", exitCode)); String stdOut = stdOutReader.toString(); String stdErr = stdErrReader.toString(); if (exitCode != 0) { throw new ProcessExitException(exitCode, command, stdOut, stdErr); } return stdOut; } private Process startProcess(String[] command) { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(this.workingDirectory); try { return processBuilder.start(); } catch (IOException ex) { String path = processBuilder.environment().get("PATH"); if (MAC_OS && path != null && !path.contains(USR_LOCAL_BIN) && !command[0].startsWith(USR_LOCAL_BIN + "/")) { String[] localCommand = command.clone(); localCommand[0] = USR_LOCAL_BIN + "/" + localCommand[0]; return startProcess(localCommand); } throw new ProcessStartException(command, ex); } } private int waitForProcess(Process process) { try { return process.waitFor(); } catch (InterruptedException ex) { throw new IllegalStateException("Interrupted waiting for %s".formatted(process)); } } /** * Thread used to read stream input from the process. */ private static class ReaderThread extends Thread { private final InputStream source; private final @Nullable Consumer<String> outputConsumer; private final StringBuilder output = new StringBuilder(); private final CountDownLatch latch = new CountDownLatch(1); ReaderThread(InputStream source, String name, @Nullable Consumer<String> outputConsumer) { this.source = source;
this.outputConsumer = outputConsumer; setName("OutputReader-" + name); setDaemon(true); start(); } @Override public void run() { try (BufferedReader reader = new BufferedReader( new InputStreamReader(this.source, StandardCharsets.UTF_8))) { String line = reader.readLine(); while (line != null) { this.output.append(line); this.output.append("\n"); if (this.outputConsumer != null) { this.outputConsumer.accept(line); } line = reader.readLine(); } this.latch.countDown(); } catch (IOException ex) { throw new UncheckedIOException("Failed to read process stream", ex); } } @Override public String toString() { try { this.latch.await(); return this.output.toString(); } catch (InterruptedException ex) { return ""; } } } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\ProcessRunner.java
1
请完成以下Java代码
public LookupValuesList getDeviceIds() { return deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() .streamAllDeviceAccessors() .map(PrintDeviceQRCodes::toLookupValue) .distinct() .collect(LookupValuesList.collect()); } private static LookupValue toLookupValue(DeviceAccessor deviceAccessor) { return LookupValue.StringLookupValue.of(deviceAccessor.getId().getAsString(), deviceAccessor.getDisplayName()); } @Override protected String doIt() { final ImmutableList<PrintableQRCode> qrCodes = streamSelectedDevices() .map(PrintDeviceQRCodes::toDeviceQRCode) .map(DeviceQRCode::toPrintableQRCode) .collect(ImmutableList.toImmutableList()); final QRCodePDFResource pdf = globalQRCodeService.createPDF(qrCodes); getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType()); return MSG_OK; } private Stream<DeviceAccessor> streamSelectedDevices() {
final DeviceId onlyDeviceId = StringUtils.trimBlankToOptional(p_deviceIdStr) .map(DeviceId::ofString) .orElse(null); if (onlyDeviceId != null) { final DeviceAccessor deviceAccessor = deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() .getDeviceAccessorById(onlyDeviceId) .orElseThrow(() -> new AdempiereException("No device found for id: " + onlyDeviceId)); return Stream.of(deviceAccessor); } else { return deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() .streamAllDeviceAccessors(); } } private static DeviceQRCode toDeviceQRCode(final DeviceAccessor deviceAccessor) { return DeviceQRCode.builder() .deviceId(deviceAccessor.getId()) .caption(deviceAccessor.getDisplayName().getDefaultValue()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\devices\webui\process\PrintDeviceQRCodes.java
1
请完成以下Java代码
public CostAmount convertToAcctSchemaCurrency( final CostAmount amt, final CostDetailCreateRequest request) { final AcctSchemaId acctSchemaId = request.getAcctSchemaId(); return convertToAcctSchemaCurrency( amt, () -> getCurrencyConversionContext(request), acctSchemaId); } public CostAmount convertToAcctSchemaCurrency( @NonNull final CostAmount amt, @NonNull final Supplier<CurrencyConversionContext> conversionCtxSupplier, @NonNull final AcctSchemaId acctSchemaId) { final AcctSchema acctSchema = getAcctSchemaById(acctSchemaId); final CurrencyId acctCurrencyId = acctSchema.getCurrencyId(); if (CurrencyId.equals(amt.getCurrencyId(), acctCurrencyId)) { return amt; } final CurrencyConversionContext conversionCtx = conversionCtxSupplier.get() .withPrecision(acctSchema.getCosting().getCostingPrecision()); final CurrencyConversionResult result = convert( conversionCtx, amt.toMoney(), acctCurrencyId);
return CostAmount.of(result.getAmount(), acctCurrencyId, result.getSourceAmount(), result.getSourceCurrencyId()); } @NonNull public CurrencyConversionResult convert( final CurrencyConversionContext conversionCtx, final Money price, final CurrencyId acctCurrencyId) { return currencyBL.convert(conversionCtx, price, acctCurrencyId); } private CurrencyConversionContext getCurrencyConversionContext(final CostDetailCreateRequest request) { final CurrencyConversionContext currencyConversionContext = request.getCurrencyConversionContext(); return CoalesceUtil.coalesceSuppliersNotNull( () -> currencyConversionContext, () -> currencyBL.createCurrencyConversionContext( request.getDate(), (CurrencyConversionTypeId)null, request.getClientId(), request.getOrgId())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostingMethodHandlerUtils.java
1
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getTimezone() { return timezone;
} public void setTimezone(String timezone) { this.timezone = timezone; } @JsonIgnore @Override public String getId() { return zip; } @JsonIgnore @Override public boolean isNew() { return !persisted; } }
repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\domain\ZipCode.java
1
请完成以下Java代码
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { setMdc(request); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { super.afterCompletion(request, response, handler, ex); deleteMdc(); } /** * 为每个请求设置唯一标示到MDC容器中 */ private void setMdc(HttpServletRequest request) { try { // 设置SessionId String requestId = UUID.randomUUID().toString().replace("-", ""); MDC.put(MdcConstant.SESSION_KEY, "userId"); MDC.put(MdcConstant.REQUEST_KEY, requestId); } catch (Exception e) { logger.warn(e.getMessage(), e);
} } /** * 删除MDC标示 */ private void deleteMdc() { try { MDC.remove(MdcConstant.SESSION_KEY); MDC.remove(MdcConstant.REQUEST_KEY); } catch (Exception e) { logger.warn(e.getMessage(), e); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\interceptors\TrackInterceptor.java
1
请完成以下Java代码
public ResourceParameter newInstance(ModelTypeInstanceContext instanceContext) { return new ResourceParameterImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); typeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TYPE) .qNameAttributeReference(ItemDefinition.class) .build(); isRequiredAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_REQUIRED) .build(); typeBuilder.build(); } public ResourceParameterImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); }
public ItemDefinition getType() { return typeAttribute.getReferenceTargetElement(this); } public void setType(ItemDefinition type) { typeAttribute.setReferenceTargetElement(this, type); } public boolean isRequired() { return isRequiredAttribute.getValue(this); } public void setRequired(boolean isRequired) { isRequiredAttribute.setValue(this, isRequired); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceParameterImpl.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 Qualität-Notiz. @param M_QualityNote_ID Qualität-Notiz */ @Override public void setM_QualityNote_ID (int M_QualityNote_ID) { if (M_QualityNote_ID < 1) set_ValueNoCheck (COLUMNNAME_M_QualityNote_ID, null); else set_ValueNoCheck (COLUMNNAME_M_QualityNote_ID, Integer.valueOf(M_QualityNote_ID)); } /** Get Qualität-Notiz. @return Qualität-Notiz */ @Override public int getM_QualityNote_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityNote_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * PerformanceType AD_Reference_ID=540689 * Reference name: R_Request.PerformanceType */ public static final int PERFORMANCETYPE_AD_Reference_ID=540689; /** Liefer Performance = LP */ public static final String PERFORMANCETYPE_LieferPerformance = "LP"; /** Quality Performance = QP */ public static final String PERFORMANCETYPE_QualityPerformance = "QP";
/** Set PerformanceType. @param PerformanceType PerformanceType */ @Override public void setPerformanceType (java.lang.String PerformanceType) { set_Value (COLUMNNAME_PerformanceType, PerformanceType); } /** Get PerformanceType. @return PerformanceType */ @Override public java.lang.String getPerformanceType () { return (java.lang.String)get_Value(COLUMNNAME_PerformanceType); } /** 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_ValueNoCheck (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.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_QualityNote.java
1
请完成以下Java代码
private ImmutableSet<Integer> retrieveLocatorIds() { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_M_Transaction> queryBuilder = queryBL.createQueryBuilder(I_M_Transaction.class) .addOnlyActiveRecordsFilter(); if (minimumPrice.signum() < 0) { final Set<ProductId> productIds = Services.get(IPriceListDAO.class).retrieveHighPriceProducts(getMinimumPrice(), getMovementDate()); if (!productIds.isEmpty()) { queryBuilder.addInArrayFilter(I_M_Transaction.COLUMNNAME_M_Product_ID, productIds); } } final ImmutableSetMultimap<Integer, ProductId> productsByLocatorIds = queryBuilder .create() .listDistinct(I_M_Transaction.COLUMNNAME_M_Locator_ID, I_M_Transaction.COLUMNNAME_M_Product_ID, I_M_Transaction.COLUMNNAME_MovementDate, I_M_Transaction.COLUMNNAME_MovementType) .stream() .map(record -> { return TransactionContext.builder() .locatorId((int)record.get(I_M_Locator.COLUMNNAME_M_Locator_ID)) .productId(ProductId.ofRepoId((int)record.get(I_M_Product.COLUMNNAME_M_Product_ID)))
.movementType((String)record.get(I_M_Transaction.COLUMNNAME_MovementType)) .movementDate(TimeUtil.asLocalDate(record.get(I_M_Transaction.COLUMNNAME_MovementDate))) .build(); }) .sorted(TRANSACTIONS_COMPARATOR) .map(transaction -> { return GuavaCollectors.entry(transaction.getLocatorId(), transaction.getProductId()); }).collect(GuavaCollectors.toImmutableSetMultimap()); return productsByLocatorIds.keySet(); } private WarehouseId mapToWarehouseId(final int locatorId) { final I_M_Locator locator = InterfaceWrapperHelper.load(locatorId, I_M_Locator.class); return WarehouseId.ofRepoId(locator.getM_Warehouse_ID()); } @Override public int getMaxLocatorsAllowed() { return maxLocators; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\LeastRecentTransactionStrategy.java
1
请完成以下Java代码
public void collectDisplayedIfChanged(final IDocumentFieldView documentField, final LogicExpressionResult valueOld, final ReasonSupplier reason) { // do nothing } @Override public void collectLookupValuesStaled(final IDocumentFieldView documentField, final ReasonSupplier reason) { // do nothing } @Override public void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning) { // do nothing } @Override public void collectFrom(final IDocumentChangesCollector fromCollector) { // do nothing } @Override public Set<String> collectFrom(final Document document, final ReasonSupplier reason) { return ImmutableSet.of(); // nothing collected } @Override public void collectDocumentValidStatusChanged(final DocumentPath documentPath, final DocumentValidStatus documentValidStatus) { // do nothing } @Override public void collectValidStatus(final IDocumentFieldView documentField) { // do nothing } @Override public void collectDocumentSaveStatusChanged(final DocumentPath documentPath, final DocumentSaveStatus documentSaveStatus) { // do nothing } @Override public void collectDeleted(final DocumentPath documentPath) { // do nothing }
@Override public void collectStaleDetailId(final DocumentPath rootDocumentPath, final DetailId detailId) { // do nothing } @Override public void collectAllowNew(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew) { // do nothing } @Override public void collectAllowDelete(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete) { // do nothing } @Override public void collectEvent(final IDocumentFieldChangedEvent event) { // do nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\NullDocumentChangesCollector.java
1
请完成以下Java代码
public final class Handlers { private static final String PROTOCOL_HANDLER_PACKAGES = "java.protocol.handler.pkgs"; private static final String PACKAGE = Handlers.class.getPackageName(); private Handlers() { } /** * Register a {@literal 'java.protocol.handler.pkgs'} property so that a * {@link URLStreamHandler} will be located to deal with jar URLs. */ public static void register() { String packages = System.getProperty(PROTOCOL_HANDLER_PACKAGES, ""); packages = (!packages.isEmpty() && !packages.contains(PACKAGE)) ? packages + "|" + PACKAGE : PACKAGE; System.setProperty(PROTOCOL_HANDLER_PACKAGES, packages); resetCachedUrlHandlers();
} /** * Reset any cached handlers just in case a jar protocol has already been used. We * reset the handler by trying to set a null {@link URLStreamHandlerFactory} which * should have no effect other than clearing the handlers cache. */ private static void resetCachedUrlHandlers() { try { URL.setURLStreamHandlerFactory(null); } catch (Error ex) { // Ignore } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\Handlers.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String name = Objects.requireNonNull(config.getName(), "name must not be null"); String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null"); ServerHttpRequest req = exchange.getRequest(); UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(req.getURI()); MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(req.getQueryParams()); if (queryParams.containsKey(name)) { queryParams.remove(name); queryParams.add(name, replacement); } try { MultiValueMap<String, String> encodedQueryParams = ServerWebExchangeUtils .encodeQueryParams(queryParams); URI uri = uriComponentsBuilder.replaceQueryParams(unmodifiableMultiValueMap(encodedQueryParams)) .build(true) .toUri(); ServerHttpRequest request = req.mutate().uri(uri).build(); return chain.filter(exchange.mutate().request(request).build()); } catch (IllegalArgumentException ex) { throw new IllegalStateException("Invalid URI query: \"" + queryParams + "\""); } } @Override public String toString() { String name = Objects.requireNonNull(config.getName(), "name must not be null"); String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null"); return filterToStringCreator(RewriteRequestParameterGatewayFilterFactory.this).append(name, replacement)
.toString(); } }; } public static class Config extends AbstractGatewayFilterFactory.NameConfig { private @Nullable String replacement; public @Nullable String getReplacement() { return replacement; } public Config setReplacement(String replacement) { this.replacement = replacement; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteRequestParameterGatewayFilterFactory.java
1
请完成以下Java代码
static class Person { @NotNull UUID id; @NotNull String name; @NotNull @Email @Pattern(regexp = "\\b[A-Za-z0-9._%+-]+@baeldung\\.com\\b") String email; @NotNull String surname; @NotNull Address address; @Null String fullName; @NotNull Date createdAt;
@Size(max = 10) List<Person> friends; } static class Address { @Null String street; @NotNull String city; @NotNull String country; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\modules\JakartaValidationModuleSchemaGenerator.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setMD_Available_For_Sales_ID (final int MD_Available_For_Sales_ID) { if (MD_Available_For_Sales_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, MD_Available_For_Sales_ID); } @Override public int getMD_Available_For_Sales_ID() { return get_ValueAsInt(COLUMNNAME_MD_Available_For_Sales_ID); } @Override public void setQtyOnHandStock (final @Nullable BigDecimal QtyOnHandStock) { set_Value (COLUMNNAME_QtyOnHandStock, QtyOnHandStock); } @Override public BigDecimal getQtyOnHandStock()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandStock); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped) { set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped); } @Override public BigDecimal getQtyToBeShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setStorageAttributesKey (final java.lang.String StorageAttributesKey) { set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return get_ValueAsString(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MD_Available_For_Sales.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { AbstractEngineConfiguration engineConfiguration = commandContext.getEngineConfigurations() .get(engineScopeType); if (engineConfiguration == null) { throw new FlowableIllegalArgumentException("There is no engine configuration for scope " + engineScopeType); } List<SchemaManager> schemaManagers = new ArrayList<>(); schemaManagers.add(engineConfiguration.getCommonSchemaManager()); schemaManagers.add(engineConfiguration.getSchemaManager()); Map<String, SchemaManager> additionalSchemaManagers = engineConfiguration.getAdditionalSchemaManagers(); if (additionalSchemaManagers != null) { schemaManagers.addAll(additionalSchemaManagers.values()); }
// The drop is executed in the reverse order ListIterator<SchemaManager> listIterator = schemaManagers.listIterator(schemaManagers.size()); while (listIterator.hasPrevious()) { SchemaManager schemaManager = listIterator.previous(); try { schemaManager.schemaDrop(); } catch (RuntimeException e) { // ignore } } return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\SchemaOperationsEngineDropDbCmd.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_Channel[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_PrintColor getAD_PrintColor() throws RuntimeException { return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name) .getPO(getAD_PrintColor_ID(), get_TrxName()); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_Value (COLUMNNAME_AD_PrintColor_ID, null); else set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Channel. @param C_Channel_ID Sales Channel */ public void setC_Channel_ID (int C_Channel_ID) { if (C_Channel_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Channel_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Channel_ID, Integer.valueOf(C_Channel_ID)); } /** Get Channel. @return Sales Channel */ public int getC_Channel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Channel_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Channel.java
1
请完成以下Java代码
public static final class Builder { private final List<ITabCallout> tabCalloutsAll = new ArrayList<>(); private Builder() { super(); } public ITabCallout build() { if (tabCalloutsAll.isEmpty()) { return ITabCallout.NULL; } else if (tabCalloutsAll.size() == 1) { return tabCalloutsAll.get(0); } else {
return new CompositeTabCallout(tabCalloutsAll); } } public Builder addTabCallout(final ITabCallout tabCallout) { Check.assumeNotNull(tabCallout, "tabCallout not null"); if (tabCalloutsAll.contains(tabCallout)) { return this; } tabCalloutsAll.add(tabCallout); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\impl\CompositeTabCallout.java
1
请完成以下Java代码
protected RepositoryCacheLoaderRegionConfigurer<T, ID> newRepositoryCacheLoaderRegionConfigurer( @NonNull CrudRepository<T, ID> repository, @Nullable Predicate<String> regionBeanName) { return new RepositoryCacheLoaderRegionConfigurer<>(repository, regionBeanName); } /** * Constructs a new instance of {@link RepositoryCacheWriterRegionConfigurer} initialized with * the given {@link CrudRepository} to write-through to an external data source and {@link Predicate} * to identify the target {@link Region} on which to register the {@link CacheWriter}. * * @param repository {@link CrudRepository} used to write-through to the external data source. * @param regionBeanName {@link Predicate} used to identify the target {@link Region} on which * to register the {@link CacheWriter}. * @return a new {@link RepositoryCacheWriterRegionConfigurer}. * @see org.springframework.geode.cache.RepositoryCacheWriterRegionConfigurer * @see org.springframework.data.repository.CrudRepository * @see java.util.function.Predicate
*/ protected RepositoryCacheWriterRegionConfigurer<T, ID> newRepositoryCacheWriterRegionConfigurer( @NonNull CrudRepository<T, ID> repository, @Nullable Predicate<String> regionBeanName) { return new RepositoryCacheWriterRegionConfigurer<>(repository, regionBeanName); } @Override public void configure(String beanName, ClientRegionFactoryBean<?, ?> bean) { this.compositeRegionConfigurer.configure(beanName, bean); } @Override public void configure(String beanName, PeerRegionFactoryBean<?, ?> bean) { this.compositeRegionConfigurer.configure(beanName, bean); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\InlineCachingRegionConfigurer.java
1
请完成以下Java代码
public static IntegerLookupValue of( @NonNull final RepoIdAware id, @Nullable final ITranslatableString displayName) { return new IntegerLookupValue( id.getRepoId(), displayName, null/* helpText */, null/* attributes */, null/* active */); } public static IntegerLookupValue of( @NonNull final RepoIdAware id, @Nullable final ITranslatableString displayName, @Nullable final ITranslatableString helpText) { return new IntegerLookupValue( id.getRepoId(), displayName, helpText, null/* attributes */, null/* active */); } @Nullable public static IntegerLookupValue of(final StringLookupValue stringLookupValue) { if (stringLookupValue == null) { return null; } return new IntegerLookupValue( stringLookupValue.getIdAsInt(), stringLookupValue.displayName, stringLookupValue.description, null /* attributes */, stringLookupValue.getActive()); } public static IntegerLookupValue unknown(final int id) { return new IntegerLookupValue( id,
unknownCaption(id), null/* description */, null/* attributes */, false/* not active */); } @Builder private IntegerLookupValue( final int id, @Nullable final ITranslatableString displayName, @Nullable final ITranslatableString description, @Nullable @Singular final Map<String, Object> attributes, @Nullable final Boolean active) { super(id, displayName, description, attributes, active); } @Override public int getIdAsInt() { return (Integer)id; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValue.java
1
请在Spring Boot框架中完成以下Java代码
private void setProductInfo(final IPricingContext pricingCtx, final IPricingResult result) { final ProductId productId = pricingCtx.getProductId(); if (productId == null) { return; } final IProductDAO productDAO = Services.get(IProductDAO.class); final ProductCategoryId productCategoryId = productDAO.retrieveProductCategoryByProductId(productId); result.setProductCategoryId(productCategoryId); // // Set Price_UOM_ID (06942) final I_M_PriceList_Version plv = pricingCtx.getM_PriceList_Version(); if (plv != null) { final I_M_ProductPrice productPrice = ProductPrices.retrieveMainProductPriceOrNull(plv, productId); if (productPrice == null) { final UomId uomId = Services.get(IProductBL.class).getStockUOMId(productId); result.setPriceUomId(uomId); } else { result.setPriceUomId(UomId.ofRepoId(productPrice.getC_UOM_ID())); } } else { final UomId uomId = Services.get(IProductBL.class).getStockUOMId(productId); result.setPriceUomId(uomId); } } @Override public PricingResult createInitialResult(@NonNull final IPricingContext pricingCtx) { final PricingResult result = PricingResult.builder() .priceDate(pricingCtx.getPriceDate()) // .pricingSystemId(pricingCtx.getPricingSystemId()) .priceListId(pricingCtx.getPriceListId()) .priceListVersionId(pricingCtx.getPriceListVersionId()) .currencyId(pricingCtx.getCurrencyId()) // .productId(pricingCtx.getProductId()) // .disallowDiscount(pricingCtx.isDisallowDiscount()) // .build(); setProductInfo(pricingCtx, result); return result; } private AggregatedPricingRule createPricingRules() { final IPricingDAO pricingRulesRepo = Services.get(IPricingDAO.class); final ImmutableList<IPricingRule> rules = pricingRulesRepo.getPricingRules() .stream() .map(this::createPricingRuleNoFail) .filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList()); return AggregatedPricingRule.of(rules); } @Nullable private IPricingRule createPricingRuleNoFail(final PricingRuleDescriptor ruleDef) { try { return ruleDef.getPricingRuleClass().getReferencedClass().newInstance(); } catch (final Exception ex) { logger.warn("Cannot load rule for {}", ruleDef, ex); return null; } } private CurrencyPrecision getPricePrecision(@NonNull final PriceListId priceListId) { return Services.get(IPriceListBL.class).getPricePrecision(priceListId); } @Override public void registerPriceLimitRule(@NonNull final IPriceLimitRule rule) { priceLimitRules.addEnforcer(rule); } @Override public PriceLimitRuleResult computePriceLimit(@NonNull final PriceLimitRuleContext context) { return priceLimitRules.compute(context); } @Override public Set<CountryId> getPriceLimitCountryIds() { return priceLimitRules.getPriceCountryIds(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingBL.java
2
请在Spring Boot框架中完成以下Java代码
public String getIDENTIFICATIONDATE3() { return identificationdate3; } /** * Sets the value of the identificationdate3 property. * * @param value * allowed object is * {@link String } * */ public void setIDENTIFICATIONDATE3(String value) { this.identificationdate3 = value; } /** * Gets the value of the identificationdate4 property. * * @return * possible object is * {@link String } * */ public String getIDENTIFICATIONDATE4() { return identificationdate4; } /** * Sets the value of the identificationdate4 property. * * @param value * allowed object is * {@link String } * */ public void setIDENTIFICATIONDATE4(String value) { this.identificationdate4 = value; } /** * Gets the value of the quantity property. * * @return * possible object is * {@link String } * */ public String getQUANTITY() { return quantity; } /** * Sets the value of the quantity property. *
* @param value * allowed object is * {@link String } * */ public void setQUANTITY(String value) { this.quantity = value; } /** * Gets the value of the quantitymeasureunit property. * * @return * possible object is * {@link String } * */ public String getQUANTITYMEASUREUNIT() { return quantitymeasureunit; } /** * Sets the value of the quantitymeasureunit property. * * @param value * allowed object is * {@link String } * */ public void setQUANTITYMEASUREUNIT(String value) { this.quantitymeasureunit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DMARK1.java
2
请完成以下Java代码
public XML addXMLAttribute (String attribute, String attribute_value) { addAttribute (attribute, attribute_value); return (this); } /** * Add an element to the valuie of &lt;&gt;VALUE&lt;/&gt; * * @param element * the value of &lt;&gt;VALUE&lt;/&gt; */ public XML addElement (String element) { addElementToRegistry (element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public XML addElement (String hashcode, Element element) { addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public XML addElement (String hashcode, String element) { addElementToRegistry (hashcode, element); return (this); } /** * Add an element to the valuie of &lt;&gt;VALUE&lt;/&gt; * * @param element * the value of &lt;&gt;VALUE&lt;/&gt; */ public XML addElement (Element element) { addElementToRegistry (element); return (this); }
/** * Removes an Element from the element. * * @param hashcode * the name of the element to be removed. */ public XML removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } public boolean getNeedLineBreak () { boolean linebreak = true; java.util.Enumeration en = elements (); // if this tag has one child, and it's a String, then don't // do any linebreaks to preserve whitespace while (en.hasMoreElements ()) { Object obj = en.nextElement (); if (obj instanceof StringElement) { linebreak = false; break; } } return linebreak; } public boolean getBeginEndModifierDefined () { boolean answer = false; if (!this.getNeedClosingTag ()) answer = true; return answer; } public char getBeginEndModifier () { return '/'; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\XML.java
1
请在Spring Boot框架中完成以下Java代码
public CacheManagerCustomizer<CaffeineCacheManager> activitiSpringCaffeineCacheManagerCustomizer( ActivitiSpringCacheManagerProperties properties, ObjectProvider<ActivitiSpringCaffeineCacheConfigurer> cacheConfigurers ) { return cacheManager -> { var caffeineCacheProperties = properties.getCaffeine(); cacheManager.setCaffeineSpec(CaffeineSpec.parse(caffeineCacheProperties.getDefaultSpec())); cacheManager.setAllowNullValues(caffeineCacheProperties.isAllowNullValues()); properties .getCaches() .entrySet() .stream() .filter(it -> it.getValue().isEnabled()) .forEach(cacheEntry -> { Optional.ofNullable(cacheEntry.getValue()) .map(ActivitiSpringCacheManagerProperties.ActivitiCacheProperties::getCaffeine) .map(CacheProperties.Caffeine::getSpec) .or(() -> Optional.ofNullable(properties.getCaffeine().getDefaultSpec())) .map(CaffeineSpec::parse) .map(Caffeine::from)
.ifPresent(caffeine -> { if (caffeineCacheProperties.isUseSystemScheduler()) { caffeine.scheduler(Scheduler.systemScheduler()); } var cache = cacheConfigurers .orderedStream() .filter(configurer -> configurer.test(cacheEntry.getKey())) .findFirst() .map(configurer -> configurer.apply(caffeine)) .orElseGet(caffeine::build); cacheManager.registerCustomCache(cacheEntry.getKey(), cache); }); }); }; } }
repos\Activiti-develop\activiti-core-common\activiti-spring-cache-manager\src\main\java\org\activiti\spring\cache\config\ActivitiSpringCacheManagerAutoConfiguration.java
2
请完成以下Java代码
private boolean isCheckCreditLimitNeeded(@NonNull final I_C_Order order) { if (!order.isSOTrx()) { return false; } final BPartnerStats stats = bpartnerStatsDAO.getCreateBPartnerStats(order.getBill_BPartner_ID()); if (X_C_BPartner_Stats.SOCREDITSTATUS_NoCreditCheck.equals(stats.getSOCreditStatus())) { return false; } final I_C_DocType dt = docTypeDAO.getById(order.getC_DocTypeTarget_ID()); final PaymentRule paymentRule = PaymentRule.ofCode(order.getPaymentRule()); if (X_C_DocType.DOCSUBTYPE_POSOrder.equals(dt.getDocSubType()) && paymentRule.isCash()
&& !sysConfigBL.getBooleanValue("CHECK_CREDIT_ON_CASH_POS_ORDER", true, order.getAD_Client_ID(), order.getAD_Org_ID())) { // ignore -- don't validate for Cash POS Orders depending on sysconfig parameter return false; } else if (X_C_DocType.DOCSUBTYPE_PrepayOrder.equals(dt.getDocSubType()) && !sysConfigBL.getBooleanValue("CHECK_CREDIT_ON_PREPAY_ORDER", true, order.getAD_Client_ID(), order.getAD_Org_ID())) { // ignore -- don't validate Prepay Orders depending on sysconfig parameter return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_Order.java
1
请完成以下Java代码
public RetryTopicConfigurationBuilder listenerFactory(@Nullable String factoryBeanName) { this.listenerContainerFactoryName = factoryBeanName; return this; } /** * Create the {@link RetryTopicConfiguration} with the provided template. * @param sendToTopicKafkaTemplate the template. * @return the configuration. */ // The templates are configured per ListenerContainerFactory. Only the first configured ones will be used. public RetryTopicConfiguration create(KafkaOperations<?, ?> sendToTopicKafkaTemplate) { ListenerContainerFactoryResolver.Configuration factoryResolverConfig = new ListenerContainerFactoryResolver.Configuration(this.listenerContainerFactory, this.listenerContainerFactoryName); AllowDenyCollectionManager<String> allowListManager = new AllowDenyCollectionManager<>(this.includeTopicNames, this.excludeTopicNames); List<Long> backOffValues = new BackOffValuesGenerator(this.maxAttempts, this.backOff).generateValues(); List<DestinationTopic.Properties> destinationTopicProperties = new DestinationTopicPropertiesFactory(this.retryTopicSuffix, this.dltSuffix, backOffValues, buildExceptionMatcher(), this.topicCreationConfiguration.getNumPartitions(), sendToTopicKafkaTemplate, this.dltStrategy, this.topicSuffixingStrategy, this.sameIntervalTopicReuseStrategy, this.timeout, this.dltRoutingRules) .autoStartDltHandler(this.autoStartDltHandler) .createProperties(); return new RetryTopicConfiguration(destinationTopicProperties, this.dltHandlerMethod, this.topicCreationConfiguration, allowListManager, factoryResolverConfig, this.concurrency); } private ExceptionMatcher buildExceptionMatcher() { if (this.exceptionEntriesConfigurer == null) {
return ExceptionMatcher.forAllowList().add(Throwable.class).build(); } ExceptionMatcher.Builder builder = (this.exceptionEntriesConfigurer.matchIfFound) ? ExceptionMatcher.forAllowList() : ExceptionMatcher.forDenyList(); builder.addAll(this.exceptionEntriesConfigurer.entries); if (this.traversingCauses != null) { builder.traverseCauses(this.traversingCauses); } return builder.build(); } /** * Create a new instance of the builder. * @return the new instance. */ public static RetryTopicConfigurationBuilder newInstance() { return new RetryTopicConfigurationBuilder(); } private static final class ExceptionEntriesConfigurer { private final boolean matchIfFound; private final Set<Class<? extends Throwable>> entries = new LinkedHashSet<>(); private ExceptionEntriesConfigurer(boolean matchIfFound) { this.matchIfFound = matchIfFound; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfigurationBuilder.java
1
请完成以下Java代码
protected void handleException(Throwable exc, DelegateExecution execution) { ErrorPropagation.handleException(exc, (ExecutionEntity) execution, mapExceptions); } protected void setExecutionVariableValue(Object value, DelegateExecution execution) { if (resultVariable != null) { if (storeResultVariableAsTransient) { if (useLocalScopeForResultVariable) { execution.setTransientVariableLocal(resultVariable, value); } else { execution.setTransientVariable(resultVariable, value); } } else { if (useLocalScopeForResultVariable) { execution.setVariableLocal(resultVariable, value); } else { execution.setVariable(resultVariable, value); } } } } @Override public void trigger(DelegateExecution execution, String signalName, Object signalData) { leave(execution);
} protected class FutureCompleteAction implements BiConsumer<Object, Throwable> { protected final DelegateExecution execution; public FutureCompleteAction(DelegateExecution execution) { this.execution = execution; } @Override public void accept(Object value, Throwable throwable) { if (throwable == null) { setExecutionVariableValue(value, execution); if (!triggerable) { leave(execution); } } else { handleException(throwable, execution); } } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\ServiceTaskExpressionActivityBehavior.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Issue getAD_Issue() { return get_ValueAsPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class); } @Override public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue) { set_ValueFromPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class, AD_Issue); } @Override public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setErrorMsg (java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override public java.lang.String getErrorMsg() { return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg); } @Override public void setImportStatus (java.lang.String ImportStatus) { set_Value (COLUMNNAME_ImportStatus, ImportStatus); } @Override public java.lang.String getImportStatus() { return (java.lang.String)get_Value(COLUMNNAME_ImportStatus); } @Override public void setJsonRequest (java.lang.String JsonRequest) { set_ValueNoCheck (COLUMNNAME_JsonRequest, JsonRequest);
} @Override public java.lang.String getJsonRequest() { return (java.lang.String)get_Value(COLUMNNAME_JsonRequest); } @Override public void setJsonResponse (java.lang.String JsonResponse) { set_Value (COLUMNNAME_JsonResponse, JsonResponse); } @Override public java.lang.String getJsonResponse() { return (java.lang.String)get_Value(COLUMNNAME_JsonResponse); } @Override public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID) { if (PP_Cost_Collector_ImportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID)); } @Override public int getPP_Cost_Collector_ImportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAudit.java
1
请完成以下Java代码
public ProductsProposalRowsData load() { final List<ProductsProposalRow> rows = bpartnerProductStatsService.getByProductIds(productIds, currencyId) .stream() // .filter(stats -> excludeBPartnerId == null || !BPartnerId.equals(stats.getBpartnerId(), excludeBPartnerId)) .map(this::toProductsProposalRowOrNull) .filter(Objects::nonNull) .sorted(Comparator.comparing(ProductsProposalRow::getProductName) .thenComparing(Comparator.comparing(ProductsProposalRow::getLastSalesInvoiceDate)).reversed()) .collect(ImmutableList.toImmutableList()); return ProductsProposalRowsData.builder() .nextRowIdSequence(nextRowIdSequence) .rows(rows) .soTrx(SOTrx.SALES) .currencyId(currencyId) .build(); } private ProductsProposalRow toProductsProposalRowOrNull(@NonNull final BPartnerProductStats stats) { final LastInvoiceInfo lastSalesInvoice = stats.getLastSalesInvoice(); if (lastSalesInvoice == null) { return null;
} return ProductsProposalRow.builder() .id(nextRowIdSequence.nextDocumentId()) .bpartner(bpartnerLookup.findById(stats.getBpartnerId())) .product(productLookup.findById(stats.getProductId())) .price(ProductProposalPrice.builder() .priceListPrice(moneyService.toAmount(lastSalesInvoice.getPrice())) .build()) .lastShipmentDays(stats.getLastShipmentInDays()) .lastSalesInvoiceDate(lastSalesInvoice.getInvoiceDate()) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\OtherSalePricesProductsProposalViewFactory.java
1
请完成以下Java代码
public void setParentElement_ID (final int ParentElement_ID) { if (ParentElement_ID < 1) set_Value (COLUMNNAME_ParentElement_ID, null); else set_Value (COLUMNNAME_ParentElement_ID, ParentElement_ID); } @Override public int getParentElement_ID() { return get_ValueAsInt(COLUMNNAME_ParentElement_ID); } @Override public void setPrecision (final int Precision) { set_Value (COLUMNNAME_Precision, Precision); } @Override public int getPrecision() { return get_ValueAsInt(COLUMNNAME_Precision); } @Override public void setQty (final @Nullable java.lang.String Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public java.lang.String getQty()
{ return get_ValueAsString(COLUMNNAME_Qty); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Ingredients.java
1
请完成以下Java代码
public ExternalTaskQueryTopicBuilder processDefinitionKeyIn(String... processDefinitionKeys) { currentInstruction.setProcessDefinitionKeys(processDefinitionKeys); return this; } public ExternalTaskQueryTopicBuilder processDefinitionVersionTag(String processDefinitionVersionTag) { currentInstruction.setProcessDefinitionVersionTag(processDefinitionVersionTag); return this; } public ExternalTaskQueryTopicBuilder withoutTenantId() { currentInstruction.setTenantIds(null); return this; } public ExternalTaskQueryTopicBuilder tenantIdIn(String... tenantIds) { currentInstruction.setTenantIds(tenantIds); return this; } protected void submitCurrentInstruction() {
if (currentInstruction != null) { this.instructions.put(currentInstruction.getTopicName(), currentInstruction); } } public ExternalTaskQueryTopicBuilder enableCustomObjectDeserialization() { currentInstruction.setDeserializeVariables(true); return this; } public ExternalTaskQueryTopicBuilder localVariables() { currentInstruction.setLocalVariables(true); return this; } public ExternalTaskQueryTopicBuilder includeExtensionProperties() { currentInstruction.setIncludeExtensionProperties(true); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\ExternalTaskQueryTopicBuilderImpl.java
1
请完成以下Java代码
public CalloutStatisticsEntry getCreateChild(final ICalloutField field, final ICalloutInstance callout) { final ArrayKey key = Util.mkKey(field.getColumnName(), callout); return children.computeIfAbsent(key, (theKey) -> new CalloutStatisticsEntry(indexSupplier, field, callout)); } public CalloutStatisticsEntry childSkipped(final String columnName, final String reason) { logger.trace("Skip executing all callouts for {} because {}", columnName, reason); countChildFieldsSkipped++; return this; } public CalloutStatisticsEntry childSkipped(final ICalloutField field, final String reason) { logger.trace("Skip executing all callouts for {} because {}", field, reason); countChildFieldsSkipped++; return this;
} public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary) { final String reasonDetails = null; return childSkipped(field, callout, reasonSummary, reasonDetails); } public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary, final String reasonDetails) { logger.trace("Skip executing callout {} for field {} because {} ({})", callout, field, reasonSummary, reasonDetails); getCreateChild(field, callout).setStatusSkipped(reasonSummary, reasonDetails); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\CalloutExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public void handlePutBPartnersRequest(final PutBPartnersRequest request) { logger.debug("Importing bpartners: {}", request); int countImported = 0; int countError = 0; for (final SyncBPartner syncBpartner : request.getBpartners()) { try { bpartnersImportService.importBPartner(syncBpartner); countImported++; } catch (final Exception e) { countError++; logger.error("Failed importing {}. Skipped.", syncBpartner, e); } } logger.info("{} bpartners imported, got {} errors", countImported, countError); } public void handlePutProductsRequest(final PutProductsRequest request) { logger.debug("Importing: {}", request); int countImported = 0; int countError = 0; for (final SyncProduct syncProduct : request.getProducts()) { try { productsImportService.importProduct(syncProduct); countImported++; } catch (final Exception e) { countError++; logger.error("Failed importing {}. Skipped.", syncProduct, e); } } logger.info("{} products imported, got {} errors", countImported, countError); } public void handlePutInfoMessageRequest(final PutInfoMessageRequest request) { logger.debug("Importing: {}", request); try { settingsImportService.importSyncInfoMessage(request); } catch (final Exception e) { logger.error("Failed importing {}. Skipped.", request, e); } } public void handlePutConfirmationToProcurementWebRequest(final PutConfirmationToProcurementWebRequest request) { logger.debug("Importing: {}", request); for (final SyncConfirmation syncConfirmation : request.getSyncConfirmations()) { try { confirmationsImportService.importConfirmation(syncConfirmation); } catch (final Exception e) { logger.error("Failed importing confirmation: {}", syncConfirmation, e);
} } } public void handlePutRfQsRequest(@NonNull final PutRfQsRequest request) { logger.debug("Importing: {}", request); if (request.isEmpty()) { return; } for (final SyncRfQ syncRfq : request.getSyncRfqs()) { try { rfqImportService.importRfQ(syncRfq); } catch (final Exception e) { logger.error("Failed importing RfQ: {}", syncRfq, e); } } } public void handlePutRfQCloseEventsRequest(final PutRfQCloseEventsRequest request) { logger.debug("Importing: {}", request); if (request.isEmpty()) { return; } for (final SyncRfQCloseEvent syncRfQCloseEvent : request.getSyncRfQCloseEvents()) { try { rfqImportService.importRfQCloseEvent(syncRfQCloseEvent); } catch (final Exception e) { logger.error("Failed importing: {}", syncRfQCloseEvent, e); } } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\ReceiverFromMetasfreshHandler.java
2
请完成以下Java代码
public ClientRegistration deserialize(JsonParser parser, DeserializationContext context) throws IOException { ObjectMapper mapper = (ObjectMapper) parser.getCodec(); JsonNode clientRegistrationNode = mapper.readTree(parser); JsonNode providerDetailsNode = JsonNodeUtils.findObjectNode(clientRegistrationNode, "providerDetails"); JsonNode userInfoEndpointNode = JsonNodeUtils.findObjectNode(providerDetailsNode, "userInfoEndpoint"); return ClientRegistration .withRegistrationId(JsonNodeUtils.findStringValue(clientRegistrationNode, "registrationId")) .clientId(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientId")) .clientSecret(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientSecret")) .clientAuthenticationMethod(CLIENT_AUTHENTICATION_METHOD_CONVERTER .convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "clientAuthenticationMethod"))) .authorizationGrantType(AUTHORIZATION_GRANT_TYPE_CONVERTER .convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "authorizationGrantType"))) .redirectUri(JsonNodeUtils.findStringValue(clientRegistrationNode, "redirectUri")) .scope(JsonNodeUtils.findValue(clientRegistrationNode, "scopes", JsonNodeUtils.STRING_SET, mapper))
.clientName(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientName")) .authorizationUri(JsonNodeUtils.findStringValue(providerDetailsNode, "authorizationUri")) .tokenUri(JsonNodeUtils.findStringValue(providerDetailsNode, "tokenUri")) .userInfoUri(JsonNodeUtils.findStringValue(userInfoEndpointNode, "uri")) .userInfoAuthenticationMethod(AUTHENTICATION_METHOD_CONVERTER .convert(JsonNodeUtils.findObjectNode(userInfoEndpointNode, "authenticationMethod"))) .userNameAttributeName(JsonNodeUtils.findStringValue(userInfoEndpointNode, "userNameAttributeName")) .jwkSetUri(JsonNodeUtils.findStringValue(providerDetailsNode, "jwkSetUri")) .issuerUri(JsonNodeUtils.findStringValue(providerDetailsNode, "issuerUri")) .providerConfigurationMetadata(JsonNodeUtils.findValue(providerDetailsNode, "configurationMetadata", JsonNodeUtils.STRING_OBJECT_MAP, mapper)) .build(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\jackson2\ClientRegistrationDeserializer.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getAdditionalExclude() { return this.additionalExclude; } public void setAdditionalExclude(@Nullable String additionalExclude) { this.additionalExclude = additionalExclude; } public Duration getPollInterval() { return this.pollInterval; } public void setPollInterval(Duration pollInterval) { this.pollInterval = pollInterval; } public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } public @Nullable String getTriggerFile() { return this.triggerFile; } public void setTriggerFile(@Nullable String triggerFile) { this.triggerFile = triggerFile; } public List<File> getAdditionalPaths() { return this.additionalPaths; } public void setAdditionalPaths(List<File> additionalPaths) { this.additionalPaths = additionalPaths; } public boolean isLogConditionEvaluationDelta() { return this.logConditionEvaluationDelta;
} public void setLogConditionEvaluationDelta(boolean logConditionEvaluationDelta) { this.logConditionEvaluationDelta = logConditionEvaluationDelta; } } /** * LiveReload properties. */ public static class Livereload { /** * Whether to enable a livereload.com-compatible server. */ private boolean enabled; /** * Server port. */ private int port = 35729; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Pharmacy timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pharmacy pharmacy = (Pharmacy) o; return Objects.equals(this._id, pharmacy._id) && Objects.equals(this.name, pharmacy.name) && Objects.equals(this.address, pharmacy.address) && Objects.equals(this.postalCode, pharmacy.postalCode) && Objects.equals(this.city, pharmacy.city) && Objects.equals(this.phone, pharmacy.phone) && Objects.equals(this.fax, pharmacy.fax) && Objects.equals(this.email, pharmacy.email) && Objects.equals(this.website, pharmacy.website) && Objects.equals(this.timestamp, pharmacy.timestamp); } @Override public int hashCode() { return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, website, timestamp); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class Pharmacy {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" website: ").append(toIndentedString(website)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).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(java.lang.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\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Pharmacy.java
2
请完成以下Java代码
private final String getLinePrefix() { if (_linePrefix == null) { final int indent = getIndent(); final String token = getIndentToken(); final StringBuilder prefix = new StringBuilder(); for (int i = 1; i <= indent; i++) { prefix.append(token); } _linePrefix = prefix.toString(); } return _linePrefix; } public StringBuilder getInnerStringBuilder() { return sb; } @Override public String toString() {
return sb.toString(); } public IndentedStringBuilder appendLine(final Object obj) { final String linePrefix = getLinePrefix(); sb.append(linePrefix).append(obj).append(getNewlineToken()); return this; } public IndentedStringBuilder append(final Object obj) { sb.append(obj); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\IndentedStringBuilder.java
1
请完成以下Java代码
public <T> IQuery<T> create(final IQueryBuilder<T> builder) { // // Handle in memory queries final POJOLookupMap memDatabase; if (Check.isEmpty(builder.getModelTableName(), true)) { memDatabase = POJOLookupMap.getInMemoryDatabaseForTableName(builder.getModelTableName()); } else { final Class<T> modelClass = builder.getModelClass(); memDatabase = POJOLookupMap.getInMemoryDatabaseForModel(modelClass); } if (memDatabase != null) { return memDAO.create(builder); } return super.create(builder); } @Override protected final <T> IQuery<T> createQuery(final QueryBuildContext<T> queryBuildCtx, final ISqlQueryFilter sqlFilters, final IQueryFilter<T> nonSqlFilters) { final Properties ctx = queryBuildCtx.getCtx(); final String sqlWhereClause; final List<Object> sqlParams; if (sqlFilters != null) { sqlWhereClause = sqlFilters.getSql(); sqlParams = sqlFilters.getSqlParams(ctx); } else { sqlWhereClause = null; sqlParams = null; } final String trxName = queryBuildCtx.getTrxName(); final Class<T> modelClass = queryBuildCtx.getModelClass(); final String modelTableName = queryBuildCtx.getModelTableName(); final IQueryOrderBy queryOrderBy = queryBuildCtx.getQueryOrderBy(); final QueryLimit queryLimit = queryBuildCtx.getQueryLimit(); final PInstanceId queryOnlySelectionId = queryBuildCtx.getQueryOnlySelectionId(); final Map<String, Object> queryOptions = queryBuildCtx.getQueryOptions(); return new TypedSqlQuery<>(ctx, modelClass, modelTableName, sqlWhereClause, trxName) .setParameters(sqlParams)
.setPostQueryFilter(nonSqlFilters) .setOrderBy(queryOrderBy) .setLimit(queryLimit) .setOnlySelection(queryOnlySelectionId) .setOptions(queryOptions); } @Override public <T> String getSql( @NonNull final Properties ctx, @NonNull final ICompositeQueryFilter<T> filter, final List<Object> sqlParamsOut) { // Make sure given filter does not have nonSQL parts final IQueryFilter<T> nonSqlFilters = filter.asPartialNonSqlFilterOrNull(); if (nonSqlFilters != null) { throw new DBException("Cannot convert filter to SQL because it contains nonSQL parts too: " + filter); } final ISqlQueryFilter sqlFilter = filter.asPartialSqlQueryFilter(); final String filterSql = sqlFilter.getSql(); final List<Object> filterSqlParams = sqlFilter.getSqlParams(ctx); if (!Check.isEmpty(filterSqlParams)) { // NOTE: we enforce the sqlParamsOut to be not null, only if we really have some parameters to append Check.assumeNotNull(sqlParamsOut, "sqlParamsOut not null"); sqlParamsOut.addAll(filterSqlParams); } return filterSql; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBuilderDAO.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, PemSslBundleProperties> getPem() { return this.pem; } public Map<String, JksSslBundleProperties> getJks() { return this.jks; } public Watch getWatch() { return this.watch; } public static class Watch { /** * File watching. */ private final File file = new File(); public File getFile() { return this.file; } public static class File { /**
* Quiet period, after which changes are detected. */ private Duration quietPeriod = Duration.ofSeconds(10); public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslProperties.java
2
请完成以下Java代码
private String setVoidedOrderNewDocumenTNo( @NonNull final String voidedOrderDocumentNoPrefix, @NonNull final I_C_Order orderRecord, int attemptCount) { final String prefixToUse; if (attemptCount <= 1) { prefixToUse = String.format("%s-", voidedOrderDocumentNoPrefix); } else { prefixToUse = String.format("%s(%s)-", voidedOrderDocumentNoPrefix, attemptCount); } final String documentNo = orderRecord.getDocumentNo(); // try to update; retry on exception, with a different docNo; // Rationale: duplicate documentNos are OK if the doc has different docTypes or bPartners(!).
// I don't want to make assumptions on the exact unique constraint // Also, I hope that a voided order's copy is voided again is rare enough. try { orderRecord.setDocumentNo(prefixToUse + documentNo); saveRecord(orderRecord); } catch (final DBUniqueConstraintException e) { orderRecord.setDocumentNo(documentNo); // go back to the original documentno for the next try, to avoid <prefix>(2)-<prefix>-document setVoidedOrderNewDocumenTNo(voidedOrderDocumentNoPrefix, orderRecord, attemptCount + 1); } return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\voidorderandrelateddocs\VoidOrderHandler.java
1
请完成以下Java代码
public class BankStatementReconciliationView extends AbstractCustomView<BankStatementLineRow> implements IViewRowOverrides { public static BankStatementReconciliationView cast(final IView view) { return (BankStatementReconciliationView)view; } @Getter private final PaymentsToReconcileView paymentsToReconcileView; @Builder private BankStatementReconciliationView( @NonNull final ViewId bankStatementViewId, final BankStatementLineAndPaymentsRows rows, @Nullable final List<RelatedProcessDescriptor> paymentToReconcilateProcesses) { super(bankStatementViewId, TranslatableStrings.empty(), rows.getBankStatementLineRows(), NullDocumentFilterDescriptorsProvider.instance); paymentsToReconcileView = PaymentsToReconcileView.builder() .bankStatementViewId(bankStatementViewId) .rows(rows.getPaymentToReconcileRows()) .processes(paymentToReconcilateProcesses) .build(); }
@Override public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override public ViewId getIncludedViewId(final IViewRow row_NOTUSED) { return paymentsToReconcileView.getViewId(); } @Override protected BankStatementLineRows getRowsData() { return BankStatementLineRows.cast(super.getRowsData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementReconciliationView.java
1
请完成以下Java代码
public String getExpressionLanguage() { return expressionLanguage; } public void setExpressionLanguage(String expressionLanguage) { this.expressionLanguage = expressionLanguage; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } @Override public String toString() { return "DmnExpressionImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", typeDefinition=" + typeDefinition + ", expressionLanguage='" + expressionLanguage + '\'' + ", expression='" + expression + '\'' + '}'; }
public void cacheCompiledScript(CompiledScript compiledScript) { this.cachedCompiledScript = compiledScript; } public CompiledScript getCachedCompiledScript() { return this.cachedCompiledScript; } public ElExpression getCachedExpression() { return this.cachedExpression; } public void setCachedExpression(ElExpression expression) { this.cachedExpression = expression; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnExpressionImpl.java
1
请完成以下Java代码
public boolean getParameterAsBoolean() { return StringUtils.toBoolean(m_Parameter); } @Nullable public Boolean getParameterAsBooleanOrNull() { return StringUtils.toBoolean(m_Parameter, null); } @Nullable public Boolean getParameterAsBoolean(@Nullable Boolean defaultValue) { return StringUtils.toBoolean(m_Parameter, defaultValue); } public boolean getParameter_ToAsBoolean() { return StringUtils.toBoolean(m_Parameter_To); } @Nullable public Timestamp getParameterAsTimestamp() { return TimeUtil.asTimestamp(m_Parameter); } @Nullable public Timestamp getParameter_ToAsTimestamp() { return TimeUtil.asTimestamp(m_Parameter_To); } @Nullable public LocalDate getParameterAsLocalDate() { return TimeUtil.asLocalDate(m_Parameter); } @Nullable public LocalDate getParameter_ToAsLocalDate() { return TimeUtil.asLocalDate(m_Parameter_To); } @Nullable public ZonedDateTime getParameterAsZonedDateTime() { return TimeUtil.asZonedDateTime(m_Parameter); } @Nullable public Instant getParameterAsInstant() { return TimeUtil.asInstant(m_Parameter); } @Nullable
public ZonedDateTime getParameter_ToAsZonedDateTime() { return TimeUtil.asZonedDateTime(m_Parameter_To); } @Nullable public BigDecimal getParameterAsBigDecimal() { return toBigDecimal(m_Parameter); } @Nullable public BigDecimal getParameter_ToAsBigDecimal() { return toBigDecimal(m_Parameter_To); } @Nullable private static BigDecimal toBigDecimal(@Nullable final Object value) { if (value == null) { return null; } else if (value instanceof BigDecimal) { return (BigDecimal)value; } else if (value instanceof Integer) { return BigDecimal.valueOf((Integer)value); } else { return new BigDecimal(value.toString()); } } } // ProcessInfoParameter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(NAME_KEY, REGEXP_KEY, REPLACEMENT_KEY); } @Override public GatewayFilter apply(Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return chain.filter(exchange).then(Mono.fromRunnable(() -> rewriteHeaders(exchange, config))); } @Override public String toString() { return filterToStringCreator(RewriteResponseHeaderGatewayFilterFactory.this) .append("name", config.getName()) .append("regexp", config.getRegexp()) .append("replacement", config.getReplacement()) .toString(); } }; } protected void rewriteHeaders(ServerWebExchange exchange, Config config) { final String name = Objects.requireNonNull(config.getName(), "name must not be null"); final HttpHeaders responseHeaders = exchange.getResponse().getHeaders(); if (responseHeaders.get(name) != null) { List<String> oldValue = Objects.requireNonNull(responseHeaders.get(name), "oldValue must not be null"); List<String> newValue = rewriteHeaders(config, oldValue); if (newValue != null) { responseHeaders.put(name, newValue); } else { responseHeaders.remove(name); } } } protected List<String> rewriteHeaders(Config config, List<String> headers) { String regexp = Objects.requireNonNull(config.getRegexp(), "regexp must not be null"); String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null"); ArrayList<String> rewrittenHeaders = new ArrayList<>(); for (int i = 0; i < headers.size(); i++) { String rewriten = rewrite(headers.get(i), regexp, replacement);
rewrittenHeaders.add(rewriten); } return rewrittenHeaders; } String rewrite(String value, String regexp, String replacement) { return value.replaceAll(regexp, replacement.replace("$\\", "$")); } public static class Config extends AbstractGatewayFilterFactory.NameConfig { private @Nullable String regexp; private @Nullable String replacement; public @Nullable String getRegexp() { return regexp; } public Config setRegexp(String regexp) { this.regexp = regexp; return this; } public @Nullable String getReplacement() { return replacement; } public Config setReplacement(String replacement) { this.replacement = replacement; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteResponseHeaderGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public DirectDebitType getDirectDebit() { return directDebit; } /** * Sets the value of the directDebit property. * * @param value * allowed object is * {@link DirectDebitType } * */ public void setDirectDebit(DirectDebitType value) { this.directDebit = value; } /** * Used to denote details about a SEPA direct debit, via which this invoice has to be paid. * * @return
* possible object is * {@link SEPADirectDebitType } * */ public SEPADirectDebitType getSEPADirectDebit() { return sepaDirectDebit; } /** * Sets the value of the sepaDirectDebit property. * * @param value * allowed object is * {@link SEPADirectDebitType } * */ public void setSEPADirectDebit(SEPADirectDebitType value) { this.sepaDirectDebit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PaymentMethodType.java
2
请完成以下Java代码
public class TeamsMessageCard { @JsonProperty("@type") private final String type = "MessageCard"; @JsonProperty("@context") private final String context = "http://schema.org/extensions"; private String themeColor; private String summary; private String text; private List<Section> sections; private List<ActionCard> potentialAction; @Data public static class Section { private String activityTitle; private String activitySubtitle; private String activityImage; private List<Fact> facts; private boolean markdown; @Data public static class Fact { private final String name; private final String value; } } @Data @JsonInclude(JsonInclude.Include.NON_NULL) public static class ActionCard { @JsonProperty("@type") private String type; // ActionCard, OpenUri private String name; private List<Input> inputs; // for ActionCard private List<Action> actions; // for ActionCard
private List<Target> targets; @Data public static class Input { @JsonProperty("@type") private String type; // TextInput, DateInput, MultichoiceInput private String id; private boolean isMultiple; private String title; private boolean isMultiSelect; @Data public static class Choice { private final String display; private final String value; } } @Data public static class Action { @JsonProperty("@type") private final String type; // HttpPOST private final String name; private final String target; // url } @Data public static class Target { private final String os; private final String uri; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\TeamsMessageCard.java
1
请完成以下Java代码
default void toResource(WritableResource out) throws IOException { Assert.notNull(out, "'out' must not be null"); try (OutputStream outputStream = out.getOutputStream()) { toOutputStream(outputStream); } } /** * Write the JSON to the provided {@link WritableResource} using the given * {@link Charset}. * @param out the {@link OutputStream} to receive the JSON * @param charset the charset to use * @throws IOException on IO error */ default void toResource(WritableResource out, Charset charset) throws IOException { Assert.notNull(out, "'out' must not be null"); Assert.notNull(charset, "'charset' must not be null"); try (OutputStream outputStream = out.getOutputStream()) { toOutputStream(outputStream, charset); } } /** * Write the JSON to the provided {@link OutputStream} using * {@link StandardCharsets#UTF_8 UTF8} encoding. The output stream will not be closed. * @param out the {@link OutputStream} to receive the JSON * @throws IOException on IO error * @see #toOutputStream(OutputStream, Charset) */ default void toOutputStream(OutputStream out) throws IOException { toOutputStream(out, StandardCharsets.UTF_8); } /** * Write the JSON to the provided {@link OutputStream} using the given * {@link Charset}. The output stream will not be closed. * @param out the {@link OutputStream} to receive the JSON * @param charset the charset to use * @throws IOException on IO error */ default void toOutputStream(OutputStream out, Charset charset) throws IOException { Assert.notNull(out, "'out' must not be null"); Assert.notNull(charset, "'charset' must not be null"); toWriter(new OutputStreamWriter(out, charset)); } /** * Write the JSON to the provided {@link Writer}. The writer will be flushed but not * closed. * @param out the {@link Writer} to receive the JSON * @throws IOException on IO error * @see #toOutputStream(OutputStream, Charset) */ default void toWriter(Writer out) throws IOException { Assert.notNull(out, "'out' must not be null"); to(out); out.flush();
} /** * Factory method used to create a {@link WritableJson} with a sensible * {@link Object#toString()} that delegate to {@link WritableJson#toJsonString()}. * @param writableJson the source {@link WritableJson} * @return a new {@link WritableJson} with a sensible {@link Object#toString()}. */ static WritableJson of(WritableJson writableJson) { return new WritableJson() { @Override public void to(Appendable out) throws IOException { writableJson.to(out); } @Override public String toString() { return toJsonString(); } }; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\json\WritableJson.java
1
请完成以下Java代码
public AvailableForSalesConfig getConfig(@NonNull final ConfigQuery query) { cache.getOrLoad(query, () -> retrieveConfigRecord(query)); return retrieveConfigRecord(query); } @NonNull private AvailableForSalesConfig retrieveConfigRecord(@NonNull final ConfigQuery query) { final I_MD_AvailableForSales_Config configRecord = Services.get(IQueryBL.class) .createQueryBuilder(I_MD_AvailableForSales_Config.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MD_AvailableForSales_Config.COLUMNNAME_AD_Client_ID, query.getClientId()) .addInArrayFilter(I_MD_AvailableForSales_Config.COLUMNNAME_AD_Org_ID, query.getOrgId(), OrgId.ANY) .orderByDescending(I_MD_AvailableForSales_Config.COLUMNNAME_AD_Org_ID) .create() .first(); return ofRecord(configRecord); } @NonNull private AvailableForSalesConfig ofRecord(@Nullable final I_MD_AvailableForSales_Config configRecord) { if (configRecord == null) { return AvailableForSalesConfig .builder() .featureEnabled(false)
.insufficientQtyAvailableForSalesColorId(null) .salesOrderLookBehindHours(0) .shipmentDateLookAheadHours(0) .build(); } return AvailableForSalesConfig .builder() .featureEnabled(configRecord.isFeatureActivated()) .insufficientQtyAvailableForSalesColorId(ColorId.ofRepoId(configRecord.getInsufficientQtyAvailableForSalesColor_ID())) .salesOrderLookBehindHours(configRecord.getSalesOrderLookBehindHours()) .shipmentDateLookAheadHours(configRecord.getShipmentDateLookAheadHours()) .runAsync(configRecord.isAsync()) .asyncTimeoutMillis(configRecord.getAsyncTimeoutMillis()) .qtyPerWarehouse(configRecord.isQtyPerWarehouse()) .build(); } @Value @Builder public static class ConfigQuery { ClientId clientId; OrgId orgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesConfigRepo.java
1
请完成以下Java代码
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView) { if (!m_valid || m_barcode == null) return; // Position Point2D.Double location = getAbsoluteLocation(pageStart); int x = (int)location.x; if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType)) x += p_maxWidth - p_width; else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType)) x += (p_maxWidth - p_width) / 2; int y = (int)location.y; try { int w = m_barcode.getWidth(); int h = m_barcode.getHeight(); // draw barcode to buffer BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D temp = (Graphics2D) image.getGraphics(); m_barcode.draw(temp, 0, 0); // scale barcode and paint AffineTransform transform = new AffineTransform(); transform.translate(x,y); transform.scale(m_scaleFactor, m_scaleFactor); g2D.drawImage(image, transform, this);
} catch (OutputException e) { } } // paint /** * String Representation * @return info */ public String toString () { if (m_barcode == null) return super.toString(); return super.toString() + " " + m_barcode.getData(); } // toString } // BarcodeElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\BarcodeElement.java
1
请完成以下Java代码
private static final class DocumentPostRequestHandlerAsEventListener implements IEventListener { @NonNull private final DocumentPostRequestHandler handler; @NonNull private final EventConverter eventConverter; @NonNull private final EventLogUserService eventLogUserService; @Override public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event) { final DocumentPostRequest request = eventConverter.extractDocumentPostRequest(event); try (final IAutoCloseable ignored = switchCtx(request); final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(request.getRecord()); final MDCCloseable ignored2 = MDC.putCloseable("eventHandler.className", handler.getClass().getName())) { eventLogUserService.invokeHandlerAndLog(InvokeHandlerAndLogRequest.builder() .handlerClass(handler.getClass()) .invokaction(() -> handleRequest(request)) .build()); }
} private void handleRequest(@NonNull final DocumentPostRequest request) { handler.handleRequest(request); } private IAutoCloseable switchCtx(@NonNull final DocumentPostRequest request) { final Properties ctx = createCtx(request); return Env.switchContext(ctx); } private Properties createCtx(@NonNull final DocumentPostRequest request) { final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, request.getClientId()); return ctx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingBusService.java
1
请完成以下Java代码
public InfoWindowMenuBuilder setParentWindowNo(final int windowNo) { return setParentWindowNo(Suppliers.ofInstance(windowNo)); } public InfoWindowMenuBuilder setParentWindowNo(final Supplier<Integer> windowNoSupplier) { Check.assumeNotNull(windowNoSupplier, "windowNoSupplier not null"); _parentWindowNoSupplier = windowNoSupplier; return this; } private final int getParentWindowNo() { final Integer parentWindowNo = _parentWindowNoSupplier.get(); return parentWindowNo == null ? Env.WINDOW_MAIN : parentWindowNo; } private final JFrame getParentFrame() { final int parentWindowNo = getParentWindowNo(); // No windowNo => use main window if (parentWindowNo < 0 || parentWindowNo == Env.WINDOW_None) { return Env.getWindow(Env.WINDOW_MAIN); } // Use particular window final JFrame frame = Env.getWindow(parentWindowNo); if (frame != null) { return frame; }
// Fallback to main window (shall not happen) return Env.getWindow(Env.WINDOW_MAIN); } /** Sets the menu where we shall add the info windows menu items */ public InfoWindowMenuBuilder setMenu(final JMenu menu) { assertNotBuilt(); Check.assumeNotNull(menu, "menu not null"); _menu = menu; return this; } private final JMenu getMenu() { Check.assumeNotNull(_menu, "menu not null"); return _menu; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoWindowMenuBuilder.java
1
请完成以下Java代码
public static TaxCategoryId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<TaxCategoryId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(final TaxCategoryId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(final TaxCategoryId o1, final TaxCategoryId o2) {
return Objects.equals(o1, o2); } int repoId; private TaxCategoryId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_TaxCategory_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\TaxCategoryId.java
1
请完成以下Java代码
private final void processTableSelectedRows(final SelectableRowProcessor processor) { final AnnotatedTableModel<?> tableModel = getTableModelOrNull(); if (tableModel == null) { return; } final TableColumnInfo selectionColumnInfo = tableModel.getMetaInfo().getSelectionTableColumnInfoOrNull(); if (selectionColumnInfo == null) { return; } final int selectionColumnIndex = tableModel.getColumnIndexByColumnName(selectionColumnInfo.getColumnName()); if (selectionColumnIndex < 0) { return; } final ListSelectionModel selectionModel = getSelectionModelOrNull(); if (selectionModel == null) { return; } final int selectionRowIndexMin = selectionModel.getMinSelectionIndex(); final int selectionRowIndexMax = selectionModel.getMaxSelectionIndex(); for (int selectionRowIndex = selectionRowIndexMin; selectionRowIndex <= selectionRowIndexMax; selectionRowIndex++) { if (!processor.isContinue()) { break; } if (!selectionModel.isSelectedIndex(selectionRowIndex)) { continue; } SelectableRowAdapter row = new SelectableRowAdapter(tableModel, selectionRowIndex, selectionColumnIndex); processor.process(row); } } protected static abstract class SelectableRowProcessor { public abstract void process(SelectableRowAdapter row);
public boolean isContinue() { return true; } } protected static final class SelectableRowAdapter { private final AnnotatedTableModel<?> tableModel; private final int rowModelIndex; private final int selectedColumnIndex; public SelectableRowAdapter(final AnnotatedTableModel<?> tableModel, final int rowModelIndex, final int selectedColumnIndex) { super(); this.tableModel = tableModel; this.rowModelIndex = rowModelIndex; this.selectedColumnIndex = selectedColumnIndex; } public void setSelected(final boolean selected) { tableModel.setValueAt(selected, rowModelIndex, selectedColumnIndex); } public boolean isSelected() { final Object valueObj = tableModel.getValueAt(rowModelIndex, selectedColumnIndex); return DisplayType.toBoolean(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AbstractManageSelectableRowsAction.java
1
请在Spring Boot框架中完成以下Java代码
public class DunningExportClientFactoryImpl implements DunningExportClientFactory { private final ExportConfigRepository configRepository; private final CrossVersionServiceRegistry crossVersionServiceRegistry; public DunningExportClientFactoryImpl( @NonNull final ExportConfigRepository configRepository, @NonNull final CrossVersionServiceRegistry crossVersionServiceRegistry) { this.configRepository = configRepository; this.crossVersionServiceRegistry = crossVersionServiceRegistry; } @Override public String getDunningExportProviderId() { return ForumDatenaustauschChConstants.DUNNING_EXPORT_PROVIDER_ID; } @Override public Optional<DunningExportClient> newClientForDunning(@NonNull final DunningToExport dunning) { final String requiredAttachmentTagName = InvoiceExportClientFactory.ATTACHMENT_TAGNAME_EXPORT_PROVIDER; final String requiredAttachmentTagValue = ForumDatenaustauschChConstants.INVOICE_EXPORT_PROVIDER_ID; boolean atLeastOneattachmentWasCreatedByForumDatenaustausch = false; for (final DunningAttachment dunningAttachment : dunning.getDunningAttachments()) { final String invoiceExportProvider = dunningAttachment.getTags().get(requiredAttachmentTagName); if (requiredAttachmentTagValue.equals(invoiceExportProvider)) { atLeastOneattachmentWasCreatedByForumDatenaustausch = true; break; } } if (!atLeastOneattachmentWasCreatedByForumDatenaustausch)
{ Loggables.addLog("forum_datenaustausch_ch - The dunning with id={} has no attachment with an {}={}-tag", dunning.getId(), requiredAttachmentTagName, requiredAttachmentTagValue); return Optional.empty(); } final BPartnerId recipientId = dunning.getRecipientId(); final BPartnerQuery query = BPartnerQuery .builder() .bPartnerId(de.metas.bpartner.BPartnerId.ofRepoId(recipientId.getRepoId())) .build(); final ExportConfig config = configRepository.getForQueryOrNull(query); if (config == null) { Loggables.addLog("forum_datenaustausch_ch - There is no export config for the recipiend-id={} of the invoice with id={}", recipientId, dunning.getId()); return Optional.empty(); } final DunningExportClientImpl client = new DunningExportClientImpl(crossVersionServiceRegistry, config); if (!client.canExport(dunning)) { Loggables.addLog("forum_datenaustausch_ch - the export-client {} claims that it can't export the dunning with id={}", client.getClass().getSimpleName(), dunning.getId()); return Optional.empty(); } return Optional.of(client); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientFactoryImpl.java
2
请完成以下Java代码
public Event findLatestDebugRuleNodeInEvent(UUID tenantId, UUID entityId) { return DaoUtil.getData(ruleNodeDebugEventRepository.findLatestDebugRuleNodeInEvent(tenantId, entityId)); } @Override public void cleanupEvents(long regularEventExpTs, long debugEventExpTs, boolean cleanupDb) { if (regularEventExpTs > 0) { log.info("Going to cleanup regular events with exp time: {}", regularEventExpTs); if (cleanupDb) { cleanupEvents(regularEventExpTs, false); } else { cleanupPartitionsCache(regularEventExpTs, false); } } if (debugEventExpTs > 0) { log.info("Going to cleanup debug events with exp time: {}", debugEventExpTs); if (cleanupDb) { cleanupEvents(debugEventExpTs, true); } else { cleanupPartitionsCache(debugEventExpTs, true); } } } private void cleanupEvents(long eventExpTime, boolean debug) { for (EventType eventType : EventType.values()) { if (eventType.isDebug() == debug) { cleanupPartitions(eventType, eventExpTime); } } } private void cleanupPartitions(EventType eventType, long eventExpTime) { partitioningRepository.dropPartitionsBefore(eventType.getTable(), eventExpTime, partitionConfiguration.getPartitionSizeInMs(eventType)); } private void cleanupPartitionsCache(long expTime, boolean isDebug) { for (EventType eventType : EventType.values()) { if (eventType.isDebug() == isDebug) { partitioningRepository.cleanupPartitionsCache(eventType.getTable(), expTime, partitionConfiguration.getPartitionSizeInMs(eventType)); } } }
private void parseUUID(String src, String paramName) { if (!StringUtils.isEmpty(src)) { try { UUID.fromString(src); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Failed to convert " + paramName + " to UUID!"); } } } private EventRepository<? extends EventEntity<?>, ?> getEventRepository(EventType eventType) { var repository = repositories.get(eventType); if (repository == null) { throw new RuntimeException("Event type: " + eventType + " is not supported!"); } return repository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\JpaBaseEventDao.java
1
请完成以下Java代码
public static ContactPerson deliveryContactFromPO(final I_GO_DeliveryOrder orderPO) { final String phoneNo = orderPO.getGO_DeliverToPhoneNo(); if (Check.isEmpty(phoneNo, true)) { return null; } return ContactPerson.builder() .phone(PhoneNumber.fromString(phoneNo)) .build(); } public static void deliveryContactToPO(final I_GO_DeliveryOrder orderPO, final ContactPerson deliveryContact) { orderPO.setGO_DeliverToPhoneNo(deliveryContact != null ? deliveryContact.getPhoneAsStringOrNull() : null); } public static DeliveryPosition deliveryPositionFromPO(final I_GO_DeliveryOrder orderPO, final Set<PackageId> mpackageIds) { return DeliveryPosition.builder() .numberOfPackages(orderPO.getGO_NumberOfPackages()) .packageIds(mpackageIds) .grossWeightKg(BigDecimal.valueOf(orderPO.getGO_GrossWeightKg())) .content(orderPO.getGO_PackageContentDescription()) .build(); } public static void deliveryPositionToPO(final I_GO_DeliveryOrder orderPO, final DeliveryPosition deliveryPosition)
{ orderPO.setGO_NumberOfPackages(deliveryPosition.getNumberOfPackages()); final int go_grossWeightKg = deliveryPosition.getGrossWeightKg() .setScale(0, RoundingMode.UP) .intValue(); orderPO.setGO_GrossWeightKg(go_grossWeightKg); orderPO.setGO_PackageContentDescription(deliveryPosition.getContent()); } // ------------ private static int createC_Location_ID(final Address address) { final I_C_Location locationPO = InterfaceWrapperHelper.newInstanceOutOfTrx(I_C_Location.class); locationPO.setAddress1(address.getStreet1()); locationPO.setAddress2(address.getStreet2()); locationPO.setAddress3(address.getHouseNo()); locationPO.setPostal(address.getZipCode()); locationPO.setCity(address.getCity()); final String countryCode2 = address.getCountry().getAlpha2(); final I_C_Country country = Services.get(ICountryDAO.class).retrieveCountryByCountryCode(countryCode2); locationPO.setC_Country(country); InterfaceWrapperHelper.save(locationPO); return locationPO.getC_Location_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GODeliveryOrderConverters.java
1
请完成以下Java代码
public BigDecimal getSeqNb() { return seqNb; } /** * Sets the value of the seqNb property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSeqNb(BigDecimal value) { this.seqNb = value; } /** * Gets the value of the rcrd property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rcrd property. * * <p>
* For example, to add a new item, do as follows: * <pre> * getRcrd().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TaxRecord1 } * * */ public List<TaxRecord1> getRcrd() { if (rcrd == null) { rcrd = new ArrayList<TaxRecord1>(); } return this.rcrd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxInformation3.java
1
请完成以下Java代码
private void fetchVariableValues(List<HistoricVariableUpdate> historicVariableUpdates, CommandContext commandContext) { if (!CollectionUtil.isEmpty(historicVariableUpdates)) { List<String> byteArrayIds = getByteArrayIds(historicVariableUpdates); if (!byteArrayIds.isEmpty()) { // pre-fetch all byte arrays into dbEntityCache to avoid (n+1) number of queries commandContext.getOptimizeManager().fetchHistoricVariableUpdateByteArrays(byteArrayIds); } resolveTypedValues(historicVariableUpdates); } } protected boolean shouldFetchValue(HistoricDetailVariableInstanceUpdateEntity entity) { final ValueType entityType = entity.getSerializer().getType(); // do no fetch values for byte arrays/blob variables (e.g. files or bytes) return !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entityType.getName()) // nor object values unless enabled && (!ValueType.OBJECT.equals(entityType) || !excludeObjectValues); } protected boolean isHistoricDetailVariableInstanceUpdateEntity(HistoricVariableUpdate variableUpdate) { return variableUpdate instanceof HistoricDetailVariableInstanceUpdateEntity; } protected List<String> getByteArrayIds(List<HistoricVariableUpdate> variableUpdates) { List<String> byteArrayIds = new ArrayList<>(); for (HistoricVariableUpdate variableUpdate : variableUpdates) { if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) { HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate; if (shouldFetchValue(entity)) { String byteArrayId = entity.getByteArrayValueId();
if (byteArrayId != null) { byteArrayIds.add(byteArrayId); } } } } return byteArrayIds; } protected void resolveTypedValues(List<HistoricVariableUpdate> variableUpdates) { for (HistoricVariableUpdate variableUpdate : variableUpdates) { if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) { HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate; if (shouldFetchValue(entity)) { try { entity.getTypedValue(false); } catch (Exception t) { // do not fail if one of the variables fails to load LOG.exceptionWhileGettingValueForVariable(t); } } } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\optimize\OptimizeHistoricVariableUpdateQueryCmd.java
1
请完成以下Java代码
static ConfigurationPropertyCaching get(Environment environment) { return get(environment, null); } /** * Get for a specific configuration property source in the environment. * @param environment the spring environment * @param underlyingSource the * {@link ConfigurationPropertySource#getUnderlyingSource() underlying source} that * must match * @return a caching instance that controls the matching source */ static ConfigurationPropertyCaching get(Environment environment, @Nullable Object underlyingSource) { Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment); return get(sources, underlyingSource); } /** * Get for all specified configuration property sources. * @param sources the configuration property sources * @return a caching instance that controls the sources */ static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources) { return get(sources, null); } /** * Get for a specific configuration property source in the specified configuration * property sources. * @param sources the configuration property sources * @param underlyingSource the * {@link ConfigurationPropertySource#getUnderlyingSource() underlying source} that * must match * @return a caching instance that controls the matching source */ static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources, @Nullable Object underlyingSource) { Assert.notNull(sources, "'sources' must not be null"); if (underlyingSource == null) { return new ConfigurationPropertySourcesCaching(sources); } for (ConfigurationPropertySource source : sources) { if (source.getUnderlyingSource() == underlyingSource) { ConfigurationPropertyCaching caching = CachingConfigurationPropertySource.find(source);
if (caching != null) { return caching; } } } throw new IllegalStateException("Unable to find cache from configuration property sources"); } /** * {@link AutoCloseable} used to control a * {@link ConfigurationPropertyCaching#override() cache override}. * * @since 3.5.0 */ interface CacheOverride extends AutoCloseable { @Override void close(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertyCaching.java
1
请在Spring Boot框架中完成以下Java代码
public void start(PlatformServiceContainer mBeanServiceContainer) { // nothing to do } public void stop(PlatformServiceContainer mBeanServiceContainer) { // clear the queue threadPoolQueue.clear(); // Ask the thread pool to finish and exit threadPoolExecutor.shutdown(); // Waits for 1 minute to finish all currently executing jobs try { if(!threadPoolExecutor.awaitTermination(60L, TimeUnit.SECONDS)) { LOG.timeoutDuringShutdownOfThreadPool(60, TimeUnit.SECONDS); } } catch (InterruptedException e) { LOG.interruptedWhileShuttingDownThreadPool(e); } } public JmxManagedThreadPool getValue() { return this; } public void setCorePoolSize(int corePoolSize) { threadPoolExecutor.setCorePoolSize(corePoolSize); } public void setMaximumPoolSize(int maximumPoolSize) { threadPoolExecutor.setMaximumPoolSize(maximumPoolSize); } public int getMaximumPoolSize() { return threadPoolExecutor.getMaximumPoolSize(); }
public void setKeepAliveTime(long time, TimeUnit unit) { threadPoolExecutor.setKeepAliveTime(time, unit); } public void purgeThreadPool() { threadPoolExecutor.purge(); } public int getPoolSize() { return threadPoolExecutor.getPoolSize(); } public int getActiveCount() { return threadPoolExecutor.getActiveCount(); } public int getLargestPoolSize() { return threadPoolExecutor.getLargestPoolSize(); } public long getTaskCount() { return threadPoolExecutor.getTaskCount(); } public long getCompletedTaskCount() { return threadPoolExecutor.getCompletedTaskCount(); } public int getQueueCount() { return threadPoolQueue.size(); } public int getQueueAddlCapacity() { return threadPoolQueue.remainingCapacity(); } public ThreadPoolExecutor getThreadPoolExecutor() { return threadPoolExecutor; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedThreadPool.java
2
请完成以下Java代码
public class AppServerXML { public static void main(String[] args) throws Exception { AppServerXML app = new AppServerXML(); Catalina catalina = app.startServer(); catalina.getServer().await(); } public Catalina startServer() throws Exception { URL staticUrl = getClass().getClassLoader().getResource("static"); if (staticUrl == null) { throw new IllegalStateException("Static directory not found in classpath"); } Path staticDir = Paths.get(staticUrl.toURI()); Path baseDir = Paths.get("target/tomcat-base").toAbsolutePath(); Files.createDirectories(baseDir); String config; try (InputStream serverXmlStream = getClass().getClassLoader().getResourceAsStream("server.xml")) { if (serverXmlStream == null) { throw new IllegalStateException("server.xml not found in classpath"); } config = new String(serverXmlStream.readAllBytes()) .replace("STATIC_DIR_PLACEHOLDER", staticDir.toString()); } Path configFile = baseDir.resolve("server.xml");
Files.writeString(configFile, config); System.setProperty("catalina.base", baseDir.toString()); System.setProperty("catalina.home", baseDir.toString()); Catalina catalina = new Catalina(); catalina.load(new String[]{"-config", configFile.toString()}); catalina.start(); System.out.println("\nTomcat started with multiple connectors!"); System.out.println("http://localhost:8081"); System.out.println("http://localhost:7081"); return catalina; } }
repos\tutorials-master\server-modules\apache-tomcat-2\src\main\java\com\baeldung\tomcat\AppServerXML.java
1
请在Spring Boot框架中完成以下Java代码
public class Exam { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Lob private String description; @Column(columnDefinition = "text") private String text; @Column(length = 20) private String shortText; public Exam() { } public Exam(String description, String text, String shortText) { this.description = description; this.text = text; this.shortText = shortText; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getShortText() { return shortText; } public void setShortText(String shortText) { this.shortText = shortText; } @Override
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((shortText == null) ? 0 : shortText.hashCode()); result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Exam other = (Exam) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (shortText == null) { if (other.shortText != null) return false; } else if (!shortText.equals(other.shortText)) return false; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\text\Exam.java
2
请完成以下Java代码
public Object getValue(VariableContainer variableContainer) { ELContext elContext = expressionManager.getElContext(variableContainer); Object originalVariableContainer = elContext.getContext(VariableContainer.class); elContext.putContext(VariableContainer.class, variableContainer); Object originalValueContext = elContext.getContext(EvaluationState.class); elContext.putContext(EvaluationState.class, EvaluationState.READ); try { return resolveGetValueExpression(elContext); } catch (PropertyNotFoundException pnfe) { throw new FlowableException("Unknown property used in expression: " + expressionText + " with " + variableContainer, pnfe); } catch (MethodNotFoundException mnfe) { throw new FlowableException("Unknown method used in expression: " + expressionText + " with " + variableContainer, mnfe); } catch (FlowableException ex) { throw ex; } catch (Exception e) { throw new FlowableException("Error while evaluating expression: " + expressionText + " with " + variableContainer, e); } finally { elContext.putContext(EvaluationState.class, originalValueContext); elContext.putContext(VariableContainer.class, originalVariableContainer); } } protected Object resolveGetValueExpression(ELContext elContext) { return valueExpression.getValue(elContext); } @Override public void setValue(Object value, VariableContainer variableContainer) { ELContext elContext = expressionManager.getElContext(variableContainer); Object originalVariableContainer = elContext.getContext(VariableContainer.class); elContext.putContext(VariableContainer.class, variableContainer);
Object originalValueContext = elContext.getContext(EvaluationState.class); elContext.putContext(EvaluationState.class, EvaluationState.WRITE); try { resolveSetValueExpression(value, elContext); } catch (Exception e) { throw new FlowableException("Error while evaluating expression: " + expressionText + " with " + variableContainer, e); } finally { elContext.putContext(EvaluationState.class, originalValueContext); elContext.putContext(VariableContainer.class, originalVariableContainer); } } protected void resolveSetValueExpression(Object value, ELContext elContext) { valueExpression.setValue(elContext, value); } @Override public String toString() { if (valueExpression != null) { return valueExpression.getExpressionString(); } return super.toString(); } @Override public String getExpressionText() { return expressionText; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\JuelExpression.java
1
请完成以下Java代码
public void fireBeforeComplete(final I_C_RfQResponse rfqResponse) { listeners.onBeforeComplete(rfqResponse); } @Override public void fireAfterComplete(final I_C_RfQResponse rfqResponse) { listeners.onAfterComplete(rfqResponse); } @Override public void fireBeforeClose(final I_C_RfQResponse rfqResponse) { listeners.onBeforeClose(rfqResponse); } @Override public void fireAfterClose(final I_C_RfQResponse rfqResponse) { listeners.onAfterClose(rfqResponse); } @Override public void fireBeforeUnClose(I_C_RfQ rfq) { listeners.onBeforeUnClose(rfq); } @Override public void fireAfterUnClose(I_C_RfQ rfq) { // TODO Auto-generated method stub
} @Override public void fireBeforeUnClose(I_C_RfQResponse rfqResponse) { // TODO Auto-generated method stub } @Override public void fireAfterUnClose(I_C_RfQResponse rfqResponse) { // TODO Auto-generated method stub } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\event\impl\RfQEventDispacher.java
1
请完成以下Java代码
default ImportProcessResult validate(@NonNull final ValidateImportRecordsRequest request) { clientId(request.getClientId()); setParameters(request.getAdditionalParameters()); selectedRecords(request.getSelectionId()); validateOnly(true); return run(); } default ImportProcessResult validateAndImport(@NonNull final ImportRecordsRequest request) { clientId(request.getClientId()); selectedRecords(request.getSelectionId()); limit(request.getLimit()); completeDocuments(request.isCompleteDocuments()); setParameters(request.getAdditionalParameters()); notifyUserId(request.getNotifyUserId()); return run();
} IImportProcess<ImportRecordType> notifyUserId(@Nullable UserId notifyUserId); /** * Run the import. */ ImportProcessResult run(); /** * Delete import records * * @return how many rows were deleted */ int deleteImportRecords(ImportDataDeleteRequest request); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\IImportProcess.java
1
请完成以下Java代码
public String toString() { // NOTE: we are making it translatable friendly because it's displayed in Prefereces->Info->Rollen final String constraintsName = getClass().getSimpleName(); final Collection<Constraint> constraintsList = constraints.values(); final StringBuilder sb = new StringBuilder(); sb.append(constraintsName).append(": "); if (constraintsList.isEmpty()) { sb.append("@None@"); } else { sb.append(Env.NL); } Joiner.on(Env.NL) .skipNulls() .appendTo(sb, constraintsList); return sb.toString(); } public <T extends Constraint> Optional<T> getConstraint(final Class<T> constraintType) { @SuppressWarnings("unchecked") final T constraint = (T)constraints.get(constraintType); return Optional.ofNullable(constraint); } public static final class Builder { private final LinkedHashMap<Class<? extends Constraint>, Constraint> constraints = new LinkedHashMap<>(); private Builder() { super(); } public Constraints build() { return new Constraints(this); }
private ImmutableMap<Class<? extends Constraint>, Constraint> getConstraints() { return ImmutableMap.copyOf(constraints); } public Builder addConstraint(final Constraint constraint) { Check.assumeNotNull(constraint, "constraint not null"); constraints.put(constraint.getClass(), constraint); return this; } public Builder addConstraintIfNotEquals(final Constraint constraint, final Constraint constraintToExclude) { Check.assumeNotNull(constraint, "constraint not null"); Check.assumeNotNull(constraintToExclude, "constraintToExclude not null"); if (constraint.equals(constraintToExclude)) { return this; } constraints.put(constraint.getClass(), constraint); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\Constraints.java
1
请完成以下Java代码
public class Payment implements ModelValidator { private int ad_Client_ID = -1; @Override public int getAD_Client_ID() { return ad_Client_ID; } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // nothing to do return null; } @Override public final void initialize(final ModelValidationEngine engine, final MClient client) { if (client != null) { ad_Client_ID = client.getAD_Client_ID(); } engine.addModelChange(I_C_Payment.Table_Name, this); } @Override public String modelChange(final PO po, final int type) throws Exception { if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE) { final MPayment payment = (MPayment)po; if (po.is_ValueChanged(I_C_Payment.COLUMNNAME_CreditCardNumber) || po.is_ValueChanged(I_C_Payment.COLUMNNAME_CreditCardVV)) { final OrgId orgId = OrgId.ofRepoId(payment.getAD_Org_ID());
final OrgInfo orgInfo = Services.get(IOrgDAO.class).getOrgInfoById(orgId); final StoreCreditCardNumberMode ccStoreMode = orgInfo.getStoreCreditCardNumberMode(); if (StoreCreditCardNumberMode.DONT_STORE.equals(ccStoreMode)) { payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardNumber, payment.getCreditCardNumber().replaceAll(" ", "").replaceAll(".", "*")); payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardVV, payment.getCreditCardVV().replaceAll(" ", "").replaceAll(".", "*")); } else if (StoreCreditCardNumberMode.LAST_4_DIGITS.equals(ccStoreMode)) { final String creditCardNumer = payment.getCreditCardNumber(); final Obscure obscure = new Obscure(creditCardNumer, X_AD_Field.OBSCURETYPE_ObscureAlphaNumericButLast4); payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardNumber, obscure.getObscuredValue()); payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardVV, "***"); } else { // nothing to do } } } return null; } @Override public String docValidate(final PO po, final int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\Payment.java
1
请在Spring Boot框架中完成以下Java代码
public class NaturalRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements NaturalRepository<T, ID> { private final EntityManager entityManager; public NaturalRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { super(entityInformation, entityManager); this.entityManager = entityManager; } @Override public Optional<T> findBySimpleNaturalId(ID naturalId) { Optional<T> entity = entityManager.unwrap(Session.class) .bySimpleNaturalId(this.getDomainClass()) .loadOptional(naturalId);
return entity; } @Override public Optional<T> findByNaturalId(Map<String, Object> naturalIds) { NaturalIdLoadAccess<T> loadAccess = entityManager.unwrap(Session.class).byNaturalId(this.getDomainClass()); naturalIds.forEach(loadAccess::using); return loadAccess.loadOptional(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalIdCache\src\main\java\com\bookstore\naturalid\NaturalRepositoryImpl.java
2
请完成以下Java代码
public class HistoricIdentityLinkEntityManagerImpl extends AbstractEntityManager<HistoricIdentityLinkEntity> implements HistoricIdentityLinkEntityManager { protected HistoricIdentityLinkDataManager historicIdentityLinkDataManager; public HistoricIdentityLinkEntityManagerImpl( ProcessEngineConfigurationImpl processEngineConfiguration, HistoricIdentityLinkDataManager historicIdentityLinkDataManager ) { super(processEngineConfiguration); this.historicIdentityLinkDataManager = historicIdentityLinkDataManager; } @Override protected DataManager<HistoricIdentityLinkEntity> getDataManager() { return historicIdentityLinkDataManager; } @Override public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByTaskId(String taskId) { return historicIdentityLinkDataManager.findHistoricIdentityLinksByTaskId(taskId); } @Override public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByProcessInstanceId(String processInstanceId) { return historicIdentityLinkDataManager.findHistoricIdentityLinksByProcessInstanceId(processInstanceId); } @Override public void deleteHistoricIdentityLinksByTaskId(String taskId) { List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByTaskId(taskId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) { delete(identityLink); } } @Override public void deleteHistoricIdentityLinksByProcInstance(final String processInstanceId) { List<HistoricIdentityLinkEntity> identityLinks = historicIdentityLinkDataManager.findHistoricIdentityLinksByProcessInstanceId(processInstanceId); for (HistoricIdentityLinkEntity identityLink : identityLinks) { delete(identityLink); } } public HistoricIdentityLinkDataManager getHistoricIdentityLinkDataManager() { return historicIdentityLinkDataManager; } public void setHistoricIdentityLinkDataManager(HistoricIdentityLinkDataManager historicIdentityLinkDataManager) { this.historicIdentityLinkDataManager = historicIdentityLinkDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityManagerImpl.java
1
请完成以下Java代码
public @Nullable Duration getPeriod() { return period; } public RateLimitConfig setPeriod(Duration period) { this.period = period; return this; } public @Nullable Function<ServerRequest, String> getKeyResolver() { return keyResolver; } public RateLimitConfig setKeyResolver(Function<ServerRequest, String> keyResolver) { Objects.requireNonNull(keyResolver, "keyResolver may not be null"); this.keyResolver = keyResolver; return this; } public HttpStatusCode getStatusCode() { return statusCode; } public RateLimitConfig setStatusCode(HttpStatusCode statusCode) { this.statusCode = statusCode; return this; } public @Nullable Duration getTimeout() { return timeout; } public RateLimitConfig setTimeout(Duration timeout) { this.timeout = timeout; return this; }
public int getTokens() { return tokens; } public RateLimitConfig setTokens(int tokens) { Assert.isTrue(tokens > 0, "tokens must be greater than zero"); this.tokens = tokens; return this; } public String getHeaderName() { return headerName; } public RateLimitConfig setHeaderName(String headerName) { Objects.requireNonNull(headerName, "headerName may not be null"); this.headerName = headerName; return this; } } public static class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(Bucket4jFilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\Bucket4jFilterFunctions.java
1
请完成以下Java代码
public String getPrivilegeId() { return privilegeId; } @Override public void setPrivilegeId(String privilegeId) { this.privilegeId = privilegeId; } @Override public String getUserId() { return userId; } @Override
public void setUserId(String userId) { this.userId = userId; } @Override public String getGroupId() { return groupId; } @Override public void setGroupId(String groupId) { this.groupId = groupId; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\PrivilegeMappingEntityImpl.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Window getOverrides_Window() { return get_ValueAsPO(COLUMNNAME_Overrides_Window_ID, org.compiere.model.I_AD_Window.class); } @Override public void setOverrides_Window(final org.compiere.model.I_AD_Window Overrides_Window) { set_ValueFromPO(COLUMNNAME_Overrides_Window_ID, org.compiere.model.I_AD_Window.class, Overrides_Window); } @Override public void setOverrides_Window_ID (final int Overrides_Window_ID) { if (Overrides_Window_ID < 1) set_Value (COLUMNNAME_Overrides_Window_ID, null); else set_Value (COLUMNNAME_Overrides_Window_ID, Overrides_Window_ID); } @Override public int getOverrides_Window_ID() { return get_ValueAsInt(COLUMNNAME_Overrides_Window_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } /** * WindowType AD_Reference_ID=108 * Reference name: AD_Window Types */ public static final int WINDOWTYPE_AD_Reference_ID=108; /** Single Record = S */ public static final String WINDOWTYPE_SingleRecord = "S"; /** Maintain = M */ public static final String WINDOWTYPE_Maintain = "M"; /** Transaktion = T */ public static final String WINDOWTYPE_Transaktion = "T"; /** Query Only = Q */ public static final String WINDOWTYPE_QueryOnly = "Q"; @Override public void setWindowType (final java.lang.String WindowType) { set_Value (COLUMNNAME_WindowType, WindowType); } @Override public java.lang.String getWindowType() {
return get_ValueAsString(COLUMNNAME_WindowType); } @Override public void setWinHeight (final int WinHeight) { set_Value (COLUMNNAME_WinHeight, WinHeight); } @Override public int getWinHeight() { return get_ValueAsInt(COLUMNNAME_WinHeight); } @Override public void setWinWidth (final int WinWidth) { set_Value (COLUMNNAME_WinWidth, WinWidth); } @Override public int getWinWidth() { return get_ValueAsInt(COLUMNNAME_WinWidth); } @Override public void setZoomIntoPriority (final int ZoomIntoPriority) { set_Value (COLUMNNAME_ZoomIntoPriority, ZoomIntoPriority); } @Override public int getZoomIntoPriority() { return get_ValueAsInt(COLUMNNAME_ZoomIntoPriority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window.java
1
请在Spring Boot框架中完成以下Java代码
public PageBean listPage(PageParam pageParam, PmsRole pmsRole) { Map<String, Object> paramMap = new HashMap<String, Object>(); // 业务条件查询参数 paramMap.put("roleName", pmsRole.getRoleName()); // 角色名称(模糊查询) return pmsRoleDao.listPage(pageParam, paramMap); } /** * 获取所有角色列表,以供添加操作员时选择. * * @return roleList . */ public List<PmsRole> listAllRole() { return pmsRoleDao.listAll(); } /** * 判断此权限是否关联有角色 * * @param permissionId * @return */ public List<PmsRole> listByPermissionId(Long permissionId) { return pmsRoleDao.listByPermissionId(permissionId); } /** * 根据角色名或者角色编号查询角色 * * @param roleName * @param roleCode
* @return */ public PmsRole getByRoleNameOrRoleCode(String roleName, String roleCode) { return pmsRoleDao.getByRoleNameOrRoleCode(roleName, roleCode); } /** * 删除 * * @param roleId */ public void delete(Long roleId) { pmsRoleDao.delete(roleId); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsRoleServiceImpl.java
2
请完成以下Java代码
protected final Boolean isDLMTable(final IProcessPreconditionsContext context) { if (Check.equals(context.getTableName(), I_DLM_Partition_Config_Line.Table_Name)) { final I_DLM_Partition_Config_Line configLine = context.getSelectedModel(I_DLM_Partition_Config_Line.class); final I_AD_Table table = InterfaceWrapperHelper.create(configLine.getDLM_Referencing_Table(), I_AD_Table.class); return table.isDLM(); // if the table is already DLMed, then return false } else if (Check.equals(context.getTableName(), org.compiere.model.I_AD_Table.Table_Name)) { final I_AD_Table table = context.getSelectedModel(I_AD_Table.class); return table.isDLM(); // if the table is already DLMed, then return false } return null; } @Override
public final Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final int configLineId = parameter.getContextAsInt(I_DLM_Partition_Config_Line.COLUMNNAME_DLM_Partition_Config_Line_ID); if (configLineId > 0) { final I_DLM_Partition_Config_Line configLine = InterfaceWrapperHelper.create(getCtx(), configLineId, I_DLM_Partition_Config_Line.class, ITrx.TRXNAME_None); return configLine.getDLM_Referencing_Table_ID(); } final int tableId = parameter.getContextAsInt(I_AD_Table.COLUMNNAME_AD_Table_ID); if (tableId > 0) { return tableId; } return DEFAULT_VALUE_NOTAVAILABLE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\process\AbstractManageDLMTableProcess.java
1
请在Spring Boot框架中完成以下Java代码
private String getVersionAttr(@Nullable final String sourceVersionAttr) { if (sourceVersionAttr == null) { return null; } if ("*".equals(sourceVersionAttr)) { return null; } return sourceVersionAttr; } @Nullable private ReplicationTypeEnum getReplicationTypeAttr(@Nullable final de.metas.edi.esb.jaxb.metasfreshinhousev2.ReplicationTypeEnum replicationType) { return Optional.ofNullable(replicationType)
.map(attr -> ReplicationTypeEnum.fromValue(attr.value())) .orElse(null); } @Nullable private ReplicationModeEnum getReplicationModeAttr(@Nullable final de.metas.edi.esb.jaxb.metasfreshinhousev2.ReplicationModeEnum replicationModeAttr) { return Optional.ofNullable(replicationModeAttr) .map(attr -> ReplicationModeEnum.fromValue(attr.value())) .orElse(null); } @Nullable private ReplicationEventEnum getReplicationEventAttr(@Nullable final de.metas.edi.esb.jaxb.metasfreshinhousev2.ReplicationEventEnum replicationEventAttr) { return Optional.ofNullable(replicationEventAttr) .map(attr -> ReplicationEventEnum.fromValue(attr.value())) .orElse(null); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\metasfreshinhousev1\MetasfreshInHouseV1XMLDesadvBean.java
2
请完成以下Java代码
public int getWorkflow_ID() { return get_ValueAsInt(COLUMNNAME_Workflow_ID); } @Override public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() { return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setXPosition (final int XPosition) { set_Value (COLUMNNAME_XPosition, XPosition); } @Override public int getXPosition() { return get_ValueAsInt(COLUMNNAME_XPosition); } @Override
public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } @Override public void setYPosition (final int YPosition) { set_Value (COLUMNNAME_YPosition, YPosition); } @Override public int getYPosition() { return get_ValueAsInt(COLUMNNAME_YPosition); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java
1
请完成以下Java代码
public final static String xmlEncodeTextAsPCDATA(String text) { if (text == null) return null; char c; StringBuffer n = new StringBuffer (text.length () * 2); for (int i = 0; i < text.length (); i++) { c = text.charAt (i); switch (c) { case '&': n.append ("&amp;"); break; case '<': n.append ("&lt;"); break; case '>': n.append ("&gt;"); break;
case '"': n.append ("&quot;"); break; case '\'': n.append ("&apos;"); break; default: { n.append (c); break; } } } return n.toString (); } // xmlEncodeTextAsPCDATA } //Ofx1To2Convertor
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\impexp\OFX1ToXML.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_HU_Trx_Hdr_ID (final int M_HU_Trx_Hdr_ID) { if (M_HU_Trx_Hdr_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Trx_Hdr_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Trx_Hdr_ID, M_HU_Trx_Hdr_ID); } @Override public int getM_HU_Trx_Hdr_ID() {
return get_ValueAsInt(COLUMNNAME_M_HU_Trx_Hdr_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Hdr.java
1
请完成以下Java代码
public Map<String, Credential> getUsers() { return users; } public void setUsers(Map<String, Credential> users) { this.users = users; } public static class Credential { private String username; private String password; public String getUsername() { return username;
} public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties-2\src\main\java\com\baeldung\properties\yamlmap\pojo\ServerProperties.java
1
请完成以下Java代码
public void updateArchiveFlags(final I_AD_Archive archive) { if (archive.getC_Doc_Outbound_Config_ID() <= 0) { return; // nothing to do } // task 09417: also check if the archive references a docOutBoundConfig, and if yes, use its settings. final I_C_Doc_Outbound_Config config = InterfaceWrapperHelper.create(archive.getC_Doc_Outbound_Config(), I_C_Doc_Outbound_Config.class); archive.setIsDirectEnqueue(config.isDirectEnqueue()); archive.setIsDirectProcessQueueItem(config.isDirectProcessQueueItem()); } /** * If direct print is required for given {@link AD_Archive} then this method enqueues the archive to printing queue. */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_AD_Archive.COLUMNNAME_IsDirectProcessQueueItem, I_AD_Archive.COLUMNNAME_IsDirectEnqueue, I_AD_Archive.COLUMNNAME_C_Doc_Outbound_Config_ID, I_AD_Archive.COLUMNNAME_IsActive }) public void printArchive(final I_AD_Archive archive) { final PrintArchiveParameters printArchiveParameters = PrintArchiveParameters.builder() .archive(archive) .printOutputFacade(printOutputFacade) .hwPrinterId(null) .hwTrayId(null) .enforceEnqueueToPrintQueue(false) .build(); printingQueueBL.printArchive(printArchiveParameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_Archive.java
1
请完成以下Java代码
public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID) { if (EDI_cctop_invoic_v_ID < 1) set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null); else set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID); } @Override public int getEDI_cctop_invoic_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID); } @Override public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName()
{ return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_140_v.java
1
请完成以下Java代码
private AdWindowId getFactAcctWindowId(@Nullable final AdWindowId expectedTargetWindowId) { // // Get the Fact_Acct AD_Window_ID final AdWindowId factAcctWindowId = CoalesceUtil.coalesceSuppliers( () -> RecordWindowFinder.findAdWindowId(TABLENAME_Fact_Acct_Transactions_View).orElse(null), () -> RecordWindowFinder.findAdWindowId(I_Fact_Acct.Table_Name).orElse(null) ); if (factAcctWindowId == null) { return null; } // If not our target window ID, return nothing if (expectedTargetWindowId != null && !AdWindowId.equals(expectedTargetWindowId, factAcctWindowId)) { return null;
} return factAcctWindowId; } private OptionalBoolean checkIsPosted(@NonNull final IZoomSource document) { if (document.hasField(COLUMNNAME_Posted)) { final boolean posted = document.getFieldValueAsBoolean(COLUMNNAME_Posted); return OptionalBoolean.ofBoolean(posted); } else { return OptionalBoolean.UNKNOWN; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\open_items\related_documents\ClearingFactAcctsRelatedDocumentsProvider.java
1
请完成以下Java代码
private void concatenatePDFsToOutputStream( @NonNull final OutputStream outputStream, @NonNull final ImmutableList<PdfDataProvider> pdfDataToConcatenate) { final Document document = new Document(); try { final PdfCopy copyDestination = new PdfCopy(document, outputStream); document.open(); for (final PdfDataProvider pdfData : pdfDataToConcatenate) { appendPdfPages(copyDestination, pdfData); } document.close(); } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e); } } private static void appendPdfPages(@NonNull final PdfCopy copyDestination, @NonNull final PdfDataProvider pdfData) throws IOException, BadPdfFormatException { final Resource data = pdfData.getPdfData(); final PdfReader pdfReader = new PdfReader(data.getInputStream()); for (int page = 0; page < pdfReader.getNumberOfPages(); ) { copyDestination.addPage(copyDestination.getImportedPage(pdfReader, ++page));
} copyDestination.freeReader(pdfReader); pdfReader.close(); } @Value public static class PdfDataProvider { public static PdfDataProvider forData(@NonNull final Resource pdfData) { return new PdfDataProvider(pdfData); } Resource pdfData; private PdfDataProvider(@NonNull final Resource pdfData) { this.pdfData = pdfData; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ExecuteReportStrategyUtil.java
1
请完成以下Java代码
public int getM_Product_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo)
{ set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxDefinition.java
1
请完成以下Java代码
public Mono<ClientGraphQlResponse> execute() { return initRequestSpec().execute(); } /** * Create {@link GraphQLQueryRequest}, serialize it to a String document * to send, and delegate to the wrapped {@code GraphQlClient}. * <p>See Javadoc of delegate method * {@link GraphQlClient.RequestSpec#executeSubscription()} for details. */ public Flux<ClientGraphQlResponse> executeSubscription() { return initRequestSpec().executeSubscription(); } private GraphQLQueryRequest createRequest() { Assert.state(this.projectionNode != null || this.coercingMap == null, "Coercing map provided without projection"); GraphQLQueryRequest request; if (this.coercingMap != null && this.projectionNode != null) { request = new GraphQLQueryRequest(this.query, this.projectionNode, this.coercingMap); } else if (this.projectionNode != null) { request = new GraphQLQueryRequest(this.query, this.projectionNode); } else { request = new GraphQLQueryRequest(this.query); } return request; } @SuppressWarnings("NullAway")
private GraphQlClient.RequestSpec initRequestSpec() { String document; String operationName; if (!this.additionalRequests.isEmpty()) { this.additionalRequests.add(createRequest()); document = new GraphQLMultiQueryRequest(this.additionalRequests).serialize(); operationName = null; } else { document = createRequest().serialize(); operationName = (this.query.getName() != null) ? this.query.getName() : null; } return DgsGraphQlClient.this.graphQlClient.document(document) .operationName(operationName) .attributes((map) -> { if (this.attributes != null) { map.putAll(this.attributes); } }); } private String getDefaultPath() { return this.query.getOperationName(); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DgsGraphQlClient.java
1
请完成以下Java代码
protected Parser createParser(String expression) { return new Parser(this, expression); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } return features.equals(((Builder) obj).features); } @Override public int hashCode() { return getClass().hashCode(); } /** * Dump out abstract syntax tree for a given expression * * @param args array with one element, containing the expression string */ public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java " + Builder.class.getName() + " <expression string>"); System.exit(1); } PrintWriter out = new PrintWriter(System.out); Tree tree = null; try { tree = new Builder(Feature.METHOD_INVOCATIONS).build(args[0]); } catch (TreeBuilderException e) { System.out.println(e.getMessage()); System.exit(0); } NodePrinter.dump(out, tree.getRoot()); if (!tree.getFunctionNodes().iterator().hasNext() && !tree.getIdentifierNodes().iterator().hasNext()) { ELContext context = new ELContext() { @Override public VariableMapper getVariableMapper() { return null; } @Override
public FunctionMapper getFunctionMapper() { return null; } @Override public ELResolver getELResolver() { return null; } }; out.print(">> "); try { out.println(tree.getRoot().getValue(new Bindings(null, null), context, null)); } catch (ELException e) { out.println(e.getMessage()); } } out.flush(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Builder.java
1
请在Spring Boot框架中完成以下Java代码
public ServerConfig ratpackServerConfig() { return ServerConfig .builder() .findBaseDir("public") .build(); } public static void main(String[] args) { SpringApplication.run(EmbedRatpackStreamsApp.class, args); } public static class RandomBytesPublisher implements Publisher<ByteBuf> { private int bufCount; private int bufSize; private Random rnd = new Random(); RandomBytesPublisher(int bufCount, int bufSize) { this.bufCount = bufCount; this.bufSize = bufSize; } @Override public void subscribe(Subscriber<? super ByteBuf> s) { s.onSubscribe(new Subscription() { private boolean cancelled = false; private boolean recurse; private long requested = 0; @Override public void request(long n) { if ( bufCount == 0 ) { s.onComplete(); return; } requested += n; if ( recurse ) { return; } recurse = true;
try { while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) { byte[] data = new byte[bufSize]; rnd.nextBytes(data); ByteBuf buf = Unpooled.wrappedBuffer(data); s.onNext(buf); } } finally { recurse = false; } } @Override public void cancel() { cancelled = true; } }); } } }
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\spring\EmbedRatpackStreamsApp.java
2
请完成以下Java代码
protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) { Header header = headers.lastHeader(headerName); if (header != null) { String classId = null; if (header.value() != null) { classId = new String(header.value(), StandardCharsets.UTF_8); } return classId; } return null; } private void createReverseMap() { this.classIdMapping.clear(); for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) { String id = entry.getKey(); Class<?> clazz = entry.getValue(); this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8)); }
} public Map<String, Class<?>> getIdClassMapping() { return Collections.unmodifiableMap(this.idClassMapping); } /** * Configure the TypeMapper to use default key type class. * @param isKey Use key type headers if true * @since 2.1.3 */ public void setUseForKey(boolean isKey) { if (isKey) { setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME); setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME); setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java
1
请完成以下Java代码
final class Canonicalizer { private Canonicalizer() { } static String canonicalizeAfter(String path, int pos) { int pathLength = path.length(); boolean noDotSlash = path.indexOf("./", pos) == -1; if (pos >= pathLength || (noDotSlash && path.charAt(pathLength - 1) != '.')) { return path; } String before = path.substring(0, pos); String after = path.substring(pos); return before + canonicalize(after); } static String canonicalize(String path) { path = removeEmbeddedSlashDotDotSlash(path); path = removeEmbeddedSlashDotSlash(path); path = removeTrailingSlashDotDot(path); path = removeTrailingSlashDot(path); return path; } private static String removeEmbeddedSlashDotDotSlash(String path) { int index; while ((index = path.indexOf("/../")) >= 0) { int priorSlash = path.lastIndexOf('/', index - 1); String after = path.substring(index + 3);
path = (priorSlash >= 0) ? path.substring(0, priorSlash) + after : after; } return path; } private static String removeEmbeddedSlashDotSlash(String path) { int index; while ((index = path.indexOf("/./")) >= 0) { String before = path.substring(0, index); String after = path.substring(index + 2); path = before + after; } return path; } private static String removeTrailingSlashDot(String path) { return (!path.endsWith("/.")) ? path : path.substring(0, path.length() - 1); } private static String removeTrailingSlashDotDot(String path) { int index; while (path.endsWith("/..")) { index = path.indexOf("/.."); int priorSlash = path.lastIndexOf('/', index - 1); path = (priorSlash >= 0) ? path.substring(0, priorSlash + 1) : path.substring(0, index); } return path; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\Canonicalizer.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public List<String> getMoveToPlanItemDefinitionIds() { return moveToPlanItemDefinitionIds; } public void setMoveToPlanItemDefinitionIds(List<String> moveToPlanItemDefinitionIds) { this.moveToPlanItemDefinitionIds = moveToPlanItemDefinitionIds; } public CmmnModel getCmmnModel() { return cmmnModel; } public void setCmmnModel(CmmnModel cmmnModel) { this.cmmnModel = cmmnModel; } public String getNewAssigneeId() { return newAssigneeId; } public void setNewAssigneeId(String newAssigneeId) { this.newAssigneeId = newAssigneeId; } public Map<String, PlanItemInstanceEntity> getContinueParentPlanItemInstanceMap() { return continueParentPlanItemInstanceMap; } public void setContinueParentPlanItemInstanceMap(Map<String, PlanItemInstanceEntity> continueParentPlanItemInstanceMap) { this.continueParentPlanItemInstanceMap = continueParentPlanItemInstanceMap; } public void addContinueParentPlanItemInstance(String planItemInstanceId, PlanItemInstanceEntity continueParentPlanItemInstance) { continueParentPlanItemInstanceMap.put(planItemInstanceId, continueParentPlanItemInstance); } public PlanItemInstanceEntity getContinueParentPlanItemInstance(String planItemInstanceId) { return continueParentPlanItemInstanceMap.get(planItemInstanceId); } public Map<String, PlanItemMoveEntry> getMoveToPlanItemMap() {
return moveToPlanItemMap; } public void setMoveToPlanItemMap(Map<String, PlanItemMoveEntry> moveToPlanItemMap) { this.moveToPlanItemMap = moveToPlanItemMap; } public PlanItemMoveEntry getMoveToPlanItem(String planItemId) { return moveToPlanItemMap.get(planItemId); } public List<PlanItemMoveEntry> getMoveToPlanItems() { return new ArrayList<>(moveToPlanItemMap.values()); } public static class PlanItemMoveEntry { protected PlanItem originalPlanItem; protected PlanItem newPlanItem; public PlanItemMoveEntry(PlanItem originalPlanItem, PlanItem newPlanItem) { this.originalPlanItem = originalPlanItem; this.newPlanItem = newPlanItem; } public PlanItem getOriginalPlanItem() { return originalPlanItem; } public PlanItem getNewPlanItem() { return newPlanItem; } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemInstanceEntityContainer.java
1