instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceManager() { return getSession(HistoricProcessInstanceEntityManager.class); } protected HistoricDetailEntityManager getHistoricDetailManager() { return getSession(HistoricDetailEntityManager.class); } protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceManager() { return getSession(HistoricActivityInstanceEntityManager.class); } protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceManager() { return getSession(HistoricVariableInstanceEntityManager.class); } protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceManager() { return getSession(HistoricTaskInstanceEntityManager.class); } protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return getSession(HistoricIdentityLinkEntityManager.class);
} protected AttachmentEntityManager getAttachmentManager() { return getSession(AttachmentEntityManager.class); } protected HistoryManager getHistoryManager() { return getSession(HistoryManager.class); } protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return Context.getProcessEngineConfiguration(); } @Override public void close() { } @Override public void flush() { } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<InvoicePayScheduleCreateRequest> newInvoicePayScheduleCreateRequest_fromOrderPaySchedule() { final OrderId orderId = OrderId.ofRepoIdOrNull(invoiceRecord.getC_Order_ID()); if (orderId == null) { return Optional.empty(); } final OrderPaySchedule orderPaySchedule = orderPayScheduleService.getByOrderId(orderId).orElse(null); if (orderPaySchedule == null) { return Optional.empty(); } return Optional.of( InvoicePayScheduleCreateRequest.builder() .invoiceId(InvoiceId.ofRepoId(invoiceRecord.getC_Invoice_ID())) .lines(orderPaySchedule.getLines() .stream() .map(line -> InvoicePayScheduleCreateRequest.Line.builder() .dueDate(line.getDueDate()) .dueAmount(line.getDueAmount()) .orderAndPayScheduleId(line.getOrderAndPayScheduleId()) .build()) .collect(ImmutableList.toImmutableList())) .build() ); } private Optional<InvoicePayScheduleCreateRequest> newInvoicePayScheduleCreateRequest_fromPaymentTerm() { final PaymentTermId paymentTermId = PaymentTermId.ofRepoIdOrNull(invoiceRecord.getC_PaymentTerm_ID()); if (paymentTermId == null) { return Optional.empty(); } final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId); if (!paymentTerm.isValid() || paymentTerm.getPaySchedules().isEmpty()) { return Optional.empty(); } final Money grandTotal = invoiceBL.extractGrandTotal(invoiceRecord).toMoney(); final CurrencyPrecision currencyPrecision = currencyDAO.getStdPrecision(grandTotal.getCurrencyId()); final LocalDate dateInvoiced = invoiceRecord.getDateInvoiced().toLocalDateTime().toLocalDate();
final ArrayList<InvoicePayScheduleCreateRequest.Line> lines = new ArrayList<>(); Money dueAmtRemaining = grandTotal; final ImmutableList<PaySchedule> paySchedules = paymentTerm.getPaySchedules(); for (int i = 0, paySchedulesCount = paySchedules.size(); i < paySchedulesCount; i++) { final PaySchedule paySchedule = paySchedules.get(i); final boolean isLast = i == paySchedulesCount - 1; final Money dueAmt = isLast ? dueAmtRemaining : paySchedule.calculateDueAmt(grandTotal, currencyPrecision); lines.add(InvoicePayScheduleCreateRequest.Line.builder() .valid(true) .dueDate(paySchedule.calculateDueDate(dateInvoiced)) .dueAmount(dueAmt) .discountDate(paySchedule.calculateDiscountDate(dateInvoiced)) .discountAmount(paySchedule.calculateDiscountAmt(dueAmt, currencyPrecision)) .paymentTermScheduleId(paySchedule.getId()) .build()); dueAmtRemaining = dueAmtRemaining.subtract(dueAmt); } return Optional.of( InvoicePayScheduleCreateRequest.builder() .invoiceId(InvoiceId.ofRepoId(invoiceRecord.getC_Invoice_ID())) .lines(lines) .build() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\service\InvoicePayScheduleCreateCommand.java
2
请完成以下Java代码
public void setOccurCount(Integer occurCount) { this.occurCount = occurCount; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public Date getResponsedTime() { return responsedTime; } public void setResponsedTime(Date responsedTime) { this.responsedTime = responsedTime; } public String getResponsedBy() { return responsedBy; } public void setResponsedBy(String responsedBy) { this.responsedBy = responsedBy; } public Date getResolvedTime() { return resolvedTime; } public void setResolvedTime(Date resolvedTime) { this.resolvedTime = resolvedTime; } public String getResolvedBy() { return resolvedBy; } public void setResolvedBy(String resolvedBy) { this.resolvedBy = resolvedBy; } public Date getClosedTime() { return closedTime; } public void setClosedTime(Date closedTime) { this.closedTime = closedTime; } public String getClosedBy() { return closedBy; } public void setClosedBy(String closedBy) { this.closedBy = closedBy; } @Override public String toString() { return "Event{" +
"id=" + id + ", rawEventId=" + rawEventId + ", host=" + host + ", ip=" + ip + ", source=" + source + ", type=" + type + ", startTime=" + startTime + ", endTime=" + endTime + ", content=" + content + ", dataType=" + dataType + ", suggest=" + suggest + ", businessSystemId=" + businessSystemId + ", departmentId=" + departmentId + ", status=" + status + ", occurCount=" + occurCount + ", owner=" + owner + ", responsedTime=" + responsedTime + ", responsedBy=" + responsedBy + ", resolvedTime=" + resolvedTime + ", resolvedBy=" + resolvedBy + ", closedTime=" + closedTime + ", closedBy=" + closedBy + '}'; } }
repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java
1
请完成以下Java代码
public class ZipSampleFileStore { public static final String ENTRY_NAME_PATTERN = "str-data-%s.txt"; private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; private final File file; private final List<String> dataList; public ZipSampleFileStore(int numOfFiles, int fileSize) throws IOException { dataList = new ArrayList<>(numOfFiles); file = File.createTempFile("zip-sample", ""); try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file))) { for (int idx=0; idx<=numOfFiles; idx++) { byte[] data = createRandomStringInByte(fileSize); dataList.add(new String(data, DEFAULT_ENCODING)); ZipEntry entry = new ZipEntry(String.format(ENTRY_NAME_PATTERN, idx)); zos.putNextEntry(entry); zos.write(data); zos.closeEntry(); } } } public static byte[] createRandomStringInByte(int size) { Random random = new Random(); byte[] data = new byte[size]; for (int n = 0; n < data.length; n++) { char randomChar;
int choice = random.nextInt(2); // 0 for uppercase, 1 for lowercase if (choice == 0) { randomChar = (char) ('A' + random.nextInt(26)); // 'A' to 'Z' } else { randomChar = (char) ('a' + random.nextInt(26)); // 'a' to 'z' } data[n] = (byte) randomChar; } return data; } public File getFile() { return file; } public List<String> getDataList() { return dataList; } public static String getString(InputStream inputStream) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(inputStream, byteArrayOutputStream); return byteArrayOutputStream.toString(DEFAULT_ENCODING); } }
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\zip\ZipSampleFileStore.java
1
请完成以下Java代码
public int getAge() { return age; } public void setAge(final int age) { this.age = age; } public LocalDate getCreationDate() { return creationDate; } public LocalDate getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(LocalDate lastLoginDate) { this.lastLoginDate = lastLoginDate; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public String toString() {
return "User [name=" + name + ", id=" + id + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && age == user.age && Objects.equals(name, user.name) && Objects.equals(creationDate, user.creationDate) && Objects.equals(email, user.email) && Objects.equals(status, user.status); } @Override public int hashCode() { return Objects.hash(id, name, creationDate, age, email, status); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\query\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "http://localhost:8182/repository/deployments/2/resources/testProcess.xml", value = "Contains the actual deployed BPMN 2.0 xml.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a process for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setDiagramResource(String diagramResource) { this.diagramResource = diagramResource; } @ApiModelProperty(example = "http://localhost:8182/repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the process, null when no diagram is available.") public String getDiagramResource() { return diagramResource; } public void setGraphicalNotationDefined(boolean graphicalNotationDefined) { this.graphicalNotationDefined = graphicalNotationDefined; } @ApiModelProperty(value = "Indicates the process definition contains graphical information (BPMN DI).") public boolean isGraphicalNotationDefined() { return graphicalNotationDefined; }
public void setSuspended(boolean suspended) { this.suspended = suspended; } public boolean isSuspended() { return suspended; } public void setStartFormDefined(boolean startFormDefined) { this.startFormDefined = startFormDefined; } public boolean isStartFormDefined() { return startFormDefined; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionResponse.java
2
请在Spring Boot框架中完成以下Java代码
public String getHandleStatus() { return handleStatus; } public void setHandleStatus(String handleStatus) { this.handleStatus = handleStatus == null ? null : handleStatus.trim(); } public String getBankType() { return bankType; } public void setBankType(String bankType) { this.bankType = bankType == null ? null : bankType.trim(); } public Integer getMistakeCount() { return mistakeCount; } public void setMistakeCount(Integer mistakeCount) { this.mistakeCount = mistakeCount; } public Integer getUnhandleMistakeCount() { return unhandleMistakeCount; } public void setUnhandleMistakeCount(Integer unhandleMistakeCount) { this.unhandleMistakeCount = unhandleMistakeCount; } public Integer getTradeCount() { return tradeCount; } public void setTradeCount(Integer tradeCount) { this.tradeCount = tradeCount; } public Integer getBankTradeCount() { return bankTradeCount; } public void setBankTradeCount(Integer bankTradeCount) { this.bankTradeCount = bankTradeCount; } public BigDecimal getTradeAmount() { return tradeAmount; } public void setTradeAmount(BigDecimal tradeAmount) { this.tradeAmount = tradeAmount; } public BigDecimal getBankTradeAmount() { return bankTradeAmount; } public void setBankTradeAmount(BigDecimal bankTradeAmount) { this.bankTradeAmount = bankTradeAmount; } public BigDecimal getRefundAmount() { return refundAmount; } public void setRefundAmount(BigDecimal refundAmount) { this.refundAmount = refundAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; }
public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } public String getOrgCheckFilePath() { return orgCheckFilePath; } public void setOrgCheckFilePath(String orgCheckFilePath) { this.orgCheckFilePath = orgCheckFilePath == null ? null : orgCheckFilePath.trim(); } public String getReleaseCheckFilePath() { return releaseCheckFilePath; } public void setReleaseCheckFilePath(String releaseCheckFilePath) { this.releaseCheckFilePath = releaseCheckFilePath == null ? null : releaseCheckFilePath.trim(); } public String getReleaseStatus() { return releaseStatus; } public void setReleaseStatus(String releaseStatus) { this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim(); } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public String getCheckFailMsg() { return checkFailMsg; } public void setCheckFailMsg(String checkFailMsg) { this.checkFailMsg = checkFailMsg; } public String getBankErrMsg() { return bankErrMsg; } public void setBankErrMsg(String bankErrMsg) { this.bankErrMsg = bankErrMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java
2
请完成以下Java代码
public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_Shipper_RoutingCode_ID (final int M_Shipper_RoutingCode_ID) { if (M_Shipper_RoutingCode_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, M_Shipper_RoutingCode_ID); } @Override
public int getM_Shipper_RoutingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_ID); } @Override public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_RoutingCode.java
1
请完成以下Java代码
public void addRowToTable(Document doc, int tableOrder) { Element table = doc.select("table") .get(tableOrder); Element tbody = table.select("tbody") .get(0); Elements rows = table.select("tr"); Elements headerCols = rows.get(0) .select("th,td"); int numCols = headerCols.size(); Elements colVals = new Elements(numCols); for (int colCount = 0; colCount < numCols; colCount++) { Element colVal = new Element("td"); colVal.text("11"); colVals.add(colVal); } Elements dataRows = tbody.select("tr"); Element newDataRow = new Element("tr");
newDataRow.appendChildren(colVals); dataRows.add(newDataRow); tbody.html(dataRows.toString()); } public void deleteRowFromTable(Document doc, int tableOrder, int rowNumber) { Element table = doc.select("table") .get(tableOrder); Element tbody = table.select("tbody") .get(0); Elements dataRows = tbody.select("tr"); if (rowNumber < dataRows.size()) { dataRows.remove(rowNumber); } } }
repos\tutorials-master\jsoup\src\main\java\com\baeldung\jsoup\JsoupTableParser.java
1
请完成以下Java代码
public Object renderStartForm(StartFormData startForm) { if (startForm.getFormKey() == null) { return null; } String formTemplateString = getFormTemplateString(startForm, startForm.getFormKey()); ScriptingEngines scriptingEngines = CommandContextUtil.getProcessEngineConfiguration().getScriptingEngines(); ScriptEngineRequest scriptEngineRequest = ScriptEngineRequest.builder() .language(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE) .script(formTemplateString) .build(); return scriptingEngines.evaluate(scriptEngineRequest).getResult(); } @Override public Object renderTaskForm(TaskFormData taskForm) { if (taskForm.getFormKey() == null) { return null; } String formTemplateString = getFormTemplateString(taskForm, taskForm.getFormKey()); ScriptingEngines scriptingEngines = CommandContextUtil.getProcessEngineConfiguration().getScriptingEngines(); TaskEntity task = (TaskEntity) taskForm.getTask(); ExecutionEntity executionEntity = null; if (task.getExecutionId() != null) { executionEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getExecutionId()); }
ScriptEngineRequest.Builder builder = ScriptEngineRequest.builder() .script(formTemplateString) .language(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE) .scopeContainer(executionEntity); return scriptingEngines.evaluate(builder.build()).getResult(); } protected String getFormTemplateString(FormData formInstance, String formKey) { String deploymentId = formInstance.getDeploymentId(); ResourceEntity resourceStream = CommandContextUtil.getResourceEntityManager().findResourceByDeploymentIdAndResourceName(deploymentId, formKey); if (resourceStream == null) { throw new FlowableObjectNotFoundException("Form with formKey '" + formKey + "' does not exist", String.class); } return new String(resourceStream.getBytes(), StandardCharsets.UTF_8); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\JuelFormEngine.java
1
请完成以下Java代码
public @NonNull WorkflowId getWorkflowId() { return workflowModel.getId(); } public @NonNull ClientId getClientId() {return node.getClientId();} public @NonNull WFNodeAction getAction() {return node.getAction();} public @NonNull ITranslatableString getName() {return node.getName();} @NonNull public ITranslatableString getDescription() {return node.getDescription();} @NonNull public ITranslatableString getHelp() {return node.getHelp();} public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();} public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();} public void setXPosition(final int x) { this.xPosition = x; } public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();} public void setYPosition(final int y) { this.yPosition = y; }
public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId) { return node.getTransitions(clientId) .stream() .map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition)) .collect(ImmutableList.toImmutableList()); } public void saveEx() { workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder() .nodeId(getId()) .xPosition(getXPosition()) .yPosition(getYPosition()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java
1
请完成以下Java代码
public class HistoricDetailEntityManager extends AbstractManager { @SuppressWarnings({ "unchecked", "rawtypes" }) public void deleteHistoricDetailsByProcessInstanceId(String historicProcessInstanceId) { if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.AUDIT)) { List<HistoricDetailEntity> historicDetails = (List) getDbSqlSession() .createHistoricDetailQuery() .processInstanceId(historicProcessInstanceId) .list(); for (HistoricDetailEntity historicDetail : historicDetails) { historicDetail.delete(); } } } public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByQueryCriteria", historicVariableUpdateQuery); } @SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery, Page page) {
return getDbSqlSession().selectList("selectHistoricDetailsByQueryCriteria", historicVariableUpdateQuery, page); } public void deleteHistoricDetailsByTaskId(String taskId) { if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.FULL)) { HistoricDetailQueryImpl detailsQuery = new HistoricDetailQueryImpl().taskId(taskId); List<HistoricDetail> details = detailsQuery.list(); for (HistoricDetail detail : details) { ((HistoricDetailEntity) detail).delete(); } } } @SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return getDbSqlSession().selectListWithRawParameter("selectHistoricDetailByNativeQuery", parameterMap, firstResult, maxResults); } public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByNativeQuery", parameterMap); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityManager.java
1
请完成以下Java代码
public int getM_Warehouse_Dest_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Dest_ID); if (ii == null) return 0; return ii.intValue(); } /** * Set Verarbeitet. * * @param Processed * Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ public void setProcessed(boolean Processed) { set_Value(COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** * Get Verarbeitet. * * @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ public boolean isProcessed() { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTree.java
1
请完成以下Java代码
public void setCM_Chat_ID (int CM_Chat_ID) { if (CM_Chat_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, Integer.valueOf(CM_Chat_ID)); } /** Get Chat. @return Chat or discussion thread */ public int getCM_Chat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Chat_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Self-Service. @param IsSelfService This is a Self-Service entry or this entry can be changed via Self-Service */
public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); } /** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatUpdate.java
1
请在Spring Boot框架中完成以下Java代码
public final Map<String, GrpcChannelProperties> getClient() { return this.client; } /** * Gets the properties for the given channel. If the properties for the specified channel name do not yet exist, * they are created automatically. Before the instance is returned, the unset values are filled with values from the * global properties. * * @param name The name of the channel to get the properties for. * @return The properties for the given channel name. */ public GrpcChannelProperties getChannel(final String name) { final GrpcChannelProperties properties = getRawChannel(name); properties.copyDefaultsFrom(getGlobalChannel()); return properties; } /** * Gets the global channel properties. Global properties are used, if the channel properties don't overwrite them. * If neither the global nor the per client properties are set then default values will be used. * * @return The global channel properties. */ public final GrpcChannelProperties getGlobalChannel() { // This cannot be moved to its own field, // as Spring replaces the instance in the map and inconsistencies would occur. return getRawChannel(GLOBAL_PROPERTIES_KEY); } /** * Gets or creates the channel properties for the given client. * * @param name The name of the channel to get the properties for. * @return The properties for the given channel name. */ private GrpcChannelProperties getRawChannel(final String name) { return this.client.computeIfAbsent(name, key -> new GrpcChannelProperties()); }
private String defaultScheme; /** * Get the default scheme that should be used, if the client doesn't specify a scheme/address. * * @return The default scheme to use or null. * @see #setDefaultScheme(String) */ public String getDefaultScheme() { return this.defaultScheme; } /** * Sets the default scheme to use, if the client doesn't specify a scheme/address. If not specified it will default * to the default scheme of the {@link io.grpc.NameResolver.Factory}. Examples: {@code dns}, {@code discovery}. * * @param defaultScheme The default scheme to use or null. */ public void setDefaultScheme(String defaultScheme) { this.defaultScheme = defaultScheme; } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\config\GrpcChannelsProperties.java
2
请完成以下Java代码
public class LoggingEventListener extends AbstractCassandraEventListener<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(LoggingEventListener.class); /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onBeforeSave(org.springframework.data.cassandra.core.mapping.event.BeforeSaveEvent) */ @Override public void onBeforeSave(BeforeSaveEvent<Object> event) { LOGGER.info("onBeforeSave: {}, {}", event.getSource(), event.getStatement()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterSave(org.springframework.data.cassandra.core.mapping.event.AfterSaveEvent) */ @Override public void onAfterSave(AfterSaveEvent<Object> event) { LOGGER.info("onAfterSave: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onBeforeDelete(org.springframework.data.cassandra.core.mapping.event.BeforeDeleteEvent) */ @Override public void onBeforeDelete(BeforeDeleteEvent<Object> event) { LOGGER.info("onBeforeDelete: {}", event.getSource()); } /*
* (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterDelete(org.springframework.data.cassandra.core.mapping.event.AfterDeleteEvent) */ @Override public void onAfterDelete(AfterDeleteEvent<Object> event) { LOGGER.info("onAfterDelete: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterLoad(org.springframework.data.cassandra.core.mapping.event.AfterLoadEvent) */ @Override public void onAfterLoad(AfterLoadEvent<Object> event) { LOGGER.info("onAfterLoad: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterConvert(org.springframework.data.cassandra.core.mapping.event.AfterConvertEvent) */ @Override public void onAfterConvert(AfterConvertEvent<Object> event) { LOGGER.info("onAfterConvert: {}", event.getSource()); } }
repos\spring-data-examples-main\cassandra\example\src\main\java\example\springdata\cassandra\events\LoggingEventListener.java
1
请完成以下Java代码
public AttachmentEntry withAdditionalLinkedRecord(@NonNull final TableRecordReference modelRef) { if (getLinkedRecords().contains(modelRef)) { return this; } return toBuilder().linkedRecord(modelRef).build(); } public AttachmentEntry withAdditionalTag(@NonNull final String tagName, @NonNull final String tagValue) { return toBuilder() .tags(getTags().withTag(tagName, tagValue)) .build(); } public AttachmentEntry withRemovedLinkedRecord(@NonNull final TableRecordReference modelRef) { final HashSet<TableRecordReference> linkedRecords = new HashSet<>(getLinkedRecords()); if (linkedRecords.remove(modelRef)) { return toBuilder().clearLinkedRecords().linkedRecords(linkedRecords).build(); } else { return this; } } public AttachmentEntry withoutLinkedRecords() { return toBuilder().clearLinkedRecords().build(); } public AttachmentEntry withAdditionalLinkedRecords(@NonNull final List<TableRecordReference> additionalLinkedRecords) { if (getLinkedRecords().containsAll(additionalLinkedRecords)) { return this; } final Set<TableRecordReference> tmp = new HashSet<>(getLinkedRecords()); tmp.addAll(additionalLinkedRecords); return toBuilder().linkedRecords(tmp).build(); } public AttachmentEntry withRemovedLinkedRecords(@NonNull final List<TableRecordReference> linkedRecordsToRemove) { final HashSet<TableRecordReference> linkedRecords = new HashSet<>(getLinkedRecords()); if (linkedRecords.removeAll(linkedRecordsToRemove)) { return toBuilder().clearLinkedRecords().linkedRecords(linkedRecords).build(); } else { return this; } } public AttachmentEntry withAdditionalTag(@NonNull final AttachmentTags attachmentTags) {
return toBuilder() .tags(getTags().withTags(attachmentTags)) .build(); } public AttachmentEntry withoutTags(@NonNull final AttachmentTags attachmentTags) { return toBuilder() .tags(getTags().withoutTags(attachmentTags)) .build(); } /** * @return the attachment's filename as seen from the given {@code tableRecordReference}. Note that different records might share the same attachment, but refer to it under different file names. */ @NonNull public String getFilename(@NonNull final TableRecordReference tableRecordReference) { if (linkedRecord2AttachmentName == null) { return filename; } return CoalesceUtil.coalesceNotNull( linkedRecord2AttachmentName.get(tableRecordReference), filename); } public boolean hasLinkToRecord(@NonNull final TableRecordReference tableRecordReference) { return linkedRecords.contains(tableRecordReference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntry.java
1
请在Spring Boot框架中完成以下Java代码
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono.fromRunnable(() -> { if (event instanceof InstanceStatusChangedEvent) { LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(), ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()); String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus(); switch (status) { // 健康检查没通过 case "DOWN": System.out.println("发送 健康检查没通过 的通知!"); break; // 服务离线 case "OFFLINE": System.out.println("发送 服务离线 的通知!"); break; //服务上线 case "UP": System.out.println("发送 服务上线 的通知!");
break; // 服务未知异常 case "UNKNOWN": System.out.println("发送 服务未知异常 的通知!"); break; default: break; } } else { LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(), event.getType()); } }); } }
repos\SpringBootLearning-master (1)\springboot-admin\sc-admin-server\src\main\java\com\gf\config\CustomNotifier.java
2
请完成以下Java代码
public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(firstName, student.firstName) && Objects.equals(lastName, student.lastName); } @Override public int hashCode() { return super.hashCode(); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-7\src\main\java\com\baeldung\map\readandwritefile\Student.java
1
请完成以下Java代码
public String getOrgCode() { return orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getAddress() {
return address; } public void setAddress(String address) { this.address = address; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> addVisitsNumber(@RequestParam(name="id",required=true) String id) { int count = oConvertUtils.getInt(redisUtil.get(ANNO_CACHE_KEY+id),0) + 1; redisUtil.set(ANNO_CACHE_KEY+id, count); if (count % 5 == 0) { cachedThreadPool.execute(() -> { sysAnnouncementService.updateVisitsNum(id, count); }); // 重置访问次数 redisUtil.del(ANNO_CACHE_KEY+id); } return Result.ok("公告消息访问次数+1次"); } /** * 批量下载文件 * @param id * @param request * @param response */ @GetMapping("/downLoadFiles") public void downLoadFiles(@RequestParam(name="id") String id, HttpServletRequest request, HttpServletResponse response){ sysAnnouncementService.downLoadFiles(id,request,response); } /** * 根据异常信息确定友好的错误提示 */ private String determineErrorMessage(Exception e) { String errorMsg = e.getMessage(); if (isSpecialCharacterError(errorMsg)) { return SPECIAL_CHAR_ERROR; } else if (isContentTooLongError(errorMsg)) { return CONTENT_TOO_LONG_ERROR; } else { return DEFAULT_ERROR;
} } /** * 判断是否为特殊字符错误 */ private boolean isSpecialCharacterError(String errorMsg) { return errorMsg != null && errorMsg.contains("Incorrect string value") && errorMsg.contains("column 'msg_content'"); } /** * 判断是否为内容过长错误 */ private boolean isContentTooLongError(String errorMsg) { return errorMsg != null && errorMsg.contains("Data too long for column 'msg_content'"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysAnnouncementController.java
2
请完成以下Java代码
public class DefaultJobExecutor extends ThreadPoolJobExecutor { private final static JobExecutorLogger LOG = ProcessEngineLogger.JOB_EXECUTOR_LOGGER; protected int queueSize = 3; protected int corePoolSize = 3; protected int maxPoolSize = 10; protected void startExecutingJobs() { if (threadPoolExecutor==null || threadPoolExecutor.isShutdown()) { BlockingQueue<Runnable> threadPoolQueue = new ArrayBlockingQueue<Runnable>(queueSize); threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 0L, TimeUnit.MILLISECONDS, threadPoolQueue); threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); } super.startExecutingJobs(); } protected void stopExecutingJobs() { super.stopExecutingJobs(); // 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.timeoutDuringShutdown(); } } catch (InterruptedException e) { LOG.interruptedWhileShuttingDownjobExecutor(e); } } // getters and setters //////////////////////////////////////////////////////
public int getQueueSize() { return queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public int getCorePoolSize() { return corePoolSize; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\DefaultJobExecutor.java
1
请完成以下Java代码
public void put(TenantProfile profile) { if (profile.getId() != null) { tenantProfilesMap.put(profile.getId(), profile); notifyTenantListeners(profile); } } @Override public void evict(TenantProfileId profileId) { tenantProfilesMap.remove(profileId); notifyTenantListeners(get(profileId)); } public void notifyTenantListeners(TenantProfile tenantProfile) { if (tenantProfile != null) { tenantsMap.forEach(((tenantId, tenantProfileId) -> { if (tenantProfileId.equals(tenantProfile.getId())) { ConcurrentMap<EntityId, Consumer<TenantProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(tenantProfile)); } } })); } } @Override public void evict(TenantId tenantId) { tenantsMap.remove(tenantId); TenantProfile tenantProfile = get(tenantId); if (tenantProfile != null) { ConcurrentMap<EntityId, Consumer<TenantProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(tenantProfile)); } } } @Override public void addListener(TenantId tenantId, EntityId listenerId, Consumer<TenantProfile> profileListener) { //Force cache of the tenant id. get(tenantId); if (profileListener != null) { profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener); } } @Override public void removeListener(TenantId tenantId, EntityId listenerId) { ConcurrentMap<EntityId, Consumer<TenantProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.remove(listenerId); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\DefaultTbTenantProfileCache.java
1
请完成以下Java代码
public void setES_DocumentToIndexTemplate (final java.lang.String ES_DocumentToIndexTemplate) { set_Value (COLUMNNAME_ES_DocumentToIndexTemplate, ES_DocumentToIndexTemplate); } @Override public java.lang.String getES_DocumentToIndexTemplate() { return get_ValueAsString(COLUMNNAME_ES_DocumentToIndexTemplate); } @Override public void setES_FTS_Config_ID (final int ES_FTS_Config_ID) { if (ES_FTS_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID); } @Override public int getES_FTS_Config_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID); } @Override public void setES_Index (final java.lang.String ES_Index) { set_Value (COLUMNNAME_ES_Index, ES_Index); }
@Override public java.lang.String getES_Index() { return get_ValueAsString(COLUMNNAME_ES_Index); } @Override public void setES_QueryCommand (final java.lang.String ES_QueryCommand) { set_Value (COLUMNNAME_ES_QueryCommand, ES_QueryCommand); } @Override public java.lang.String getES_QueryCommand() { return get_ValueAsString(COLUMNNAME_ES_QueryCommand); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getEnabled() { return (this.enabled != null) ? this.enabled : StringUtils.hasText(this.bundle); } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } public static class Timeouts { /** * Bucket connect timeout. */ private Duration connect = Duration.ofSeconds(10); /** * Bucket disconnect timeout. */ private Duration disconnect = Duration.ofSeconds(10); /** * Timeout for operations on a specific key-value. */ private Duration keyValue = Duration.ofMillis(2500); /** * Timeout for operations on a specific key-value with a durability level. */ private Duration keyValueDurable = Duration.ofSeconds(10); /** * N1QL query operations timeout. */ private Duration query = Duration.ofSeconds(75); /** * Regular and geospatial view operations timeout. */ private Duration view = Duration.ofSeconds(75); /** * Timeout for the search service. */ private Duration search = Duration.ofSeconds(75); /** * Timeout for the analytics service. */ private Duration analytics = Duration.ofSeconds(75); /** * Timeout for the management operations. */ private Duration management = Duration.ofSeconds(75); public Duration getConnect() { return this.connect; } public void setConnect(Duration connect) { this.connect = connect; } public Duration getDisconnect() { return this.disconnect; } public void setDisconnect(Duration disconnect) { this.disconnect = disconnect; } public Duration getKeyValue() { return this.keyValue; }
public void setKeyValue(Duration keyValue) { this.keyValue = keyValue; } public Duration getKeyValueDurable() { return this.keyValueDurable; } public void setKeyValueDurable(Duration keyValueDurable) { this.keyValueDurable = keyValueDurable; } public Duration getQuery() { return this.query; } public void setQuery(Duration query) { this.query = query; } public Duration getView() { return this.view; } public void setView(Duration view) { this.view = view; } public Duration getSearch() { return this.search; } public void setSearch(Duration search) { this.search = search; } public Duration getAnalytics() { return this.analytics; } public void setAnalytics(Duration analytics) { this.analytics = analytics; } public Duration getManagement() { return this.management; } public void setManagement(Duration management) { this.management = management; } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseProperties.java
2
请完成以下Java代码
private Object checkAllowedTypes(Expression expression, DelegateExecution execution) { if (expression == null) { return null; } Object value = expression.getValue(execution); if (value == null) { return null; } for (Class<?> allowedType : ALLOWED_ATT_TYPES) { if (allowedType.isInstance(value)) { return value; } } throw new ActivitiException("Invalid attachment type: " + value.getClass()); } protected boolean fileExists(File file) { return file != null && file.exists() && file.isFile() && file.canRead(); } protected Expression getExpression(DelegateExecution execution, Expression var) { String variable = (String) execution.getVariable(var.getExpressionText()); return Context.getProcessEngineConfiguration().getExpressionManager().createExpression(variable); } protected void handleException(
DelegateExecution execution, String msg, Exception e, boolean doIgnoreException, String exceptionVariable ) { if (doIgnoreException) { LOG.info("Ignoring email send error: " + msg, e); if (exceptionVariable != null && exceptionVariable.length() > 0) { execution.setVariable(exceptionVariable, msg); } } else { if (e instanceof ActivitiException) { throw (ActivitiException) e; } else { throw new ActivitiException(msg, e); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MailActivityBehavior.java
1
请完成以下Java代码
public String process(String to_process) { if ( to_process == null || to_process.length() == 0 ) return ""; String tmp = ""; // the true at the end is the key to making it work StringTokenizer st = new StringTokenizer(to_process, " ", true); StringBuffer newValue = new StringBuffer(to_process.length() + 50); while ( st.hasMoreTokens() ) { tmp = st.nextToken(); if (hasAttribute(tmp)) newValue.append((String)get(tmp)); else newValue.append(tmp); } return newValue.toString(); } /** Put a filter somewhere we can get to it. */ public Filter addAttribute(String attribute,Object entity) { put(attribute,entity); return(this); } /** Get rid of a current filter. */
public Filter removeAttribute(String attribute) { try { remove(attribute); } catch(NullPointerException exc) { // don't really care if this throws a null pointer exception } return(this); } /** Does the filter filter this? */ public boolean hasAttribute(String attribute) { return(containsKey(attribute)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\WordFilter.java
1
请完成以下Java代码
public void delete(String userId) { UserEntity user = findById(userId); if (user != null) { List<IdentityInfoEntity> identityInfos = getIdentityInfoEntityManager().findIdentityInfoByUserId(userId); for (IdentityInfoEntity identityInfo : identityInfos) { getIdentityInfoEntityManager().delete(identityInfo); } getMembershipEntityManager().deleteMembershipByUserId(userId); delete(user); } } @Override public List<User> findUserByQueryCriteria(UserQueryImpl query) { return dataManager.findUserByQueryCriteria(query); } @Override public long findUserCountByQueryCriteria(UserQueryImpl query) { return dataManager.findUserCountByQueryCriteria(query); } @Override public UserQuery createNewUserQuery() { return new UserQueryImpl(getCommandExecutor()); } @Override public Boolean checkPassword(String userId, String password, PasswordEncoder passwordEncoder, PasswordSalt salt) { User user = null; if (userId != null) { user = findById(userId); } return (user != null) && (password != null) && passwordEncoder.isMatches(password, user.getPassword(), salt); } @Override public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findUsersByNativeQuery(parameterMap); } @Override public long findUserCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findUserCountByNativeQuery(parameterMap); } @Override public boolean isNewUser(User user) {
return ((UserEntity) user).getRevision() == 0; } @Override public Picture getUserPicture(User user) { UserEntity userEntity = (UserEntity) user; return userEntity.getPicture(); } @Override public void setUserPicture(User user, Picture picture) { UserEntity userEntity = (UserEntity) user; userEntity.setPicture(picture); dataManager.update(userEntity); } @Override public List<User> findUsersByPrivilegeId(String name) { return dataManager.findUsersByPrivilegeId(name); } public UserDataManager getUserDataManager() { return dataManager; } public void setUserDataManager(UserDataManager userDataManager) { this.dataManager = userDataManager; } protected IdentityInfoEntityManager getIdentityInfoEntityManager() { return engineConfiguration.getIdentityInfoEntityManager(); } protected MembershipEntityManager getMembershipEntityManager() { return engineConfiguration.getMembershipEntityManager(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityManagerImpl.java
1
请完成以下Java代码
public abstract class CriterionImpl extends CmmnElementImpl implements Criterion { protected static Attribute<String> nameAttribute; protected static AttributeReference<Sentry> sentryRefAttribute; public CriterionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Sentry getSentry() { return sentryRefAttribute.getReferenceTargetElement(this); } public void setSentry(Sentry sentry) { sentryRefAttribute.setReferenceTargetElement(this, sentry); } public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Criterion.class, CMMN_ELEMENT_CRITERION) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .abstractType(); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); sentryRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SENTRY_REF) .idAttributeReference(Sentry.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CriterionImpl.java
1
请完成以下Java代码
public class InfoQueryCriteriaBPRadius extends InfoQueryCriteriaBPRadiusAbstract { private CTextField fieldCityZip; private GeodbAutoCompleter fieldCityZipAutocompleter; private VNumber fieldRadius; @Override public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText) { final int defaultRadius = Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_DefaultRadius, 0, Env.getAD_Client_ID(Env.getCtx())); // fieldCityZip = new CTextField(); fieldCityZip.setPreferredSize(new Dimension(200, (int)fieldCityZip.getPreferredSize().getHeight())); fieldCityZipAutocompleter = new GeodbAutoCompleter(fieldCityZip); fieldCityZipAutocompleter.setUserObject(null); // fieldRadius = new VNumber("RadiusKM", false, false, true, DisplayType.Integer, ""); fieldRadius.setValue(defaultRadius); fieldRadius.setRange(0.0, 999999.0); } @Override public Object getParameterComponent(int index) { if (index == 0) return fieldCityZip; else if (index == 1) return fieldRadius; else return null; } @Override public String[] getWhereClauses(List<Object> params) { final GeodbObject go = getGeodbObject(); final String searchText = getText(); if (go == null && !Check.isEmpty(searchText, true)) return new String[]{"1=2"}; if (go == null) return new String[]{"1=1"}; final int radius = getRadius();
// final String whereClause = "EXISTS (SELECT 1 FROM geodb_coordinates co WHERE " + " co.zip=" + locationTableAlias + ".Postal" // join to C_Location.Postal + " AND co.c_country_id=" + locationTableAlias + ".C_Country_ID" + " AND " + getSQLDistanceFormula("co", go.getLat(), go.getLon()) + " <= " + radius + ")"; return new String[]{whereClause}; } private static String getSQLDistanceFormula(String tableAlias, double lat, double lon) { return "DEGREES(" + " (ACOS(" + " SIN(RADIANS(" + lat + ")) * SIN(RADIANS(" + tableAlias + ".lat)) " + " + COS(RADIANS(" + lat + "))*COS(RADIANS(" + tableAlias + ".lat))*COS(RADIANS(" + tableAlias + ".lon) - RADIANS(" + lon + "))" + ") * 60 * 1.1515 " // miles + " * 1.609344" // KM factor + " )" + " )"; } private GeodbObject getGeodbObject() { return (GeodbObject)fieldCityZipAutocompleter.getUserOject(); } @Override public String getText() { return fieldCityZipAutocompleter.getText(); } private int getRadius() { if (fieldRadius == null) return 0; Object o = fieldRadius.getValue(); if (o instanceof Number) return ((Number)o).intValue(); return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoQueryCriteriaBPRadius.java
1
请在Spring Boot框架中完成以下Java代码
public Packages getPackages() { return this.packages; } String determineBrokerUrl() { if (this.brokerUrl != null) { return this.brokerUrl; } if (this.embedded.isEnabled()) { return DEFAULT_EMBEDDED_BROKER_URL; } return DEFAULT_NETWORK_BROKER_URL; } /** * Configuration for an embedded ActiveMQ broker. */ public static class Embedded { /** * Whether to enable embedded mode if the ActiveMQ Broker is available. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Packages { /** * Whether to trust all packages. */
private @Nullable Boolean trustAll; /** * List of specific packages to trust (when not trusting all packages). */ private List<String> trusted = new ArrayList<>(); public @Nullable Boolean getTrustAll() { return this.trustAll; } public void setTrustAll(@Nullable Boolean trustAll) { this.trustAll = trustAll; } public List<String> getTrusted() { return this.trusted; } public void setTrusted(List<String> trusted) { this.trusted = trusted; } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java
2
请完成以下Java代码
public Map<String, Boolean> getCommunicationPreferences() { return communicationPreferences; } public void setCommunicationPreferences(Map<String, Boolean> communicationPreferences) { this.communicationPreferences = communicationPreferences; } public List<String> getFavorites() { return favorites; } public void setFavorites(List<String> favorites) { this.favorites = favorites; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Customer)) { return false; } Customer customer = (Customer) o; return Objects.equals(id, customer.id); } @Override public int hashCode() { return Objects.hash(id); } }
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\model\Customer.java
1
请完成以下Java代码
public final class AdempiereToolsHelper { public static final transient AdempiereToolsHelper instance = new AdempiereToolsHelper(); public static final AdempiereToolsHelper getInstance() { return instance; } /** * starts up in backend mode. Suitable for the little server-site-tools that we run during rollout */ public void startupMinimal() { startupMinimal(RunMode.BACKEND); } /** * Minimal adempiere system startup. */ public void startupMinimal(RunMode runMode) { // Disable distributed events because we don't want to broadcast events to network. EventBusConfig.disableDistributedEvents();
AddonStarter.warnIfPropertiesFileMissing = false; // don't warn because it we know it's missing. // // Adempiere system shall be started with a minimal set of entity types. // In particular, we don't want async, btw, because it doesn't stop when this process is already finished ModelValidationEngine.setInitEntityTypes(ModelValidationEngine.INITENTITYTYPE_Minimal); ModelValidationEngine.setFailOnMissingModelInteceptors(false); // // Initialize logging LogManager.initialize(true); // running it here to make sure we get the client side config // // Start Adempiere system Env.getSingleAdempiereInstance(null).startup(runMode); System.out.println("ADempiere system started in tools minimal mode."); } private AdempiereToolsHelper() { super(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\tools\AdempiereToolsHelper.java
1
请完成以下Java代码
public void assertLUValid(final I_M_ShipmentSchedule_QtyPicked alloc) { final I_M_HU luHU = alloc.getM_LU_HU(); if (luHU == null || luHU.getM_HU_ID() <= 0) { // not set => ok return; } final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); if (!handlingUnitsBL.isLoadingUnit(luHU)) { final HUException ex = new HUException("Loading unit expected." + "\n@M_LU_HU_ID@: " + handlingUnitsBL.getDisplayName(luHU) + "\n@M_ShipmentSchedule_QtyPicked_ID@: " + alloc + "\n@M_ShipmentSchedule_ID@: " + alloc.getM_ShipmentSchedule()); // logger.warn(ex.getLocalizedMessage(), ex); throw ex; } } /** * Asserts {@link I_M_ShipmentSchedule_QtyPicked#COLUMNNAME_M_LU_TU_ID} has a valid TU or null. * * @param alloc */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE } , ifColumnsChanged = { I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_M_TU_HU_ID }) public void assertTUValid(final I_M_ShipmentSchedule_QtyPicked alloc) { final I_M_HU tuHU = alloc.getM_TU_HU(); if (tuHU == null || tuHU.getM_HU_ID() <= 0) { // not set => ok return; } final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
if (!handlingUnitsBL.isTransportUnitOrVirtual(tuHU)) { final HUException ex = new HUException("Transport unit expected." + "\n@M_TU_HU_ID@: " + handlingUnitsBL.getDisplayName(tuHU) + "\n@M_ShipmentSchedule_QtyPicked_ID@: " + alloc + "\n@M_ShipmentSchedule_ID@: " + alloc.getM_ShipmentSchedule()); // logger.warn(ex.getLocalizedMessage(), ex); throw ex; } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_QtyPicked, I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_QtyDeliveredCatch, I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_Catch_UOM_ID }) public void syncInvoiceCandidateQtyPicked(@NonNull final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked) { final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(shipmentScheduleQtyPicked.getM_ShipmentSchedule_ID()); if (shipmentScheduleId == null) { return; } final I_M_ShipmentSchedule shipmentSchedule = shipmentSchedulePA.getById(shipmentScheduleId); final OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID()); if (orderLineId == null) { return; } final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId); invoiceCandidateHandlerBL.invalidateCandidatesFor(orderLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\interceptor\M_ShipmentSchedule_QtyPicked.java
1
请完成以下Java代码
default Object getProperty(EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter, PropertySource<T> source, String name) { Object value = source.getProperty(name); if (value != null && filter.shouldInclude(source, name) && value instanceof String) { String stringValue = String.valueOf(value); return resolver.resolvePropertyValue(stringValue); } return value; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override default Origin getOrigin(String key) { if(getDelegate() instanceof OriginLookup) { return ((OriginLookup<String>) getDelegate()).getOrigin(key); } return null; } /** {@inheritDoc} */ @Override
default boolean isImmutable() { if(getDelegate() instanceof OriginLookup) { return ((OriginLookup<?>) getDelegate()).isImmutable(); } return OriginLookup.super.isImmutable(); } /** {@inheritDoc} */ @Override default String getPrefix() { if(getDelegate() instanceof OriginLookup) { return ((OriginLookup<?>) getDelegate()).getPrefix(); } return OriginLookup.super.getPrefix(); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\EncryptablePropertySource.java
1
请在Spring Boot框架中完成以下Java代码
public class ForecastId implements RepoIdAware { @JsonCreator public static ForecastId ofRepoId(final int repoId) { return new ForecastId(repoId); } @Nullable public static ForecastId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ForecastId(repoId) : null; } public static int toRepoId(@Nullable final ForecastId forecastId) { return forecastId != null ? forecastId.getRepoId() : -1; }
int repoId; private ForecastId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_Forecast_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impl\ForecastId.java
2
请在Spring Boot框架中完成以下Java代码
public BigDecimal getTodayExpend() { return todayExpend; } public void setTodayExpend(BigDecimal todayExpend) { this.todayExpend = todayExpend; } public String getAccountType() { return accountType; } public void setAccountType(String accountType) { this.accountType = accountType == null ? null : accountType.trim(); }
public BigDecimal getSettAmount() { return settAmount; } public void setSettAmount(BigDecimal settAmount) { this.settAmount = settAmount; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java
2
请完成以下Java代码
public String getPOReference() { if (poReferenceSet) { return poReference; } else if (defaults != null) { return defaults.getPOReference(); } else { return null; } } public void setPOReference(@Nullable final String poReference) { this.poReference = poReference; poReferenceSet = true; } @Nullable @Override public BigDecimal getCheck_NetAmtToInvoice() { if (check_NetAmtToInvoice != null) { return check_NetAmtToInvoice; } else if (defaults != null) { return defaults.getCheck_NetAmtToInvoice(); } return null; } @Override public boolean isStoreInvoicesInResult() { if (storeInvoicesInResult != null) { return storeInvoicesInResult; } else if (defaults != null) { return defaults.isStoreInvoicesInResult(); } else { return false; } } public PlainInvoicingParams setStoreInvoicesInResult(final boolean storeInvoicesInResult) { this.storeInvoicesInResult = storeInvoicesInResult; return this; } @Override
public boolean isAssumeOneInvoice() { if (assumeOneInvoice != null) { return assumeOneInvoice; } else if (defaults != null) { return defaults.isAssumeOneInvoice(); } else { return false; } } public PlainInvoicingParams setAssumeOneInvoice(final boolean assumeOneInvoice) { this.assumeOneInvoice = assumeOneInvoice; return this; } public boolean isUpdateLocationAndContactForInvoice() { return updateLocationAndContactForInvoice; } public void setUpdateLocationAndContactForInvoice(boolean updateLocationAndContactForInvoice) { this.updateLocationAndContactForInvoice = updateLocationAndContactForInvoice; } public PlainInvoicingParams setCompleteInvoices(final boolean completeInvoices) { this.completeInvoices = completeInvoices; return this; } @Override public boolean isCompleteInvoices() { return completeInvoices; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\PlainInvoicingParams.java
1
请完成以下Java代码
public Class<? extends BaseElement> getBpmnElementType() { return Association.class; } @Override protected String getXMLElementName() { return ELEMENT_ASSOCIATION; } @Override protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { Association association = new Association(); BpmnXMLUtil.addXMLLocation(association, xtr); association.setSourceRef(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SOURCE_REF)); association.setTargetRef(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_TARGET_REF)); association.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); String asociationDirectionString = xtr.getAttributeValue(null, ATTRIBUTE_ASSOCIATION_DIRECTION); if (StringUtils.isNotEmpty(asociationDirectionString)) { AssociationDirection associationDirection = AssociationDirection.valueOf( asociationDirectionString.toUpperCase() ); association.setAssociationDirection(associationDirection);
} parseChildElements(getXMLElementName(), association, model, xtr); return association; } @Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { Association association = (Association) element; writeDefaultAttribute(ATTRIBUTE_FLOW_SOURCE_REF, association.getSourceRef(), xtw); writeDefaultAttribute(ATTRIBUTE_FLOW_TARGET_REF, association.getTargetRef(), xtw); AssociationDirection associationDirection = association.getAssociationDirection(); if (associationDirection != null) { writeDefaultAttribute(ATTRIBUTE_ASSOCIATION_DIRECTION, associationDirection.getValue(), xtw); } } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {} }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\AssociationXMLConverter.java
1
请完成以下Java代码
private static class HardwarePrinterMap { private final ImmutableMap<HardwarePrinterId, HardwarePrinter> byId; private HardwarePrinterMap(final List<HardwarePrinter> list) { this.byId = Maps.uniqueIndex(list, HardwarePrinter::getId); } public HardwarePrinter getById(@NonNull final HardwarePrinterId id) { final HardwarePrinter hardwarePrinter = byId.get(id); if (hardwarePrinter == null) { throw new AdempiereException("No active hardware printer found for id " + id); } return hardwarePrinter; } public Collection<HardwarePrinter> getByIds(final @NonNull Collection<HardwarePrinterId> ids) { return streamByIds(ids).collect(ImmutableList.toImmutableList()); }
public Stream<HardwarePrinter> streamByIds(final @NonNull Collection<HardwarePrinterId> ids) { if (ids.isEmpty()) { return Stream.empty(); } return ids.stream() .map(byId::get) .filter(Objects::nonNull); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwarePrinterRepository.java
1
请完成以下Spring Boot application配置
## Spring view resolver set up spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false spring.datasource.username=root spring.datasource.password=Mysql@123 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.
MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto = update spring.messages.basename=validation logging.level.root = INFO,ERROR
repos\Spring-Boot-Advanced-Projects-main\login-registration-springboot-hibernate-jsp-auth\src\main\resources\application.properties
2
请完成以下Java代码
public class MAssetGroup extends X_A_Asset_Group { /** * */ private static final long serialVersionUID = 1364948077775028283L; /** * Get from Cache * @param ctx context * @param A_Asset_Group_ID id * @return category */ public static MAssetGroup get (Properties ctx, int A_Asset_Group_ID) { Integer ii = new Integer (A_Asset_Group_ID); MAssetGroup pc = (MAssetGroup)s_cache.get(ii); if (pc == null) pc = new MAssetGroup (ctx, A_Asset_Group_ID, null); return pc; } // get /** Categopry Cache */ private static CCache<Integer, MAssetGroup> s_cache = new CCache<Integer, MAssetGroup> ("A_Asset_Group", 10); /** * Standard Constructor * @param ctx context * @param A_Asset_Group_ID id * @param trxName trx */ public MAssetGroup (Properties ctx, int A_Asset_Group_ID, String trxName) { super (ctx, A_Asset_Group_ID, trxName);
if (A_Asset_Group_ID == 0) { // setName (null); setIsDepreciated (false); setIsOneAssetPerUOM (false); setIsOwned (false); setIsCreateAsActive(true); setIsTrackIssues(false); } } // MAssetGroup /** * Load Cosntructor * @param ctx context * @param rs result set * @param trxName trx */ public MAssetGroup (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MAssetGroup } // MAssetGroup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAssetGroup.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList("fields", "replacement"); } @Override public GatewayFilter apply(Config config) { return modifyResponseBodyFilterFactory .apply(c -> c.setRewriteFunction(JsonNode.class, JsonNode.class, new Scrubber(config))); } public static class Config { private String fields; private String replacement; public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } } public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> { private final Pattern fields; private final String replacement; public Scrubber(Config config) { this.fields = Pattern.compile(config.getFields()); this.replacement = config.getReplacement(); } @Override public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) { return Mono.just(scrubRecursively(u)); }
private JsonNode scrubRecursively(JsonNode u) { if ( !u.isContainerNode()) { return u; } if ( u.isObject()) { ObjectNode node = (ObjectNode)u; node.fields().forEachRemaining((f) -> { if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) { f.setValue(TextNode.valueOf(replacement)); } else { f.setValue(scrubRecursively(f.getValue())); } }); } else if ( u.isArray()) { ArrayNode array = (ArrayNode)u; for ( int i = 0 ; i < array.size() ; i++ ) { array.set(i, scrubRecursively(array.get(i))); } } return u; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ScrubResponseGatewayFilterFactory.java
1
请完成以下Java代码
public synchronized <BT, T extends BT> void registerJUnitBeans( @NonNull final Class<BT> beanType, @NonNull final List<T> beansToAdd) { assertJUnitMode(); final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>()); beans.addAll(beansToAdd); logger.info("JUnit testing: Registered beans {}={}", beanType, beansToAdd); } public synchronized <T> T getBeanOrNull(@NonNull final Class<T> beanType) { assertJUnitMode(); final ArrayList<Object> beans = map.get(ClassReference.of(beanType)); if (beans == null || beans.isEmpty()) { return null; } if (beans.size() > 1) { logger.warn("Found more than one bean for {} but returning the first one: {}", beanType, beans); } final T beanImpl = castBean(beans.get(0), beanType); logger.debug("JUnit testing Returning manually registered bean: {}", beanImpl); return beanImpl; } private static <T> T castBean(final Object beanImpl, final Class<T> ignoredBeanType) { @SuppressWarnings("unchecked") final T beanImplCasted = (T)beanImpl; return beanImplCasted;
} public synchronized <T> ImmutableList<T> getBeansOfTypeOrNull(@NonNull final Class<T> beanType) { assertJUnitMode(); List<Object> beanObjs = map.get(ClassReference.of(beanType)); if (beanObjs == null) { final List<Object> assignableBeans = map.values() .stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(impl -> beanType.isAssignableFrom(impl.getClass())) .collect(Collectors.toList()); if (assignableBeans.isEmpty()) { return null; } beanObjs = assignableBeans; } return beanObjs .stream() .map(beanObj -> castBean(beanObj, beanType)) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\JUnitBeansMap.java
1
请在Spring Boot框架中完成以下Java代码
public void setPrice(Double price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Car)) { return false; } return getId() != null && getId().equals(((Car) o).getId()); }
@Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Car{" + "id=" + getId() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\domain\Car.java
2
请完成以下Java代码
public StringAppender build() { StringAppender stringAppender = new StringAppender(resolveStringAppenderWrapper()); stringAppender.setContext(resolveContext()); stringAppender.setName(resolveName()); getDelegate().ifPresent(delegate -> { Appender appender = this.replace ? stringAppender : CompositeAppender.compose(delegate.getAppender(), stringAppender); delegate.setAppender(appender); }); getLogger().ifPresent(logger -> logger.addAppender(stringAppender)); return stringAppender; } public StringAppender buildAndStart() { StringAppender stringAppender = build(); stringAppender.start(); return stringAppender; } } private final StringAppenderWrapper stringAppenderWrapper; protected StringAppender(StringAppenderWrapper stringAppenderWrapper) { if (stringAppenderWrapper == null) { throw new IllegalArgumentException("StringAppenderWrapper must not be null"); } this.stringAppenderWrapper = stringAppenderWrapper;
} public String getLogOutput() { return getStringAppenderWrapper().toString(); } protected StringAppenderWrapper getStringAppenderWrapper() { return this.stringAppenderWrapper; } @Override protected void append(ILoggingEvent loggingEvent) { Optional.ofNullable(loggingEvent) .map(event -> preProcessLogMessage(toString(event))) .filter(this::isValidLogMessage) .ifPresent(getStringAppenderWrapper()::append); } protected boolean isValidLogMessage(String message) { return message != null && !message.isEmpty(); } protected String preProcessLogMessage(String message) { return message != null ? message.trim() : null; } protected String toString(ILoggingEvent loggingEvent) { return loggingEvent != null ? loggingEvent.getFormattedMessage() : null; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\StringAppender.java
1
请完成以下Java代码
class ImmutableTableNamesGroupsIndex { public static ImmutableTableNamesGroupsIndex EMPTY = new ImmutableTableNamesGroupsIndex(); public static ImmutableTableNamesGroupsIndex ofCollection(final Collection<TableNamesGroup> groups) { return new ImmutableTableNamesGroupsIndex(groups); } private static final String DEFAULT_GROUP_ID = "default"; private final ImmutableMap<String, TableNamesGroup> groupsById; private final ImmutableSet<String> tableNames; private ImmutableTableNamesGroupsIndex(final Collection<TableNamesGroup> groups) { this.groupsById = Maps.uniqueIndex(groups, TableNamesGroup::getGroupId); tableNames = groups.stream() .flatMap(group -> group.getTableNames().stream()) .collect(ImmutableSet.toImmutableSet()); } private ImmutableTableNamesGroupsIndex() { groupsById = ImmutableMap.of(); tableNames = ImmutableSet.of(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(groupsById) .toString(); } public ImmutableSet<String> getTableNames() { return tableNames; } public boolean containsTableName(final String tableName) { return tableNames.contains(tableName); } public ImmutableTableNamesGroupsIndex addingToDefaultGroup(@NonNull final String tableName) { return addingToDefaultGroup(ImmutableSet.of(tableName)); } public ImmutableTableNamesGroupsIndex addingToDefaultGroup(@NonNull final Collection<String> tableNames) { if (tableNames.isEmpty()) { return this; } final TableNamesGroup defaultGroupExisting = groupsById.get(DEFAULT_GROUP_ID); final TableNamesGroup defaultGroupNew;
if (defaultGroupExisting != null) { defaultGroupNew = defaultGroupExisting.toBuilder() .tableNames(tableNames) .build(); } else { defaultGroupNew = TableNamesGroup.builder() .groupId(DEFAULT_GROUP_ID) .tableNames(tableNames) .build(); } if (Objects.equals(defaultGroupExisting, defaultGroupNew)) { return this; } return replacingGroup(defaultGroupNew); } public ImmutableTableNamesGroupsIndex replacingGroup(@NonNull final TableNamesGroup groupToAdd) { if (groupsById.isEmpty()) { return new ImmutableTableNamesGroupsIndex(ImmutableList.of(groupToAdd)); } final ArrayList<TableNamesGroup> newGroups = new ArrayList<>(groupsById.size() + 1); boolean added = false; for (final TableNamesGroup group : groupsById.values()) { if (Objects.equals(group.getGroupId(), groupToAdd.getGroupId())) { newGroups.add(groupToAdd); added = true; } else { newGroups.add(group); } } if (!added) { newGroups.add(groupToAdd); added = true; } return new ImmutableTableNamesGroupsIndex(newGroups); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\ImmutableTableNamesGroupsIndex.java
1
请完成以下Java代码
public String getTips() { return tips; } /** * 设置 备注. * * @param tips 备注. */ public void setTips(String tips) { this.tips = tips; } /** * 获取 状态 1:正常 2:禁用. * * @return 状态 1:正常 2:禁用. */ public Integer getState() { return state; } /** * 设置 状态 1:正常 2:禁用. * * @param state 状态 1:正常 2:禁用. */ public void setState(Integer state) { this.state = state; } /** * 获取 创建时间. * * @return 创建时间. */ public Date getCreatedTime() { return createdTime; } /** * 设置 创建时间. * * @param createdTime 创建时间. */
public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } /** * 获取 更新时间. * * @return 更新时间. */ public Date getUpdatedTime() { return updatedTime; } /** * 设置 更新时间. * * @param updatedTime 更新时间. */ public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } protected Serializable pkVal() { return this.id; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Manager.java
1
请完成以下Java代码
protected void prepare() { if (createSelection() <= 0) { throw new AdempiereException("@NoSelection@"); } } private int createSelection() { final IQueryBuilder<I_C_DocType> queryBuilder = createDocTypesQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); return queryBuilder .create() .createSelection(adPInstanceId); }
@NonNull private IQueryBuilder<I_C_DocType> createDocTypesQueryBuilder() { final IQueryFilter<I_C_DocType> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_C_DocType.class, getCtx(), ITrx.TRXNAME_None) .filter(userSelectionFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\process\C_DocType_Clone_Selection.java
1
请完成以下Java代码
public String add(@Valid UserParam userParam,BindingResult result, ModelMap model) { String errorMsg=""; if(result.hasErrors()) { List<ObjectError> list = result.getAllErrors(); for (ObjectError error : list) { errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";"; } model.addAttribute("errorMsg",errorMsg); return "user/userAdd"; } UserEntity u= userRepository.findByUserNameOrEmail(userParam.getUserName(),userParam.getEmail()); if(u!=null){ model.addAttribute("errorMsg","用户已存在!"); return "user/userAdd"; } UserEntity user=new UserEntity(); BeanUtils.copyProperties(userParam,user); user.setRegTime(new Date()); user.setUserType("user"); userRepository.save(user); return "redirect:/list"; } @RequestMapping("/toEdit") public String toEdit(Model model,String id) { UserEntity user=userRepository.findById(id); model.addAttribute("user", user); return "user/userEdit"; } @RequestMapping("/edit") public String edit(@Valid UserParam userParam, BindingResult result,ModelMap model) {
String errorMsg=""; if(result.hasErrors()) { List<ObjectError> list = result.getAllErrors(); for (ObjectError error : list) { errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";"; } model.addAttribute("errorMsg",errorMsg); model.addAttribute("user", userParam); return "user/userEdit"; } UserEntity user=userRepository.findById(userParam.getId()); BeanUtils.copyProperties(userParam,user); user.setRegTime(new Date()); userRepository.save(user); return "redirect:/list"; } @RequestMapping("/delete") public String delete(String id) { userRepository.delete(id); return "redirect:/list"; } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\web\UserController.java
1
请完成以下Java代码
public void setAD_Tree_ID (int AD_Tree_ID) { if (AD_Tree_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, Integer.valueOf(AD_Tree_ID)); } /** Get Tree. @return Identifies a Tree */ public int getAD_Tree_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Node_ID. @param Node_ID Node_ID */ public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_ValueNoCheck (COLUMNNAME_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent. @param Parent_ID Parent of Entity */ public void setParent_ID (int Parent_ID) { if (Parent_ID < 1) set_Value (COLUMNNAME_Parent_ID, null); else set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID)); } /** Get Parent.
@return Parent of Entity */ public int getParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** 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(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeNode.java
1
请完成以下Java代码
public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public de.metas.ui.web.base.model.I_WEBUI_Dashboard getWEBUI_Dashboard() { return get_ValueAsPO(COLUMNNAME_WEBUI_Dashboard_ID, de.metas.ui.web.base.model.I_WEBUI_Dashboard.class); } @Override public void setWEBUI_Dashboard(final de.metas.ui.web.base.model.I_WEBUI_Dashboard WEBUI_Dashboard) { set_ValueFromPO(COLUMNNAME_WEBUI_Dashboard_ID, de.metas.ui.web.base.model.I_WEBUI_Dashboard.class, WEBUI_Dashboard); } @Override public void setWEBUI_Dashboard_ID (final int WEBUI_Dashboard_ID) { if (WEBUI_Dashboard_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, WEBUI_Dashboard_ID); } @Override public int getWEBUI_Dashboard_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Dashboard_ID); } @Override public void setWEBUI_DashboardItem_ID (final int WEBUI_DashboardItem_ID) { if (WEBUI_DashboardItem_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_DashboardItem_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_DashboardItem_ID, WEBUI_DashboardItem_ID); } @Override public int getWEBUI_DashboardItem_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_DashboardItem_ID); } /** * WEBUI_DashboardWidgetType AD_Reference_ID=540697 * Reference name: WEBUI_DashboardWidgetType
*/ public static final int WEBUI_DASHBOARDWIDGETTYPE_AD_Reference_ID=540697; /** Target = T */ public static final String WEBUI_DASHBOARDWIDGETTYPE_Target = "T"; /** KPI = K */ public static final String WEBUI_DASHBOARDWIDGETTYPE_KPI = "K"; @Override public void setWEBUI_DashboardWidgetType (final java.lang.String WEBUI_DashboardWidgetType) { set_Value (COLUMNNAME_WEBUI_DashboardWidgetType, WEBUI_DashboardWidgetType); } @Override public java.lang.String getWEBUI_DashboardWidgetType() { return get_ValueAsString(COLUMNNAME_WEBUI_DashboardWidgetType); } @Override public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI() { return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class); } @Override public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI) { set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_Value (COLUMNNAME_WEBUI_KPI_ID, null); else set_Value (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_DashboardItem.java
1
请完成以下Java代码
public String getAddtlTxInf() { return addtlTxInf; } /** * Sets the value of the addtlTxInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlTxInf(String value) { this.addtlTxInf = value; } /** * Gets the value of the splmtryData 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 splmtryData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSplmtryData().add(newItem); * </pre>
* * * <p> * Objects of the following type(s) are allowed in the list * {@link SupplementaryData1 } * * */ public List<SupplementaryData1> getSplmtryData() { if (splmtryData == null) { splmtryData = new ArrayList<SupplementaryData1>(); } return this.splmtryData; } }
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\EntryTransaction4.java
1
请完成以下Java代码
public IInvoiceCandRecomputeTagger setContext(final Properties ctx, final String trxName) { this._ctx = ctx; this._trxName = trxName; return this; } @Override public final Properties getCtx() { Check.assumeNotNull(_ctx, "_ctx not null"); return _ctx; } String getTrxName() { return _trxName; } @Override public IInvoiceCandRecomputeTagger setRecomputeTag(final InvoiceCandRecomputeTag recomputeTag) { this._recomputeTagToUseForTagging = recomputeTag; return this; } private void generateRecomputeTagIfNotSet() { // Do nothing if the recompute tag was already generated if (!InvoiceCandRecomputeTag.isNull(_recomputeTag)) { return; } // Use the recompute tag which was suggested if (!InvoiceCandRecomputeTag.isNull(_recomputeTagToUseForTagging)) { _recomputeTag = _recomputeTagToUseForTagging; return; } // Generate a new recompute tag _recomputeTag = invoiceCandDAO.generateNewRecomputeTag(); } /** * @return recompute tag; never returns null */ final InvoiceCandRecomputeTag getRecomputeTag() { Check.assumeNotNull(_recomputeTag, "_recomputeTag not null"); return _recomputeTag; } @Override public InvoiceCandRecomputeTagger setLockedBy(final ILock lockedBy) { this._lockedBy = lockedBy; return this; } /* package */ILock getLockedBy() { return _lockedBy; } @Override public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag) { _taggedWith = tag; return this; } @Override public InvoiceCandRecomputeTagger setTaggedWithNoTag() {
return setTaggedWith(InvoiceCandRecomputeTag.NULL); } @Override public IInvoiceCandRecomputeTagger setTaggedWithAnyTag() { return setTaggedWith(null); } /* package */ @Nullable InvoiceCandRecomputeTag getTaggedWith() { return _taggedWith; } @Override public InvoiceCandRecomputeTagger setLimit(final int limit) { this._limit = limit; return this; } /* package */int getLimit() { return _limit; } @Override public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds) { this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds; } @Override @Nullable public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds() { return onlyInvoiceCandidateIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(HttpSecurity http) throws Exception { http .csrf() .ignoringAntMatchers("/h2-console/**") .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .and() .addFilterBefore(corsFilter, CsrfFilter.class) .headers() .frameOptions() .disable() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/**").authenticated() .antMatchers("/management/health").permitAll() .antMatchers("/management/info").permitAll() .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN); } @Bean public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { return new JwtTokenStore(jwtAccessTokenConverter); } @Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(OAuth2SignatureVerifierClient signatureVerifierClient) { return new OAuth2JwtAccessTokenConverter(oAuth2Properties, signatureVerifierClient); } @Bean @Qualifier("loadBalancedRestTemplate") public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) { RestTemplate restTemplate = new RestTemplate(); customizer.customize(restTemplate); return restTemplate; } @Bean @Qualifier("vanillaRestTemplate") public RestTemplate vanillaRestTemplate() { return new RestTemplate(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\SecurityConfiguration.java
2
请完成以下Java代码
public static PropertyEntityManager getPropertyEntityManager() { return getPropertyEntityManager(getCommandContext()); } public static PropertyEntityManager getPropertyEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getIdmPropertyEntityManager(); } public static UserEntityManager getUserEntityManager() { return getUserEntityManager(getCommandContext()); } public static UserEntityManager getUserEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getUserEntityManager(); } public static GroupEntityManager getGroupEntityManager() { return getGroupEntityManager(getCommandContext()); } public static GroupEntityManager getGroupEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getGroupEntityManager(); } public static MembershipEntityManager getMembershipEntityManager() { return getMembershipEntityManager(getCommandContext()); } public static MembershipEntityManager getMembershipEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getMembershipEntityManager(); } public static PrivilegeEntityManager getPrivilegeEntityManager() { return getPrivilegeEntityManager(getCommandContext()); } public static PrivilegeEntityManager getPrivilegeEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getPrivilegeEntityManager(); } public static PrivilegeMappingEntityManager getPrivilegeMappingEntityManager() {
return getPrivilegeMappingEntityManager(getCommandContext()); } public static PrivilegeMappingEntityManager getPrivilegeMappingEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getPrivilegeMappingEntityManager(); } public static TokenEntityManager getTokenEntityManager() { return getTokenEntityManager(getCommandContext()); } public static TokenEntityManager getTokenEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getTokenEntityManager(); } public static IdentityInfoEntityManager getIdentityInfoEntityManager() { return getIdentityInfoEntityManager(getCommandContext()); } public static IdentityInfoEntityManager getIdentityInfoEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getIdentityInfoEntityManager(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\util\CommandContextUtil.java
1
请完成以下Java代码
public void addModelValidator(@NonNull final Object validator, @Nullable final I_AD_Client client) { if (validator instanceof ModelValidator) { initialize((ModelValidator)validator, client); } else if (validator instanceof IModelInterceptor) { final IModelInterceptor interceptor = (IModelInterceptor)validator; final ModelValidator interceptor2validator = ModelInterceptor2ModelValidatorWrapper.wrapIfNeeded(interceptor); initialize(interceptor2validator, client); } else { final IModelInterceptor annotatedInterceptor = AnnotatedModelInterceptorFactory.get().createModelInterceptor(validator); if (annotatedInterceptor == null) { logger.warn("No pointcuts found for model validator: " + validator + " [SKIP]"); } else { final ModelValidator annotatedValidator = ModelInterceptor2ModelValidatorWrapper.wrapIfNeeded(annotatedInterceptor); initialize(annotatedValidator, client); } } } /** * Specify if model changed events with type=deferred should be processed when they occur (still after the po has been saved an all other logic has been finished) or some time later. */ public void enableModelValidatorSubsequentProcessing(final ModelValidator validator, final boolean processDirectly) { m_modelChangeSubsequent.put(validator, processDirectly); } public void disableModelValidatorSubsequentProcessing(final ModelValidator validator) { m_modelChangeSubsequent.remove(validator); } // public static final String CTX_InitEntityTypes = ModelValidationEngine.class.getCanonicalName() + "#InitEntityTypes"; /** * Name of a dynamic attribute to disable model interceptors (i.e. validators) on ModelChange for a particular PO. Set the value to <code>true</code> if you want to bypass <b>all</b> model * validators. * <p> * * @FIXME [12:09:52] Teo metas: use org.adempiere.ad.persistence.ModelDynAttributeAccessor<ModelType, AttributeType> to define the dynamic attribute */ public static final String DYNATTR_DO_NOT_INVOKE_ON_MODEL_CHANGE = "DO_NOT_INVOKE_ON_MODEL_CHANGE"; private enum State { /** In this state, {@link #get()} does not attempt to initialize this model validator and basically returns a "no-op" instance. */
SKIP_INITIALIZATION, /** In this state, the next invocation of {@link #get()} will to initialize the model validator before returning an instance. */ TO_BE_INITALIZED, INITIALIZING, INITIALIZED } private static State state = State.TO_BE_INITALIZED; public static IAutoCloseable postponeInit() { changeStateToSkipInitialization(); return ModelValidationEngine::changeStateToBeInitialized; } private static synchronized void changeStateToSkipInitialization() { Check.assumeEquals(state, State.TO_BE_INITALIZED); state = State.SKIP_INITIALIZATION; } private static synchronized void changeStateToBeInitialized() { if (state == State.SKIP_INITIALIZATION) { state = State.TO_BE_INITALIZED; } } } // ModelValidatorEngine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\ModelValidationEngine.java
1
请完成以下Java代码
public String discountAmt(final ICalloutField calloutField) { if (isCalloutActive()) { return NO_ERROR; } final I_C_PaySelectionLine paySelectionLine = calloutField.getModel(I_C_PaySelectionLine.class); setDifferenceAmt(paySelectionLine); return NO_ERROR; } private void setDifferenceAmt(final I_C_PaySelectionLine paySelectionLine) { final BigDecimal OpenAmt = paySelectionLine.getOpenAmt(); final BigDecimal PayAmt = paySelectionLine.getPayAmt(); final BigDecimal DiscountAmt = paySelectionLine.getDiscountAmt(); final BigDecimal DifferenceAmt = OpenAmt.subtract(PayAmt).subtract(DiscountAmt); paySelectionLine.setDifferenceAmt(DifferenceAmt); } /** * Payment Selection Line - Invoice. * - called from C_PaySelectionLine.C_Invoice_ID * - update PayAmt & DifferenceAmt */ public String invoice(final ICalloutField calloutField) { // FIXME: refactor it and use de.metas.banking.payment.impl.PaySelectionUpdater. In meantime pls keep in sync. if (isCalloutActive()) { return NO_ERROR; } // get invoice final I_C_PaySelectionLine psl = calloutField.getModel(I_C_PaySelectionLine.class); final int C_Invoice_ID = psl.getC_Invoice_ID(); if (C_Invoice_ID <= 0) { return NO_ERROR; } final I_C_PaySelection paySelection = psl.getC_PaySelection(); final int C_BP_BankAccount_ID = paySelection.getC_BP_BankAccount_ID(); Timestamp PayDate = paySelection.getPayDate(); if (PayDate == null) {
PayDate = new Timestamp(System.currentTimeMillis()); } BigDecimal OpenAmt = BigDecimal.ZERO; BigDecimal DiscountAmt = BigDecimal.ZERO; boolean IsSOTrx = false; final String sql = "SELECT currencyConvert(invoiceOpen(i.C_Invoice_ID, 0), i.C_Currency_ID," + "ba.C_Currency_ID, i.DateInvoiced, i.C_ConversionType_ID, i.AD_Client_ID, i.AD_Org_ID)," + " paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?), i.IsSOTrx " + "FROM C_Invoice_v i, C_BP_BankAccount ba " + "WHERE i.C_Invoice_ID=? AND ba.C_BP_BankAccount_ID=?"; // #1..2 ResultSet rs = null; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); pstmt.setTimestamp(1, PayDate); pstmt.setInt(2, C_Invoice_ID); pstmt.setInt(3, C_BP_BankAccount_ID); rs = pstmt.executeQuery(); if (rs.next()) { OpenAmt = rs.getBigDecimal(1); DiscountAmt = rs.getBigDecimal(2); IsSOTrx = DisplayType.toBoolean(rs.getString(3)); } } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } psl.setOpenAmt(OpenAmt); psl.setPayAmt(OpenAmt.subtract(DiscountAmt)); psl.setDiscountAmt(DiscountAmt); psl.setDifferenceAmt(BigDecimal.ZERO); psl.setIsSOTrx(IsSOTrx); return NO_ERROR; } // invoice } // CalloutPaySelection
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutPaySelection.java
1
请完成以下Java代码
public CostAmount toCostAmount() { return getOwnCostPrice().add(getComponentsCostPrice()); } @VisibleForTesting public BigDecimal toBigDecimal() { return toCostAmount().toBigDecimal(); } public CostPrice addToOwnCostPrice(@NonNull final CostAmount ownCostPriceToAdd) { if (ownCostPriceToAdd.isZero()) { return this; } return withOwnCostPrice(getOwnCostPrice().add(ownCostPriceToAdd)); } public CostPrice withOwnCostPrice(final CostAmount ownCostPrice) { return toBuilder().ownCostPrice(ownCostPrice).build(); } public CostPrice withZeroOwnCostPrice() { final CostAmount ownCostPrice = getOwnCostPrice(); if (ownCostPrice.isZero()) { return this; } return withOwnCostPrice(ownCostPrice.toZero()); } public CostPrice withZeroComponentsCostPrice() { final CostAmount componentsCostPrice = getComponentsCostPrice(); if (componentsCostPrice.isZero()) { return this; } return withComponentsCostPrice(componentsCostPrice.toZero()); } public CostPrice withComponentsCostPrice(final CostAmount componentsCostPrice) { return toBuilder().componentsCostPrice(componentsCostPrice).build(); } public CostPrice add(final CostPrice costPrice) { if (!UomId.equals(this.getUomId(), costPrice.getUomId())) { throw new AdempiereException("UOM does not match: " + this + ", " + costPrice); } return builder() .ownCostPrice(getOwnCostPrice().add(costPrice.getOwnCostPrice())) .componentsCostPrice(getComponentsCostPrice().add(costPrice.getComponentsCostPrice())) .uomId(getUomId())
.build(); } public CostAmount multiply(@NonNull final Quantity quantity) { if (!UomId.equals(uomId, quantity.getUomId())) { throw new AdempiereException("UOM does not match: " + this + ", " + quantity); } return toCostAmount().multiply(quantity); } public CostAmount multiply( @NonNull final Duration duration, @NonNull final TemporalUnit durationUnit) { final BigDecimal durationBD = DurationUtils.toBigDecimal(duration, durationUnit); return toCostAmount().multiply(durationBD); } public CostPrice convertAmounts( @NonNull final UomId toUomId, @NonNull final UnaryOperator<CostAmount> converter) { if (UomId.equals(this.uomId, toUomId)) { return this; } return toBuilder() .uomId(toUomId) .ownCostPrice(converter.apply(getOwnCostPrice())) .componentsCostPrice(converter.apply(getComponentsCostPrice())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostPrice.java
1
请完成以下Java代码
public int getC_DirectDebitLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebitLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public I_C_Invoice getC_Invoice() throws Exception { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } /** Set Invoice. @param C_Invoice_ID Invoice Identifier */ @Override public void setC_Invoice_ID (int C_Invoice_ID) {
if (C_Invoice_ID < 1) throw new IllegalArgumentException ("C_Invoice_ID is mandatory."); set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID)); } /** Get Invoice. @return Invoice Identifier */ @Override public int getC_Invoice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebitLine.java
1
请完成以下Java代码
public void setC_Currency_ID (final int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID); } @Override public int getC_Currency_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_ID); } @Override public void setDescription (final @Nullable String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setSEPA_Export_ID (final int SEPA_Export_ID) { if (SEPA_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, SEPA_Export_ID); }
@Override public int getSEPA_Export_ID() { return get_ValueAsInt(COLUMNNAME_SEPA_Export_ID); } @Override public void setSEPA_Export_Line_ID (final int SEPA_Export_Line_ID) { if (SEPA_Export_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, SEPA_Export_Line_ID); } @Override public int getSEPA_Export_Line_ID() { return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_ID); } @Override public void setSEPA_Export_Line_Ref_ID (final int SEPA_Export_Line_Ref_ID) { if (SEPA_Export_Line_Ref_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, SEPA_Export_Line_Ref_ID); } @Override public int getSEPA_Export_Line_Ref_ID() { return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_Ref_ID); } @Override public void setStructuredRemittanceInfo (final @Nullable String StructuredRemittanceInfo) { set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo); } @Override public String getStructuredRemittanceInfo() { return get_ValueAsString(COLUMNNAME_StructuredRemittanceInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line_Ref.java
1
请完成以下Java代码
public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseCatalog() { return databaseCatalog; } public void setDatabaseCatalog(String databaseCatalog) { this.databaseCatalog = databaseCatalog; } public String getDatabaseSchema() { return databaseSchema;
} public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) { this.tablePrefixIsSchema = tablePrefixIsSchema; } public boolean isTablePrefixIsSchema() { return tablePrefixIsSchema; } public int getMaxNrOfStatementsInBulkInsert() { return maxNrOfStatementsInBulkInsert; } public void setMaxNrOfStatementsInBulkInsert(int maxNrOfStatementsInBulkInsert) { this.maxNrOfStatementsInBulkInsert = maxNrOfStatementsInBulkInsert; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSessionFactory.java
1
请完成以下Java代码
protected void performStart(CmmnActivityExecution execution) { execution.createTask(taskDecorator); } protected void performTerminate(CmmnActivityExecution execution) { terminating(execution); super.performTerminate(execution); } protected void performExit(CmmnActivityExecution execution) { terminating(execution); super.performExit(execution); } protected void terminating(CmmnActivityExecution execution) { TaskEntity task = getTask(execution); // it can happen that a there does not exist // a task, because the given execution was never // active. if (task != null) { task.delete("terminated", false); } } protected void completing(CmmnActivityExecution execution) { TaskEntity task = getTask(execution); if (task != null) { task.caseExecutionCompleted(); } } protected void manualCompleting(CmmnActivityExecution execution) { completing(execution); } protected void suspending(CmmnActivityExecution execution) { String id = execution.getId(); Context .getCommandContext() .getTaskManager()
.updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.SUSPENDED); } protected void resuming(CmmnActivityExecution execution) { String id = execution.getId(); Context .getCommandContext() .getTaskManager() .updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.ACTIVE); } protected TaskEntity getTask(CmmnActivityExecution execution) { return Context .getCommandContext() .getTaskManager() .findTaskByCaseExecutionId(execution.getId()); } protected String getTypeName() { return "human task"; } // getters/setters ///////////////////////////////////////////////// public TaskDecorator getTaskDecorator() { return taskDecorator; } public void setTaskDecorator(TaskDecorator taskDecorator) { this.taskDecorator = taskDecorator; } public TaskDefinition getTaskDefinition() { return taskDecorator.getTaskDefinition(); } public ExpressionManager getExpressionManager() { return taskDecorator.getExpressionManager(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\HumanTaskActivityBehavior.java
1
请完成以下Java代码
public class ValidationsType { @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice", required = true) protected List<ValidationType> validation; /** * Gets the value of the validation 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 validation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getValidation().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ValidationType } * * */ public List<ValidationType> getValidation() { if (validation == null) { validation = new ArrayList<ValidationType>(); } return this.validation; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ValidationsType.java
1
请完成以下Java代码
private List<ShipmentScheduleAvailableStockDetail> createPickFromStockDetails( @NonNull final StockDataQuery mainProductQuery, @Nullable final PPOrderId pickFromOrderId) { final ProductId mainProductId = mainProductQuery.getProductId(); final QtyCalculationsBOM pickingBOM = getPickingBOM(pickFromOrderId).orElse(null); if (pickingBOM == null) { return ImmutableList.of(); } final ListMultimap<WarehouseId, ShipmentScheduleAvailableStockDetail> allComponentStockDetails = ArrayListMultimap.create(); for (final QtyCalculationsBOMLine bomLine : pickingBOM.getLines()) { final StockDataQuery componentQuery = toPickBOMComponentQuery(mainProductQuery, bomLine); for (final ShipmentScheduleAvailableStockDetail componentStockDetail : getStockDetailsMatching(componentQuery)) { allComponentStockDetails.put(componentStockDetail.getWarehouseId(), componentStockDetail); } } final ArrayList<ShipmentScheduleAvailableStockDetail> pickFromStockDetails = new ArrayList<>(); for (final WarehouseId warehouseId : allComponentStockDetails.keySet()) { final List<ShipmentScheduleAvailableStockDetail> componentStockDetails = allComponentStockDetails.get(warehouseId); if (componentStockDetails.isEmpty()) { continue; } pickFromStockDetails.add(ShipmentScheduleAvailableStockDetail.builder() .productId(mainProductId) .warehouseId(warehouseId) .storageAttributesKey(AttributesKey.ALL) .qtyOnHand(BigDecimal.ZERO) .pickingBOM(pickingBOM) .componentStockDetails(componentStockDetails) .build()); } return pickFromStockDetails; }
private ImmutableList<ShipmentScheduleAvailableStockDetail> getStockDetailsMatching(@NonNull final StockDataQuery query) { return stockDetails .stream() .filter(stockDetail -> matching(query, stockDetail)) .collect(ImmutableList.toImmutableList()); } private static boolean matching(final StockDataQuery query, final ShipmentScheduleAvailableStockDetail stockDetail) { // // Product if (!ProductId.equals(query.getProductId(), stockDetail.getProductId())) { return false; } // // Warehouse final Set<WarehouseId> queryWarehouseIds = query.getWarehouseIds(); if (!queryWarehouseIds.isEmpty() && !queryWarehouseIds.contains(stockDetail.getWarehouseId())) { return false; } // // Attributes final boolean queryMatchesAll = query.getStorageAttributesKey().isAll(); final boolean queryMatchesStockDetail = AttributesKey.equals(query.getStorageAttributesKey(), stockDetail.getStorageAttributesKey()); if (!queryMatchesAll && !queryMatchesStockDetail) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentScheduleQtyOnHandStorage.java
1
请在Spring Boot框架中完成以下Java代码
protected boolean shouldGenerateId() { return false; } @Override protected boolean shouldGenerateIdAsFallback() { return true; } @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { if (element.hasAttribute(ADDRESSES) && (element.hasAttribute(HOST_ATTRIBUTE) || element.hasAttribute(PORT_ATTRIBUTE))) { parserContext.getReaderContext().error("If the 'addresses' attribute is provided, a connection " + "factory can not have 'host' or 'port' attributes.", element); } NamespaceUtils.addConstructorArgParentRefIfAttributeDefined(builder, element, CONNECTION_FACTORY_ATTRIBUTE); NamespaceUtils.setValueIfAttributeDefined(builder, element, CHANNEL_CACHE_SIZE_ATTRIBUTE); NamespaceUtils.setValueIfAttributeDefined(builder, element, HOST_ATTRIBUTE); NamespaceUtils.setValueIfAttributeDefined(builder, element, PORT_ATTRIBUTE); NamespaceUtils.setValueIfAttributeDefined(builder, element, USER_ATTRIBUTE); NamespaceUtils.setValueIfAttributeDefined(builder, element, PASSWORD_ATTRIBUTE); NamespaceUtils.setValueIfAttributeDefined(builder, element, VIRTUAL_HOST_ATTRIBUTE); NamespaceUtils.setReferenceIfAttributeDefined(builder, element, EXECUTOR_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, ADDRESSES); NamespaceUtils.setValueIfAttributeDefined(builder, element, SHUFFLE_ADDRESSES); if (element.hasAttribute(SHUFFLE_ADDRESSES) && element.hasAttribute(SHUFFLE_MODE)) { parserContext.getReaderContext() .error("You must not specify both '" + SHUFFLE_ADDRESSES + "' and '" + SHUFFLE_MODE + "'", element); } NamespaceUtils.setValueIfAttributeDefined(builder, element, SHUFFLE_MODE); NamespaceUtils.setReferenceIfAttributeDefined(builder, element, ADDRESS_RESOLVER); NamespaceUtils.setValueIfAttributeDefined(builder, element, PUBLISHER_RETURNS); NamespaceUtils.setValueIfAttributeDefined(builder, element, REQUESTED_HEARTBEAT, "requestedHeartBeat"); NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_TIMEOUT); NamespaceUtils.setValueIfAttributeDefined(builder, element, CACHE_MODE); NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_CACHE_SIZE_ATTRIBUTE); NamespaceUtils.setReferenceIfAttributeDefined(builder, element, THREAD_FACTORY, "connectionThreadFactory"); NamespaceUtils.setValueIfAttributeDefined(builder, element, FACTORY_TIMEOUT, "channelCheckoutTimeout"); NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_LIMIT); NamespaceUtils.setReferenceIfAttributeDefined(builder, element, "connection-name-strategy"); NamespaceUtils.setValueIfAttributeDefined(builder, element, CONFIRM_TYPE, "publisherConfirmType"); } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\ConnectionFactoryParser.java
2
请完成以下Java代码
public static <V, K> FixedOrderByKeyComparator<V, K> notMatchedAtTheEnd(final List<K> fixedOrderList, final Function<V, K> keyMapper) { final int notMatchedMarkerIndex = Integer.MAX_VALUE; return new FixedOrderByKeyComparator<>(fixedOrderList, notMatchedMarkerIndex, keyMapper); } private final List<K> fixedOrderKeys; private final int notMatchedMarkerIndex; private final Function<V, K> keyMapper; @Builder private FixedOrderByKeyComparator( @NonNull @Singular final List<K> fixedOrderKeys, final int notMatchedMarkerIndex, @NonNull final Function<V, K> keyMapper) { // Check.assume(!fixedOrderKeys.isEmpty(), "fixedOrderList not empty"); // empty list shall be OK this.fixedOrderKeys = fixedOrderKeys; this.notMatchedMarkerIndex = notMatchedMarkerIndex; this.keyMapper = keyMapper; } @Override public int compare(final V o1, final V o2) { final int idx1 = getIndexOf(o1);
final int idx2 = getIndexOf(o2); return idx1 - idx2; } private int getIndexOf(final V obj) { final K key = keyMapper.apply(obj); int idx = fixedOrderKeys.indexOf(key); if (idx < 0) { idx = notMatchedMarkerIndex; } return idx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\FixedOrderByKeyComparator.java
1
请完成以下Java代码
public class GetCaseExecutionVariablesCmd implements Command<VariableMap>, Serializable { private static final long serialVersionUID = 1L; protected String caseExecutionId; protected Collection<String> variableNames; protected boolean isLocal; protected boolean deserializeValues; public GetCaseExecutionVariablesCmd(String caseExecutionId, Collection<String> variableNames, boolean isLocal, boolean deserializeValues) { this.caseExecutionId = caseExecutionId; this.variableNames = variableNames; this.isLocal = isLocal; this.deserializeValues = deserializeValues; } public VariableMap execute(CommandContext commandContext) { ensureNotNull("caseExecutionId", caseExecutionId); CaseExecutionEntity caseExecution = commandContext
.getCaseExecutionManager() .findCaseExecutionById(caseExecutionId); ensureNotNull(CaseExecutionNotFoundException.class, "case execution " + caseExecutionId + " doesn't exist", "caseExecution", caseExecution); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadCaseInstance(caseExecution); } VariableMapImpl result = new VariableMapImpl(); // collect variables caseExecution.collectVariables(result, variableNames, isLocal, deserializeValues); return result; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\cmd\GetCaseExecutionVariablesCmd.java
1
请完成以下Java代码
public List<RelatedDocumentsCandidateGroup> retrieveRelatedDocumentsCandidates( @NonNull final IZoomSource fromDocument, @Nullable final AdWindowId targetWindowId) { if (!acctDocRegistry.isAccountingTable(fromDocument.getTableName())) { return ImmutableList.of(); } final AdWindowId factAcctWindowId = getFactAcctWindowId(targetWindowId); if (factAcctWindowId == null) { return ImmutableList.of(); } // Return nothing if source is not Posted if (checkIsPosted(fromDocument).isFalse()) { return ImmutableList.of(); } final TableRecordReference fromRecordRef = TableRecordReference.of(fromDocument.getAD_Table_ID(), fromDocument.getRecord_ID()); final ClearingFactAcctsQuerySupplier querySupplier = new ClearingFactAcctsQuerySupplier(factAcctDAO, fromRecordRef); final RelatedDocumentsId id = RelatedDocumentsId.ofString("OI_Clearing_GLJ_Fact_Acct"); return ImmutableList.of( RelatedDocumentsCandidateGroup.of( RelatedDocumentsCandidate.builder() .id(id) .internalName(id.toJson()) .targetWindow(RelatedDocumentsTargetWindow.ofAdWindowIdAndCategory(factAcctWindowId, id.toJson())) .priority(relatedDocumentsPriority) .windowCaption(TranslatableStrings.anyLanguage("Clearing journal accounting transactions")) // TODO trl .querySupplier(querySupplier) .documentsCountSupplier(querySupplier) .build())); } 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代码
public String getAuthorizationUserId() { return authorizationUserId; } public String getProcDefId() { return procDefId; } public String getEventSubscriptionName() { return eventSubscriptionName; } public String getEventSubscriptionType() { return eventSubscriptionType; } public String getTenantId() { return tenantId;
} public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } @Override public ProcessDefinitionQueryImpl startableByUser(String userId) { if (userId == null) { throw new ActivitiIllegalArgumentException("userId is null"); } this.authorizationUserId = userId; return this; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ProcessDefinitionQueryImpl.java
1
请完成以下Java代码
private static MTreeNode getTopParent(final MTreeNode nd) { if (nd == null) { // shall not happen return null; } MTreeNode currentNode = nd; while (currentNode != null) { // If parent node is null or it has no ID (i.e. like the root node), // we consider current node as the top node final MTreeNode parent = (MTreeNode)currentNode.getParent(); if (parent == null || parent.getNode_ID() <= 0) { return currentNode; } // navigate up to parent, and check currentNode = parent; } return null; } public void removeItem(final FavoriteItem item) { if (item == null) { return; } // Database sync final MTreeNode node = item.getNode(); favoritesDAO.remove(getLoggedUserId(), node.getNode_ID()); // UI final FavoritesGroup group = item.getGroup(); group.removeItem(item); if (group.isEmpty()) { removeGroup(group); } updateUI(); } private void clearGroups() { for (final FavoritesGroup group : topNodeId2group.values()) { group.removeAllItems(); } topNodeId2group.clear(); panel.removeAll(); } public boolean isEmpty() { return topNodeId2group.isEmpty(); } private final void updateUI() { final JComponent comp = getComponent(); panel.invalidate(); panel.repaint();
final boolean visible = !isEmpty(); final boolean visibleOld = comp.isVisible(); if (visible == visibleOld) { return; } comp.setVisible(visible); // // If this group just became visible if (visible) { updateParentSplitPaneDividerLocation(); } } private final void updateParentSplitPaneDividerLocation() { final JComponent comp = getComponent(); if (!comp.isVisible()) { return; // nothing to update } // Find parent split pane if any JSplitPane parentSplitPane = null; for (Component c = comp.getParent(); c != null; c = c.getParent()) { if (c instanceof JSplitPane) { parentSplitPane = (JSplitPane)c; break; } } // Update it's divider location. // NOTE: if we would not do this, user would have to manually drag it when the first component is added. if (parentSplitPane != null) { if (parentSplitPane.getDividerLocation() <= 0) { parentSplitPane.setDividerLocation(Ini.getDividerLocation()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\FavoritesGroupContainer.java
1
请完成以下Java代码
public final class OAuth2TokenIntrospectionClaimNames { /** * {@code active} - Indicator whether or not the token is currently active */ public static final String ACTIVE = "active"; /** * {@code username} - A human-readable identifier for the resource owner that * authorized the token */ public static final String USERNAME = "username"; /** * {@code client_id} - The Client identifier for the token */ public static final String CLIENT_ID = "client_id"; /** * {@code scope} - The scopes for the token */ public static final String SCOPE = "scope"; /** * {@code token_type} - The type of the token, for example {@code bearer}. */ public static final String TOKEN_TYPE = "token_type"; /** * {@code exp} - A timestamp indicating when the token expires */ public static final String EXP = "exp"; /** * {@code iat} - A timestamp indicating when the token was issued */ public static final String IAT = "iat"; /** * {@code nbf} - A timestamp indicating when the token is not to be used before */
public static final String NBF = "nbf"; /** * {@code sub} - Usually a machine-readable identifier of the resource owner who * authorized the token */ public static final String SUB = "sub"; /** * {@code aud} - The intended audience for the token */ public static final String AUD = "aud"; /** * {@code iss} - The issuer of the token */ public static final String ISS = "iss"; /** * {@code jti} - The identifier for the token */ public static final String JTI = "jti"; private OAuth2TokenIntrospectionClaimNames() { } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2TokenIntrospectionClaimNames.java
1
请完成以下Java代码
public class HttpExchangesEndpoint { private final HttpExchangeRepository repository; /** * Create a new {@link HttpExchangesEndpoint} instance. * @param repository the exchange repository */ public HttpExchangesEndpoint(HttpExchangeRepository repository) { Assert.notNull(repository, "'repository' must not be null"); this.repository = repository; } @ReadOperation public HttpExchangesDescriptor httpExchanges() { return new HttpExchangesDescriptor(this.repository.findAll()); }
/** * Description of an application's {@link HttpExchange} entries. */ public static final class HttpExchangesDescriptor implements OperationResponseBody { private final List<HttpExchange> exchanges; private HttpExchangesDescriptor(List<HttpExchange> exchanges) { this.exchanges = exchanges; } public List<HttpExchange> getExchanges() { return this.exchanges; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\web\exchanges\HttpExchangesEndpoint.java
1
请完成以下Java代码
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.requestMatcher.matches(request)) { filterChain.doFilter(request, response); return; } GenerateOneTimeTokenRequest generateRequest = this.requestResolver.resolve(request); if (generateRequest == null) { filterChain.doFilter(request, response); return; } OneTimeToken ott = this.tokenService.generate(generateRequest); this.tokenGenerationSuccessHandler.handle(request, response, ott); } /** * Use the given {@link RequestMatcher} to match the request. * @param requestMatcher */ public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } /** * Use the given {@link GenerateOneTimeTokenRequestResolver} to resolve * {@link GenerateOneTimeTokenRequest}. * @param requestResolver {@link GenerateOneTimeTokenRequestResolver} * @since 6.5 */ public void setRequestResolver(GenerateOneTimeTokenRequestResolver requestResolver) { Assert.notNull(requestResolver, "requestResolver cannot be null"); this.requestResolver = requestResolver; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\ott\GenerateOneTimeTokenFilter.java
1
请完成以下Java代码
public String getSitedomain() { return sitedomain; } public void setSitedomain(String sitedomain) { this.sitedomain = sitedomain; } public String getSitetype() { return sitetype; } public void setSitetype(String sitetype) { this.sitetype = sitetype; } public String getCdate() { return cdate; } public void setCdate(String cdate) { this.cdate = cdate; } public String getComtype() { return comtype; } public void setComtype(String comtype) { this.comtype = comtype; } public String getComname() { return comname; } public void setComname(String comname) { this.comname = comname; } public String getComaddress() { return comaddress;
} public void setComaddress(String comaddress) { this.comaddress = comaddress; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "DomainDetail{" + "id='" + id + '\'' + ", sitename='" + sitename + '\'' + ", sitedomain='" + sitedomain + '\'' + ", sitetype='" + sitetype + '\'' + ", cdate='" + cdate + '\'' + ", comtype='" + comtype + '\'' + ", comname='" + comname + '\'' + ", comaddress='" + comaddress + '\'' + ", updateTime='" + updateTime + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-feign\src\main\java\com\quick\feign\entity\DomainDetail.java
1
请完成以下Java代码
public HistoricExternalTaskLogQuery orderByTenantId() { orderBy(HistoricExternalTaskLogQueryProperty.TENANT_ID); return this; } // results ////////////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsCountByQueryCriteria(this); } @Override public List<HistoricExternalTaskLog> executeList(CommandContext commandContext, Page page) { checkQueryOk();
return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsByQueryCriteria(this, page); } // getters & setters //////////////////////////////////////////////////////////// protected void setState(ExternalTaskState state) { this.state = state; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricExternalTaskLogQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PPOrderQtyId implements RepoIdAware { @JsonCreator public static PPOrderQtyId ofRepoId(final int repoId) { return new PPOrderQtyId(repoId); } @Nullable public static PPOrderQtyId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PPOrderQtyId(repoId) : null; } public static Optional<PPOrderQtyId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final PPOrderQtyId id) { return id != null ? id.getRepoId() : -1;
} int repoId; private PPOrderQtyId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Qty_ID"); } @JsonValue public int toJson() { return getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\PPOrderQtyId.java
2
请在Spring Boot框架中完成以下Java代码
public static class RouterFunctionHolder { private final RouterFunction<ServerResponse> routerFunction; public RouterFunctionHolder(RouterFunction<ServerResponse> routerFunction) { this.routerFunction = routerFunction; } public RouterFunction<ServerResponse> getRouterFunction() { return this.routerFunction; } } /** * Delegating RouterFunction impl that delegates to the refreshable * RouterFunctionHolder. */ static class DelegatingRouterFunction implements RouterFunction<ServerResponse> { final RouterFunctionHolder provider; DelegatingRouterFunction(RouterFunctionHolder provider) { this.provider = provider; } @Override public RouterFunction<ServerResponse> and(RouterFunction<ServerResponse> other) { return this.provider.getRouterFunction().and(other); } @Override public RouterFunction<?> andOther(RouterFunction<?> other) { return this.provider.getRouterFunction().andOther(other); } @Override public RouterFunction<ServerResponse> andRoute(RequestPredicate predicate, HandlerFunction<ServerResponse> handlerFunction) { return this.provider.getRouterFunction().andRoute(predicate, handlerFunction); } @Override public RouterFunction<ServerResponse> andNest(RequestPredicate predicate, RouterFunction<ServerResponse> routerFunction) { return this.provider.getRouterFunction().andNest(predicate, routerFunction); }
@Override public <S extends ServerResponse> RouterFunction<S> filter( HandlerFilterFunction<ServerResponse, S> filterFunction) { return this.provider.getRouterFunction().filter(filterFunction); } @Override public void accept(RouterFunctions.Visitor visitor) { this.provider.getRouterFunction().accept(visitor); } @Override public RouterFunction<ServerResponse> withAttribute(String name, Object value) { return this.provider.getRouterFunction().withAttribute(name, value); } @Override public RouterFunction<ServerResponse> withAttributes(Consumer<Map<String, Object>> attributesConsumer) { return this.provider.getRouterFunction().withAttributes(attributesConsumer); } @Override public Optional<HandlerFunction<ServerResponse>> route(ServerRequest request) { return this.provider.getRouterFunction().route(request); } @Override public String toString() { return this.provider.getRouterFunction().toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcPropertiesBeanDefinitionRegistrar.java
2
请完成以下Java代码
public static Collector<Candidate, ?, CandidatesGroup> collect() {return GuavaCollectors.collectUsingListAccumulator(CandidatesGroup::ofList);} public void assertNotEmpty() { if (list.isEmpty()) { throw new AdempiereException("candidates list shall not be empty"); } } public boolean isEmpty() {return list.isEmpty();} @Override @NonNull public Iterator<Candidate> iterator() {return list.iterator();} @Override public void forEach(@NonNull final Consumer<? super Candidate> action) {list.forEach(action);} public ClientAndOrgId getClientAndOrgId() { assertNotEmpty(); return list.get(0).getClientAndOrgId(); } public MaterialDispoGroupId getEffectiveGroupId() { assertNotEmpty();
return list.get(0).getEffectiveGroupId(); } public CandidateBusinessCase getBusinessCase() { assertNotEmpty(); return CollectionUtils.extractSingleElement(list, Candidate::getBusinessCase); } public Candidate getSingleCandidate() { return CollectionUtils.singleElement(list); } public Candidate getSingleSupplyCandidate() { return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.SUPPLY)); } public Candidate getSingleDemandCandidate() { return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.DEMAND)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidatesGroup.java
1
请完成以下Spring Boot application配置
server: port: 8080 # for example purposes of Camel version 2.18 and below baeldung: api: path: '/camel' camel: springboot: # The Camel context name name: ServicesRest # Binding health checks to a different port management: port: 8081 # disable all management enpoints except health endpoints: enabled:
false health: enabled: true # The application configuration properties quickstart: generateOrderPeriod: 10s processOrderPeriod: 30s
repos\tutorials-master\messaging-modules\spring-apache-camel\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class Application { public static void main(String[] args) { System.setProperty("LOG_PATH", "./logs"); System.setProperty("LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE", "1KB"); SpringApplication.run(Application.class); } private static final org.apache.commons.logging.Log logger1 = org.apache.commons.logging .LogFactory .getLog(Application.class); private static final org.slf4j.Logger logger2 = org.slf4j.LoggerFactory .getLogger(Application.class); @Bean public CommandLineRunner commandLineRunner() {
return (args) -> { logger1.error("commons logging error..."); logger1.warn("commons logging warn"); logger1.info("commons logging info..."); logger1.debug("commons logging debug..."); logger2.error("slf4j error..."); logger2.warn("commons logging warn"); logger2.info("slf4j info..."); logger2.debug("slf4j debug..."); logger2.info("CONSOLE_LOG_STRUCTURED_FORMAT:{}", System.getProperty("CONSOLE_LOG_STRUCTURED_FORMAT")); logger2.info("CONSOLE_LOG_CHARSET:{}", System.getProperty("CONSOLE_LOG_CHARSET")); }; } }
repos\spring-boot-best-practice-master\spring-boot-logging\src\main\java\cn\javastack\springboot\logging\Application.java
2
请完成以下Java代码
public String getParentCaseInstanceId() { return parentCaseInstanceId; } public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null; } public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public boolean isWithJobException() { return withJobException; } public String getLocale() { return locale;
} public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(ProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public static final void assertMatching(final PricingConditionsId id, PricingConditionsBreakId breakId) { if (!matching(id, breakId)) { throw new AdempiereException("" + id + " and " + breakId + " are not matching") .setParameter("pricingConditionsId", id) .setParameter("pricingConditionsBreakId", breakId); } } private final PricingConditionsId pricingConditionsId; private final int discountSchemaBreakId; private PricingConditionsBreakId(@NonNull final PricingConditionsId pricingConditionsId, final int discountSchemaBreakId) {
Check.assumeGreaterThanZero(discountSchemaBreakId, "discountSchemaBreakId"); this.pricingConditionsId = pricingConditionsId; this.discountSchemaBreakId = discountSchemaBreakId; } public boolean matchingDiscountSchemaId(final int discountSchemaId) { return pricingConditionsId.getRepoId() == discountSchemaId; } public int getDiscountSchemaId() { return pricingConditionsId.getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakId.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_C_AcctSchema getC_AcctSchema() { return get_ValueAsPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class); } @Override public void setC_AcctSchema(final org.compiere.model.I_C_AcctSchema C_AcctSchema) { set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema); } @Override public void setC_AcctSchema_ID (final int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID); } @Override public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public org.compiere.model.I_C_ValidCombination getPJ_Asset_A() { return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A) { set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A); }
@Override public void setPJ_Asset_Acct (final int PJ_Asset_Acct) { set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct); } @Override public int getPJ_Asset_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct); } @Override public org.compiere.model.I_C_ValidCombination getPJ_WIP_A() { return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A) { set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A); } @Override public void setPJ_WIP_Acct (final int PJ_WIP_Acct) { set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct); } @Override public int getPJ_WIP_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java
1
请完成以下Java代码
public static PurchaseCandidateId ofRepoId(final int repoId) { return new PurchaseCandidateId(repoId); } public static PurchaseCandidateId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PurchaseCandidateId(repoId) : null; } public static Set<PurchaseCandidateId> ofRepoIds(final Set<Integer> repoIds) { if (repoIds == null || repoIds.isEmpty()) { return ImmutableSet.of(); } return repoIds.stream().map(PurchaseCandidateId::ofRepoId).collect(ImmutableSet.toImmutableSet()); } public static int getRepoIdOr(final PurchaseCandidateId id, final int defaultValue) { return id != null ? id.getRepoId() : defaultValue; } public static Set<Integer> toIntSet(final Collection<PurchaseCandidateId> purchaseCandidateIds) { if (purchaseCandidateIds == null || purchaseCandidateIds.isEmpty()) {
return ImmutableSet.of(); } else { return purchaseCandidateIds.stream().map(PurchaseCandidateId::getRepoId).collect(ImmutableSet.toImmutableSet()); } } int repoId; private PurchaseCandidateId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidateId.java
1
请完成以下Java代码
public basefont setFace(String face) { addAttribute("face",face); return(this); } /** sets the color="" attribute. @param color sets the color="" attribute. Convience colors are defined in the HtmlColors interface. */ public basefont setColor(String color) { addAttribute("color",HtmlColor.convertColor(color)); return(this); } /** sets the size="" attribute. @param size sets the size="" attribute. */ public basefont setSize(int size) { addAttribute("size",Integer.toString(size)); return(this); } /** sets the size="" attribute. @param size sets the size="" attribute. */ public basefont setSize(String size) { addAttribute("size",size); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); 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 basefont 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 basefont addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public basefont addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public basefont addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public basefont removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\basefont.java
1
请在Spring Boot框架中完成以下Java代码
public boolean hashHasKey(String key, String item) { return hashOperations.hasKey(key, item); } //============================set============================= public Set<Object> setMembers(String key) { return setOperations.members(key); } public boolean setIsMember(String key, Object value) { return setOperations.isMember(key, value); } public long setAdd(String key, Object... values) { return setOperations.add(key, values); } public long setAdd(String key, long milliseconds, Object... values) { Long count = setOperations.add(key, values); if (milliseconds > 0) { expire(key, milliseconds); } return count; } public long setSize(String key) { return setOperations.size(key); } public long setRemove(String key, Object... values) { return setOperations.remove(key, values); } //===============================list================================= public List<Object> lGet(String key, long start, long end) { return listOperations.range(key, start, end); } public long listSize(String key) { return listOperations.size(key); } public Object listIndex(String key, long index) { return listOperations.index(key, index); } public void listRightPush(String key, Object value) { listOperations.rightPush(key, value);
} public boolean listRightPush(String key, Object value, long milliseconds) { listOperations.rightPush(key, value); if (milliseconds > 0) { return expire(key, milliseconds); } return false; } public long listRightPushAll(String key, List<Object> value) { return listOperations.rightPushAll(key, value); } public boolean listRightPushAll(String key, List<Object> value, long milliseconds) { listOperations.rightPushAll(key, value); if (milliseconds > 0) { return expire(key, milliseconds); } return false; } public void listSet(String key, long index, Object value) { listOperations.set(key, index, value); } public long listRemove(String key, long count, Object value) { return listOperations.remove(key, count, value); } //===============================zset================================= public boolean zsAdd(String key, Object value, double score) { return zSetOperations.add(key, value, score); } }
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java
2
请完成以下Java代码
protected void init(final FindPanelBuilder builder) { findPanel.setVisible(expanded); findPanel.setEnabled(expanded); } @Override public final JComponent getComponent() { return findPanel; } @Override public boolean isExpanded() { return expanded; } @Override public void setExpanded(final boolean expanded) { if (this.expanded == expanded) { return; } this.expanded = expanded; findPanel.setVisible(expanded); findPanel.setEnabled(expanded); _pcs.firePropertyChange(PROPERTY_Expanded, !expanded, expanded); } @Override public boolean isFocusable() { return findPanel.isFocusable(); } @Override public void requestFocus() { findPanel.requestFocus(); } @Override public boolean requestFocusInWindow() { return findPanel.requestFocusInWindow(); }
private final synchronized PropertyChangeSupport getPropertyChangeSupport() { if (_pcs == null) { _pcs = new PropertyChangeSupport(this); } return _pcs; } @Override public void runOnExpandedStateChange(final Runnable runnable) { Check.assumeNotNull(runnable, "runnable not null"); getPropertyChangeSupport().addPropertyChangeListener(PROPERTY_Expanded, new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { runnable.run(); } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_EmbeddedPanel.java
1
请完成以下Java代码
public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; }
public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", icon=").append(icon); sb.append(", email=").append(email); sb.append(", nickName=").append(nickName); sb.append(", note=").append(note); sb.append(", createTime=").append(createTime); sb.append(", loginTime=").append(loginTime); sb.append(", status=").append(status); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java
1
请完成以下Java代码
private final PT getParentModel() { final PT parentModel = parentModelRef.get(); if (parentModel == null) { throw new IllegalStateException("Model list cache expired for good"); } return parentModel; } /** * Creates a {@link PlainContextAware} from given <code>model</code>. * * @param model * @return */ private static final PlainContextAware createPlainContextAware(final Object model) { final IContextAware contextAware = InterfaceWrapperHelper.getContextAware(model); final PlainContextAware contextAwarePlainCopy = PlainContextAware.newCopy(contextAware); return contextAwarePlainCopy; } /** * Load items from database. */ private final void loadItems() { final PT parentModel = getParentModel(); final IContextAware ctx = createPlainContextAware(parentModel); // // Retrieve fresh items final List<T> items = retrieveItems(ctx, parentModel); // // Update status this.ctx = ctx; this.items = items == null ? null : new ArrayList<T>(items); // NOTE: we need to do a copy just in case we get an unmodifiable list this.parentModelLoadCount = InterfaceWrapperHelper.getLoadCount(parentModel); this.debugEmptyNotStaledSet = false; } /** * Sets an empty inner list and flag this list as not staled anymore. * * To be used after parent model is created, to start maintaining this list from the very beginning. */ public final void setEmptyNotStaled() { final PT parentModel = getParentModel();
this.ctx = createPlainContextAware(parentModel); this.items = new ArrayList<T>(); this.debugEmptyNotStaledSet = true; debugCheckItemsValid(); } private final void debugCheckItemsValid() { if (!DEBUG) { return; } final PT parentModel = getParentModel(); final IContextAware ctx = createPlainContextAware(parentModel); final boolean instancesTrackerEnabled = POJOLookupMapInstancesTracker.ENABLED; POJOLookupMapInstancesTracker.ENABLED = false; try { // // Retrieve fresh items final List<T> itemsRetrievedNow = retrieveItems(ctx, parentModel); if (itemsComparator != null) { Collections.sort(itemsRetrievedNow, itemsComparator); } if (!Objects.equals(this.items, itemsRetrievedNow)) { final int itemsCount = this.items == null ? 0 : this.items.size(); final int itemsRetrievedNowCount = itemsRetrievedNow.size(); throw new AdempiereException("Loaded items and cached items does not match." + "\n Parent: " + parentModelRef.get() + "\n Cached items(" + itemsCount + "): " + this.items + "\n Fresh items(" + itemsRetrievedNowCount + "): " + itemsRetrievedNow + "\n debugEmptyNotStaledSet=" + debugEmptyNotStaledSet // ); } } finally { POJOLookupMapInstancesTracker.ENABLED = instancesTrackerEnabled; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\cache\AbstractModelListCacheLocal.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this).addValue(gridTab).toString(); } @Override public AdWindowId getAdWindowId() { return gridTab.getAdWindowId(); } @Override public AdTabId getAdTabId() { return AdTabId.ofRepoId(gridTab.getAD_Tab_ID()); } @Override public String getTableName() { return gridTab.getTableName(); } @Override public <T> T getSelectedModel(final Class<T> modelClass) { return gridTab.getModel(modelClass); } @Override public <T> List<T> getSelectedModels(final Class<T> modelClass) {
// backward compatibility return streamSelectedModels(modelClass) .collect(ImmutableList.toImmutableList()); } @NonNull @Override public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass) { return Stream.of(getSelectedModel(modelClass)); } @Override public int getSingleSelectedRecordId() { return gridTab.getRecord_ID(); } @Override public SelectionSize getSelectionSize() { // backward compatibility return SelectionSize.ofSize(1); } @Override public <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass) { return gridTab.createCurrentRecordsQueryFilter(recordClass); } } } // GridTab
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTab.java
1
请完成以下Java代码
public void setM_Promotion_ID (int M_Promotion_ID) { if (M_Promotion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID)); } /** Get Promotion. @return Promotion */ public int getM_Promotion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_PromotionLine getM_PromotionLine() throws RuntimeException { return (I_M_PromotionLine)MTable.get(getCtx(), I_M_PromotionLine.Table_Name) .getPO(getM_PromotionLine_ID(), get_TrxName()); } /** Set Promotion Line. @param M_PromotionLine_ID Promotion Line */ public void setM_PromotionLine_ID (int M_PromotionLine_ID) { if (M_PromotionLine_ID < 1) set_Value (COLUMNNAME_M_PromotionLine_ID, null); else set_Value (COLUMNNAME_M_PromotionLine_ID, Integer.valueOf(M_PromotionLine_ID)); } /** Get Promotion Line. @return Promotion Line */ public int getM_PromotionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Operation AD_Reference_ID=53294 */ public static final int OPERATION_AD_Reference_ID=53294; /** >= = >= */ public static final String OPERATION_GtEq = ">="; /** <= = <= */ public static final String OPERATION_LeEq = "<="; /** Set Operation. @param Operation Compare Operation */ public void setOperation (String Operation) { set_Value (COLUMNNAME_Operation, Operation);
} /** Get Operation. @return Compare Operation */ public String getOperation () { return (String)get_Value(COLUMNNAME_Operation); } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** 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(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionDistribution.java
1
请完成以下Java代码
class MessageExpressionConfigAttribute implements ConfigAttribute, EvaluationContextPostProcessor<Message<?>> { private final Expression authorizeExpression; private final MessageMatcher<Object> matcher; /** * Creates a new instance * @param authorizeExpression the {@link Expression} to use. Cannot be null * @param matcher the {@link MessageMatcher} used to match the messages. */ MessageExpressionConfigAttribute(Expression authorizeExpression, MessageMatcher<?> matcher) { Assert.notNull(authorizeExpression, "authorizeExpression cannot be null"); Assert.notNull(matcher, "matcher cannot be null"); this.authorizeExpression = authorizeExpression; this.matcher = (MessageMatcher<Object>) matcher; } Expression getAuthorizeExpression() { return this.authorizeExpression; }
@Override public @Nullable String getAttribute() { return null; } @Override public String toString() { return this.authorizeExpression.getExpressionString(); } @Override public EvaluationContext postProcess(EvaluationContext ctx, Message<?> message) { Map<String, String> variables = this.matcher.matcher(message).getVariables(); for (Map.Entry<String, String> entry : variables.entrySet()) { ctx.setVariable(entry.getKey(), entry.getValue()); } return ctx; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\messaging\access\expression\MessageExpressionConfigAttribute.java
1
请完成以下Java代码
public String getClientId() { return this.clientId; } /** * Returns the state. * @return the state */ public String getState() { return this.state; } /** * Returns the requested (or authorized) scope(s). * @return the requested (or authorized) scope(s), or an empty {@code Set} if not
* available */ public Set<String> getScopes() { return this.scopes; } /** * Returns the additional parameters. * @return the additional parameters, or an empty {@code Map} if not available */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationConsentAuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
public JobLauncher getJobLauncher() throws Exception { TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); // TaskExecutorJobLauncher's methods Throws Generic Exception, // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; } @Bean public Step firstStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("firstStep", jobRepository) .<String, String>chunk(1, transactionManager) .reader(new IteratorItemReader<>(Stream.of("Data from Step 1").iterator())) .processor(item -> { System.out.println("Processing: " + item); return item; }) .writer(items -> items.forEach(System.out::println)) .build(); } @Bean public Step secondStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("secondStep", jobRepository) .<String, String>chunk(1, transactionManager) .reader(new IteratorItemReader<>(Stream.of("Data from Step 2").iterator())) .processor(item -> { System.out.println("Processing: " + item); return item;
}) .writer(items -> items.forEach(System.out::println)) .build(); } @Bean(name = "parentJob") public Job parentJob(JobRepository jobRepository, @Qualifier("firstStep") Step firstStep, @Qualifier("secondStep") Step secondStep) { return new JobBuilder("parentJob", jobRepository) .start(firstStep) .next(secondStep) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\SpringBatchConfig.java
2
请完成以下Java代码
public class News { private Integer id; private String title; private String content; private String imagePath; private Integer readSum; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; }
public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public Integer getReadSum() { return readSum; } public void setReadSum(Integer readSum) { this.readSum = readSum; } }
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\bean\News.java
1
请完成以下Java代码
public class Post { private String message; private Instant date; public Post(String message) { this.message = message; this.date = Instant.now().minus(new Random().nextLong(100), ChronoUnit.MINUTES); } public String getMessage() { return message; } public void setMessage(String message) {
this.message = message; } public Instant getDate() { return date; } public void setDate(Instant date) { this.date = date; } @Override public String toString() { return message; } }
repos\spring-data-examples-main\mongodb\aot-optimization\src\main\java\example\springdata\aot\Post.java
1
请完成以下Java代码
public void setDLM_Partition_ID(final int DLM_Partition_ID) { if (DLM_Partition_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, Integer.valueOf(DLM_Partition_ID)); } } /** * Get Partition. * * @return Partition */ @Override public int getDLM_Partition_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Partition is vollständig. * * @param IsPartitionComplete * Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann. */ @Override public void setIsPartitionComplete(final boolean IsPartitionComplete) { set_Value(COLUMNNAME_IsPartitionComplete, Boolean.valueOf(IsPartitionComplete)); } /** * Get Partition is vollständig. * * @return Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann. */ @Override public boolean isPartitionComplete() { final Object oo = get_Value(COLUMNNAME_IsPartitionComplete); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** * Set Anz. zugeordneter Datensätze. * * @param PartitionSize Anz. zugeordneter Datensätze */ @Override public void setPartitionSize(final int PartitionSize) { set_Value(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize)); } /**
* Get Anz. zugeordneter Datensätze. * * @return Anz. zugeordneter Datensätze */ @Override public int getPartitionSize() { final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Ziel-DLM-Level. * * @param Target_DLM_Level Ziel-DLM-Level */ @Override public void setTarget_DLM_Level(final int Target_DLM_Level) { set_Value(COLUMNNAME_Target_DLM_Level, Integer.valueOf(Target_DLM_Level)); } /** * Get Ziel-DLM-Level. * * @return Ziel-DLM-Level */ @Override public int getTarget_DLM_Level() { final Integer ii = (Integer)get_Value(COLUMNNAME_Target_DLM_Level); if (ii == null) { return 0; } return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition.java
1
请在Spring Boot框架中完成以下Java代码
public class ManufacturingOrderRestController { private final ManufacturingOrderAPIService manufacturingOrderAPIService; public ManufacturingOrderRestController( @NonNull final ManufacturingOrderAPIService manufacturingOrderAPIService) { this.manufacturingOrderAPIService = manufacturingOrderAPIService; } @GetMapping public ResponseEntity<JsonResponseManufacturingOrdersBulk> exportOrders( @Parameter(description = "Max number of items to be returned in one request.") // @RequestParam(name = "limit", required = false, defaultValue = "500") // @Nullable final Integer limit) { final Instant canBeExportedFrom = SystemTime.asInstant(); final QueryLimit limitEffective = QueryLimit.ofNullableOrNoLimit(limit).ifNoLimitUse(500); final String adLanguage = Env.getADLanguageOrBaseLanguage(); final JsonResponseManufacturingOrdersBulk result = manufacturingOrderAPIService.exportOrders( canBeExportedFrom, limitEffective, adLanguage); return ResponseEntity.ok(result); }
@PostMapping("/exportStatus") public ResponseEntity<String> setExportStatus(@RequestBody @NonNull final JsonRequestSetOrdersExportStatusBulk request) { try (final MDC.MDCCloseable ignore = MDC.putCloseable("TransactionIdAPI", request.getTransactionKey())) { manufacturingOrderAPIService.setExportStatus(request); return ResponseEntity.accepted().body("Manufacturing orders updated"); } } @PostMapping("/report") public ResponseEntity<JsonResponseManufacturingOrdersReport> report(@RequestBody @NonNull final JsonRequestManufacturingOrdersReport request) { final JsonResponseManufacturingOrdersReport response = manufacturingOrderAPIService.report(request); return response.isOK() ? ResponseEntity.ok(response) : ResponseEntity.unprocessableEntity().body(response); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrderRestController.java
2
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataInput.class, BPMN_ELEMENT_DATA_INPUT) .namespaceUri(BPMN20_NS) .extendsType(ItemAwareElement.class) .instanceProvider(new ModelTypeInstanceProvider<DataInput>() { public DataInput newInstance(ModelTypeInstanceContext instanceContext) { return new DataInputImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); isCollectionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_COLLECTION) .defaultValue(false) .build(); typeBuilder.build(); } public DataInputImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); }
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public boolean isCollection() { return isCollectionAttribute.getValue(this); } public void setCollection(boolean isCollection) { isCollectionAttribute.setValue(this, isCollection); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataInputImpl.java
1