instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class TbJsonPathNode implements TbNode { private Configuration configurationJsonPath; private JsonPath jsonPath; private String jsonPathValue; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbJsonPathNodeConfiguration.class); jsonPathValue = config.getJsonPath(); if (!TbJsonPathNodeConfiguration.DEFAULT_JSON_PATH.equals(jsonPathValue)) { configurationJsonPath = Configuration.builder() .jsonProvider(new JacksonJsonNodeJsonProvider()) .build(); jsonPath = JsonPath.compile(config.getJsonPath()); } } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
if (!TbJsonPathNodeConfiguration.DEFAULT_JSON_PATH.equals(jsonPathValue)) { try { Object jsonPathData = jsonPath.read(msg.getData(), configurationJsonPath); ctx.tellSuccess(msg.transform() .data(JacksonUtil.toString(jsonPathData)) .build()); } catch (PathNotFoundException e) { ctx.tellFailure(msg, e); } } else { ctx.tellSuccess(msg); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\transform\TbJsonPathNode.java
1
请在Spring Boot框架中完成以下Java代码
public static class DeleteResult { @NonNull CandidateId candidateId; @NonNull DateAndSeqNo previousTime; @NonNull BigDecimal previousQty; } public BigDecimal getCurrentAtpAndUpdateQtyDetails(@NonNull final Candidate candidate, @NonNull final Candidate stockCandidate, @Nullable final Candidate previousStockCandidate) { final Candidate actualPreviousStockCandidate = CoalesceUtil.coalesceSuppliers(() -> previousStockCandidate, () -> getPreviousStockCandidateOrNull(stockCandidate)); final BigDecimal previousQty = actualPreviousStockCandidate == null ? BigDecimal.ZERO : actualPreviousStockCandidate.getQuantity(); final CandidateId actualPreviousStockCandidateId = actualPreviousStockCandidate == null ? null : actualPreviousStockCandidate.getId(); final CandidateId currentCandidateId = candidate.getId(); final CandidateQtyDetailsPersistMultiRequest request = CandidateQtyDetailsPersistMultiRequest.builder() .candidateId(currentCandidateId) .stockCandidateId(stockCandidate.getId()) .details(ImmutableList.of(CandidateQtyDetailsPersistRequest.builder() .detailCandidateId(actualPreviousStockCandidateId) .qtyInStockUom(previousQty) .build(), CandidateQtyDetailsPersistRequest.builder() .detailCandidateId(currentCandidateId) .qtyInStockUom(candidate.getStockImpactPlannedQuantity()) .build() )) .build(); candidateQtyDetailsRepository.save(request); return candidate.getStockImpactPlannedQuantity().add(previousQty); } @Nullable private Candidate getPreviousStockCandidateOrNull(final @NonNull Candidate stockCandidate) {
final MaterialDescriptor materialDescriptor = stockCandidate.getMaterialDescriptor(); final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.builder() .warehouseId(materialDescriptor.getWarehouseId()) .productId(materialDescriptor.getProductId()) .storageAttributesKey(materialDescriptor.getStorageAttributesKey()) .customer(BPartnerClassifier.specificOrAny(materialDescriptor.getCustomerId())) .customerIdOperator(MaterialDescriptorQuery.CustomerIdOperator.GIVEN_ID_ONLY) .timeRangeEnd(DateAndSeqNo.atTimeNoSeqNo(stockCandidate.getMaterialDescriptor().getDate()) .withOperator(DateAndSeqNo.Operator.EXCLUSIVE)) .build(); final CandidatesQuery findPreviousStockQuery = CandidatesQuery.builder() .materialDescriptorQuery(materialDescriptorQuery) .type(CandidateType.STOCK) .matchExactStorageAttributesKey(true) .build(); return candidateRepositoryRetrieval.retrievePreviousMatchForCandidateIdOrNull(findPreviousStockQuery, stockCandidate.getId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateRepositoryWriteService.java
2
请完成以下Java代码
protected String getTargetTableName() { return I_C_Payment.Table_Name; } @Override protected void updateAndValidateImportRecordsImpl() { final ImportRecordsSelection selection = getImportRecordsSelection(); CPaymentImportTableSqlUpdater.updatePaymentImportTable(selection); } @Override protected String getImportOrderBySql() { return I_I_Datev_Payment.COLUMNNAME_C_BPartner_ID; } @Override public I_I_Datev_Payment retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { return new X_I_Datev_Payment(ctx, rs, ITrx.TRXNAME_ThreadInherited); } @Override protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state, @NonNull final I_I_Datev_Payment importRecord, final boolean isInsertOnly) throws Exception { return importDatevPayment(importRecord, isInsertOnly); } private ImportRecordResult importDatevPayment(@NonNull final I_I_Datev_Payment importRecord, final boolean isInsertOnly) { final ImportRecordResult schemaImportResult; final boolean paymentExists = importRecord.getC_Payment_ID() > 0; if (paymentExists && isInsertOnly) { // do not update return ImportRecordResult.Nothing; } final I_C_Payment payment; if (!paymentExists) { payment = createNewPayment(importRecord); schemaImportResult = ImportRecordResult.Inserted; } else { payment = importRecord.getC_Payment(); schemaImportResult = ImportRecordResult.Updated; } ModelValidationEngine.get().fireImportValidate(this, importRecord, payment, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(payment);
importRecord.setC_Payment_ID(payment.getC_Payment_ID()); InterfaceWrapperHelper.save(importRecord); return schemaImportResult; } private I_C_Payment createNewPayment(@NonNull final I_I_Datev_Payment importRecord) { final LocalDate date = TimeUtil.asLocalDate(importRecord.getDateTrx()); final IPaymentBL paymentsService = Services.get(IPaymentBL.class); return paymentsService.newBuilderOfInvoice(importRecord.getC_Invoice()) //.receipt(importRecord.isReceipt()) .adOrgId(OrgId.ofRepoId(importRecord.getAD_Org_ID())) .bpartnerId(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID())) .payAmt(importRecord.getPayAmt()) .discountAmt(importRecord.getDiscountAmt()) .tenderType(TenderType.DirectDeposit) .dateAcct(date) .dateTrx(date) .description("Import for debitorId/creditorId" + importRecord.getBPartnerValue()) .createAndProcess(); } @Override protected void markImported(@NonNull final I_I_Datev_Payment importRecord) { importRecord.setI_IsImported(X_I_Datev_Payment.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impexp\DatevPaymentImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentService { private static final int BATCH_SIZE = 5; private final StudentRepository repository; private final EmailService emailService; private final EntityManager entityManager; public StudentService(StudentRepository repository, EmailService emailService, EntityManager entityManager) { this.repository = repository; this.emailService = emailService; this.entityManager = entityManager; } public void processStudentsByFirstName(String firstName) { Slice<Student> slice = repository.findAllByFirstName(firstName, PageRequest.of(0, BATCH_SIZE)); List<Student> studentsInBatch = slice.getContent(); studentsInBatch.forEach(emailService::sendEmailToStudent); while (slice.hasNext()) { slice = repository.findAllByFirstName(firstName, slice.nextPageable()); slice.getContent() .forEach(emailService::sendEmailToStudent); } } public void processStudentsByLastName(String lastName) { Page<Student> page = repository.findAllByLastName(lastName, PageRequest.of(0, BATCH_SIZE));
page.getContent() .forEach(emailService::sendEmailToStudent); while (page.hasNext()) { page = repository.findAllByLastName(lastName, page.nextPageable()); page.getContent() .forEach(emailService::sendEmailToStudent); } } @Transactional(readOnly = true) public void processStudentsByFirstNameUsingStreams(String firstName) { try (Stream<Student> students = repository.findAllByFirstName(firstName)) { students.peek(entityManager::detach) .forEach(emailService::sendEmailToStudent); } } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-3\src\main\java\com\baeldung\largeresultset\service\StudentService.java
2
请完成以下Java代码
public class BusinessRuleTaskJsonConverter extends BaseBpmnJsonConverter { public static void fillTypes( Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { fillJsonTypes(convertersToBpmnMap); fillBpmnTypes(convertersToJsonMap); } public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_TASK_BUSINESS_RULE, BusinessRuleTaskJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { convertersToJsonMap.put(BusinessRuleTask.class, BusinessRuleTaskJsonConverter.class); } protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_BUSINESS_RULE; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { BusinessRuleTask ruleTask = (BusinessRuleTask) baseElement; propertiesNode.put(PROPERTY_RULETASK_CLASS, ruleTask.getClassName()); propertiesNode.put( PROPERTY_RULETASK_VARIABLES_INPUT, convertListToCommaSeparatedString(ruleTask.getInputVariables()) );
propertiesNode.put(PROPERTY_RULETASK_RESULT, ruleTask.getResultVariableName()); propertiesNode.put(PROPERTY_RULETASK_RULES, convertListToCommaSeparatedString(ruleTask.getRuleNames())); if (ruleTask.isExclude()) { propertiesNode.put(PROPERTY_RULETASK_EXCLUDE, PROPERTY_VALUE_YES); } } protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { BusinessRuleTask task = new BusinessRuleTask(); task.setClassName(getPropertyValueAsString(PROPERTY_RULETASK_CLASS, elementNode)); task.setInputVariables(getPropertyValueAsList(PROPERTY_RULETASK_VARIABLES_INPUT, elementNode)); task.setResultVariableName(getPropertyValueAsString(PROPERTY_RULETASK_RESULT, elementNode)); task.setRuleNames(getPropertyValueAsList(PROPERTY_RULETASK_RULES, elementNode)); task.setExclude(getPropertyValueAsBoolean(PROPERTY_RULETASK_EXCLUDE, elementNode)); return task; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BusinessRuleTaskJsonConverter.java
1
请完成以下Java代码
public void onFailure(Throwable t) { if (onFailure == null) { return; } onFailure.accept(t); } }; if (executor != null) { Futures.addCallback(future, callback, executor); } else { Futures.addCallback(future, callback, MoreExecutors.directExecutor()); } } public static <T> ListenableFuture<T> submit(Callable<T> task, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor) { return submit(task, onSuccess, onFailure, executor, null); } public static <T> ListenableFuture<T> submit(Callable<T> task, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor, Executor callbackExecutor) { ListenableFuture<T> future = Futures.submit(task, executor);
withCallback(future, onSuccess, onFailure, callbackExecutor); return future; } public static <T> FluentFuture<T> toFluentFuture(CompletableFuture<T> completable) { SettableFuture<T> future = SettableFuture.create(); completable.whenComplete((result, exception) -> { if (exception != null) { future.setException(exception); } else { future.set(result); } }); return FluentFuture.from(future); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\DonAsynchron.java
1
请完成以下Java代码
public void setPicture(Picture picture) { if (picture != null) { savePicture(picture); } else { deletePicture(); } } protected void savePicture(Picture picture) { if (pictureByteArrayRef == null) { pictureByteArrayRef = new ByteArrayRef(); } pictureByteArrayRef.setValue(picture.getMimeType(), picture.getBytes()); } protected void deletePicture() { if (pictureByteArrayRef != null) { pictureByteArrayRef.delete(); } } @Override public String getFirstName() { return firstName; } @Override public void setFirstName(String firstName) { this.firstName = firstName; } @Override public String getLastName() { return lastName; } @Override public void setLastName(String lastName) { this.lastName = lastName; } @Override public String getDisplayName() { return displayName; } @Override public void setDisplayName(String displayName) { this.displayName = displayName; } @Override public String getEmail() { return email; } @Override public void setEmail(String email) { this.email = email; }
@Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public boolean isPictureSet() { return pictureByteArrayRef != null && pictureByteArrayRef.getId() != null; } @Override public ByteArrayRef getPictureByteArrayRef() { return pictureByteArrayRef; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class MyConfiguration { @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) public static class Fonts { private String letter; private int textSize; public String getLetter() { return letter; } public void setLetter(String letter) { this.letter = letter; } public int getTextSize() { return textSize; } public void setTextSize(int textSize) { this.textSize = textSize; } } public static class Background { private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; } } @JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) public static class RequestResult { private int requestCode; public int getRequestCode() { return requestCode; } public void setRequestCode(int requestCode) { this.requestCode = requestCode; } } @JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) public static class ResponseResult { private int resultCode; public int getResultCode() { return resultCode; }
public void setResultCode(int resultCode) { this.resultCode = resultCode; } } private Fonts fonts; private Background background; @JsonProperty("RequestResult") private RequestResult requestResult; @JsonProperty("ResponseResult") private ResponseResult responseResult; public Fonts getFonts() { return fonts; } public void setFonts(Fonts fonts) { this.fonts = fonts; } public Background getBackground() { return background; } public void setBackground(Background background) { this.background = background; } public RequestResult getRequestResult() { return requestResult; } public void setRequestResult(RequestResult requestResult) { this.requestResult = requestResult; } public ResponseResult getResponseResult() { return responseResult; } public void setResponseResult(ResponseResult responseResult) { this.responseResult = responseResult; } }
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\ini\MyConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public Shutdown getShutdown() { return this.shutdown; } public String getThreadNamePrefix() { return this.threadNamePrefix; } public void setThreadNamePrefix(String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; } public static class Pool { /** * Maximum allowed number of threads. Doesn't have an effect if virtual threads * are enabled. */ private int size = 1; public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } } public static class Simple { /** * Set the maximum number of parallel accesses allowed. -1 indicates no * concurrency limit at all. */ private @Nullable Integer concurrencyLimit; public @Nullable Integer getConcurrencyLimit() { return this.concurrencyLimit; } public void setConcurrencyLimit(@Nullable Integer concurrencyLimit) { this.concurrencyLimit = concurrencyLimit; } } public static class Shutdown { /** * Whether the executor should wait for scheduled tasks to complete on shutdown. */ private boolean awaitTermination;
/** * Maximum time the executor should wait for remaining tasks to complete. */ private @Nullable Duration awaitTerminationPeriod; public boolean isAwaitTermination() { return this.awaitTermination; } public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; } public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingProperties.java
2
请完成以下Java代码
protected String getProcessImageResourceName(String bpmnFileResource, String processKey, String diagramSuffix) { String bpmnFileResourceBase = stripBpmnFileSuffix(bpmnFileResource); return bpmnFileResourceBase + processKey + "." + diagramSuffix; } protected String stripBpmnFileSuffix(String bpmnFileResource) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (bpmnFileResource.endsWith(suffix)) { return bpmnFileResource.substring(0, bpmnFileResource.length() - suffix.length()); } } return bpmnFileResource; } protected void createResource(String name, byte[] bytes, DeploymentEntity deploymentEntity) { ResourceEntity resource = new ResourceEntity(); resource.setName(name); resource.setBytes(bytes); resource.setDeploymentId(deploymentEntity.getId()); // Mark the resource as 'generated' resource.setGenerated(true); Context .getCommandContext() .getDbSqlSession() .insert(resource); } protected boolean isBpmnResource(String resourceName) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (resourceName.endsWith(suffix)) { return true; } } return false; } public ExpressionManager getExpressionManager() { return expressionManager; }
public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请完成以下Java代码
public String toString() { return String.valueOf(precision); } @JsonValue public int toInt() { return precision; } public BigDecimal roundIfNeeded(@NonNull final BigDecimal amt) { if (amt.scale() > precision) { return amt.setScale(precision, getRoundingMode()); } else { return amt; } }
public BigDecimal round(@NonNull final BigDecimal amt) { return amt.setScale(precision, getRoundingMode()); } public RoundingMode getRoundingMode() { return RoundingMode.HALF_UP; } public CurrencyPrecision min(final CurrencyPrecision other) { return this.precision <= other.precision ? this : other; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyPrecision.java
1
请完成以下Java代码
public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_Value (COLUMNNAME_AD_Role_ID, null); else set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Scheduler getAD_Scheduler() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class); } @Override public void setAD_Scheduler(org.compiere.model.I_AD_Scheduler AD_Scheduler) { set_ValueFromPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class, AD_Scheduler); } /** Set Ablaufsteuerung. @param AD_Scheduler_ID Schedule Processes */ @Override public void setAD_Scheduler_ID (int AD_Scheduler_ID) { if (AD_Scheduler_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, Integer.valueOf(AD_Scheduler_ID)); } /** Get Ablaufsteuerung. @return Schedule Processes */ @Override public int getAD_Scheduler_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Scheduler_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Empfänger. @param AD_SchedulerRecipient_ID Recipient of the Scheduler Notification */ @Override public void setAD_SchedulerRecipient_ID (int AD_SchedulerRecipient_ID) { if (AD_SchedulerRecipient_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, Integer.valueOf(AD_SchedulerRecipient_ID));
} /** Get Empfänger. @return Recipient of the Scheduler Notification */ @Override public int getAD_SchedulerRecipient_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_SchedulerRecipient_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerRecipient.java
1
请完成以下Java代码
public class MyClass { private int id; private String name; public MyClass(int id, String name) { this.id = id; this.name = name; } public MyClass() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name;
} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MyClass myClass = (MyClass) o; return id == myClass.id && Objects.equals(name, myClass.name); } @Override public int hashCode() { return Objects.hash(id, name); } }
repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\entities\MyClass.java
1
请完成以下Java代码
protected void checkQueryOk() { super.checkQueryOk(); ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId); } // getters ///////////////////////////////////////////////// public String getProcessDefinitionId() { return processDefinitionId; } public boolean isIncludeFinished() { return includeFinished; } public boolean isIncludeCanceled() { return includeCanceled;
} public boolean isIncludeCompleteScope() { return includeCompleteScope; } public String[] getProcessInstanceIds() { return processInstanceIds; } public boolean isIncludeIncidents() { return includeIncidents; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricActivityStatisticsQueryImpl.java
1
请完成以下Java代码
public static void main(String[] args) { try { generateDocFromPDF(FILENAME); } catch (IOException e) { e.printStackTrace(); } } private static void generateDocFromPDF(String filename) throws IOException { XWPFDocument doc = new XWPFDocument(); String pdf = filename; PdfReader reader = new PdfReader(pdf); PdfReaderContentParser parser = new PdfReaderContentParser(reader); for (int i = 1; i <= reader.getNumberOfPages(); i++) {
TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); String text = strategy.getResultantText(); XWPFParagraph p = doc.createParagraph(); XWPFRun run = p.createRun(); run.setText(text); run.addBreak(BreakType.PAGE); } FileOutputStream out = new FileOutputStream("src/output/pdf.docx"); doc.write(out); out.close(); reader.close(); doc.close(); } }
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDF2WordExample.java
1
请完成以下Java代码
public class EthListener extends EthereumListenerAdapter { private Logger l = LoggerFactory.getLogger(EthListener.class); private Ethereum ethereum; private boolean syncDone = false; private static final int thou = 1000; private void out(String t) { l.info(t); } private String calcNetHashRate(Block block) { String response = "Net hash rate not available"; if (block.getNumber() > thou) { long timeDelta = 0; for (int i = 0; i < thou; ++i) { Block parent = ethereum .getBlockchain() .getBlockByHash(block.getParentHash()); timeDelta += Math.abs(block.getTimestamp() - parent.getTimestamp()); } response = String.valueOf(block .getDifficultyBI() .divide(BIUtil.toBI(timeDelta / thou)) .divide(new BigInteger("1000000000")) .doubleValue()) + " GH/s"; } return response; } public EthListener(Ethereum ethereum) { this.ethereum = ethereum; } @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { if (syncDone) {
out("Net hash rate: " + calcNetHashRate(block)); out("Block difficulty: " + block.getDifficultyBI().toString()); out("Block transactions: " + block.getTransactionsList().toString()); out("Best block (last block): " + ethereum .getBlockchain() .getBestBlock().toString()); out("Total difficulty: " + ethereum .getBlockchain() .getTotalDifficulty().toString()); } } @Override public void onSyncDone(SyncState state) { out("onSyncDone " + state); if (!syncDone) { out(" ** SYNC DONE ** "); syncDone = true; } } }
repos\tutorials-master\ethereum\src\main\java\com\baeldung\ethereumj\listeners\EthListener.java
1
请完成以下Spring Boot application配置
spring.application.name=swaggeryml springdoc.api-docs.enabled=true springdoc.api-docs.path=/v3/api-docs springdoc.api-docs.resolve-schema-properties=false springdoc
.swagger-ui.url=/openapi.yml springdoc.swagger-ui.path=/swagger-ui.html
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\resources\application-yml.properties
2
请完成以下Java代码
public class MADBoilerPlateVarEval extends X_AD_BoilerPlate_Var_Eval { private static final IQueryBL queryBL = Services.get(IQueryBL.class); private static final long serialVersionUID = 6355649371361977481L; private static final CCache<Integer, ImmutableList<MADBoilerPlateVarEval>> s_cache = new CCache<>(Table_Name + "#DocTiming", 2); public static @NotNull List<MADBoilerPlateVarEval> getAll() { //noinspection DataFlowIssue return s_cache.getOrLoad(0, MADBoilerPlateVarEval::retrieveAll); } private static ImmutableList<MADBoilerPlateVarEval> retrieveAll() { return queryBL.createQueryBuilder(I_AD_BoilerPlate_Var_Eval.Table_Name) .orderBy(I_AD_BoilerPlate_Var_Eval.COLUMNNAME_AD_BoilerPlate_Var_ID) .orderBy(I_AD_BoilerPlate_Var_Eval.COLUMNNAME_C_DocType_ID) .create() .listImmutable(MADBoilerPlateVarEval.class); } @SuppressWarnings("unused") public MADBoilerPlateVarEval(Properties ctx, int AD_BoilerPlate_Var_Eval_ID, String trxName) { super(ctx, AD_BoilerPlate_Var_Eval_ID, trxName); } @SuppressWarnings("unused") public MADBoilerPlateVarEval(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); }
@Override public I_AD_BoilerPlate_Var getAD_BoilerPlate_Var() throws RuntimeException { if (get_TrxName() == null) return MADBoilerPlateVar.get(getCtx(), getAD_BoilerPlate_Var_ID()); else return super.getAD_BoilerPlate_Var(); } @Override public I_C_DocType getC_DocType() throws RuntimeException { if (get_TrxName() == null) return MDocType.get(getCtx(), getC_DocType_ID()); else return super.getC_DocType(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlateVarEval.java
1
请在Spring Boot框架中完成以下Java代码
public class OrgMappingId implements RepoIdAware { int repoId; @JsonCreator public static OrgMappingId ofRepoId(final int repoId) { return new OrgMappingId(repoId); } @Nullable public static OrgMappingId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new OrgMappingId(repoId) : null; } @Nullable public static OrgMappingId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new OrgMappingId(repoId) : null; } public static Optional<OrgMappingId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final OrgMappingId orgMappingId) { return toRepoIdOr(orgMappingId, -1); } public static int toRepoIdOr(@Nullable final OrgMappingId orgMappingId, final int defaultValue) { return orgMappingId != null ? orgMappingId.getRepoId() : defaultValue; }
private OrgMappingId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Org_Mapping_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final OrgMappingId o1, @Nullable final OrgMappingId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\OrgMappingId.java
2
请完成以下Java代码
protected int getQueueSize() { return queue.size(); } public void printStats() { int queueSize = getQueueSize(); int rateLimitedTenantsCount = (int) stats.getRateLimitedTenants().values().stream() .filter(defaultCounter -> defaultCounter.get() > 0) .count(); if (queueSize > 0 || rateLimitedTenantsCount > 0 || concurrencyLevel.get() > 0 || stats.getStatsCounters().stream().anyMatch(counter -> counter.get() > 0) ) { StringBuilder statsBuilder = new StringBuilder(); statsBuilder.append("queueSize").append(" = [").append(queueSize).append("] "); stats.getStatsCounters().forEach(counter -> { statsBuilder.append(counter.getName()).append(" = [").append(counter.get()).append("] "); }); statsBuilder.append("totalRateLimitedTenants").append(" = [").append(rateLimitedTenantsCount).append("] "); statsBuilder.append(CONCURRENCY_LEVEL).append(" = [").append(concurrencyLevel.get()).append("] "); stats.getStatsCounters().forEach(StatsCounter::clear); log.info("[{}] Permits {}", bufferName, statsBuilder); } stats.getRateLimitedTenants().entrySet().stream() .filter(entry -> entry.getValue().get() > 0) .forEach(entry -> { TenantId tenantId = entry.getKey(); DefaultCounter counter = entry.getValue(); int rateLimitedRequests = counter.get();
counter.clear(); if (printTenantNames) { String name = tenantNamesCache.computeIfAbsent(tenantId, tId -> { String defaultName = "N/A"; try { return entityService.fetchEntityName(TenantId.SYS_TENANT_ID, tenantId).orElse(defaultName); } catch (Exception e) { log.error("[{}][{}] Failed to get tenant name", bufferName, tenantId, e); return defaultName; } }); log.info("[{}][{}][{}] Rate limited requests: {}", bufferName, tenantId, name, rateLimitedRequests); } else { log.info("[{}][{}] Rate limited requests: {}", bufferName, tenantId, rateLimitedRequests); } }); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\util\AbstractBufferedRateExecutor.java
1
请完成以下Java代码
public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, final int col) { final Component comp = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); if (hasFocus && table.isCellEditable(row, col)) table.editCellAt(row, col); return comp; } } // ProxyRenderer /** * Create a new row */ public void newRow() { stopEditor(true); final FindAdvancedSearchTableModel model = getModel(); model.newRow(); final int rowIndex = model.getRowCount() - 1; getSelectionModel().setSelectionInterval(rowIndex, rowIndex); requestFocusInWindow(); } public void deleteCurrentRow() { stopEditor(false);
final int rowIndex = getSelectedRow(); if (rowIndex >= 0) { final FindAdvancedSearchTableModel model = getModel(); model.removeRow(rowIndex); // Select next row if possible final int rowToSelect = Math.min(rowIndex, model.getRowCount() - 1); if (rowToSelect >= 0) { getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect); } } requestFocusInWindow(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindAdvancedSearchTable.java
1
请完成以下Java代码
private Dialog getParentDialog() { Dialog parent = null; Container e = getParent(); while (e != null) { if (e instanceof Dialog) { parent = (Dialog)e; break; } e = e.getParent(); } return parent; } public boolean print() { throw new UnsupportedOperationException(); } public static boolean isHtml(String s) { if (s == null) return false; String s2 = s.trim().toUpperCase(); return s2.startsWith("<HTML>"); } public static String convertToHtml(String plainText) { if (plainText == null)
return null; return plainText.replaceAll("[\r]*\n", "<br/>\n"); } public boolean isResolveVariables() { return boilerPlateMenu.isResolveVariables(); } public void setResolveVariables(boolean isResolveVariables) { boilerPlateMenu.setResolveVariables(isResolveVariables); } public void setEnablePrint(boolean enabled) { butPrint.setEnabled(enabled); butPrint.setVisible(enabled); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
1
请在Spring Boot框架中完成以下Java代码
public class ErpelMessageType { @XmlElement(name = "ErpelBusinessDocumentHeader", namespace = "http://erpel.at/schemas/1p0/messaging/header") protected ErpelBusinessDocumentHeaderType erpelBusinessDocumentHeader; @XmlElement(name = "Document", namespace = "http://erpel.at/schemas/1p0/documents", required = true) protected List<DocumentType> document; /** * Gets the value of the erpelBusinessDocumentHeader property. * * @return * possible object is * {@link ErpelBusinessDocumentHeaderType } * */ public ErpelBusinessDocumentHeaderType getErpelBusinessDocumentHeader() { return erpelBusinessDocumentHeader; } /** * Sets the value of the erpelBusinessDocumentHeader property. * * @param value * allowed object is * {@link ErpelBusinessDocumentHeaderType } * */ public void setErpelBusinessDocumentHeader(ErpelBusinessDocumentHeaderType value) { this.erpelBusinessDocumentHeader = value; } /**
* Gets the value of the document 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 document property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDocument().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentType } * * */ public List<DocumentType> getDocument() { if (document == null) { document = new ArrayList<DocumentType>(); } return this.document; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\message\ErpelMessageType.java
2
请完成以下Java代码
private boolean addGLJournalLine(final I_GL_JournalLine glJournalLine) { final AtomicBoolean addedRef = new AtomicBoolean(false); trxManager.run(getTrxNameInitial(), localTrxName -> { final boolean added = addGLJournalLine0(glJournalLine); addedRef.set(added); }); return addedRef.get(); } private boolean addGLJournalLine0(final I_GL_JournalLine glJournalLine) { final List<I_Fact_Acct> factAcctRecords = factAcctDAO.retrieveForDocumentLine(I_GL_Journal.Table_Name, glJournalLine.getGL_Journal_ID(), glJournalLine); // // Skip not posted GL Journal Lines, but warn the user if (factAcctRecords.isEmpty()) { final String summary = journalLineBL.getDocumentNo(glJournalLine); loggable.addLog("@Error@: @I_GL_JournalLine_ID@ @Posted@=@N@: " + summary); return false; } final I_C_TaxDeclarationLine taxDeclarationLine = createTaxDeclarationLine(glJournalLine); createTaxDeclarationAccts(taxDeclarationLine, factAcctRecords.iterator()); return true; } private I_C_TaxDeclarationLine createTaxDeclarationLine(final I_GL_JournalLine glJournalLine) { final String summary = journalLineBL.getDocumentNo(glJournalLine); final I_C_TaxDeclarationLine taxDeclarationLine = newTaxDeclarationLine(); taxDeclarationLine.setAD_Org_ID(glJournalLine.getAD_Org_ID()); taxDeclarationLine.setIsManual(false); // taxDeclarationLine.setGL_JournalLine(glJournalLine); taxDeclarationLine.setC_Currency_ID(glJournalLine.getC_Currency_ID());
taxDeclarationLine.setDateAcct(glJournalLine.getDateAcct()); taxDeclarationLine.setC_DocType_ID(glJournalLine.getGL_Journal().getC_DocType_ID()); taxDeclarationLine.setDocumentNo(summary); // final ITaxAccountable taxAccountable = journalLineBL.asTaxAccountable(glJournalLine); // NOTE: Tax on sales transactions is booked on CR, tax on purchase transactions is booked on DR final boolean isSOTrx = taxAccountable.isAccountSignCR(); taxDeclarationLine.setIsSOTrx(isSOTrx); taxDeclarationLine.setC_Tax_ID(taxAccountable.getC_Tax_ID()); taxDeclarationLine.setTaxBaseAmt(taxAccountable.getTaxBaseAmt()); taxDeclarationLine.setTaxAmt(taxAccountable.getTaxAmt()); save(taxDeclarationLine); return taxDeclarationLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\tax\impl\TaxDeclarationLinesBuilder.java
1
请完成以下Java代码
public static class ErrorItem { @JsonInclude(JsonInclude.Include.NON_NULL) private String code; private String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }
} public static class ErrorResponse { private List<ErrorItem> errors = new ArrayList<>(); public List<ErrorItem> getErrors() { return errors; } public void setErrors(List<ErrorItem> errors) { this.errors = errors; } public void addError(ErrorItem error) { this.errors.add(error); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\exception\ApiExceptionHandler.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Integer getDId() { return dId; } public void setDId(Integer dId) { this.dId = dId; } }
repos\SpringBootLearning-master (1)\springboot-cache\src\main\java\com\gf\entity\Employee.java
1
请完成以下Java代码
public int getAD_LabelPrinter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_LabelPrinter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Function Prefix. @param FunctionPrefix Data sent before the function */ public void setFunctionPrefix (String FunctionPrefix) { set_Value (COLUMNNAME_FunctionPrefix, FunctionPrefix); } /** Get Function Prefix. @return Data sent before the function */ public String getFunctionPrefix () { return (String)get_Value(COLUMNNAME_FunctionPrefix); } /** Set Function Suffix. @param FunctionSuffix Data sent after the function */ public void setFunctionSuffix (String FunctionSuffix) { set_Value (COLUMNNAME_FunctionSuffix, FunctionSuffix); } /** Get Function Suffix. @return Data sent after the function */ public String getFunctionSuffix () { return (String)get_Value(COLUMNNAME_FunctionSuffix); } /** Set XY Position. @param IsXYPosition The Function is XY position */ public void setIsXYPosition (boolean IsXYPosition) { set_Value (COLUMNNAME_IsXYPosition, Boolean.valueOf(IsXYPosition)); } /** Get XY Position. @return The Function is XY position */ public boolean isXYPosition () { Object oo = get_Value(COLUMNNAME_IsXYPosition); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name.
@param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set XY Separator. @param XYSeparator The separator between the X and Y function. */ public void setXYSeparator (String XYSeparator) { set_Value (COLUMNNAME_XYSeparator, XYSeparator); } /** Get XY Separator. @return The separator between the X and Y function. */ public String getXYSeparator () { return (String)get_Value(COLUMNNAME_XYSeparator); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java
1
请完成以下Java代码
protected String doIt() { final PPOrderId ppOrderId = getPPOrderId(); final I_PP_Order ppOrder = ppOrdersRepo.getById(ppOrderId); if (!isEligible(ppOrder)) { throw new AdempiereException("@NotValid@ " + ppOrder); } unclose(ppOrder); return MSG_OK; } private PPOrderId getPPOrderId() { Check.assumeEquals(getTableName(), I_PP_Order.Table_Name, "TableName"); return PPOrderId.ofRepoId(getRecord_ID()); } private void unclose(final I_PP_Order ppOrder) { ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_BEFORE_UNCLOSE); // // Unclose PP_Order's Qty ppOrderBL.uncloseQtyOrdered(ppOrder); ppOrdersRepo.save(ppOrder); // // Unclose PP_Order BOM Line's quantities final List<I_PP_Order_BOMLine> lines = ppOrderBOMDAO.retrieveOrderBOMLines(ppOrder); for (final I_PP_Order_BOMLine line : lines) { ppOrderBOMBL.unclose(line); } // // Unclose activities final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); ppOrderBL.uncloseActivities(ppOrderId); // firing this before having updated the docstatus. This is how the *real* DocActions like MInvoice do it too. ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_AFTER_UNCLOSE);
// // Update DocStatus ppOrder.setDocStatus(IDocument.STATUS_Completed); ppOrder.setDocAction(IDocument.ACTION_Close); ppOrdersRepo.save(ppOrder); // // Reverse ALL cost collectors reverseCostCollectorsGeneratedOnClose(ppOrderId); } private void reverseCostCollectorsGeneratedOnClose(final PPOrderId ppOrderId) { final ArrayList<I_PP_Cost_Collector> costCollectors = new ArrayList<>(ppCostCollectorDAO.getByOrderId(ppOrderId)); // Sort the cost collectors in reverse order of their creation, // just to make sure we are reversing the effect from last one to first one. costCollectors.sort(ModelByIdComparator.getInstance().reversed()); for (final I_PP_Cost_Collector cc : costCollectors) { final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(cc.getDocStatus()); if (docStatus.isReversedOrVoided()) { continue; } final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType()); if (costCollectorType == CostCollectorType.UsageVariance) { if (docStatus.isClosed()) { cc.setDocStatus(DocStatus.Completed.getCode()); ppCostCollectorDAO.save(cc); } docActionBL.processEx(cc, IDocument.ACTION_Reverse_Correct, DocStatus.Reversed.getCode()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_UnClose.java
1
请完成以下Java代码
public boolean isHostEnabled() { return hostEnabled; } public void setHostEnabled(boolean hostEnabled) { this.hostEnabled = hostEnabled; } public boolean isPortEnabled() { return portEnabled; } public void setPortEnabled(boolean portEnabled) { this.portEnabled = portEnabled; } public boolean isProtoEnabled() { return protoEnabled; } public void setProtoEnabled(boolean protoEnabled) { this.protoEnabled = protoEnabled; } public boolean isPrefixEnabled() { return prefixEnabled; } public void setPrefixEnabled(boolean prefixEnabled) { this.prefixEnabled = prefixEnabled; } public boolean isForAppend() { return forAppend; } public void setForAppend(boolean forAppend) { this.forAppend = forAppend; } public boolean isHostAppend() {
return hostAppend; } public void setHostAppend(boolean hostAppend) { this.hostAppend = hostAppend; } public boolean isPortAppend() { return portAppend; } public void setPortAppend(boolean portAppend) { this.portAppend = portAppend; } public boolean isProtoAppend() { return protoAppend; } public void setProtoAppend(boolean protoAppend) { this.protoAppend = protoAppend; } public boolean isPrefixAppend() { return prefixAppend; } public void setPrefixAppend(boolean prefixAppend) { this.prefixAppend = prefixAppend; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\XForwardedRequestHeadersFilterProperties.java
1
请完成以下Java代码
public class NettyServerB { private int port; private NettyServerB(int port) { this.port = port; } private void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB()); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); // (7) f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { new NettyServerB(8080).run(); } }
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\netty\NettyServerB.java
1
请完成以下Java代码
public class OrderPayScheduleLine { final @NonNull OrderPayScheduleId id; final @NonNull OrderId orderId; final @NonNull SeqNo seqNo; final @NonNull PaymentTermBreakId paymentTermBreakId; final @NonNull ReferenceDateType referenceDateType; final @NonNull Percent percent; final int offsetDays; @Setter @NonNull OrderPayScheduleStatus status; @Setter @NonNull LocalDate dueDate; final @NonNull Money dueAmount; public OrderAndPayScheduleId getOrderAndPayScheduleId() {return OrderAndPayScheduleId.of(orderId, id);} public void applyAndProcess(@NonNull final DueDateAndStatus dueDateAndStatus) {
final OrderPayScheduleStatus nextStatus = dueDateAndStatus.getStatus(); if (nextStatus.equals(this.status)) { return; } if (!this.status.isAllowTransitionTo(nextStatus)) { throw new AdempiereException("Cannot change status from " + this.status + " to " + nextStatus); } this.status = nextStatus; this.dueDate = dueDateAndStatus.getDueDate(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderPayScheduleLine.java
1
请完成以下Java代码
public String getSollHabenKennung() { return sollHabenKennung; } public void setSollHabenKennung(String sollHabenKennung) { this.sollHabenKennung = sollHabenKennung; } public String getWaehrung() { return waehrung; } public void setWaehrung(String waehrung) { this.waehrung = waehrung; } public Date getBuchungsdatum() {
return buchungsdatum; } public void setBuchungsdatum(Date buchungsdatum) { this.buchungsdatum = buchungsdatum; } public BigDecimal getBetrag() { return betrag; } public void setBetrag(BigDecimal betrag) { this.betrag = betrag; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Saldo.java
1
请完成以下Java代码
public boolean isTemplate() { return isTemplateRepoId(repoId); } public static boolean isTemplateRepoId(final int repoId) { return repoId == TEMPLATE.repoId; } public boolean isVirtual() { return isVirtualRepoId(repoId); }
public static boolean isVirtualRepoId(final int repoId) { return repoId == VIRTUAL.repoId; } public boolean isRealPackingInstructions() { return isRealPackingInstructionsRepoId(repoId); } public static boolean isRealPackingInstructionsRepoId(final int repoId) { return repoId > 0 && !isTemplateRepoId(repoId) && !isVirtualRepoId(repoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuPackingInstructionsId.java
1
请完成以下Java代码
public void syncSendOrderly(String topic, Message<?> message, String hashKey) { LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey); rocketMQTemplate.syncSendOrderly(topic, message, hashKey); } /** * 发送顺序消息 * * @param message * @param topic * @param hashKey * @param timeout */ public void syncSendOrderly(String topic, Message<?> message, String hashKey, long timeout) { LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey + ",timeout:" + timeout); rocketMQTemplate.syncSendOrderly(topic, message, hashKey, timeout); } /** * 默认CallBack函数 * * @return */ private SendCallback getDefaultSendCallBack() { return new SendCallback() { @Override public void onSuccess(SendResult sendResult) { LOG.info("---发送MQ成功---"); }
@Override public void onException(Throwable throwable) { throwable.printStackTrace(); LOG.error("---发送MQ失败---"+throwable.getMessage(), throwable.getMessage()); } }; } @PreDestroy public void destroy() { LOG.info("---RocketMq助手注销---"); } }
repos\springboot-demo-master\rocketmq\src\main\java\demo\et59\rocketmq\util\RocketMqHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class StoreOrders { protected PrintOptions printOptions; @XmlElement(required = true) protected List<ShipmentServiceData> order; /** * Gets the value of the printOptions property. * * @return * possible object is * {@link PrintOptions } * */ public PrintOptions getPrintOptions() { return printOptions; } /** * Sets the value of the printOptions property. * * @param value * allowed object is * {@link PrintOptions } * */ public void setPrintOptions(PrintOptions value) { this.printOptions = value; } /** * Gets the value of the order 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 order property.
* * <p> * For example, to add a new item, do as follows: * <pre> * getOrder().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ShipmentServiceData } * * */ public List<ShipmentServiceData> getOrder() { if (order == null) { order = new ArrayList<ShipmentServiceData>(); } return this.order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\StoreOrders.java
2
请完成以下Java代码
protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; return updateHeader(); } // afterSave /** * Update Header * @return true if header updated */ private boolean updateHeader() { // Update header only if the document is not processed if (isProcessed() && !is_ValueChanged(COLUMNNAME_Processed))
return true; // Update Shipper Transportation Header String sql = DB.convertSqlToNative("UPDATE M_ShipperTransportation st" + " SET (PackageWeight,PackageNetTotal)=" + "(SELECT COALESCE(SUM(PackageWeight),0), COALESCE(SUM(PackageNetTotal),0) FROM M_ShippingPackage sp WHERE sp.M_ShipperTransportation_ID=st.M_ShipperTransportation_ID) " + "WHERE st.M_ShipperTransportation_ID=?"); int no = DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[]{getM_ShipperTransportation_ID()}, get_TrxName()); if (no != 1) log.warn("(1) #" + no); return no == 1; } // updateHeader } // MMShippingPackage
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\MMShippingPackage.java
1
请在Spring Boot框架中完成以下Java代码
public class MybatisSuspendedJobDataManager extends AbstractDataManager<SuspendedJobEntity> implements SuspendedJobDataManager { protected CachedEntityMatcher<SuspendedJobEntity> suspendedJobsByExecutionIdMatcher = new SuspendedJobsByExecutionIdMatcher(); protected SingleCachedEntityMatcher<SuspendedJobEntity> suspendedJobByCorrelationIdMatcher = new JobByCorrelationIdMatcher<>(); protected JobServiceConfiguration jobServiceConfiguration; public MybatisSuspendedJobDataManager(JobServiceConfiguration jobServiceConfiguration) { this.jobServiceConfiguration = jobServiceConfiguration; } @Override public Class<? extends SuspendedJobEntity> getManagedEntityClass() { return SuspendedJobEntityImpl.class; } @Override public SuspendedJobEntity create() { return new SuspendedJobEntityImpl(); } @Override public SuspendedJobEntity findJobByCorrelationId(String correlationId) { return getEntity("selectSuspendedJobByCorrelationId", correlationId, suspendedJobByCorrelationIdMatcher, true); } @Override @SuppressWarnings("unchecked") public List<Job> findJobsByQueryCriteria(SuspendedJobQueryImpl jobQuery) { String query = "selectSuspendedJobByQueryCriteria"; return getDbSqlSession().selectList(query, jobQuery); } @Override
public long findJobCountByQueryCriteria(SuspendedJobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectSuspendedJobCountByQueryCriteria", jobQuery); } @Override public List<SuspendedJobEntity> findJobsByExecutionId(String executionId) { DbSqlSession dbSqlSession = getDbSqlSession(); // If the execution has been inserted in the same command execution as this query, there can't be any in the database if (isEntityInserted(dbSqlSession, "execution", executionId)) { return getListFromCache(suspendedJobsByExecutionIdMatcher, executionId); } return getList(dbSqlSession, "selectSuspendedJobsByExecutionId", executionId, suspendedJobsByExecutionIdMatcher, true); } @Override @SuppressWarnings("unchecked") public List<SuspendedJobEntity> findJobsByProcessInstanceId(final String processInstanceId) { return getDbSqlSession().selectList("selectSuspendedJobsByProcessInstanceId", processInstanceId); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateSuspendedJobTenantIdForDeployment", params); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisSuspendedJobDataManager.java
2
请完成以下Java代码
public Optional<Quantity> getQtyPicked() { return map.values() .stream() .map(pickFrom -> pickFrom.getQtyPicked().orElse(null)) .filter(Objects::nonNull) .reduce(Quantity::add); } public Optional<Quantity> getQtyRejected() { // returning only from mainPickFrom because I wanted to keep the same logic we already have in misc/services/mobile-webui/mobile-webui-frontend/src/utils/picking.js, getQtyPickedOrRejectedTotalForLine return getMainPickFrom().getQtyRejected(); } @NonNull public List<HuId> getPickedHUIds() { return map.values() .stream() .map(PickingJobStepPickFrom::getPickedTo) .filter(Objects::nonNull) .filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0) .map(PickingJobStepPickedTo::getPickedHuIds) .flatMap(List::stream) .collect(ImmutableList.toImmutableList()); }
@NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHU() { return map.values() .stream() .map(PickingJobStepPickFrom::getPickedTo) .filter(Objects::nonNull) .filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0) .map(PickingJobStepPickedTo::getLastPickedHu) .filter(Optional::isPresent) .map(Optional::get) .max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFromMap.java
1
请完成以下Java代码
public SendTaskBuilder builder() { return new SendTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getImplementation() { return implementationAttribute.getValue(this); } public void setImplementation(String implementation) { implementationAttribute.setValue(this, implementation); } public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } /** camunda extensions */ public String getCamundaClass() { return camundaClassAttribute.getValue(this); } public void setCamundaClass(String camundaClass) { camundaClassAttribute.setValue(this, camundaClass); } public String getCamundaDelegateExpression() { return camundaDelegateExpressionAttribute.getValue(this); } public void setCamundaDelegateExpression(String camundaExpression) { camundaDelegateExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaResultVariable() { return camundaResultVariableAttribute.getValue(this); } public void setCamundaResultVariable(String camundaResultVariable) { camundaResultVariableAttribute.setValue(this, camundaResultVariable); }
public String getCamundaTopic() { return camundaTopicAttribute.getValue(this); } public void setCamundaTopic(String camundaTopic) { camundaTopicAttribute.setValue(this, camundaTopic); } public String getCamundaType() { return camundaTypeAttribute.getValue(this); } public void setCamundaType(String camundaType) { camundaTypeAttribute.setValue(this, camundaType); } @Override public String getCamundaTaskPriority() { return camundaTaskPriorityAttribute.getValue(this); } @Override public void setCamundaTaskPriority(String taskPriority) { camundaTaskPriorityAttribute.setValue(this, taskPriority); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SendTaskImpl.java
1
请完成以下Java代码
public class CallableElementParameter { protected ParameterValueProvider sourceValueProvider; protected String target; protected boolean allVariables; protected boolean readLocal = false; // source //////////////////////////////////////////////////////// public Object getSource(VariableScope variableScope) { if (sourceValueProvider instanceof ConstantValueProvider) { String variableName = (String) sourceValueProvider.getValue(variableScope); return variableScope.getVariableTyped(variableName); } else { return sourceValueProvider.getValue(variableScope); } } public void applyTo(VariableScope variableScope, VariableMap variables) { if (readLocal) { variableScope = new VariableScopeLocalAdapter(variableScope); } if (allVariables) { Map<String, Object> allVariables = variableScope.getVariables(); variables.putAll(allVariables); } else { Object value = getSource(variableScope); variables.put(target, value); } } public ParameterValueProvider getSourceValueProvider() { return sourceValueProvider;
} public void setSourceValueProvider(ParameterValueProvider source) { this.sourceValueProvider = source; } // target ////////////////////////////////////////////////////////// public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } // all variables ////////////////////////////////////////////////// public boolean isAllVariables() { return allVariables; } public void setAllVariables(boolean allVariables) { this.allVariables = allVariables; } // local public void setReadLocal(boolean readLocal) { this.readLocal = readLocal; } public boolean isReadLocal() { return readLocal; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CallableElementParameter.java
1
请完成以下Java代码
public DocumentPath getDocumentPath() { return documentPath; } @Override public String getFieldName() { return fieldName; } @Override public DocumentFieldWidgetType getWidgetType() { return widgetType; } @Override public boolean isValueSet()
{ return valueSet; } @Override public Object getValue() { return value; } public MutableDocumentFieldChangedEvent setValue(final Object value) { this.value = value; valueSet = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\MutableDocumentFieldChangedEvent.java
1
请完成以下Java代码
private JsonResponsePriceList execute() { try { return execute0(); } catch (final Exception ex) { throw populateWithParameters(ex); } } private JsonResponsePriceList execute0() { countryId = servicesFacade.getCountryIdByCountryCode(countryCode); bpartnerId = servicesFacade.getBPartnerId(bpartnerIdentifier, null) .orElseThrow(() -> new AdempiereException("No BPartner found for " + bpartnerIdentifier)); pricingSystemId = servicesFacade.getPricingSystemId(bpartnerId, soTrx) .orElseThrow(() -> new AdempiereException("No pricing system defined for " + bpartnerId)); final PriceListsCollection priceLists = servicesFacade.getPriceListsCollection(pricingSystemId); final I_M_PriceList priceList = priceLists.getPriceList(countryId, soTrx).orElse(null); if (priceList == null) { throw new AdempiereException("No PriceList found for given country and SOTrx"); } final CurrencyId currencyId = CurrencyId.ofRepoId(priceList.getC_Currency_ID()); final CurrencyCode currencyCode = servicesFacade.getCurrencyCodeById(currencyId); priceListId = PriceListId.ofRepoId(priceList.getM_PriceList_ID()); final PriceListVersionId priceListVersionId = servicesFacade.getPriceListVersionId(priceListId, TimeUtil.asZonedDateTime(date, SystemTime.zoneId())); final ImmutableList<ProductPrice> productPriceRecords = servicesFacade.getProductPrices(priceListVersionId); final ImmutableSet<ProductId> productIds = productPriceRecords.stream() .map(ProductPrice::getProductId) .collect(ImmutableSet.toImmutableSet()); final ImmutableMap<ProductId, String> productValues = servicesFacade.getProductValues(productIds); final ImmutableList<JsonResponsePrice> prices = productPriceRecords.stream()
.map(productPrice -> toJsonResponsePrice(productPrice, productValues, currencyCode)) .collect(ImmutableList.toImmutableList()); return JsonResponsePriceList.builder() .prices(prices) .build(); } private JsonResponsePrice toJsonResponsePrice( @NonNull final ProductPrice productPrice, @NonNull final ImmutableMap<ProductId, String> productValues, @NonNull final CurrencyCode currencyCode) { final ProductId productId = productPrice.getProductId(); return JsonResponsePrice.builder() .productId(productId) .productCode(productValues.get(productId)) .price(productPrice.getPriceStd()) .currencyCode(currencyCode) .taxCategoryId(productPrice.getTaxCategoryId()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\command\GetPriceListCommand.java
1
请完成以下Java代码
public java.math.BigDecimal getQtyPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPrice); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Quantity Ranking. @param QtyRanking Quantity Ranking */ @Override public void setQtyRanking (int QtyRanking) { set_ValueNoCheck (COLUMNNAME_QtyRanking, Integer.valueOf(QtyRanking)); } /** Get Quantity Ranking. @return Quantity Ranking */ @Override public int getQtyRanking () { Integer ii = (Integer)get_Value(COLUMNNAME_QtyRanking); if (ii == null) return 0; return ii.intValue(); } /** Set Ranking. @param Ranking Relative Rank Number */
@Override public void setRanking (int Ranking) { set_ValueNoCheck (COLUMNNAME_Ranking, Integer.valueOf(Ranking)); } /** Get Ranking. @return Relative Rank Number */ @Override public int getRanking () { Integer ii = (Integer)get_Value(COLUMNNAME_Ranking); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_RV_C_RfQResponse.java
1
请完成以下Java代码
protected HistoricDecisionInstanceQuery createHistoricDecisionInstanceQuery(CommandContext commandContext) { return commandContext.getProcessEngineConfiguration() .getHistoryService() .createHistoricDecisionInstanceQuery(); } protected void writeUserOperationLog(CommandContext commandContext, int numInstances) { List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("mode", null, builder.getMode())); propertyChanges.add(new PropertyChange("removalTime", null, builder.getRemovalTime())); propertyChanges.add(new PropertyChange("hierarchical", null, builder.isHierarchical())); propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances)); propertyChanges.add(new PropertyChange("async", null, true)); commandContext.getOperationLogManager() .logDecisionInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_SET_REMOVAL_TIME, null, propertyChanges);
} protected boolean hasRemovalTime() { return builder.getMode() == Mode.ABSOLUTE_REMOVAL_TIME || builder.getMode() == Mode.CLEARED_REMOVAL_TIME; } public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) { return new SetRemovalTimeBatchConfiguration(elementConfiguration.getIds(), elementConfiguration.getMappings()) .setHierarchical(builder.isHierarchical()) .setHasRemovalTime(hasRemovalTime()) .setRemovalTime(builder.getRemovalTime()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\removaltime\SetRemovalTimeToHistoricDecisionInstancesCmd.java
1
请完成以下Java代码
public void setFrom(@NonNull final I_M_InOut from) { setFrom(new DocumentLocationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Invoice from) { setFrom(InvoiceDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_M_InOut getWrappedRecord() {
return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentLocationAdapter.java
1
请完成以下Java代码
public void validate(@NonNull final I_C_OLCand olCand) { for (final IOLCandValidator olCandValdiator : validators) { try { olCandValdiator.validate(olCand); } catch (final Exception e) { final AdempiereException me = AdempiereException .wrapIfNeeded(e) .appendParametersToMessage() .setParameter("OLCandValidator", olCandValdiator.getClass().getSimpleName()); olCand.setIsError(true); olCand.setErrorMsg(me.getLocalizedMessage());
final AdIssueId issueId = errorManager.createIssue(e); olCand.setAD_Issue_ID(issueId.getRepoId()); olCand.setErrorMsgJSON(JsonObjectMapperHolder.toJsonNonNull(JsonErrorItem.builder() .message(me.getLocalizedMessage()) .errorCode(AdempiereException.extractErrorCodeOrNull(me)) .stackTrace(Trace.toOneLineStackTraceString(me.getStackTrace())) .adIssueId(JsonMetasfreshId.of(issueId.getRepoId())) .errorCode(AdempiereException.extractErrorCodeOrNull(me)) .throwable(me) .build())); break; } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandSPIRegistry.java
1
请完成以下Java代码
public class TokenRelayGatewayFilterFactory extends AbstractGatewayFilterFactory<AbstractGatewayFilterFactory.NameConfig> { private final ObjectProvider<ReactiveOAuth2AuthorizedClientManager> clientManagerProvider; public TokenRelayGatewayFilterFactory(ObjectProvider<ReactiveOAuth2AuthorizedClientManager> clientManagerProvider) { super(NameConfig.class); this.clientManagerProvider = clientManagerProvider; } @Override public List<String> shortcutFieldOrder() { return Collections.singletonList(NAME_KEY); } public GatewayFilter apply() { return apply((NameConfig) null); } @Override public GatewayFilter apply(@Nullable NameConfig config) { String defaultClientRegistrationId = (config == null) ? null : config.getName(); return (exchange, chain) -> exchange.getPrincipal() // .log("token-relay-filter") .filter(principal -> principal instanceof Authentication) .cast(Authentication.class) .flatMap(principal -> authorizationRequest(defaultClientRegistrationId, principal)) .flatMap(this::authorizedClient) .map(OAuth2AuthorizedClient::getAccessToken) .map(token -> withBearerAuth(exchange, token)) // TODO: adjustable behavior if empty .defaultIfEmpty(exchange) .flatMap(chain::filter); } private Mono<OAuth2AuthorizeRequest> authorizationRequest(@Nullable String defaultClientRegistrationId, Authentication principal) { String clientRegistrationId = defaultClientRegistrationId; if (clientRegistrationId == null && principal instanceof OAuth2AuthenticationToken) { clientRegistrationId = ((OAuth2AuthenticationToken) principal).getAuthorizedClientRegistrationId(); } return Mono.justOrEmpty(clientRegistrationId) .map(OAuth2AuthorizeRequest::withClientRegistrationId) .map(builder -> builder.principal(principal).build());
} private Mono<OAuth2AuthorizedClient> authorizedClient(OAuth2AuthorizeRequest request) { ReactiveOAuth2AuthorizedClientManager clientManager = clientManagerProvider.getIfAvailable(); if (clientManager == null) { return Mono.error(new IllegalStateException( "No ReactiveOAuth2AuthorizedClientManager bean was found. Did you include the " + "org.springframework.boot:spring-boot-starter-oauth2-client dependency?")); } // TODO: use Mono.defer() for request above? return clientManager.authorize(request); } private ServerWebExchange withBearerAuth(ServerWebExchange exchange, OAuth2AccessToken accessToken) { return exchange.mutate() .request(r -> r.headers(headers -> headers.setBearerAuth(accessToken.getTokenValue()))) .build(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\TokenRelayGatewayFilterFactory.java
1
请完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public CmmnEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (cmmnEngineConfiguration.getBeans() == null) { cmmnEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.cmmnEngine = cmmnEngineConfiguration.buildCmmnEngine(); return this.cmmnEngine; } protected void configureExternallyManagedTransactions() { if (cmmnEngineConfiguration instanceof SpringCmmnEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringCmmnEngineConfiguration engineConfiguration = (SpringCmmnEngineConfiguration) cmmnEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { cmmnEngineConfiguration.setTransactionsExternallyManaged(true);
} } } @Override public Class<CmmnEngine> getObjectType() { return CmmnEngine.class; } @Override public boolean isSingleton() { return true; } public CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } public void setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-cmmn-spring\src\main\java\org\flowable\cmmn\spring\CmmnEngineFactoryBean.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-producer-application cloud: # Spring Cloud Stream 配置项,对应 BindingServiceProperties 类 stream: # Binding 配置项,对应 BindingProperties Map bindings: demo01-output: destination: DEMO-TOPIC-01 # 目的地。这里使用 RocketMQ Topic content-type: application/json # 内容格式。这里使用 JSON # Producer 配置项,对应 ProducerProperties 类 producer: partition-key-expression: payload['id'] # 分区 key 表达式。该表达式基于 Spring EL,从消息中获得分区 key。 # Spring Cloud Stream RocketMQ 配置项 rocketmq: # RocketMQ Binder 配置项,对应 RocketMQBinderConfigurationProperties 类 binder: name-server: 127.0.0.1:9876 # RocketMQ Namesrv 地址
# RocketMQ 自定义 Binding 配置项,对应 RocketMQBindingProperties Map bindings: demo01-output: # RocketMQ Producer 配置项,对应 RocketMQProducerProperties 类 producer: group: test # 生产者分组 sync: true # 是否同步发送消息,默认为 false 异步。 server: port: 18080
repos\SpringBoot-Labs-master\labx-06-spring-cloud-stream-rocketmq\labx-06-sca-stream-rocketmq-producer-orderly\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class ContactType { @XmlElement(name = "Name", required = true) protected String name; @XmlElement(name = "Email") protected String email; @XmlElement(name = "Phone") protected String phone; @XmlElement(name = "Fax") protected String fax; /** * Name of the contact. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Email address of the contact. * * @return * possible object is * {@link String } * */ public String getEmail() { return email; } /** * Sets the value of the email property. * * @param value * allowed object is * {@link String } * */ public void setEmail(String value) { this.email = value; }
/** * Phone number of the contact. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */ public void setPhone(String value) { this.phone = value; } /** * Fax number of the contact. * * @return * possible object is * {@link String } * */ public String getFax() { return fax; } /** * Sets the value of the fax property. * * @param value * allowed object is * {@link String } * */ public void setFax(String value) { this.fax = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ContactType.java
2
请完成以下Java代码
public BigDecimal getQty() { return invoiceLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { // // Check the invoice line first final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID(); if (invoiceLine_PIItemProductId > 0) { return invoiceLine_PIItemProductId; } // // Check order line final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class); if (orderline == null) { // // C_OrderLine not found (i.e Manual Invoice) return -1; } return orderline.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return invoiceLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) {
invoiceLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
1
请完成以下Java代码
private CurrencyConversionContext createCurrencyConversionCtxForBankInTransit() { final I_C_Payment payment = getC_Payment(); if (payment != null) { return paymentBL.extractCurrencyConversionContext(payment); } else { final I_C_BankStatementLine line = getC_BankStatementLine(); final PaymentCurrencyContext paymentCurrencyContext = bankStatementBL.getPaymentCurrencyContext(line); final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
CurrencyConversionContext conversionCtx = services.createCurrencyConversionContext( LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone), paymentCurrencyContext.getCurrencyConversionTypeId(), ClientId.ofRepoId(line.getAD_Client_ID())); final FixedConversionRate fixedCurrencyRate = paymentCurrencyContext.toFixedConversionRateOrNull(); if (fixedCurrencyRate != null) { conversionCtx = conversionCtx.withFixedConversionRate(fixedCurrencyRate); } return conversionCtx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\DocLine_BankStatement.java
1
请在Spring Boot框架中完成以下Java代码
public class MyProperties { /** * socket端口 */ private Integer socketPort; /** * Ping消息间隔(毫秒) */ private Integer pingInterval; /** * Ping消息超时时间(毫秒) */ private Integer pingTimeout; /** * APK文件访问URL前缀 */ private String apkUrlPrefix; public Integer getSocketPort() { return socketPort; } public void setSocketPort(Integer socketPort) { this.socketPort = socketPort; } public Integer getPingInterval() { return pingInterval; } public void setPingInterval(Integer pingInterval) { this.pingInterval = pingInterval;
} public Integer getPingTimeout() { return pingTimeout; } public void setPingTimeout(Integer pingTimeout) { this.pingTimeout = pingTimeout; } public String getApkUrlPrefix() { return apkUrlPrefix; } public void setApkUrlPrefix(String apkUrlPrefix) { this.apkUrlPrefix = apkUrlPrefix; } }
repos\SpringBootBucket-master\springboot-socketio\src\main\java\com\xncoding\jwt\config\properties\MyProperties.java
2
请在Spring Boot框架中完成以下Java代码
public List<RestVariableConverter> getVariableConverters() { return variableConverters; } /** * Called once when the converters need to be initialized. Override of custom conversion needs to be done between java and rest. */ protected void initializeVariableConverters() { variableConverters.add(new StringRestVariableConverter()); variableConverters.add(new IntegerRestVariableConverter()); variableConverters.add(new LongRestVariableConverter()); variableConverters.add(new ShortRestVariableConverter()); variableConverters.add(new DoubleRestVariableConverter()); variableConverters.add(new BigDecimalRestVariableConverter()); variableConverters.add(new BigIntegerRestVariableConverter()); variableConverters.add(new BooleanRestVariableConverter()); variableConverters.add(new DateRestVariableConverter()); variableConverters.add(new InstantRestVariableConverter()); variableConverters.add(new LocalDateRestVariableConverter()); variableConverters.add(new LocalDateTimeRestVariableConverter());
variableConverters.add(new UUIDRestVariableConverter()); variableConverters.add(new JsonObjectRestVariableConverter(objectMapper)); } protected String formatUrl(String serverRootUrl, String[] fragments, Object... arguments) { StringBuilder urlBuilder = new StringBuilder(serverRootUrl); for (String urlFragment : fragments) { urlBuilder.append("/"); urlBuilder.append(MessageFormat.format(urlFragment, arguments)); } return urlBuilder.toString(); } protected RestUrlBuilder createUrlBuilder() { return RestUrlBuilder.fromCurrentRequest(); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\CmmnRestResponseFactory.java
2
请完成以下Java代码
public class SubTypeConstructorStructure { public static class Fleet { private List<Vehicle> vehicles; public List<Vehicle> getVehicles() { return vehicles; } public void setVehicles(List<Vehicle> vehicles) { this.vehicles = vehicles; } } public static abstract class Vehicle { private String make; private String model; protected Vehicle(String make, String model) { this.make = make; this.model = model; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } } public static class Car extends Vehicle { private int seatingCapacity; private double topSpeed;
@JsonCreator public Car(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("seating") int seatingCapacity, @JsonProperty("topSpeed") double topSpeed) { super(make, model); this.seatingCapacity = seatingCapacity; this.topSpeed = topSpeed; } public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed; } } public static class Truck extends Vehicle { private double payloadCapacity; @JsonCreator public Truck(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("payload") double payloadCapacity) { super(make, model); this.payloadCapacity = payloadCapacity; } public double getPayloadCapacity() { return payloadCapacity; } public void setPayloadCapacity(double payloadCapacity) { this.payloadCapacity = payloadCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\SubTypeConstructorStructure.java
1
请完成以下Java代码
public void put(String propertyName, BigDecimal value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, BigInteger value) { jsonNode.put(propertyName, value); } @Override public void put(String propertyName, byte[] value) { jsonNode.put(propertyName, value); } @Override public void putNull(String propertyName) { jsonNode.putNull(propertyName); } @Override
public FlowableArrayNode putArray(String propertyName) { return new FlowableJackson2ArrayNode(jsonNode.putArray(propertyName)); } @Override public void set(String propertyName, FlowableJsonNode value) { jsonNode.set(propertyName, asJsonNode(value)); } @Override public FlowableObjectNode putObject(String propertyName) { return new FlowableJackson2ObjectNode(jsonNode.putObject(propertyName)); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ObjectNode.java
1
请完成以下Java代码
public static void paint3Deffect (Graphics2D g2D, Rectangle r, boolean round, boolean out) { // paint upper gradient GradientPaint topPaint = null; if (out) topPaint = new GradientPaint(r.x, r.y, COL_1TOP, r.x, r.y+r.height/2, COL_1END); else topPaint = new GradientPaint(r.x, r.y, COL_2END, r.x, r.y+r.height/2, COL_2TOP); g2D.setPaint(topPaint); // RectangularShape topRec = null; if (round) topRec = new RoundRectangle2D.Float(r.x,r.y, r.width,r.height/2, 15,15); else topRec = new Rectangle(r.x,r.y, r.width,r.height/2); g2D.fill(topRec);
// paint lower gradient GradientPaint endPaint = null; // upper left corner to lower left if (out) endPaint = new GradientPaint(r.x, r.y+r.height/2, COL_2TOP, r.x, r.y+r.height, COL_2END); else endPaint = new GradientPaint(r.x, r.y+r.height/2, COL_1END, r.x, r.y+r.height, COL_1TOP); g2D.setPaint(endPaint); // RectangularShape endRec = null; if (round) endRec = new RoundRectangle2D.Float(r.x, r.y+r.height/2, r.width, r.height/2, 15,15); else endRec = new Rectangle(r.x, r.y+r.height/2, r.width, r.height/2); g2D.fill(endRec); } // paint3Deffect }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\plaf\CompiereUtils.java
1
请完成以下Java代码
public boolean accept(final T model) { final ImmutablePair<String, Object> modelColumnAndValue = getFirstNonNullModelValue(model); if (modelColumnAndValue == null) { return value == null; } final String columnName = modelColumnAndValue.getLeft(); final Object modelValue = modelColumnAndValue.getRight(); final Object modelValueModified = modifier.convertValue(columnName, modelValue, model); final Object expectedValueModified = modifier.convertValue(columnName, this.value, model); return Objects.equals(modelValueModified, expectedValueModified); } @Nullable private ImmutablePair<String, Object> getFirstNonNullModelValue(final T model) { for (final String columnName : columnNames) { if (InterfaceWrapperHelper.isNull(model, columnName)) { continue; } final Object modelValue = InterfaceWrapperHelper.getValue(model, columnName).orElse(null); if (modelValue != null) { return ImmutablePair.of(columnName, modelValue); } } return null; } @Override public String getSql() { buildSql(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx) { return getSqlParams(); } public List<Object> getSqlParams() { buildSql(); return sqlParams;
} private boolean sqlBuilt = false; private String sqlWhereClause = null; private List<Object> sqlParams = null; private void buildSql() { if (sqlBuilt) { return; } final StringBuilder sqlWhereClause = new StringBuilder(); final List<Object> sqlParams; final String sqlColumnNames = modifier.getColumnSql("COALESCE(" + String.join(",", columnNames) + ")"); sqlWhereClause.append(sqlColumnNames); if (value == null) { sqlWhereClause.append(" IS NULL"); sqlParams = null; } else { sqlParams = new ArrayList<>(); sqlWhereClause.append("=").append(modifier.getValueSql(value, sqlParams)); } this.sqlWhereClause = sqlWhereClause.toString(); this.sqlParams = sqlParams != null && !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of(); this.sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CoalesceEqualsQueryFilter.java
1
请完成以下Java代码
public void setAccountNumber (final @Nullable java.lang.String AccountNumber) { set_Value (COLUMNNAME_AccountNumber, AccountNumber); } @Override public java.lang.String getAccountNumber() { return get_ValueAsString(COLUMNNAME_AccountNumber); } @Override public void setapplicationID (final @Nullable java.lang.String applicationID) { set_Value (COLUMNNAME_applicationID, applicationID); } @Override public java.lang.String getapplicationID() { return get_ValueAsString(COLUMNNAME_applicationID); } @Override public void setApplicationToken (final @Nullable java.lang.String ApplicationToken) { set_Value (COLUMNNAME_ApplicationToken, ApplicationToken); } @Override public java.lang.String getApplicationToken() { return get_ValueAsString(COLUMNNAME_ApplicationToken); } @Override public void setdhl_api_url (final @Nullable java.lang.String dhl_api_url) { set_Value (COLUMNNAME_dhl_api_url, dhl_api_url); } @Override public java.lang.String getdhl_api_url() { return get_ValueAsString(COLUMNNAME_dhl_api_url); } @Override public void setDhl_LenghtUOM_ID (final int Dhl_LenghtUOM_ID) { if (Dhl_LenghtUOM_ID < 1) set_ValueNoCheck (COLUMNNAME_Dhl_LenghtUOM_ID, null); else set_ValueNoCheck (COLUMNNAME_Dhl_LenghtUOM_ID, Dhl_LenghtUOM_ID); } @Override public int getDhl_LenghtUOM_ID() { return get_ValueAsInt(COLUMNNAME_Dhl_LenghtUOM_ID); } @Override public void setDHL_Shipper_Config_ID (final int DHL_Shipper_Config_ID) { if (DHL_Shipper_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, DHL_Shipper_Config_ID); } @Override public int getDHL_Shipper_Config_ID() { return get_ValueAsInt(COLUMNNAME_DHL_Shipper_Config_ID); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override
public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } @Override 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 setSignature (final @Nullable java.lang.String Signature) { set_Value (COLUMNNAME_Signature, Signature); } @Override public java.lang.String getSignature() { return get_ValueAsString(COLUMNNAME_Signature); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_Shipper_Config.java
1
请完成以下Java代码
public void setEDI_cctop_111_v_ID (final int EDI_cctop_111_v_ID) { if (EDI_cctop_111_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, EDI_cctop_111_v_ID); } @Override public int getEDI_cctop_111_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_111_v_ID); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); } @Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { if (M_InOut_ID < 1) set_Value (COLUMNNAME_M_InOut_ID, null); else set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID); } @Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); }
@Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_111_v.java
1
请完成以下Java代码
public boolean isValid() { if (productId <= 0) { return false; } if (qty == null || qty.signum() == 0) { return false; } return true; } @Override public void apply(final Object model) { if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OrderLine.class)) { logger.debug("Skip applying because it's not an order line: {}", model); return; }
final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class); apply(orderLine); } private void apply(final I_C_OrderLine orderLine) { // Note: There is only the product's stocking-UOM.,.the C_UOM can't be changed in the product info UI. // That's why we don't need to convert orderLine.setQtyEntered(qty); orderLine.setQtyOrdered(qty); } @Override public boolean isCreateNewRecord() { return true; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\OrderLineProductQtyGridRowBuilder.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } public int getAge() { return age; }
public void setAge(int age) { this.age = age; } public League getLeague() { return league; } public void setLeague(League league) { this.league = league; } @Override public String toString() { return "Player{" + "id=" + id + ", playerName='" + playerName + '\'' + ", teamName='" + teamName + '\'' + ", age=" + age + ", league_id=" + (league != null ? league.getId() : "null") + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\joinfetchcriteriaquery\model\Player.java
1
请完成以下Java代码
public void appendLine(List<Object> values) throws IOException { throw new UnsupportedOperationException("Not implemented"); } @Override public void close() throws IOException { // nothing } public void append(final JdbcExportDataSource source) { final StringBuilder sqlInsert = new StringBuilder(); final StringBuilder sqlSelect = new StringBuilder(); final List<Object> sqlSelectParams = new ArrayList<Object>(); for (final Column field : fields.values()) { final String columnName = field.getColumnName(); // // INSERT part if (sqlInsert.length() > 0) { sqlInsert.append(", "); } sqlInsert.append(columnName); if (sqlSelect.length() > 0) { sqlSelect.append("\n, "); } // // SELECT part final String sourceColumnName = field.getSourceColumnName(); if (!Check.isEmpty(sourceColumnName)) { sqlSelect.append(sourceColumnName).append(" AS ").append(columnName); } // Constant
else { sqlSelect.append("? AS ").append(columnName); sqlSelectParams.add(field.getConstantValue()); } } final String sql = new StringBuilder() .append("INSERT INTO ").append(tableName).append(" (").append(sqlInsert).append(")") .append("\nSELECT ").append(sqlSelect) .append("\nFROM (").append(source.getSqlSelect()).append(") t") .toString(); final List<Object> sqlParams = new ArrayList<Object>(); sqlParams.addAll(sqlSelectParams); sqlParams.addAll(source.getSqlParams()); final String trxName = Trx.TRXNAME_None; final int count = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), trxName); logger.info("Inserted {} records into {} from {}", new Object[] { count, tableName, source }); } public void addField(final String fieldName, final String sourceFieldName) { final Column field = new Column(fieldName, sourceFieldName, null); fields.put(fieldName, field); } public void addConstant(final String fieldName, final Object value) { final Column field = new Column(fieldName, null, value); fields.put(fieldName, field); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcTableExportDataDestination.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AddEvidencePaymentDisputeRequest addEvidencePaymentDisputeRequest = (AddEvidencePaymentDisputeRequest)o; return Objects.equals(this.evidenceType, addEvidencePaymentDisputeRequest.evidenceType) && Objects.equals(this.files, addEvidencePaymentDisputeRequest.files) && Objects.equals(this.lineItems, addEvidencePaymentDisputeRequest.lineItems); } @Override public int hashCode() { return Objects.hash(evidenceType, files, lineItems); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AddEvidencePaymentDisputeRequest {\n"); sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n"); sb.append(" files: ").append(toIndentedString(files)).append("\n"); sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n"); sb.append("}"); return sb.toString();
} /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AddEvidencePaymentDisputeRequest.java
2
请在Spring Boot框架中完成以下Java代码
public void setSUMUP_CardReader(final de.metas.payment.sumup.repository.model.I_SUMUP_CardReader SUMUP_CardReader) { set_ValueFromPO(COLUMNNAME_SUMUP_CardReader_ID, de.metas.payment.sumup.repository.model.I_SUMUP_CardReader.class, SUMUP_CardReader); } @Override public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID) { if (SUMUP_CardReader_ID < 1) set_Value (COLUMNNAME_SUMUP_CardReader_ID, null); else set_Value (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID); } @Override public int getSUMUP_CardReader_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
} @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } @Override public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code) { set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code); } @Override public java.lang.String getSUMUP_merchant_code() { return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Config.java
2
请完成以下Java代码
public final String docValidate(final PO po, final int timingCode) throws Exception { final DocTimingType timing = DocTimingType.valueOf(timingCode); interceptor.onDocValidate(po, timing); return null; } @Override public final String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); return null; } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); } @Override public void beforeLogout(final MFSession session) {
if (userLoginListener != null) { userLoginListener.beforeLogout(session); } } @Override public void afterLogout(final MFSession session) { if (userLoginListener != null) { userLoginListener.afterLogout(session); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelInterceptor2ModelValidatorWrapper.java
1
请完成以下Java代码
private final void init(final HUReceiptLinePartCandidate receiptLinePart) { Check.assume(isNew(), "this candidate shall be new in order to be able to initialize it: {}", this); _subProducerBPartnerId = receiptLinePart.getSubProducer_BPartner_ID(); _asiAggregationKey = receiptLinePart.getAttributeStorageAggregationKey(); } private final void updateIfStale() { if (!_stale) { return; } // // Iterate all Parts and // * Compute qty and QtyWithIssues // * Collect quality notices // * Collect receipt schedule allocations final ReceiptQty qtyAndQuality = ReceiptQty.newWithoutCatchWeight(productId); final List<I_M_ReceiptSchedule_Alloc> receiptScheduleAllocs = new ArrayList<I_M_ReceiptSchedule_Alloc>(); for (final HUReceiptLinePartCandidate receiptLinePart : receiptLinePartCandidates) { // In case there are several qualityNotes, only the first one shall be remembered if (_qualityNote == null) { _qualityNote = receiptLinePart.getQualityNote(); } final ReceiptQty partQtyAndQuality = receiptLinePart.getQtyAndQuality(); if (partQtyAndQuality.isZero()) { // skip receipt line parts where Qty is ZERO // NOTE: we will also skip receipt schedule allocs but that shall be fine // because if Qty is ZERO it means it was an allocation and deallocation // so we don't need the packing materials from them continue; } qtyAndQuality.add(partQtyAndQuality); receiptScheduleAllocs.addAll(receiptLinePart.getReceiptScheduleAllocs()); } // // Update candidate's cumulated values _qtyAndQuality = qtyAndQuality; _receiptScheduleAllocs = Collections.unmodifiableList(receiptScheduleAllocs); _stale = false; // not staled anymore }
/** @return receipt schedule; never return null */ public I_M_ReceiptSchedule getM_ReceiptSchedule() { return _receiptSchedule; } public int getSubProducer_BPartner_ID() { // updateIfStale(); // no need return _subProducerBPartnerId; } public List<I_M_ReceiptSchedule_Alloc> getReceiptScheduleAllocs() { updateIfStale(); return _receiptScheduleAllocs; } public I_C_UOM getC_UOM() { return loadOutOfTrx(getM_ReceiptSchedule().getC_UOM_ID(), I_C_UOM.class); } public ReceiptQty getQtyAndQuality() { updateIfStale(); return _qtyAndQuality; } public I_M_QualityNote get_qualityNote() { return _qualityNote; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLineCandidate.java
1
请完成以下Java代码
public List<HistoricVariableInstance> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); List<HistoricVariableInstance> historicVariableInstances = commandContext .getHistoricVariableInstanceEntityManager() .findHistoricVariableInstancesByQueryCriteria(this, page); if (!excludeVariableInitialization) { for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) { if (historicVariableInstance instanceof HistoricVariableInstanceEntity) { HistoricVariableInstanceEntity variableEntity = (HistoricVariableInstanceEntity) historicVariableInstance; if (variableEntity != null && variableEntity.getVariableType() != null) { variableEntity.getValue(); // make sure JPA entities are cached for later retrieval if ( JPAEntityVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) ) { ((CacheableVariable) variableEntity.getVariableType()).setForceCacheable(true); } } } } } return historicVariableInstances; } // order by // ///////////////////////////////////////////////////////////////// public HistoricVariableInstanceQuery orderByProcessInstanceId() { orderBy(HistoricVariableInstanceQueryProperty.PROCESS_INSTANCE_ID); return this; } public HistoricVariableInstanceQuery orderByVariableName() { orderBy(HistoricVariableInstanceQueryProperty.VARIABLE_NAME); return this; } // getters and setters // ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getTaskId() {
return taskId; } public String getActivityInstanceId() { return activityInstanceId; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getVariableName() { return variableName; } public String getVariableNameLike() { return variableNameLike; } public QueryVariableValue getQueryVariableValue() { return queryVariableValue; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricVariableInstanceQueryImpl.java
1
请完成以下Java代码
private OrgId getOrgIdFromPurchaseCandidates(final Collection<PurchaseCandidate> purchaseCandidates) { final OrgId orgId = purchaseCandidates.stream() .map(PurchaseCandidate::getOrgId) .reduce((a, b) -> { throw new AdempiereException("Can only process purchase candidates from a single organization."); }) .orElseThrow(() -> new AdempiereException("No purchase candidates available. Can't derive OrgId.")); Check.errorIf(orgId.isAny(), "Cannot process purchase candidates with orgId = ANY"); return orgId; } private static Map<Integer, I_C_UOM> extractUOMsMap(@NonNull final Collection<PurchaseCandidate> purchaseCandidates) { return purchaseCandidates.stream() .map(PurchaseCandidate::getQtyToPurchase) .map(Quantity::getUOM) .collect(GuavaCollectors.toImmutableMapByKeyKeepFirstDuplicate(I_C_UOM::getC_UOM_ID)); } private static PurchaseOrderRequestItem createPurchaseOrderRequestItem(final PurchaseCandidate purchaseCandidate) { final Quantity qtyToPurchase = purchaseCandidate.getQtyToPurchase(); final ProductAndQuantity productAndQuantity = ProductAndQuantity.of(purchaseCandidate.getVendorProductNo(), qtyToPurchase.toBigDecimal(), qtyToPurchase.getUOMId()); return PurchaseOrderRequestItem.builder() .purchaseCandidateId(PurchaseCandidateId.getRepoIdOr(purchaseCandidate.getId(), -1)) .productAndQuantity(productAndQuantity) .build(); } @Override public void updateRemoteLineReferences(@NonNull final Collection<PurchaseOrderItem> purchaseOrderItems) { purchaseOrderItems.forEach(this::updateRemoteLineReference);
} private void updateRemoteLineReference(@NonNull final PurchaseOrderItem purchaseOrderItem) { final RemotePurchaseOrderCreatedItem remotePurchaseOrderCreatedItem = map.get(purchaseOrderItem); final OrderAndLineId purchaseOrderAndLineId = purchaseOrderItem.getPurchaseOrderAndLineId(); final LocalPurchaseOrderForRemoteOrderCreated localPurchaseOrderForRemoteOrderCreated = // LocalPurchaseOrderForRemoteOrderCreated.builder() .purchaseOrderId(OrderAndLineId.getOrderRepoIdOr(purchaseOrderAndLineId, -1)) .purchaseOrderLineId(OrderAndLineId.getOrderLineRepoIdOr(purchaseOrderAndLineId, -1)) .remotePurchaseOrderCreatedItem(remotePurchaseOrderCreatedItem) .build(); vendorGatewayService.associateLocalWithRemotePurchaseOrderId(localPurchaseOrderForRemoteOrderCreated); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remoteorder\RealVendorGatewayInvoker.java
1
请完成以下Java代码
protected void createInitialUserInternal(String processEngineName, UserDto user, ProcessEngine processEngine) { ObjectMapper objectMapper = getObjectMapper(); // make sure we can process this request at this time ensureSetupAvailable(processEngine); // reuse logic from rest api implementation UserRestServiceImpl userRestServiceImpl = new UserRestServiceImpl(processEngineName, objectMapper); userRestServiceImpl.createUser(user); // crate the camunda admin group ensureCamundaAdminGroupExists(processEngine); // create group membership (add new user to admin group) processEngine.getIdentityService() .createMembership(user.getProfile().getId(), Groups.CAMUNDA_ADMIN); } protected ObjectMapper getObjectMapper() { if(providers != null) { return ProvidersUtil .resolveFromContext(providers, ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE, this.getClass()); } else { return null; } } protected void ensureCamundaAdminGroupExists(ProcessEngine processEngine) { final IdentityService identityService = processEngine.getIdentityService(); final AuthorizationService authorizationService = processEngine.getAuthorizationService(); // create group if(identityService.createGroupQuery().groupId(Groups.CAMUNDA_ADMIN).count() == 0) { Group camundaAdminGroup = identityService.newGroup(Groups.CAMUNDA_ADMIN); camundaAdminGroup.setName("camunda BPM Administrators"); camundaAdminGroup.setType(Groups.GROUP_TYPE_SYSTEM); identityService.saveGroup(camundaAdminGroup); } // create ADMIN authorizations on all built-in resources for (Resource resource : Resources.values()) { if(authorizationService.createAuthorizationQuery().groupIdIn(Groups.CAMUNDA_ADMIN).resourceType(resource).resourceId(ANY).count() == 0) {
AuthorizationEntity userAdminAuth = new AuthorizationEntity(AUTH_TYPE_GRANT); userAdminAuth.setGroupId(Groups.CAMUNDA_ADMIN); userAdminAuth.setResource(resource); userAdminAuth.setResourceId(ANY); userAdminAuth.addPermission(ALL); authorizationService.saveAuthorization(userAdminAuth); } } } protected void ensureSetupAvailable(ProcessEngine processEngine) { if (processEngine.getIdentityService().isReadOnly() || (processEngine.getIdentityService().createUserQuery().memberOfGroup(Groups.CAMUNDA_ADMIN).count() > 0)) { throw LOGGER.setupActionNotAvailable(); } } protected ProcessEngine lookupProcessEngine(String engineName) { ServiceLoader<ProcessEngineProvider> serviceLoader = ServiceLoader.load(ProcessEngineProvider.class); Iterator<ProcessEngineProvider> iterator = serviceLoader.iterator(); if (iterator.hasNext()) { ProcessEngineProvider provider = iterator.next(); return provider.getProcessEngine(engineName); } else { throw LOGGER.processEngineProviderNotFound(); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\web\SetupResource.java
1
请完成以下Java代码
public void setM_ProductPrice_Attribute_ID (int M_ProductPrice_Attribute_ID) { if (M_ProductPrice_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_ID, Integer.valueOf(M_ProductPrice_Attribute_ID)); } /** Get Attribute price. @return Attribute price */ @Override public int getM_ProductPrice_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribute price line.
@param M_ProductPrice_Attribute_Line_ID Attribute price line */ @Override public void setM_ProductPrice_Attribute_Line_ID (int M_ProductPrice_Attribute_Line_ID) { if (M_ProductPrice_Attribute_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_Line_ID, Integer.valueOf(M_ProductPrice_Attribute_Line_ID)); } /** Get Attribute price line. @return Attribute price line */ @Override public int getM_ProductPrice_Attribute_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_Line_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute_Line.java
1
请完成以下Java代码
public List<AuthorizationDto> queryAuthorizations(AuthorizationQueryDto queryDto, Integer firstResult, Integer maxResults) { queryDto.setObjectMapper(getObjectMapper()); AuthorizationQuery query = queryDto.toQuery(getProcessEngine()); List<Authorization> resultList = QueryUtil.list(query, firstResult, maxResults); return AuthorizationDto.fromAuthorizationList(resultList, getProcessEngine().getProcessEngineConfiguration()); } @Override public CountResultDto getAuthorizationCount(UriInfo uriInfo) { AuthorizationQueryDto queryDto = new AuthorizationQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return getAuthorizationCount(queryDto); } protected CountResultDto getAuthorizationCount(AuthorizationQueryDto queryDto) { AuthorizationQuery query = queryDto.toQuery(getProcessEngine()); long count = query.count(); return new CountResultDto(count); } @Override public AuthorizationDto createAuthorization(UriInfo context, AuthorizationCreateDto dto) { final AuthorizationService authorizationService = getProcessEngine().getAuthorizationService(); Authorization newAuthorization = authorizationService.createNewAuthorization(dto.getType()); AuthorizationCreateDto.update(dto, newAuthorization, getProcessEngine().getProcessEngineConfiguration()); newAuthorization = authorizationService.saveAuthorization(newAuthorization); return getAuthorization(newAuthorization.getId()).getAuthorization(context); }
// utility methods ////////////////////////////////////// protected IdentityService getIdentityService() { return getProcessEngine().getIdentityService(); } protected List<String> getUserGroups(String userId) { List<Group> userGroups = getIdentityService().createGroupQuery() .groupMember(userId) .unlimitedList(); List<String> groupIds = new ArrayList<>(); for (Group group : userGroups) { groupIds.add(group.getId()); } return groupIds; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\AuthorizationRestServiceImpl.java
1
请完成以下Java代码
public class Person { private String firstName; private String lastName; private Date birthdate; private List<String> emails; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName;
} public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } public List<String> getEmails() { return emails; } public void setEmails(List<String> emails) { this.emails = emails; } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\json\Person.java
1
请在Spring Boot框架中完成以下Java代码
@Nullable String getProfile() { return this.profile; } boolean isSkippable() { return this.configDataLocation.isOptional() || this.directory != null || this.profile != null; } PropertySourceLoader getPropertySourceLoader() { return this.propertySourceLoader; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; }
StandardConfigDataReference other = (StandardConfigDataReference) obj; return this.resourceLocation.equals(other.resourceLocation); } @Override public int hashCode() { return this.resourceLocation.hashCode(); } @Override public String toString() { return this.resourceLocation; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataReference.java
2
请在Spring Boot框架中完成以下Java代码
public void setOperation(String operation) { this.operation = operation; } public String getOperation() { return operation; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public enum QueryVariableOperation { EQUALS("equals"), NOT_EQUALS("notEquals"), EQUALS_IGNORE_CASE("equalsIgnoreCase"), NOT_EQUALS_IGNORE_CASE("notEqualsIgnoreCase"), LIKE("like"), LIKE_IGNORE_CASE("likeIgnoreCase"), GREATER_THAN("greaterThan"), GREATER_THAN_OR_EQUALS( "greaterThanOrEquals"), LESS_THAN("lessThan"), LESS_THAN_OR_EQUALS("lessThanOrEquals"); private final String friendlyName; private QueryVariableOperation(String friendlyName) { this.friendlyName = friendlyName; }
public String getFriendlyName() { return friendlyName; } public static QueryVariableOperation forFriendlyName(String friendlyName) { for (QueryVariableOperation type : values()) { if (type.friendlyName.equals(friendlyName)) { return type; } } throw new FlowableIllegalArgumentException("Unsupported variable query operation: " + friendlyName); } } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\variable\QueryVariable.java
2
请完成以下Java代码
public String toString() {return toJson();} @JsonValue public String toJson() { String json = this._json; if (json == null) { json = this._json = computeJson(); } return json; } private String computeJson() { return elements.stream() .map(ContextPathElement::toJson) .collect(Collectors.joining(".")); } public ContextPath newChild(@NonNull final String name) { return newChild(ContextPathElement.ofName(name)); } public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor) { return newChild(ContextPathElement.ofNameAndId( extractName(entityDescriptor), AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull()) )); } private ContextPath newChild(@NonNull final ContextPathElement element) { return new ContextPath(ImmutableList.<ContextPathElement>builder() .addAll(elements) .add(element) .build()); } public AdWindowId getAdWindowId() { return AdWindowId.ofRepoId(elements.get(0).getId()); } @Override public int compareTo(@NonNull final ContextPath other) { return toJson().compareTo(other.toJson()); } } @Value
class ContextPathElement { @NonNull String name; int id; @JsonCreator public static ContextPathElement ofJson(@NonNull final String json) { try { final int idx = json.indexOf("/"); if (idx > 0) { String name = json.substring(0, idx); int id = Integer.parseInt(json.substring(idx + 1)); return new ContextPathElement(name, id); } else { return new ContextPathElement(json, -1); } } catch (final Exception ex) { throw new AdempiereException("Failed parsing: " + json, ex); } } public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);} public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);} @Override public String toString() {return toJson();} @JsonValue public String toJson() {return id > 0 ? name + "/" + id : name;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java
1
请完成以下Java代码
public String getCamundaCaseVersion() { return camundaCaseVersionAttribute.getValue(this); } public void setCamundaCaseVersion(String camundaCaseVersion) { camundaCaseVersionAttribute.setValue(this, camundaCaseVersion); } public String getCamundaCalledElementTenantId() { return camundaCalledElementTenantIdAttribute.getValue(this); } public void setCamundaCalledElementTenantId(String tenantId) { camundaCalledElementTenantIdAttribute.setValue(this, tenantId); } public String getCamundaCaseTenantId() { return camundaCaseTenantIdAttribute.getValue(this); } public void setCamundaCaseTenantId(String tenantId) { camundaCaseTenantIdAttribute.setValue(this, tenantId); } @Override public String getCamundaVariableMappingClass() { return camundaVariableMappingClassAttribute.getValue(this);
} @Override public void setCamundaVariableMappingClass(String camundaClass) { camundaVariableMappingClassAttribute.setValue(this, camundaClass); } @Override public String getCamundaVariableMappingDelegateExpression() { return camundaVariableMappingDelegateExpressionAttribute.getValue(this); } @Override public void setCamundaVariableMappingDelegateExpression(String camundaExpression) { camundaVariableMappingDelegateExpressionAttribute.setValue(this, camundaExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallActivityImpl.java
1
请完成以下Java代码
public class TagSet implements IIdStringMap, IStringIdMap, Iterable<Map.Entry<String, Integer>>, ICacheAble { private Map<String, Integer> stringIdMap; private ArrayList<String> idStringMap; private int[] allTags; public TaskType type; public TagSet(TaskType type) { stringIdMap = new TreeMap<String, Integer>(); idStringMap = new ArrayList<String>(); this.type = type; } public int add(String tag) { // assertUnlock(); Integer id = stringIdMap.get(tag); if (id == null) { id = stringIdMap.size(); stringIdMap.put(tag, id); idStringMap.add(tag); } return id; } public int size() { return stringIdMap.size(); } public int sizeIncludingBos() { return size() + 1; } public int bosId() { return size(); } public void lock() { // assertUnlock(); allTags = new int[size()]; for (int i = 0; i < size(); i++) { allTags[i] = i; } } // private void assertUnlock() // { // if (allTags != null) // { // throw new IllegalStateException("标注集已锁定,无法修改"); // } // } @Override public String stringOf(int id) { return idStringMap.get(id); } @Override public int idOf(String string) { Integer id = stringIdMap.get(string); if (id == null) id = -1; return id; } @Override public Iterator<Map.Entry<String, Integer>> iterator() { return stringIdMap.entrySet().iterator();
} /** * 获取所有标签及其下标 * * @return */ public int[] allTags() { return allTags; } public void save(DataOutputStream out) throws IOException { out.writeInt(type.ordinal()); out.writeInt(size()); for (String tag : idStringMap) { out.writeUTF(tag); } } @Override public boolean load(ByteArray byteArray) { idStringMap.clear(); stringIdMap.clear(); int size = byteArray.nextInt(); for (int i = 0; i < size; i++) { String tag = byteArray.nextUTF(); idStringMap.add(tag); stringIdMap.put(tag, i); } lock(); return true; } public void load(DataInputStream in) throws IOException { idStringMap.clear(); stringIdMap.clear(); int size = in.readInt(); for (int i = 0; i < size; i++) { String tag = in.readUTF(); idStringMap.add(tag); stringIdMap.put(tag, i); } lock(); } public Collection<String> tags() { return idStringMap; } public boolean contains(String tag) { return idStringMap.contains(tag); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\TagSet.java
1
请完成以下Java代码
public TechnicalInputChannel1Choice getTechInptChanl() { return techInptChanl; } /** * Sets the value of the techInptChanl property. * * @param value * allowed object is * {@link TechnicalInputChannel1Choice } * */ public void setTechInptChanl(TechnicalInputChannel1Choice value) { this.techInptChanl = value; } /** * Gets the value of the intrst property. * * @return * possible object is * {@link TransactionInterest3 } * */ public TransactionInterest3 getIntrst() { return intrst; } /** * Sets the value of the intrst property. * * @param value * allowed object is * {@link TransactionInterest3 } * */ public void setIntrst(TransactionInterest3 value) { this.intrst = value; } /** * Gets the value of the cardTx property. * * @return * possible object is * {@link CardEntry1 } * */ public CardEntry1 getCardTx() { return cardTx; } /** * Sets the value of the cardTx property. * * @param value * allowed object is * {@link CardEntry1 } *
*/ public void setCardTx(CardEntry1 value) { this.cardTx = value; } /** * Gets the value of the ntryDtls 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 ntryDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNtryDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EntryDetails3 } * * */ public List<EntryDetails3> getNtryDtls() { if (ntryDtls == null) { ntryDtls = new ArrayList<EntryDetails3>(); } return this.ntryDtls; } /** * Gets the value of the addtlNtryInf property. * * @return * possible object is * {@link String } * */ public String getAddtlNtryInf() { return addtlNtryInf; } /** * Sets the value of the addtlNtryInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlNtryInf(String value) { this.addtlNtryInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\ReportEntry4.java
1
请完成以下Java代码
public Element getRootElement() { return rootElement; } public List<Problem> getProblems() { return errors; } public void addError(SAXParseException e) { errors.add(new ProblemImpl(e)); } public void addError(String errorMessage, Element element) { errors.add(new ProblemImpl(errorMessage, element)); } public void addError(String errorMessage, Element element, String... elementIds) { errors.add(new ProblemImpl(errorMessage, element, elementIds)); } public void addError(BpmnParseException e) { errors.add(new ProblemImpl(e)); } public void addError(BpmnParseException e, String elementId) { errors.add(new ProblemImpl(e, elementId)); } public boolean hasErrors() { return errors != null && !errors.isEmpty(); } public void addWarning(SAXParseException e) { warnings.add(new ProblemImpl(e)); } public void addWarning(String errorMessage, Element element) { warnings.add(new ProblemImpl(errorMessage, element)); } public void addWarning(String errorMessage, Element element, String... elementIds) { warnings.add(new ProblemImpl(errorMessage, element, elementIds)); } public boolean hasWarnings() {
return warnings != null && !warnings.isEmpty(); } public void logWarnings() { StringBuilder builder = new StringBuilder(); for (Problem warning : warnings) { builder.append("\n* "); builder.append(warning.getMessage()); builder.append(" | resource " + name); builder.append(warning.toString()); } LOG.logParseWarnings(builder.toString()); } public void throwExceptionForErrors() { StringBuilder strb = new StringBuilder(); for (Problem error : errors) { strb.append("\n* "); strb.append(error.getMessage()); strb.append(" | resource " + name); strb.append(error.toString()); } throw LOG.exceptionDuringParsing(strb.toString(), name, errors, warnings); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Parse.java
1
请在Spring Boot框架中完成以下Java代码
public static CamundaHistoryLevelAutoHandlingConfiguration historyLevelAutoHandlingConfiguration() { return new DefaultHistoryLevelAutoHandlingConfiguration(); } //TODO to be removed within CAM-8108 @Bean(name = "historyLevelDeterminator") @ConditionalOnMissingBean(name = { "camundaBpmJdbcTemplate", "historyLevelDeterminator" }) @ConditionalOnBean(name = "historyLevelAutoConfiguration") public static HistoryLevelDeterminator historyLevelDeterminator(CamundaBpmProperties camundaBpmProperties, JdbcTemplate jdbcTemplate) { return createHistoryLevelDeterminator(camundaBpmProperties, jdbcTemplate); } //TODO to be removed within CAM-8108 @Bean(name = "historyLevelDeterminator") @ConditionalOnBean(name = { "camundaBpmJdbcTemplate", "historyLevelAutoConfiguration", "historyLevelDeterminator" }) @ConditionalOnMissingBean(name = "historyLevelDeterminator") public static HistoryLevelDeterminator historyLevelDeterminatorMultiDatabase(CamundaBpmProperties camundaBpmProperties, @Qualifier("camundaBpmJdbcTemplate") JdbcTemplate jdbcTemplate) { return createHistoryLevelDeterminator(camundaBpmProperties, jdbcTemplate); } @Bean @ConditionalOnMissingBean(CamundaAuthorizationConfiguration.class) public static CamundaAuthorizationConfiguration camundaAuthorizationConfiguration() { return new DefaultAuthorizationConfiguration(); } @Bean @ConditionalOnMissingBean(CamundaDeploymentConfiguration.class) public static CamundaDeploymentConfiguration camundaDeploymentConfiguration() { return new DefaultDeploymentConfiguration(); } @Bean public GenericPropertiesConfiguration genericPropertiesConfiguration() { return new GenericPropertiesConfiguration(); } @Bean @ConditionalOnProperty(prefix = "camunda.bpm.admin-user", name = "id") public CreateAdminUserConfiguration createAdminUserConfiguration() { return new CreateAdminUserConfiguration(); } @Bean
@ConditionalOnMissingBean(CamundaFailedJobConfiguration.class) public static CamundaFailedJobConfiguration failedJobConfiguration() { return new DefaultFailedJobConfiguration(); } @Bean @ConditionalOnProperty(prefix = "camunda.bpm.filter", name = "create") public CreateFilterConfiguration createFilterConfiguration() { return new CreateFilterConfiguration(); } @Bean public EventPublisherPlugin eventPublisherPlugin(CamundaBpmProperties properties, ApplicationEventPublisher publisher) { return new EventPublisherPlugin(properties.getEventing(), publisher); } @Bean public CamundaIntegrationDeterminator camundaIntegrationDeterminator() { return new CamundaIntegrationDeterminator(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmConfiguration.java
2
请完成以下Java代码
public void setMSV3_VerfuegbarkeitsanfrageEinzelne(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne MSV3_VerfuegbarkeitsanfrageEinzelne) { set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class, MSV3_VerfuegbarkeitsanfrageEinzelne); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne. @param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1) set_Value (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null); else set_Value (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne. @return MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort getMSV3_VerfuegbarkeitsanfrageEinzelneAntwort() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort.class); } @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelneAntwort(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort MSV3_VerfuegbarkeitsanfrageEinzelneAntwort) { set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort.class, MSV3_VerfuegbarkeitsanfrageEinzelneAntwort); }
/** Set MSV3_VerfuegbarkeitsanfrageEinzelneAntwort. @param MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID MSV3_VerfuegbarkeitsanfrageEinzelneAntwort */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID (int MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID < 1) set_Value (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID, null); else set_Value (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelneAntwort. @return MSV3_VerfuegbarkeitsanfrageEinzelneAntwort */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Verfuegbarkeit_Transaction.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Long> saveCity(@RequestBody City city) { return cityHandler.save(city); } @PutMapping() @ResponseBody public Mono<Long> modifyCity(@RequestBody City city) { return cityHandler.modifyCity(city); } @DeleteMapping(value = "/{id}") @ResponseBody public Mono<Long> deleteCity(@PathVariable("id") Long id) { return cityHandler.deleteCity(id); } @GetMapping("/hello")
public Mono<String> hello(final Model model) { model.addAttribute("name", "泥瓦匠"); model.addAttribute("city", "浙江温岭"); String path = "hello"; return Mono.create(monoSink -> monoSink.success(path)); } private static final String CITY_LIST_PATH_NAME = "cityList"; @GetMapping("/page/list") public String listPage(final Model model) { final Flux<City> cityFluxList = cityHandler.findAllCity(); model.addAttribute("cityList", cityFluxList); return CITY_LIST_PATH_NAME; } }
repos\springboot-learning-example-master\springboot-webflux-4-thymeleaf\src\main\java\org\spring\springboot\webflux\controller\CityWebFluxController.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }
public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } @PrePersist public void prePersist() { if (name == null) { name = "John Snow"; } if (age == null) { age = 25; } if (locked == null) { locked = false; } } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\defaultvalues\UserEntity.java
1
请完成以下Java代码
private int getInitDelayMillis() { // I will leave the default value of 3 minutes, which was the common time until #2894 return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_ASYNC_INIT_DELAY_MILLIS, THREE_MINUTES); } @Override protected void registerInterceptors(@NonNull final IModelValidationEngine engine) { engine.addModelValidator(new C_Queue_PackageProcessor()); engine.addModelValidator(new C_Queue_Processor()); engine.addModelValidator(new de.metas.lock.model.validator.Main()); engine.addModelValidator(new C_Async_Batch()); } /** * Init the async queue processor service on user login. */ @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { if (!Ini.isSwingClient()) { return; } final int delayMillis = getInitDelayMillis();
Services.get(IQueueProcessorExecutorService.class).init(delayMillis); } /** * Destroy all queueud processors on user logout. */ @Override public void beforeLogout(final MFSession session) { if (!Ini.isSwingClient()) { return; } Services.get(IQueueProcessorExecutorService.class).removeAllQueueProcessors(); } @Override protected List<Topic> getAvailableUserNotificationsTopics() { return ImmutableList.of( Async_Constants.WORKPACKAGE_ERROR_USER_NOTIFICATIONS_TOPIC, DataImportService.USER_NOTIFICATIONS_TOPIC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\Main.java
1
请完成以下Java代码
public class MResourceType extends X_S_ResourceType { /** * */ private static final long serialVersionUID = 6303797933825680667L; /** Cache */ private static CCache<Integer, MResourceType> s_cache = new CCache<Integer, MResourceType>(Table_Name, 20); /** * Get from Cache * @param ctx * @param S_ResourceType_ID * @return MResourceType */ public static MResourceType get(Properties ctx, int S_ResourceType_ID) { if (S_ResourceType_ID <= 0) return null; MResourceType type = s_cache.get(S_ResourceType_ID); if (type == null) { type = new MResourceType(ctx, S_ResourceType_ID, null); if (type.get_ID() == S_ResourceType_ID) { s_cache.put(S_ResourceType_ID, type); } } return type; } /** * Standard Constructor * @param ctx context * @param S_ResourceType_ID id */ public MResourceType (Properties ctx, int S_ResourceType_ID, String trxName) { super (ctx, S_ResourceType_ID, trxName); } // MResourceType /** * Load Constructor * @param ctx context * @param rs result set */ public MResourceType (Properties ctx, ResultSet rs, String trxName) {
super(ctx, rs, trxName); } // MResourceType @Override public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("MResourceType[") .append(get_ID()) .append(",Value=").append(getValue()) .append(",Name=").append(getName()); if (isTimeSlot()) { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); sb.append(",TimeSlot="); Timestamp start = getTimeSlotStart(); Timestamp end = getTimeSlotEnd(); sb.append(start != null ? df.format(start) : " - "); sb.append("-"); sb.append(end != null ? df.format(end) : " - "); } if (isDateSlot()) { sb.append(",DaySlot=") .append(isOnMonday() ? "M" : "-") .append(isOnTuesday() ? "T" : "-") .append(isOnWednesday() ? "W" : "-") .append(isOnThursday() ? "T" : "-") .append(isOnFriday() ? "F" : "-") .append(isOnSaturday() ? "S" : "-") .append(isOnSunday() ? "S" : "-"); } return sb.append("]").toString(); } } // MResourceType
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MResourceType.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } if (!streamEligibleSelectedRows().findAny().isPresent()) { return ProcessPreconditionsResolution.reject(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final ImmutableList<I_M_HU> husToReturn = getSelectedHUsToReturn(); if (husToReturn.isEmpty()) { throw new AdempiereException("@NoSelection@"); } this.result = returnsServiceFacade.createCustomerReturnInOutForHUs(husToReturn); return MSG_OK; } private Stream<HUEditorRow> streamEligibleSelectedRows() { return streamSelectedRows(ELIGIBLE_ROWS_FILTER); } private ImmutableList<I_M_HU> getSelectedHUsToReturn() { ImmutableList<I_M_HU> selectedHUsToReturn = this._selectedHUsToReturn;
if (selectedHUsToReturn == null) { final ImmutableSet<HuId> huIds = streamEligibleSelectedRows() .map(HUEditorRow::getHuId) .distinct() .collect(ImmutableSet.toImmutableSet()); selectedHUsToReturn = this._selectedHUsToReturn = ImmutableList.copyOf(handlingUnitsRepo.getByIds(huIds)); } return selectedHUsToReturn; } @Override protected void postProcess(final boolean success) { if (!success) { return; } final HashSet<HuId> huIdsToRefresh = new HashSet<>(); getSelectedHUsToReturn().stream() .map(hu -> HuId.ofRepoId(hu.getM_HU_ID())) .forEach(huIdsToRefresh::add); if (result != null) { huIdsToRefresh.addAll(result.getReturnedHUIds()); } addHUIdsAndInvalidateView(huIdsToRefresh); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnFromCustomer.java
1
请完成以下Java代码
public class ApiClient { private String name; private String url; private String key; public ApiClient(String name, String url, String key) { this.name = name; this.url = url; this.key = key; } public ApiClient() { } public String getName() { return name; } public String getUrl() { return url; } public String getKey() { return key; }
public String getConnectionProperties() { return "Connecting to " + name + " at " + url; } public void setName(String name) { this.name = name; } public void setUrl(String url) { this.url = url; } public void setKey(String key) { this.key = key; } }
repos\tutorials-master\spring-di-4\src\main\java\com\baeldung\registrypostprocessor\bean\ApiClient.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String code) { this.title = code; }
public String getBody() { return body; } public void setBody(String body) { this.body = body; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\querydsl\intro\entities\BlogPost.java
1
请完成以下Java代码
public class ConnectionCheck { public static MongoClient checkingConnection() { MongoClientSettings settings = MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress("localhost", 27017)))) .applyToConnectionPoolSettings(builder -> { builder.maxSize(100); builder.maxWaitTime(60000, TimeUnit.MILLISECONDS); }) .applyToSocketSettings(builder -> { builder.connectTimeout(1500,TimeUnit.MILLISECONDS); builder.readTimeout(60000,TimeUnit.MILLISECONDS); }) .build(); MongoClient mongoClient = MongoClients.create(settings); try { System.out.println("MongoDB Server is Up"); MongoDatabase database = mongoClient.getDatabase("baeldung"); Document stats = database.runCommand(new Document("dbStats", 1)); System.out.println(stats.toJson());
} catch (Exception e) { System.out.println("MongoDB Server is Down"); e.printStackTrace(); } return mongoClient; } public static void main(String[] args) { // // Connection check // checkingConnection(); } }
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\connectioncheck\ConnectionCheck.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomMessageToMFRouteBuilder extends RouteBuilder { public final static String CUSTOM_TO_MF_ROUTE_ID = "RabbitMQ_custom_to_MF_ID"; @Override public void configure() { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(direct(MF_ERROR_ROUTE_ID)); from(direct(CUSTOM_TO_MF_ROUTE_ID)) .routeId(CUSTOM_TO_MF_ROUTE_ID) .group(CamelRoutesGroup.ALWAYS_ON.getCode()) .streamCache("true")
.log("Invoked - requesting http auth token from MF.") .process(this::postAuthorizationMessage) .marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonExternalSystemMessage.class)) .to(CUSTOM_TO_MF_ROUTE); } private void postAuthorizationMessage(@NonNull final Exchange exchange) { final JsonExternalSystemMessage message = JsonExternalSystemMessage.builder() .type(JsonExternalSystemMessageType.REQUEST_AUTHORIZATION) .build(); exchange.getIn().setBody(message); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\authorization\CustomMessageToMFRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public class GeocodingConfigRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<Integer, Optional<GeocodingConfig>> cache = CCache.<Integer, Optional<GeocodingConfig>>builder() .tableName(I_GeocodingConfig.Table_Name) .build(); public Optional<GeocodingConfig> getGeocodingConfig() { return cache.getOrLoad(0, this::retrieveGeocodingConfig); } private Optional<GeocodingConfig> retrieveGeocodingConfig() { final I_GeocodingConfig record = queryBL.createQueryBuilderOutOfTrx(I_GeocodingConfig.class) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_GeocodingConfig.class); return toGeocodingConfig(record); } private static Optional<GeocodingConfig> toGeocodingConfig(@Nullable final I_GeocodingConfig record) { if (record == null) { return Optional.empty(); } final GeocodingProviderName providerName = GeocodingProviderName.ofNullableCode(record.getGeocodingProvider()); final GoogleMapsConfig googleMapsConfig; final OpenStreetMapsConfig openStreetMapsConfig; if (providerName == null) {
return Optional.empty(); } else if (GeocodingProviderName.GOOGLE_MAPS.equals(providerName)) { googleMapsConfig = GoogleMapsConfig.builder() .apiKey(record.getgmaps_ApiKey()) .cacheCapacity(record.getcacheCapacity()) .build(); openStreetMapsConfig = null; } else if (GeocodingProviderName.OPEN_STREET_MAPS.equals(providerName)) { googleMapsConfig = null; openStreetMapsConfig = OpenStreetMapsConfig.builder() .baseURL(record.getosm_baseURL()) .millisBetweenRequests(record.getosm_millisBetweenRequests()) .cacheCapacity(record.getcacheCapacity()) .build(); } else { throw new AdempiereException("Unknown provider: " + providerName); } final GeocodingConfig geocodingConfig = GeocodingConfig.builder() .providerName(providerName) .googleMapsConfig(googleMapsConfig) .openStreetMapsConfig(openStreetMapsConfig) .build(); return Optional.of(geocodingConfig); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\GeocodingConfigRepository.java
2
请完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; }
public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getZone() { return zone; } public void setZone(String zone) { this.zone = zone; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\entities\Persons.java
1
请在Spring Boot框架中完成以下Java代码
public Rating createRating(Rating rating) { Rating newRating = new Rating(); newRating.setBookId(rating.getBookId()); newRating.setStars(rating.getStars()); Rating persisted = ratingRepository.save(newRating); cacheRepository.createRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public void deleteRating(Long ratingId) { ratingRepository.deleteById(ratingId); cacheRepository.deleteRating(ratingId); } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Map<String, String> updates, Long ratingId) { final Rating rating = findRatingById(ratingId); updates.keySet() .forEach(key -> {
switch (key) { case "stars": rating.setStars(Integer.parseInt(updates.get(key))); break; } }); Rating persisted = ratingRepository.save(rating); cacheRepository.updateRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Rating rating, Long ratingId) { Preconditions.checkNotNull(rating); Preconditions.checkState(rating.getId() == ratingId); Preconditions.checkNotNull(ratingRepository.findById(ratingId)); return ratingRepository.save(rating); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingService.java
2
请完成以下Java代码
public void setWebParam1 (String WebParam1) { set_Value (COLUMNNAME_WebParam1, WebParam1); } /** Get Web Parameter 1. @return Web Site Parameter 1 (default: header image) */ public String getWebParam1 () { return (String)get_Value(COLUMNNAME_WebParam1); } /** Set Web Parameter 2. @param WebParam2 Web Site Parameter 2 (default index page) */ public void setWebParam2 (String WebParam2) { set_Value (COLUMNNAME_WebParam2, WebParam2); } /** Get Web Parameter 2. @return Web Site Parameter 2 (default index page) */ public String getWebParam2 () { return (String)get_Value(COLUMNNAME_WebParam2); } /** Set Web Parameter 3. @param WebParam3 Web Site Parameter 3 (default left - menu) */ public void setWebParam3 (String WebParam3) { set_Value (COLUMNNAME_WebParam3, WebParam3);
} /** Get Web Parameter 3. @return Web Site Parameter 3 (default left - menu) */ public String getWebParam3 () { return (String)get_Value(COLUMNNAME_WebParam3); } /** Set Web Parameter 4. @param WebParam4 Web Site Parameter 4 (default footer left) */ public void setWebParam4 (String WebParam4) { set_Value (COLUMNNAME_WebParam4, WebParam4); } /** Get Web Parameter 4. @return Web Site Parameter 4 (default footer left) */ public String getWebParam4 () { return (String)get_Value(COLUMNNAME_WebParam4); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Advertisement.java
1
请在Spring Boot框架中完成以下Java代码
static class JacksonWebSocketMessageConverterConfiguration implements WebSocketMessageBrokerConfigurer { private final JsonMapper jsonMapper; JacksonWebSocketMessageConverterConfiguration(JsonMapper jsonMapper) { this.jsonMapper = jsonMapper; } @Override public boolean configureMessageConverters(List<MessageConverter> messageConverters) { JacksonJsonMessageConverter converter = new JacksonJsonMessageConverter(this.jsonMapper); DefaultContentTypeResolver resolver = new DefaultContentTypeResolver(); resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON); converter.setContentTypeResolver(resolver); messageConverters.add(converter); return false; } } @Order(1) @Configuration(proxyBeanMethods = false) @Deprecated(since = "4.0.0", forRemoval = true) @SuppressWarnings("removal") @Conditional(NoJacksonOrJackson2Preferred.class) @ConditionalOnClass(ObjectMapper.class) static class Jackson2WebSocketMessageConverterConfiguration implements WebSocketMessageBrokerConfigurer { private final ObjectMapper objectMapper; Jackson2WebSocketMessageConverterConfiguration(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public boolean configureMessageConverters(List<MessageConverter> messageConverters) { org.springframework.messaging.converter.MappingJackson2MessageConverter converter = new org.springframework.messaging.converter.MappingJackson2MessageConverter( this.objectMapper); DefaultContentTypeResolver resolver = new DefaultContentTypeResolver(); resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON); converter.setContentTypeResolver(resolver); messageConverters.add(converter); return false; }
} static class NoJacksonOrJackson2Preferred extends AnyNestedCondition { NoJacksonOrJackson2Preferred() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper") static class NoJackson { } @ConditionalOnProperty(name = "spring.websocket.messaging.preferred-json-mapper", havingValue = "jackson2") static class Jackson2Preferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-websocket\src\main\java\org\springframework\boot\websocket\autoconfigure\servlet\WebSocketMessagingAutoConfiguration.java
2
请完成以下Java代码
public CloseableHttpClient build(@Nullable HttpClientSettings settings) { settings = (settings != null) ? settings : HttpClientSettings.defaults(); HttpClientBuilder builder = HttpClientBuilder.create() .useSystemProperties() .setRedirectStrategy(HttpComponentsRedirectStrategy.get(settings.redirects())) .setConnectionManager(createConnectionManager(settings)) .setDefaultRequestConfig(createDefaultRequestConfig()); this.customizer.accept(builder); return builder.build(); } private PoolingHttpClientConnectionManager createConnectionManager(HttpClientSettings settings) { PoolingHttpClientConnectionManagerBuilder builder = PoolingHttpClientConnectionManagerBuilder.create() .useSystemProperties(); PropertyMapper map = PropertyMapper.get(); builder.setDefaultSocketConfig(createSocketConfig()); builder.setDefaultConnectionConfig(createConnectionConfig(settings)); map.from(settings::sslBundle) .always() .as(this.tlsSocketStrategyFactory::getTlsSocketStrategy) .to(builder::setTlsSocketStrategy); this.connectionManagerCustomizer.accept(builder); return builder.build(); } private SocketConfig createSocketConfig() { SocketConfig.Builder builder = SocketConfig.custom(); this.socketConfigCustomizer.accept(builder); return builder.build(); } private ConnectionConfig createConnectionConfig(HttpClientSettings settings) { ConnectionConfig.Builder builder = ConnectionConfig.custom(); PropertyMapper map = PropertyMapper.get(); map.from(settings::connectTimeout) .as(Duration::toMillis)
.to((timeout) -> builder.setConnectTimeout(timeout, TimeUnit.MILLISECONDS)); map.from(settings::readTimeout) .asInt(Duration::toMillis) .to((timeout) -> builder.setSocketTimeout(timeout, TimeUnit.MILLISECONDS)); this.connectionConfigCustomizer.accept(builder); return builder.build(); } private RequestConfig createDefaultRequestConfig() { RequestConfig.Builder builder = RequestConfig.custom(); this.defaultRequestConfigCustomizer.accept(builder); return builder.build(); } /** * Factory that can be used to optionally create a {@link TlsSocketStrategy} given an * {@link SslBundle}. * * @since 4.0.0 */ public interface TlsSocketStrategyFactory { /** * Return the {@link TlsSocketStrategy} to use for the given bundle. * @param sslBundle the SSL bundle or {@code null} * @return the {@link TlsSocketStrategy} to use or {@code null} */ @Nullable TlsSocketStrategy getTlsSocketStrategy(@Nullable SslBundle sslBundle); } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\HttpComponentsHttpClientBuilder.java
1
请完成以下Java代码
private I_C_Order createOrder(final PurchaseCandidate candidate) { final int adOrgId = candidate.getAD_Org_ID(); final int warehouseId = candidate.getM_Warehouse_ID(); final I_C_BPartner bpartner = bpartnersRepo.getById(candidate.getC_BPartner_ID()); final int pricingSystemId = candidate.getM_PricingSystem_ID(); // the price is taken from the candidates and C_OrderLine.IsManualPrice is set to 'Y' // gh #1088 I have no clue wtf the comment above "the price is taken from..." is supposed to mean. // So instead of using M_PriceList_ID_None here, we use the candidate's PL. // Because otherwise, de.metas.order.model.interceptor.C_Order#onPriceListChangeInterceptor(...) will update the order pricing system to M_PricingSystem_ID_None // and then the system won't be able to get the new order lines' C_TaxCategories and MOrderLine.beforeSave() will fail // final int priceListId = MPriceList.M_PriceList_ID_None; final int priceListId = candidate.getM_PriceList_ID(); final int currencyId = candidate.getC_Currency_ID(); final Timestamp datePromised = candidate.getDatePromised(); final Timestamp dateOrdered = TimeUtil.min(SystemTime.asDayTimestamp(), datePromised); final I_C_Order order = InterfaceWrapperHelper.newInstance(I_C_Order.class); // // Doc type order.setAD_Org_ID(adOrgId); order.setIsSOTrx(false); orderBL.setDefaultDocTypeTargetId(order); // // Warehouse order.setM_Warehouse_ID(warehouseId); // // BPartner orderBL.setBPartner(order, bpartner); orderBL.setBill_User_ID(order); // // Dates order.setDateOrdered(dateOrdered); order.setDateAcct(dateOrdered); order.setDatePromised(datePromised); // // Price list if (pricingSystemId > 0) { order.setM_PricingSystem_ID(pricingSystemId); } if (priceListId > 0) { order.setM_PriceList_ID(priceListId); }
order.setC_Currency_ID(currencyId); // // SalesRep: // * let it to be set from BPartner (this was done above, by orderBL.setBPartner method) // * if not set use it from context final Properties ctx = InterfaceWrapperHelper.getCtx(order); if (order.getSalesRep_ID() <= 0) { order.setSalesRep_ID(Env.getContextAsInt(ctx, Env.CTXNAME_SalesRep_ID)); } if (order.getSalesRep_ID() <= 0) { order.setSalesRep_ID(Env.getAD_User_ID(ctx)); } order.setDocStatus(DocStatus.Drafted.getCode()); order.setDocAction(IDocument.ACTION_Complete); // // Save & return InterfaceWrapperHelper.save(order); return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrderHeaderAggregation.java
1
请完成以下Java代码
void choose_smartly(int ndocs, List<Document> docs) { int siz = size(); double[] closest = new double[siz]; if (siz < ndocs) ndocs = siz; int index, count = 0; index = random.nextInt(siz); // initial center docs.add(documents_.get(index)); ++count; double potential = 0.0; for (int i = 0; i < documents_.size(); i++) { double dist = 1.0 - SparseVector.inner_product(documents_.get(i).feature(), documents_.get(index).feature()); potential += dist; closest[i] = dist; } // choose each center while (count < ndocs) { double randval = random.nextDouble() * potential; for (index = 0; index < documents_.size(); index++) { double dist = closest[index]; if (randval <= dist) break; randval -= dist; } if (index == documents_.size()) index--; docs.add(documents_.get(index)); ++count; double new_potential = 0.0; for (int i = 0; i < documents_.size(); i++) { double dist = 1.0 - SparseVector.inner_product(documents_.get(i).feature(), documents_.get(index).feature()); double min = closest[i]; if (dist < min) { closest[i] = dist; min = dist; } new_potential += min; } potential = new_potential; } } /** * 将本簇划分为nclusters个簇 * * @param nclusters
*/ void section(int nclusters) { if (size() < nclusters) throw new IllegalArgumentException("簇数目小于文档数目"); sectioned_clusters_ = new ArrayList<Cluster<K>>(nclusters); List<Document> centroids = new ArrayList<Document>(nclusters); // choose_randomly(nclusters, centroids); choose_smartly(nclusters, centroids); for (int i = 0; i < centroids.size(); i++) { Cluster<K> cluster = new Cluster<K>(); sectioned_clusters_.add(cluster); } for (Document<K> d : documents_) { double max_similarity = -1.0; int max_index = 0; for (int j = 0; j < centroids.size(); j++) { double similarity = SparseVector.inner_product(d.feature(), centroids.get(j).feature()); if (max_similarity < similarity) { max_similarity = similarity; max_index = j; } } sectioned_clusters_.get(max_index).add_document(d); } } @Override public int compareTo(Cluster<K> o) { return Double.compare(o.sectioned_gain(), sectioned_gain()); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\Cluster.java
1
请在Spring Boot框架中完成以下Java代码
public List<T> saveAll(List<T> rules) { // TODO: check here. allRules.clear(); machineRules.clear(); appRules.clear(); if (rules == null) { return null; } List<T> savedRules = new ArrayList<>(rules.size()); for (T rule : rules) { savedRules.add(save(rule)); } return savedRules; } @Override public T delete(Long id) { T entity = allRules.remove(id); if (entity != null) { if (appRules.get(entity.getApp()) != null) { appRules.get(entity.getApp()).remove(id); } machineRules.get(MachineInfo.of(entity.getApp(), entity.getIp(), entity.getPort())).remove(id); } return entity; } @Override public T findById(Long id) { return allRules.get(id); } @Override public List<T> findAllByMachine(MachineInfo machineInfo) { Map<Long, T> entities = machineRules.get(machineInfo); if (entities == null) { return new ArrayList<>(); } return new ArrayList<>(entities.values()); } @Override public List<T> findAllByApp(String appName) {
AssertUtil.notEmpty(appName, "appName cannot be empty"); Map<Long, T> entities = appRules.get(appName); if (entities == null) { return new ArrayList<>(); } return new ArrayList<>(entities.values()); } public void clearAll() { allRules.clear(); machineRules.clear(); appRules.clear(); } protected T preProcess(T entity) { return entity; } /** * Get next unused id. * * @return next unused id */ abstract protected long nextId(); }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\repository\rule\InMemoryRuleRepositoryAdapter.java
2