instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setMetasfreshBPartnerId(final JsonMetasfreshId metasfreshBPartnerId) { this.metasfreshBPartnerId = metasfreshBPartnerId; this.metasfreshBPartnerIdSet = true; } public void setBirthday(final LocalDate birthday) { this.birthday = birthday; this.birthdaySet = true; } public void setInvoiceEmailEnabled(@Nullable final Boolean invoiceEmailEnabled) { this.invoiceEmailEnabled = invoiceEmailEnabled;
invoiceEmailEnabledSet = true; } public void setTitle(final String title) { this.title = title; this.titleSet = true; } public void setPhone2(final String phone2) { this.phone2 = phone2; this.phone2Set = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestContact.java
1
请完成以下Java代码
public final class ClearSiteDataServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; private final StaticServerHttpHeadersWriter headerWriterDelegate; /** * <p> * Constructs a new instance using the given directives. * </p> * @param directives directives that will be written as the header value * @throws IllegalArgumentException if the argument is null or empty */ public ClearSiteDataServerHttpHeadersWriter(Directive... directives) { Assert.notEmpty(directives, "directives cannot be empty or null"); this.headerWriterDelegate = StaticServerHttpHeadersWriter.builder() .header(CLEAR_SITE_DATA_HEADER, transformToHeaderValue(directives)) .build(); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { if (isSecure(exchange)) { return this.headerWriterDelegate.writeHttpHeaders(exchange); } return Mono.empty(); } /** * <p> * Represents the directive values expected by the * {@link ClearSiteDataServerHttpHeadersWriter} * </p> * . */ public enum Directive { CACHE("cache"), COOKIES("cookies"), STORAGE("storage"), EXECUTION_CONTEXTS("executionContexts"),
ALL("*"); private final String headerValue; Directive(String headerValue) { this.headerValue = "\"" + headerValue + "\""; } public String getHeaderValue() { return this.headerValue; } } private String transformToHeaderValue(Directive... directives) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); } private boolean isSecure(ServerWebExchange exchange) { String scheme = exchange.getRequest().getURI().getScheme(); return scheme != null && scheme.equalsIgnoreCase("https"); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\ClearSiteDataServerHttpHeadersWriter.java
1
请完成以下Spring Boot application配置
server: port: 8082 spring: application: name: Server-Provider eureka: client: register-with-eureka: true fetch-registry: true serviceUrl: defaultZone:
http://mrbird:123456@peer1:8080/eureka/,http://mrbird:123456@peer2:8081/eureka/
repos\SpringAll-master\28.Spring-Cloud-Eureka-Server-Discovery\Eureka-Client\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public java.lang.String getPOSPaymentProcessingSummary() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessingSummary); } @Override public void setPOSPaymentProcessing_TrxId (final @Nullable java.lang.String POSPaymentProcessing_TrxId) { set_Value (COLUMNNAME_POSPaymentProcessing_TrxId, POSPaymentProcessing_TrxId); } @Override public java.lang.String getPOSPaymentProcessing_TrxId() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessing_TrxId); } /** * POSPaymentProcessor AD_Reference_ID=541896 * Reference name: POSPaymentProcessor */ public static final int POSPAYMENTPROCESSOR_AD_Reference_ID=541896; /** SumUp = sumup */ public static final String POSPAYMENTPROCESSOR_SumUp = "sumup"; @Override public void setPOSPaymentProcessor (final @Nullable java.lang.String POSPaymentProcessor) { set_Value (COLUMNNAME_POSPaymentProcessor, POSPaymentProcessor); }
@Override public java.lang.String getPOSPaymentProcessor() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessor); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Payment.java
2
请完成以下Java代码
public void deleteIdentityLink(TaskEntity taskEntity, String userId, String groupId, String type) { List<IdentityLinkEntity> identityLinks = findIdentityLinkByTaskUserGroupAndType( taskEntity.getId(), userId, groupId, type ); List<String> identityLinkIds = new ArrayList<String>(); for (IdentityLinkEntity identityLink : identityLinks) { deleteIdentityLink(identityLink, true); identityLinkIds.add(identityLink.getId()); } // fix deleteCandidate() in create TaskListener List<IdentityLinkEntity> removedIdentityLinkEntities = new ArrayList<IdentityLinkEntity>(); for (IdentityLinkEntity identityLinkEntity : taskEntity.getIdentityLinks()) { if ( IdentityLinkType.CANDIDATE.equals(identityLinkEntity.getType()) && identityLinkIds.contains(identityLinkEntity.getId()) == false ) { if ( (userId != null && userId.equals(identityLinkEntity.getUserId())) || (groupId != null && groupId.equals(identityLinkEntity.getGroupId())) ) { deleteIdentityLink(identityLinkEntity, true); removedIdentityLinkEntities.add(identityLinkEntity); } } } taskEntity.getIdentityLinks().removeAll(removedIdentityLinkEntities); } @Override public void deleteIdentityLink(ProcessDefinitionEntity processDefinitionEntity, String userId, String groupId) { List<IdentityLinkEntity> identityLinks = findIdentityLinkByProcessDefinitionUserAndGroup( processDefinitionEntity.getId(), userId, groupId ); for (IdentityLinkEntity identityLink : identityLinks) { deleteIdentityLink(identityLink, false); } }
@Override public void deleteIdentityLinksByTaskId(String taskId) { List<IdentityLinkEntity> identityLinks = findIdentityLinksByTaskId(taskId); for (IdentityLinkEntity identityLink : identityLinks) { deleteIdentityLink(identityLink, false); } } @Override public void deleteIdentityLinksByProcDef(String processDefId) { identityLinkDataManager.deleteIdentityLinksByProcDef(processDefId); } public IdentityLinkDataManager getIdentityLinkDataManager() { return identityLinkDataManager; } public void setIdentityLinkDataManager(IdentityLinkDataManager identityLinkDataManager) { this.identityLinkDataManager = identityLinkDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityManagerImpl.java
1
请完成以下Java代码
public void setId(String id) { // Set id doesn't do anything: auto incremented column } @Override public Object getPersistentState() { return null; // Not updatable } @Override public long getLogNumber() { return logNumber; } public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Override public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public byte[] getData() {
return data; } public void setData(byte[] data) { this.data = data; } public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public String getLockTime() { return lockTime; } public void setLockTime(String lockTime) { this.lockTime = lockTime; } public int getProcessed() { return isProcessed; } public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntity.java
1
请完成以下Java代码
public void updateProductPrice(@PathVariable final Integer productId, @PathVariable String storeId, @RequestBody UpdatePriceDto priceDto) { storeService.updateProductPrice(productId, priceDto.price); } @GetMapping("/products/{productId}/changes") public String getProductChanges(@PathVariable int productId) { Product product = storeService.findProductById(productId); QueryBuilder jqlQuery = QueryBuilder.byInstance(product); Changes changes = javers.findChanges(jqlQuery.build()); return javers.getJsonConverter().toJson(changes); } @GetMapping("/products/snapshots") public String getProductSnapshots() { QueryBuilder jqlQuery = QueryBuilder.byClass(Product.class); List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build()); return javers.getJsonConverter().toJson(snapshots); }
@GetMapping("/stores/{storeId}/shadows") public String getStoreShadows(@PathVariable int storeId) { Store store = storeService.findStoreById(storeId); JqlQuery jqlQuery = QueryBuilder.byInstance(store) .withChildValueObjects().build(); List<Shadow<Store>> shadows = javers.findShadows(jqlQuery); return javers.getJsonConverter().toJson(shadows.get(0)); } @GetMapping("/stores/snapshots") public String getStoresSnapshots() { QueryBuilder jqlQuery = QueryBuilder.byClass(Store.class); List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build()); return javers.getJsonConverter().toJson(snapshots); } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\web\StoreController.java
1
请完成以下Java代码
public SecurityContext createEmptyContext() { return this.delegate.createEmptyContext(); } private void publish(SecurityContextChangedEvent event) { for (SecurityContextChangedListener listener : this.listeners) { listener.securityContextChanged(event); } } class PublishOnceSupplier implements Supplier<SecurityContext> { private final AtomicBoolean isPublished = new AtomicBoolean(false); private final Supplier<SecurityContext> old; private final Supplier<SecurityContext> updated; PublishOnceSupplier(Supplier<SecurityContext> old, Supplier<SecurityContext> updated) { if (old instanceof PublishOnceSupplier) { this.old = ((PublishOnceSupplier) old).updated;
} else { this.old = old; } this.updated = updated; } @Override public SecurityContext get() { SecurityContext updated = this.updated.get(); if (this.isPublished.compareAndSet(false, true)) { SecurityContext old = this.old.get(); if (old != updated) { publish(new SecurityContextChangedEvent(old, updated)); } } return updated; } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\ListeningSecurityContextHolderStrategy.java
1
请完成以下Spring Boot application配置
saml.keystore.location=classpath:/saml/saml-keystore.jks # Password for Java keystore and item therein saml.keystore.password=baeldungsamlokta saml.keystore.alias=baeldungspringsaml # SAML Entity ID extracted from top of SAML metadata file saml.idp=http://www.ok
ta.com/exk26fxqrz8LLk9dV4x7 saml.sp=http://localhost:8080/saml/metadata spring.main.allow-circular-references=true
repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class AlbertaPatient { @Nullable BPartnerAlbertaPatientId bPartnerAlbertaPatientId; @NonNull BPartnerId bPartnerId; @Nullable BPartnerId hospitalId; @Nullable LocalDate dischargeDate; @Nullable BPartnerId payerId; @Nullable PayerType payerType; @Nullable String numberOfInsured; @Nullable LocalDate copaymentFrom; @Nullable LocalDate copaymentTo; boolean isTransferPatient; boolean isIVTherapy; @Nullable UserId fieldNurseId; @Nullable DeactivationReasonType deactivationReason; @Nullable LocalDate deactivationDate; @Nullable String deactivationComment; @Nullable
String classification; @Nullable BigDecimal careDegree; @Nullable Instant createdAt; @Nullable UserId createdById; @Nullable Instant updatedAt; @Nullable UserId updatedById; public BPartnerAlbertaPatientId getIdNotNull() { if (bPartnerAlbertaPatientId == null) { throw new AdempiereException("getIdNotNull should be called only for persisted records"); } return bPartnerAlbertaPatientId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\patient\AlbertaPatient.java
2
请完成以下Spring Boot application配置
## Server properties server: port: 8080 ## Primary/Target Database Properties spring: datasource: url: jdbc:mysql://localhost:3306/customerdb username: root password: root jpa.hibernate.ddl-auto: create-drop jpa.show-sql: true ## Source Database Properties customer: datasource: host: localhost port: 3305 database: customerdb username: root password: root ## Logging pr
operties logging: level: root: INFO io: debezium: mysql: BinlogReader: INFO com: baeldung: libraries: debezium: DEBUG
repos\tutorials-master\libraries-data-db\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public ITrxManager trxManager() { return Services.get(ITrxManager.class); } @Bean public IQueryBL queryBL() { return Services.get(IQueryBL.class); } @Bean public ImportQueue<ImportTimeBookingInfo> timeBookingImportQueue() { return new ImportQueue<>(TIME_BOOKING_QUEUE_CAPACITY, IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX); } @Bean
public ImportQueue<ImportIssueInfo> importIssuesQueue() { return new ImportQueue<>(ISSUE_QUEUE_CAPACITY, IMPORT_LOG_MESSAGE_PREFIX); } @Bean public ObjectMapper objectMapper() { return JsonObjectMapperHolder.sharedJsonObjectMapper(); } @Bean public IMsgBL msgBL() { return Services.get(IMsgBL.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\configuration\ApplicationConfiguration.java
2
请完成以下Java代码
public final Builder addAccess(final Access access) { accesses.add(access); return this; } public final Builder removeAccess(final Access access) { accesses.remove(access); return this; } public final Builder setAccesses(final Set<Access> acceses) { accesses.clear(); accesses.addAll(acceses);
return this; } public final Builder addAccesses(final Set<Access> acceses) { accesses.addAll(acceses); return this; } public final Builder removeAllAccesses() { accesses.clear(); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java
1
请完成以下Java代码
public void updateHandoverLocationOverride(@NonNull final I_C_OLCand olCand) { try (final MDC.MDCCloseable ignore = TableRecordMDC.putTableRecordReference(olCand)) { setHandOverLocationOverride(olCand, computeHandoverLocationOverride(olCand)); } } private I_C_BPartner_Location computeHandoverLocationOverride(@NonNull final I_C_OLCand olCand) { final BPartnerId handOverPartnerOverrideId = BPartnerId.ofRepoIdOrNull(olCand.getHandOver_Partner_Override_ID()); if (handOverPartnerOverrideId == null) { // in case the handover bpartner Override was deleted, also delete the handover Location Override return null; } else { final I_C_BPartner partner = olCandEffectiveValuesBL.getC_BPartner_Effective(olCand); final I_C_BPartner handoverPartnerOverride = bPartnerDAO.getById(handOverPartnerOverrideId); final I_C_BP_Relation handoverRelation = bpRelationDAO.retrieveHandoverBPRelation(partner, handoverPartnerOverride); if (handoverRelation == null)
{ // this shall never happen, since both Handover_BPartner and Handover_BPartner_Override must come from such a bpp relation. // but I will leave this condition here as extra safety return null; } else { final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(handoverRelation.getC_BPartnerRelation_ID(), handoverRelation.getC_BPartnerRelation_Location_ID()); return bPartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId); } } } private static void setHandOverLocationOverride( @NonNull final I_C_OLCand olCand, @Nullable final I_C_BPartner_Location handOverLocation) { olCand.setHandOver_Location_Override_ID(handOverLocation != null ? handOverLocation.getC_BPartner_Location_ID() : -1); olCand.setHandOver_Location_Override_Value_ID(handOverLocation != null ? handOverLocation.getC_Location_ID() : -1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\OLCandLocationsUpdaterService.java
1
请完成以下Java代码
public I_M_Product getM_Product() { final IProductBL productBL = Services.get(IProductBL.class); return productBL.getById(ProductId.ofRepoId(ddOrderLine.getM_Product_ID())); } @Override public int getM_Product_ID() { return ddOrderLine.getM_Product_ID(); } @Override public I_M_AttributeSetInstance getM_AttributeSetInstance() { return isASITo ? ddOrderLine.getM_AttributeSetInstanceTo() : ddOrderLine.getM_AttributeSetInstance(); } @Override public int getM_AttributeSetInstance_ID() { return isASITo ? ddOrderLine.getM_AttributeSetInstanceTo_ID() : ddOrderLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi) { if (isASITo) { ddOrderLine.setM_AttributeSetInstanceTo(asi); }
else { ddOrderLine.setM_AttributeSetInstance(asi); } } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { if (isASITo) { ddOrderLine.setM_AttributeSetInstanceTo_ID(M_AttributeSetInstance_ID); } else { ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\producer\DDOrderLineAttributeSetInstanceAware.java
1
请完成以下Java代码
public AbstractServiceConfiguration<S> setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } public List<EventDispatchAction> getAdditionalEventDispatchActions() { return additionalEventDispatchActions; } public AbstractServiceConfiguration<S> setAdditionalEventDispatchActions(List<EventDispatchAction> additionalEventDispatchActions) { this.additionalEventDispatchActions = additionalEventDispatchActions; return this; } public ObjectMapper getObjectMapper() { return objectMapper; } public AbstractServiceConfiguration<S> setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper;
return this; } public Clock getClock() { return clock; } public AbstractServiceConfiguration<S> setClock(Clock clock) { this.clock = clock; return this; } public IdGenerator getIdGenerator() { return idGenerator; } public AbstractServiceConfiguration<S> setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; return this; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractServiceConfiguration.java
1
请完成以下Java代码
public String getId() { return id; } public boolean isQueryByPermission() { return queryByPermission; } public String[] getUserIds() { return userIds; } public String[] getGroupIds() { return groupIds; } public int getResourceType() { return resourceType; } public String getResourceId() { return resourceId; } public int getPermission() { return permission; } public boolean isQueryByResourceType() { return queryByResourceType; }
public Set<Resource> getResourcesIntersection() { return resourcesIntersection; } public AuthorizationQuery orderByResourceType() { orderBy(AuthorizationQueryProperty.RESOURCE_TYPE); return this; } public AuthorizationQuery orderByResourceId() { orderBy(AuthorizationQueryProperty.RESOURCE_ID); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AuthorizationQueryImpl.java
1
请完成以下Java代码
public ZebraConfigId getDefaultZebraConfigId() { final ZebraConfigId defaultZebraConfigId = queryBL .createQueryBuilderOutOfTrx(I_AD_Zebra_Config.class) .addEqualsFilter(I_AD_Zebra_Config.COLUMNNAME_IsDefault, true) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .create() .firstId(ZebraConfigId::ofRepoIdOrNull); if (defaultZebraConfigId == null) { throw new AdempiereException(MSG_NO_ZEBRA_CONFIG); } return defaultZebraConfigId; }
public ZebraConfigId retrieveZebraConfigId(final BPartnerId partnerId, final ZebraConfigId defaultZebraConfigId) { final I_C_BP_PrintFormat printFormat = queryBL .createQueryBuilder(I_C_BP_PrintFormat.class) .addEqualsFilter(I_C_BP_PrintFormat.COLUMNNAME_C_BPartner_ID, partnerId) .addNotNull(I_C_BP_PrintFormat.COLUMN_AD_Zebra_Config_ID) .create() .firstOnly(I_C_BP_PrintFormat.class); if (printFormat != null) { return ZebraConfigId.ofRepoIdOrNull(printFormat.getAD_Zebra_Config_ID()); } return defaultZebraConfigId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\ZebraConfigRepository.java
1
请完成以下Java代码
public List<String> getInputVariables() { return inputVariables; } public void setInputVariables(List<String> inputVariables) { this.inputVariables = inputVariables; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; }
public BusinessRuleTask clone() { BusinessRuleTask clone = new BusinessRuleTask(); clone.setValues(this); return clone; } public void setValues(BusinessRuleTask otherElement) { super.setValues(otherElement); setResultVariableName(otherElement.getResultVariableName()); setExclude(otherElement.isExclude()); setClassName(otherElement.getClassName()); ruleNames = new ArrayList<String>(otherElement.getRuleNames()); inputVariables = new ArrayList<String>(otherElement.getInputVariables()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BusinessRuleTask.java
1
请完成以下Java代码
public boolean isOne() {return intValue == 1;} public QtyTU add(@NonNull final QtyTU toAdd) { if (this.intValue == 0) { return toAdd; } else if (toAdd.intValue == 0) { return this; } else { return ofInt(this.intValue + toAdd.intValue); } } public QtyTU subtractOrZero(@NonNull final QtyTU toSubtract) { if (toSubtract.intValue == 0) { return this; } else { return ofInt(Math.max(this.intValue - toSubtract.intValue, 0)); } } public QtyTU min(@NonNull final QtyTU other) { return this.intValue <= other.intValue ? this : other; }
public Quantity computeQtyCUsPerTUUsingTotalQty(@NonNull final Quantity qtyCUsTotal) { if (isZero()) { throw new AdempiereException("Cannot determine Qty CUs/TU when QtyTU is zero of total CUs " + qtyCUsTotal); } else if (isOne()) { return qtyCUsTotal; } else { return qtyCUsTotal.divide(toInt()); } } public Quantity computeTotalQtyCUsUsingQtyCUsPerTU(@NonNull final Quantity qtyCUsPerTU) { return qtyCUsPerTU.multiply(toInt()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\QtyTU.java
1
请完成以下Java代码
public static StatusInfo ofOffline(@Nullable Map<String, Object> details) { return valueOf(STATUS_OFFLINE, details); } public Map<String, Object> getDetails() { return Collections.unmodifiableMap(details); } public boolean isUp() { return STATUS_UP.equals(status); } public boolean isOffline() { return STATUS_OFFLINE.equals(status); } public boolean isDown() { return STATUS_DOWN.equals(status); } public boolean isUnknown() { return STATUS_UNKNOWN.equals(status); } public static Comparator<String> severity() { return Comparator.comparingInt(STATUS_ORDER::indexOf); }
@SuppressWarnings("unchecked") public static StatusInfo from(Map<String, ?> body) { Map<String, ?> details = Collections.emptyMap(); /* * Key "details" is present when accessing Spring Boot Actuator Health using * Accept-Header {@link org.springframework.boot.actuate.endpoint.ApiVersion#V2}. */ if (body.containsKey("details")) { details = (Map<String, ?>) body.get("details"); } else if (body.containsKey("components")) { details = (Map<String, ?>) body.get("components"); } return StatusInfo.valueOf((String) body.get("status"), details); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\StatusInfo.java
1
请完成以下Java代码
public InputStream getAttachmentContent(String attachmentId) { return commandExecutor.execute(new GetAttachmentContentCmd(attachmentId)); } public InputStream getTaskAttachmentContent(String taskId, String attachmentId) { return commandExecutor.execute(new GetTaskAttachmentContentCmd(taskId, attachmentId)); } public void deleteAttachment(String attachmentId) { commandExecutor.execute(new DeleteAttachmentCmd(attachmentId)); } public void deleteTaskAttachment(String taskId, String attachmentId) { commandExecutor.execute(new DeleteAttachmentCmd(taskId, attachmentId)); } public Attachment getAttachment(String attachmentId) { return commandExecutor.execute(new GetAttachmentCmd(attachmentId)); } public Attachment getTaskAttachment(String taskId, String attachmentId) { return commandExecutor.execute(new GetTaskAttachmentCmd(taskId, attachmentId)); } public List<Attachment> getTaskAttachments(String taskId) { return commandExecutor.execute(new GetTaskAttachmentsCmd(taskId)); } public List<Attachment> getProcessInstanceAttachments(String processInstanceId) { return commandExecutor.execute(new GetProcessInstanceAttachmentsCmd(processInstanceId)); } public void saveAttachment(Attachment attachment) { commandExecutor.execute(new SaveAttachmentCmd(attachment)); } public List<Task> getSubTasks(String parentTaskId) { return commandExecutor.execute(new GetSubTasksCmd(parentTaskId)); } public TaskReport createTaskReport() {
return new TaskReportImpl(commandExecutor); } @Override public void handleBpmnError(String taskId, String errorCode) { commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode)); } @Override public void handleBpmnError(String taskId, String errorCode, String errorMessage) { commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage)); } @Override public void handleBpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) { commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage, variables)); } @Override public void handleEscalation(String taskId, String escalationCode) { commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode)); } @Override public void handleEscalation(String taskId, String escalationCode, Map<String, Object> variables) { commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode, variables)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskServiceImpl.java
1
请完成以下Java代码
public void run() { running = true; produce(); } public void stop() { running = false; } public void produce() { while (running) { if (dataQueue.isFull()) { try { dataQueue.waitIsNotFull(); } catch (InterruptedException e) { log.severe("Error while waiting to Produce messages."); break; } } // avoid spurious wake-up if (!running) { break; } dataQueue.add(generateMessage()); log.info("Size of the queue is: " + dataQueue.getSize());
//Sleeping on random time to make it realistic ThreadUtil.sleep((long) (Math.random() * 100)); } log.info("Producer Stopped"); } private Message generateMessage() { Message message = new Message(idSequence.incrementAndGet(), Math.random()); log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n", Thread.currentThread().getName(), message.getId(), message.getData())); return message; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\Producer.java
1
请完成以下Java代码
public String listAllTodos(ModelMap model) { String username = getLoggedInUsername(model); List<Todo> todos = todoService.findByUsername(username); model.addAttribute("todos", todos); return "listTodos"; } //GET, POST @RequestMapping(value="add-todo", method = RequestMethod.GET) public String showNewTodoPage(ModelMap model) { String username = getLoggedInUsername(model); Todo todo = new Todo(0, username, "", LocalDate.now().plusYears(1), false); model.put("todo", todo); return "todo"; } @RequestMapping(value="add-todo", method = RequestMethod.POST) public String addNewTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if(result.hasErrors()) { return "todo"; } String username = getLoggedInUsername(model); todoService.addTodo(username, todo.getDescription(), LocalDate.now().plusYears(1), false); return "redirect:list-todos"; } @RequestMapping("delete-todo") public String deleteTodo(@RequestParam int id) { //Delete todo todoService.deleteById(id); return "redirect:list-todos"; } @RequestMapping(value="update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam int id, ModelMap model) { Todo todo = todoService.findById(id); model.addAttribute("todo", todo); return "todo";
} @RequestMapping(value="update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if(result.hasErrors()) { return "todo"; } String username = getLoggedInUsername(model); todo.setUsername(username); todoService.updateTodo(todo); return "redirect:list-todos"; } private String getLoggedInUsername(ModelMap model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication.getName(); } }
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\TodoController.java
1
请完成以下Java代码
public void setKeepAliveTimeMillis (int KeepAliveTimeMillis) { set_Value (COLUMNNAME_KeepAliveTimeMillis, Integer.valueOf(KeepAliveTimeMillis)); } /** Get Keep Alive Time (millis). @return When the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. */ @Override public int getKeepAliveTimeMillis () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepAliveTimeMillis); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Pool Size. @param PoolSize The number of threads to keep in the pool, even if they are idle */ @Override public void setPoolSize (int PoolSize) { set_Value (COLUMNNAME_PoolSize, Integer.valueOf(PoolSize)); } /** Get Pool Size. @return The number of threads to keep in the pool, even if they are idle */ @Override public int getPoolSize () { Integer ii = (Integer)get_Value(COLUMNNAME_PoolSize); if (ii == null) return 0; return ii.intValue(); } /** * Priority AD_Reference_ID=154
* Reference name: _PriorityRule */ public static final int PRIORITY_AD_Reference_ID=154; /** High = 3 */ public static final String PRIORITY_High = "3"; /** Medium = 5 */ public static final String PRIORITY_Medium = "5"; /** Low = 7 */ public static final String PRIORITY_Low = "7"; /** Urgent = 1 */ public static final String PRIORITY_Urgent = "1"; /** Minor = 9 */ public static final String PRIORITY_Minor = "9"; /** Set Priority. @param Priority Indicates if this request is of a high, medium or low priority. */ @Override public void setPriority (java.lang.String Priority) { set_Value (COLUMNNAME_Priority, Priority); } /** Get Priority. @return Indicates if this request is of a high, medium or low priority. */ @Override public java.lang.String getPriority () { return (java.lang.String)get_Value(COLUMNNAME_Priority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor.java
1
请完成以下Java代码
public void updateEdiStatus(final I_C_Invoice document) { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(document)) { final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class); if (!ediDocumentBL.updateEdiEnabled(document)) { return; } final List<Exception> feedback = ediDocumentBL.isValidInvoice(document); final ValidationState validationState = ediDocumentBL.updateInvalid(document, document.getEDI_ExportStatus(), feedback, false); // saveLocally=false if (ValidationState.INVALID == validationState) { logger.debug("validationState={}; persisting error-message in C_Invoice", validationState); // document.setIsEdiEnabled(false); // DON'T set this to false, because then the "revalidate" button is also not available (displaylogic) // IsEdiEnabled means "enabled in general", not "valid document and can be send right now" final String errorMessage = ediDocumentBL.buildFeedback(feedback); document.setEDIErrorMsg(errorMessage); document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_Invalid); } } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_CHANGE_REPLICATION }, // ifColumnsChanged = I_C_Invoice.COLUMNNAME_EDI_ExportStatus) public void updateDocOutBoundLog(final I_C_Invoice invoiceRecord)
{ final TableRecordReference recordReference = TableRecordReference.of(invoiceRecord); final Optional<I_C_Doc_Outbound_Log> updatedDocOutboundLog = ediDocOutBoundLogService.setEdiExportStatusFromInvoiceRecord(recordReference); updatedDocOutboundLog.ifPresent(InterfaceWrapperHelper::saveRecord); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = I_C_Invoice.COLUMNNAME_EDIErrorMsg) public void translateEDIErrorMessage(final I_C_Invoice invoiceRecord) { final ITranslatableString errorMsgTrl = TranslatableStrings.parse(invoiceRecord.getEDIErrorMsg()); invoiceRecord.setEDIErrorMsg(errorMsgTrl.translate(Env.getAD_Language())); } @DocValidate(timings = ModelValidator.TIMING_BEFORE_REVERSECORRECT) public void forbiddReversal(final I_C_Invoice invoice) { final String ediStatus = invoice.getEDI_ExportStatus(); if (I_EDI_Document_Extension.EDI_EXPORTSTATUS_Sent.equals(ediStatus) || I_EDI_Document_Extension.EDI_EXPORTSTATUS_SendingStarted.equals(ediStatus) || I_EDI_Document_Extension.EDI_EXPORTSTATUS_Enqueued.equals(ediStatus)) { throw new AdempiereException(" EDI was already sent / enqueued. Can not reverse the invoice!") .appendParametersToMessage() .setParameter("invoice", invoice); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\C_Invoice.java
1
请完成以下Java代码
public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg toDeviceRequest) { logUnsupportedCommandMessage(toDeviceRequest); } @Override public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg toServerResponse) { logUnsupportedCommandMessage(toServerResponse); } private void logUnsupportedCommandMessage(Object update) { log.trace("[{}] Ignore unsupported update: {}", state.getDeviceId(), update); } public static boolean isConRequest(TbCoapObservationState state) { if (state != null) { return state.getExchange().advanced().getRequest().isConfirmable(); } else { return false; }
} public static boolean isMulticastRequest(TbCoapObservationState state) { if (state != null) { return state.getExchange().advanced().getRequest().isMulticast(); } return false; } protected void respond(Response response) { response.getOptions().setContentFormat(TbCoapContentFormatUtil.getContentFormat(exchange.getRequestOptions().getContentFormat(), state.getContentFormat())); response.setConfirmable(exchange.advanced().getRequest().isConfirmable()); exchange.respond(response); } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\callback\AbstractSyncSessionCallback.java
1
请在Spring Boot框架中完成以下Java代码
public class VaultK8SApplication { public static void main(String... args) { SpringApplication.run(VaultK8SApplication.class, args); } @Bean CommandLineRunner listSecrets(VaultTemplate vault) { return args -> { VaultKeyValueOperations ops = vault.opsForKeyValue("secrets", VaultKeyValueOperationsSupport.KeyValueBackend.KV_2); List<String> secrets = ops.list(""); if (secrets == null) { System.out.println("No secrets found"); return;
} secrets.forEach(s -> { System.out.println("secret=" + s); var response = ops.get(s); var data = response.getRequiredData(); data.entrySet() .forEach(e -> { System.out.println("- key=" + e.getKey() + " => " + e.getValue()); }); }); }; } }
repos\tutorials-master\spring-vault\src\main\java\com\baeldung\springvaultk8s\VaultK8SApplication.java
2
请在Spring Boot框架中完成以下Java代码
public HUInfo getHUInfoById(@NonNull HuId huId) { return HUInfo.builder() .id(huId) .qrCode(getQRCodeByHuId(huId)) .build(); } @NonNull public HUQRCode getQRCodeByHuId(@NonNull final HuId huId) {return huQRCodesService.getQRCodeByHuId(huId);} @NonNull public HUQRCode resolveHUQRCode(@NonNull final ScannedCode scannedCode) { final IHUQRCode parsedHUQRCode = huQRCodesService.parse(scannedCode); if (parsedHUQRCode instanceof HUQRCode) { return (HUQRCode)parsedHUQRCode; } else { throw new AdempiereException("Cannot convert " + scannedCode + " to actual HUQRCode") .setParameter("parsedHUQRCode", parsedHUQRCode) .setParameter("parsedHUQRCode type", parsedHUQRCode.getClass().getSimpleName()); } } public HuId resolveHUId(@NonNull final ScannedCode scannedCode) { final HUQRCode huQRCode = resolveHUQRCode(scannedCode); return huQRCodesService.getHuIdByQRCode(huQRCode); } public PackToHUsProducer newPackToHUsProducer() { return PackToHUsProducer.builder() .handlingUnitsBL(handlingUnitsBL) .huPIItemProductBL(hupiItemProductBL) .uomConversionBL(uomConversionBL) .inventoryService(inventoryService) .build(); } public IAutoCloseable newContext() { return HUContextHolder.temporarySet(handlingUnitsBL.createMutableHUContextForProcessing()); } public ProductId getSingleProductId(@NonNull final HUQRCode huQRCode) { final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode); return getSingleHUProductStorage(huId).getProductId(); }
public IHUProductStorage getSingleHUProductStorage(@NonNull final HuId huId) { return handlingUnitsBL.getSingleHUProductStorage(huId); } public Quantity getProductQuantity(@NonNull final HuId huId, @NonNull ProductId productId) { return getHUProductStorage(huId, productId) .map(IHUProductStorage::getQty) .filter(Quantity::isPositive) .orElseThrow(() -> new AdempiereException(PRODUCT_DOES_NOT_MATCH)); } private Optional<IHUProductStorage> getHUProductStorage(final @NotNull HuId huId, final @NotNull ProductId productId) { final I_M_HU hu = handlingUnitsBL.getById(huId); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); return Optional.ofNullable(storageFactory.getStorage(hu).getProductStorageOrNull(productId)); } public void assetHUContainsProduct(@NonNull final HUQRCode huQRCode, @NonNull final ProductId productId) { final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode); getProductQuantity(huId, productId); // shall throw exception if no qty found } public void deleteReservationsByDocumentRefs(final ImmutableSet<HUReservationDocRef> huReservationDocRefs) { huReservationService.deleteReservationsByDocumentRefs(huReservationDocRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\external_services\hu\DistributionHUService.java
2
请完成以下Java代码
public DocumentQueryOrderBy copyOverridingFieldName(final String fieldName) { if (Objects.equals(this.fieldName, fieldName)) { return this; } return new DocumentQueryOrderBy(fieldName, ascending, nullsLast); } public <T> Comparator<T> asComparator(@NonNull final FieldValueExtractor<T> fieldValueExtractor, @NonNull final JSONOptions jsonOpts) { final Function<T, Object> keyExtractor = obj -> fieldValueExtractor.getFieldValue(obj, fieldName, jsonOpts); final Comparator<? super Object> keyComparator = ValueComparator.ofAscendingAndNullsLast(ascending, nullsLast); return Comparator.comparing(keyExtractor, keyComparator); } @Deprecated @Override public String toString() { return toStringSyntax(); } public String toStringSyntax() { return ascending ? fieldName : "-" + fieldName; } @FunctionalInterface public interface FieldValueExtractor<T> { Object getFieldValue(T object, String fieldName, JSONOptions jsonOpts); } @ToString private static final class ValueComparator implements Comparator<Object> { public static ValueComparator ofAscendingAndNullsLast(final boolean ascending, final boolean nullsLast) { if (ascending) { return nullsLast ? ASCENDING_NULLS_LAST : ASCENDING_NULLS_FIRST; } else { return nullsLast ? DESCENDING_NULLS_LAST : DESCENDING_NULLS_FIRST; } } public static final ValueComparator ASCENDING_NULLS_FIRST = new ValueComparator(true, false); public static final ValueComparator ASCENDING_NULLS_LAST = new ValueComparator(true, true); public static final ValueComparator DESCENDING_NULLS_FIRST = new ValueComparator(false, false); public static final ValueComparator DESCENDING_NULLS_LAST = new ValueComparator(false, true);
private final boolean ascending; private final boolean nullsLast; private ValueComparator(final boolean ascending, final boolean nullsLast) { this.ascending = ascending; this.nullsLast = nullsLast; } @Override public int compare(final Object o1, final Object o2) { if (o1 == o2) { return 0; } else if (o1 == null || o1 instanceof JSONNullValue) { return nullsLast ? +1 : -1; } else if (o2 == null || o2 instanceof JSONNullValue) { return nullsLast ? -1 : +1; } else if (o1 instanceof Comparable) { @SuppressWarnings("unchecked") final Comparable<Object> o1cmp = (Comparable<Object>)o1; return o1cmp.compareTo(o2) * (ascending ? +1 : -1); } else { return o1.toString().compareTo(o2.toString()) * (ascending ? +1 : -1); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQueryOrderBy.java
1
请完成以下Java代码
protected UpdateJobSuspensionStateBuilderImpl createJobCommandBuilder() { UpdateJobSuspensionStateBuilderImpl builder = new UpdateJobSuspensionStateBuilderImpl(); if (jobDefinitionId != null) { builder.byJobDefinitionId(jobDefinitionId); } else if (processDefinitionId != null) { builder.byProcessDefinitionId(processDefinitionId); } else if (processDefinitionKey != null) { builder.byProcessDefinitionKey(processDefinitionKey); if (isProcessDefinitionTenantIdSet && processDefinitionTenantId != null) { builder.processDefinitionTenantId(processDefinitionTenantId); } else if (isProcessDefinitionTenantIdSet) { builder.processDefinitionWithoutTenantId(); } } return builder; } /** * Subclasses should return the type of the {@link JobHandler} here. it will be used when * the user provides an execution date on which the actual state change will happen. */ @Override
protected abstract String getDelayedExecutionJobHandlerType(); @Override protected AbstractSetStateCmd getNextCommand() { UpdateJobSuspensionStateBuilderImpl jobCommandBuilder = createJobCommandBuilder(); return getNextCommand(jobCommandBuilder); } @Override protected String getDeploymentId(CommandContext commandContext) { if (jobDefinitionId != null) { return getDeploymentIdByJobDefinition(commandContext, jobDefinitionId); } else if (processDefinitionId != null) { return getDeploymentIdByProcessDefinition(commandContext, processDefinitionId); } else if (processDefinitionKey != null) { return getDeploymentIdByProcessDefinitionKey(commandContext, processDefinitionKey, isProcessDefinitionTenantIdSet, processDefinitionTenantId); } return null; } protected abstract AbstractSetJobStateCmd getNextCommand(UpdateJobSuspensionStateBuilderImpl jobCommandBuilder); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetJobDefinitionStateCmd.java
1
请完成以下Java代码
private static boolean validate(final long step, @NonNull final SecretKey secretKey, @NonNull final OTP otp) { return OTP.equals(computeOTP(step, secretKey), otp) || OTP.equals(computeOTP(step - 1, secretKey), otp); } private static long getStep() { // 30 seconds StepSize (ID TOTP) return SystemTime.millis() / 30000; } private static OTP computeOTP(final long step, @NonNull final SecretKey secretKey) { String steps = Long.toHexString(step).toUpperCase(); while (steps.length() < 16) { steps = "0" + steps; } // Get the HEX in a Byte[] final byte[] msg = hexStr2Bytes(steps); final byte[] k = hexStr2Bytes(secretKey.toHexString()); final byte[] hash = hmac_sha1(k, msg); // put selected bytes into result int final int offset = hash[hash.length - 1] & 0xf; final int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); final int otp = binary % 1000000; String result = Integer.toString(otp); while (result.length() < 6) { result = "0" + result; } return OTP.ofString(result); } /** * @return hex string converted to byte array */ private static byte[] hexStr2Bytes(final CharSequence hex) { // Adding one byte to get the right conversion // values starting with "0" can be converted final byte[] bArray = new BigInteger("10" + hex, 16).toByteArray(); final byte[] ret = new byte[bArray.length - 1];
// Copy all the REAL bytes, not the "first" System.arraycopy(bArray, 1, ret, 0, ret.length); return ret; } /** * This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash * algorithm as a parameter. * * @param keyBytes the bytes to use for the HMAC key * @param text the message or text to be authenticated. */ private static byte[] hmac_sha1(final byte[] keyBytes, final byte[] text) { try { final Mac hmac = Mac.getInstance("HmacSHA1"); final SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (final GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\TOTPUtils.java
1
请完成以下Java代码
public int getHandOver_Partner_ID() { return get_ValueAsInt(COLUMNNAME_HandOver_Partner_ID); } @Override public void setInvoicableQtyBasedOn (final @Nullable java.lang.String InvoicableQtyBasedOn) { set_ValueNoCheck (COLUMNNAME_InvoicableQtyBasedOn, InvoicableQtyBasedOn); } @Override public java.lang.String getInvoicableQtyBasedOn() { return get_ValueAsString(COLUMNNAME_InvoicableQtyBasedOn); } @Override public void setM_InOut_ID (final int M_InOut_ID) { if (M_InOut_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOut_ID, null); else set_ValueNoCheck (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_ValueNoCheck (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_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed()
{ return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_ValueNoCheck (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSumDeliveredInStockingUOM (final @Nullable BigDecimal SumDeliveredInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM); } @Override public BigDecimal getSumDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSumOrderedInStockingUOM (final @Nullable BigDecimal SumOrderedInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM); } @Override public BigDecimal getSumOrderedInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_ValueNoCheck (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_M_InOut_Desadv_V.java
1
请完成以下Java代码
public title addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public title addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element.
@param hashcode the name of the element to be removed. */ public title removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\title.java
1
请完成以下Java代码
private OrderLineId getSalesOrderLineId() { final IView view = getView(); if (view instanceof PPOrderLinesView) { final PPOrderLinesView ppOrderLinesView = PPOrderLinesView.cast(view); return ppOrderLinesView.getSalesOrderLineId(); } else { return null; } } @Override protected String doIt() { final HURow row = getSingleHURow(); pickHU(row); // invalidate view in order to be refreshed getView().invalidateAll(); return MSG_OK; } private void pickHU(@NonNull final HURow row) { final HuId huId = row.getHuId(); final PickRequest pickRequest = PickRequest.builder() .shipmentScheduleId(shipmentScheduleId) .pickFrom(PickFrom.ofHuId(huId)) .pickingSlotId(pickingSlotId) .build(); final ProcessPickingRequest.ProcessPickingRequestBuilder pickingRequestBuilder = ProcessPickingRequest.builder() .huIds(ImmutableSet.of(huId)) .shipmentScheduleId(shipmentScheduleId) .isTakeWholeHU(isTakeWholeHU); final IView view = getView();
if (view instanceof PPOrderLinesView) { final PPOrderLinesView ppOrderView = PPOrderLinesView.cast(view); pickingRequestBuilder.ppOrderId(ppOrderView.getPpOrderId()); } WEBUI_PP_Order_ProcessHelper.pickAndProcessSingleHU(pickRequest, pickingRequestBuilder.build()); } @Override protected void postProcess(final boolean success) { if (!success) { return; } invalidateView(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Pick.java
1
请完成以下Java代码
protected void paintFocusIndicator( Graphics g, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { if (!tabPane.hasFocus() || !isSelected) return; Rectangle tabRect = rects[tabIndex]; int top = tabRect.y + 1; int left = tabRect.x + 4; int height = tabRect.height - 3; int width = tabRect.width - 9; g.setColor(focus); g.drawRect(left, top, width, height); } @Override protected void paintTabBackground(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { int sel = (isSelected) ? 0 : 1; g.setColor(selectColor); g.fillRect(x, y + sel, w, h / 2); g.fillRect(x - 1, y + sel + h / 2, w + 2, h - h / 2); } @Override protected void paintTabBorder(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { g.translate(x - 4, y); int top = 0; int right = w + 6; // Paint Border g.setColor(selectHighlight); // Paint left g.drawLine(1, h - 1, 4, top + 4); g.fillRect(5, top + 2, 1, 2); g.fillRect(6, top + 1, 1, 1); // Paint top g.fillRect(7, top, right - 12, 1);
// Paint right g.setColor(darkShadow); g.drawLine(right, h - 1, right - 3, top + 4); g.fillRect(right - 4, top + 2, 1, 2); g.fillRect(right - 5, top + 1, 1, 1); g.translate(-x + 4, -y); } @Override protected void paintContentBorderTopEdge( Graphics g, int x, int y, int w, int h, boolean drawBroken, Rectangle selRect, boolean isContentBorderPainted) { int right = x + w - 1; int top = y; g.setColor(selectHighlight); if (drawBroken && selRect.x >= x && selRect.x <= x + w) { // Break line to show visual connection to selected tab g.fillRect(x, top, selRect.x - 2 - x, 1); if (selRect.x + selRect.width < x + w - 2) { g.fillRect(selRect.x + selRect.width + 2, top, right - 2 - selRect.x - selRect.width, 1); } else { g.fillRect(x + w - 2, top, 1, 1); } } else { g.fillRect(x, top, w - 1, 1); } } @Override protected int getTabsOverlay() { return 6; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereTabbedPaneUI.java
1
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { if (!success) { return success; } // Value/Name change in Account if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) { MAccount.updateValueDescription(getCtx(), "M_Product_ID=" + getM_Product_ID(), get_TrxName()); } // Name/Description Change in Asset MAsset.setValueNameDescription if (!newRecord && (is_ValueChanged("Name") || is_ValueChanged("Description"))) { String sql = DB.convertSqlToNative("UPDATE A_Asset a " + "SET (Name, Description)=" + "(SELECT SUBSTR((SELECT bp.Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=a.C_BPartner_ID) || ' - ' || p.Name,1,60), p.Description " + "FROM M_Product p " + "WHERE p.M_Product_ID=a.M_Product_ID) " + "WHERE IsActive='Y'" // + " AND GuaranteeDate > now()" + " AND M_Product_ID=" + getM_Product_ID()); int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); log.debug("Asset Description updated #" + no); } // New - Acct, Tree, Old Costing if (newRecord) { if(!this.isCopying()) { insert_Accounting(I_M_Product_Acct.Table_Name, I_M_Product_Category_Acct.Table_Name, "p.M_Product_Category_ID=" + getM_Product_Category_ID()); } else { log.info("This M_Product is created via CopyRecordSupport; -> don't insert the default _acct records"); } insert_Tree(X_AD_Tree.TREETYPE_Product); } // Product category changed, then update the accounts if (!newRecord && is_ValueChanged(I_M_Product.COLUMNNAME_M_Product_Category_ID))
{ update_Accounting(I_M_Product_Acct.Table_Name, I_M_Product_Category_Acct.Table_Name, "p.M_Product_Category_ID=" + getM_Product_Category_ID()); } return true; } // afterSave @Override protected boolean beforeDelete() { if (PRODUCTTYPE_Resource.equals(getProductType()) && getS_Resource_ID() > 0) { throw new AdempiereException("@S_Resource_ID@<>0"); } // return delete_Accounting("M_Product_Acct"); } // beforeDelete }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProduct.java
1
请完成以下Java代码
protected void executeParse(BpmnParse bpmnParse, IntermediateCatchEvent event) { ActivityImpl nestedActivity = null; EventDefinition eventDefinition = null; if (!event.getEventDefinitions().isEmpty()) { eventDefinition = event.getEventDefinitions().get(0); } if (eventDefinition == null) { nestedActivity = createActivityOnCurrentScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH); nestedActivity.setAsync(event.isAsynchronous()); nestedActivity.setExclusive(!event.isNotExclusive()); } else { ScopeImpl scope = bpmnParse.getCurrentScope(); String eventBasedGatewayId = getPrecedingEventBasedGateway(bpmnParse, event); if (eventBasedGatewayId != null) { ActivityImpl gatewayActivity = scope.findActivity(eventBasedGatewayId); nestedActivity = createActivityOnScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH, gatewayActivity); } else { nestedActivity = createActivityOnScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH, scope); } nestedActivity.setAsync(event.isAsynchronous());
nestedActivity.setExclusive(!event.isNotExclusive()); // Catch event behavior is the same for all types nestedActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventActivityBehavior(event)); if (eventDefinition instanceof TimerEventDefinition || eventDefinition instanceof SignalEventDefinition || eventDefinition instanceof MessageEventDefinition) { bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition); } else { LOGGER.warn("Unsupported intermediate catch event type for event {}", event.getId()); } } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\IntermediateCatchEventParseHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Long getLongValue() { if (valueField != null) { return valueField.getLongValue(); } return null; } public Double getDoubleValue() { if (valueField != null) { return valueField.getDoubleValue(); } return null; } public String getTextValue2() { if (valueField != null) { return valueField.getTextValue2(); } return null; } public String getType() { if (valueType != null) { return valueType.getTypeName(); } return null; } public boolean needsTypeCheck() { // When operator is not-equals or type of value is null, type doesn't matter! if (operator == QueryOperator.NOT_EQUALS || operator == QueryOperator.NOT_EQUALS_IGNORE_CASE) {
return false; } if (valueField != null) { return !NullType.TYPE_NAME.equals(valueType.getTypeName()); } return false; } public boolean isLocal() { return local; } public String getScopeType() { return scopeType; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\QueryVariableValue.java
2
请在Spring Boot框架中完成以下Java代码
public class StaticResourcesWebConfiguration implements WebMvcConfigurer { protected static final String[] RESOURCE_LOCATIONS = { "classpath:/static/", "classpath:/static/content/", "classpath:/static/i18n/" }; protected static final String[] RESOURCE_PATHS = { "/*.js", "/*.css", "/*.svg", "/*.png", "*.ico", "/content/**", "/i18n/*" }; private final JHipsterProperties jhipsterProperties; public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) { this.jhipsterProperties = jHipsterProperties; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry); initializeResourceHandler(resourceHandlerRegistration); } protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) {
return registry.addResourceHandler(RESOURCE_PATHS); } protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) { resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl()); } protected CacheControl getCacheControl() { return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic(); } private int getJHipsterHttpCacheProperty() { return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays(); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\config\StaticResourcesWebConfiguration.java
2
请完成以下Java代码
public List<CleanableHistoricDecisionInstanceReportResult> executeList(CommandContext commandContext, Page page) { provideHistoryCleanupStrategy(commandContext); checkQueryOk(); return commandContext .getHistoricDecisionInstanceManager() .findCleanableHistoricDecisionInstancesReportByCriteria(this, page); } public String[] getDecisionDefinitionIdIn() { return decisionDefinitionIdIn; } public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) { this.decisionDefinitionIdIn = decisionDefinitionIdIn; } public String[] getDecisionDefinitionKeyIn() { return decisionDefinitionKeyIn; } public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getTenantIdIn() { return tenantIdIn;
} public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isCompact() { return isCompact; } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricDecisionInstanceReportImpl.java
1
请完成以下Java代码
public class Esr5Type { protected EsrAddressType bank; @XmlAttribute(name = "type") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String type; @XmlAttribute(name = "participant_number", required = true) protected String participantNumber; @XmlAttribute(name = "reference_number", required = true) protected String referenceNumber; @XmlAttribute(name = "coding_line", required = true) protected String codingLine; /** * Gets the value of the bank property. * * @return * possible object is * {@link EsrAddressType } * */ public EsrAddressType getBank() { return bank; } /** * Sets the value of the bank property. * * @param value * allowed object is * {@link EsrAddressType } * */ public void setBank(EsrAddressType value) { this.bank = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { if (type == null) { return "15"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the participantNumber property. * * @return * possible object is
* {@link String } * */ public String getParticipantNumber() { return participantNumber; } /** * Sets the value of the participantNumber property. * * @param value * allowed object is * {@link String } * */ public void setParticipantNumber(String value) { this.participantNumber = value; } /** * Gets the value of the referenceNumber property. * * @return * possible object is * {@link String } * */ public String getReferenceNumber() { return referenceNumber; } /** * Sets the value of the referenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setReferenceNumber(String value) { this.referenceNumber = value; } /** * Gets the value of the codingLine property. * * @return * possible object is * {@link String } * */ public String getCodingLine() { return codingLine; } /** * Sets the value of the codingLine property. * * @param value * allowed object is * {@link String } * */ public void setCodingLine(String value) { this.codingLine = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Esr5Type.java
1
请完成以下Java代码
protected Alarm toAlarm() { Alarm alarm = new Alarm(new AlarmId(id)); alarm.setCreatedTime(createdTime); if (tenantId != null) { alarm.setTenantId(TenantId.fromUUID(tenantId)); } if (customerId != null) { alarm.setCustomerId(new CustomerId(customerId)); } alarm.setOriginator(EntityIdFactory.getByTypeAndUuid(originatorType, originatorId)); alarm.setType(type); alarm.setSeverity(severity); alarm.setAcknowledged(acknowledged); alarm.setCleared(cleared); if (assigneeId != null) { alarm.setAssigneeId(new UserId(assigneeId)); } alarm.setPropagate(propagate); alarm.setPropagateToOwner(propagateToOwner);
alarm.setPropagateToTenant(propagateToTenant); alarm.setStartTs(startTs); alarm.setEndTs(endTs); alarm.setAckTs(ackTs); alarm.setClearTs(clearTs); alarm.setAssignTs(assignTs); alarm.setDetails(details); if (!StringUtils.isEmpty(propagateRelationTypes)) { alarm.setPropagateRelationTypes(Arrays.asList(propagateRelationTypes.split(","))); } else { alarm.setPropagateRelationTypes(Collections.emptyList()); } return alarm; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AbstractAlarmEntity.java
1
请完成以下Java代码
public static BigDecimal computeQtyWithScrap(final BigDecimal qty, @NonNull final Percent scrapPercent) { if (qty == null || qty.signum() == 0) { return BigDecimal.ZERO; } if (scrapPercent.isZero()) { return qty; } final int precision = 8; return scrapPercent.addToBase(qty, precision); } /** * Calculates Qty + Scrap * * @param qty qty (without scrap) * @param scrapPercent scrap percent (between 0..100) * @return qty * (1 + qtyScrap/100) */ public static Quantity computeQtyWithScrap(@NonNull final Quantity qty, @NonNull final Percent scrapPercent) { if (qty.signum() == 0)
{ return qty; } if (scrapPercent.isZero()) { return qty; } final int precision = 8; return Quantity.of( scrapPercent.addToBase(qty.toBigDecimal(), precision), qty.getUOM()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\ProductBOMQtys.java
1
请完成以下Java代码
public void putDebugProperty(final String name, final Object value) { if (debugProperties == null) { debugProperties = new LinkedHashMap<>(); } debugProperties.put(name, value); } public void putDebugProperties(final Map<String, Object> debugProperties) { if (debugProperties == null || debugProperties.isEmpty()) { return; } if (this.debugProperties == null) { this.debugProperties = new LinkedHashMap<>();
} this.debugProperties.putAll(debugProperties); } public Map<String, Object> getDebugProperties() { return debugProperties == null ? ImmutableMap.of() : debugProperties; } public void setFieldWarning(@NonNull final DocumentFieldWarning fieldWarning) { this.fieldWarning = fieldWarning; } public DocumentFieldWarning getFieldWarning() { return fieldWarning; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldChange.java
1
请完成以下Java代码
public boolean isManualQtyItemCapacity(@NonNull final I_C_OLCand olCand) { // @formatter:off // task 08147: we generally don't use the ORDERS file's QtyItemCapacity, because so far it was not reliable (it is mostly 1 and doesn't reflect the TU's actual capacity). // Instead, we go with our own master data to obtain the capacity. // if (isEDIInput(olCand)) // { // return true; // } // @formatter:on // task 08147 // were we just don't have the capacity, so we use the ORDERS file's value, but that's the only case where we do that final OLCandHUPackingAware olCandHUPackingAware = new OLCandHUPackingAware(olCand);
return huPackingAwareBL.isInfiniteCapacityTU(olCandHUPackingAware); } @Override public boolean isEDIInput(final de.metas.ordercandidate.model.I_C_OLCand olCand) { if (olCand.getAD_InputDataSource_ID() <= 0) { return false; } final int dataSourceId = olCand.getAD_InputDataSource_ID(); return ediInputDataSourceBL.isEDIInputDataSource(dataSourceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\EDIOLCandBL.java
1
请完成以下Java代码
public int getMenge() { return menge; } /** * Sets the value of the menge property. * */ public void setMenge(int value) { this.menge = value; } /** * Gets the value of the liefervorgabe property. * * @return * possible object is * {@link Liefervorgabe } *
*/ public Liefervorgabe getLiefervorgabe() { return liefervorgabe; } /** * Sets the value of the liefervorgabe property. * * @param value * allowed object is * {@link Liefervorgabe } * */ public void setLiefervorgabe(Liefervorgabe value) { this.liefervorgabe = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungPosition.java
1
请完成以下Java代码
public static QuickInputLayoutDescriptor allFields(@NonNull final DocumentEntityDescriptor entityDescriptor) { final Builder layoutBuilder = builder(); for (final DocumentFieldDescriptor field : entityDescriptor.getFields()) { final DocumentLayoutElementDescriptor.Builder element = DocumentLayoutElementDescriptor.builder(field); layoutBuilder.element(element); } return layoutBuilder.build(); } private final List<DocumentLayoutElementDescriptor> elements; private QuickInputLayoutDescriptor(final List<DocumentLayoutElementDescriptor> elements) { this.elements = ImmutableList.copyOf(elements); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("elements", elements.isEmpty() ? null : elements) .toString();
} public List<DocumentLayoutElementDescriptor> getElements() { return elements; } public static final class Builder { private final List<DocumentLayoutElementDescriptor> elements = new ArrayList<>(); private Builder() { } public QuickInputLayoutDescriptor build() { return new QuickInputLayoutDescriptor(elements); } public Builder element(@NonNull final DocumentLayoutElementDescriptor.Builder elementBuilder) { elements.add(elementBuilder.build()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputLayoutDescriptor.java
1
请完成以下Java代码
protected static List<FlowNode> gatherAllFlowNodes(FlowElementsContainer flowElementsContainer) { List<FlowNode> flowNodes = new ArrayList<FlowNode>(); for (FlowElement flowElement : flowElementsContainer.getFlowElements()) { if (flowElement instanceof FlowNode) { flowNodes.add((FlowNode) flowElement); } if (flowElement instanceof FlowElementsContainer) { flowNodes.addAll(gatherAllFlowNodes((FlowElementsContainer) flowElement)); } } return flowNodes; } public Map<Class<? extends BaseElement>, ActivityDrawInstruction> getActivityDrawInstructions() { return activityDrawInstructions; } public void setActivityDrawInstructions( Map<Class<? extends BaseElement>, ActivityDrawInstruction> activityDrawInstructions ) { this.activityDrawInstructions = activityDrawInstructions; } public Map<Class<? extends BaseElement>, ArtifactDrawInstruction> getArtifactDrawInstructions() { return artifactDrawInstructions;
} public void setArtifactDrawInstructions( Map<Class<? extends BaseElement>, ArtifactDrawInstruction> artifactDrawInstructions ) { this.artifactDrawInstructions = artifactDrawInstructions; } protected interface ActivityDrawInstruction { void draw(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode); } protected interface ArtifactDrawInstruction { void draw(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact); } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\DefaultProcessDiagramGenerator.java
1
请完成以下Java代码
private Optional<BPartnerId> getOptionalBPartnerId(@NonNull final IdentifierString identifierString) { final BPartnerQuery query = buildBPartnerQuery(identifierString); return bPartnerDAO.retrieveBPartnerIdBy(query); } @NonNull private CurrencyId getCurrencyIdByCurrencyISO(@NonNull final String currencyISO) { final CurrencyCode convertedToCurrencyCode = CurrencyCode.ofThreeLetterCode(currencyISO); return currencyRepository.getCurrencyIdByCurrencyCode(convertedToCurrencyCode); } @NonNull private BPartnerBankAccountId getBPartnerBankAccountId(@NonNull final BPartnerId bPartnerId) { final I_C_BP_BankAccount sourceBPartnerBankAccount = bankAccountDAO.retrieveDefaultBankAccountInTrx(bPartnerId) .orElseThrow(() -> new AdempiereException("No BPartnerBankAccount found for BPartnerId") .appendParametersToMessage() .setParameter("BPartnerId", bPartnerId)); return BPartnerBankAccountId.ofRepoId(BPartnerId.toRepoId(bPartnerId), sourceBPartnerBankAccount.getC_BP_BankAccount_ID()); } @NonNull private DocTypeId getDocTypeIdByType( @NonNull final String type, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { final DocTypeQuery docTypeQuery = DocTypeQuery.builder() .docBaseType(type) .adClientId(clientId.getRepoId()) .adOrgId(orgId.getRepoId()) .build(); return docTypeDAO.getDocTypeId(docTypeQuery); } private BPartnerQuery buildBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier) { final IdentifierString.Type type = bpartnerIdentifier.getType(); final BPartnerQuery query; switch (type) { case METASFRESH_ID: query = BPartnerQuery.builder() .bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId)) .build(); break; case EXTERNAL_ID: query = BPartnerQuery.builder() .externalId(bpartnerIdentifier.asExternalId()) .build(); break; case GLN: query = BPartnerQuery.builder() .gln(bpartnerIdentifier.asGLN()) .build();
break; case VALUE: query = BPartnerQuery.builder() .bpartnerValue(bpartnerIdentifier.asValue()) .build(); break; default: throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier); } return query; } @VisibleForTesting public String buildDocumentNo(@NonNull final DocTypeId docTypeId) { final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class); final String documentNo = documentNoFactory.forDocType(docTypeId.getRepoId(), /* useDefiniteSequence */false) .setClientId(Env.getClientId()) .setFailOnError(true) .build(); if (documentNo == null) { throw new AdempiereException("Cannot fetch documentNo for " + docTypeId); } return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\remittanceadvice\impl\CreateRemittanceAdviceService.java
1
请在Spring Boot框架中完成以下Java代码
public List<PostDto> getPosts( @PathVariable("page") int page, @PathVariable("size") int size, @PathVariable("sortDir") String sortDir, @PathVariable("sort") String sort) { List<Post> posts = postService.getPostsList(page, size, sortDir, sort); return posts.stream() .map(this::convertToDto) .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) @ResponseBody public PostDto createPost(@RequestBody PostDto postDto) throws ParseException { Post post = convertToEntity(postDto); Post postCreated = postService.createPost(post); return convertToDto(postCreated); } @GetMapping(value = "/{id}") @ResponseBody public PostDto getPost(@PathVariable("id") Long id) { return convertToDto(postService.getPostById(id)); } @PutMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) throws ParseException { if(!Objects.equals(id, postDto.getId())){ throw new IllegalArgumentException("IDs don't match"); } Post post = convertToEntity(postDto); postService.updatePost(post); }
private PostDto convertToDto(Post post) { PostDto postDto = modelMapper.map(post, PostDto.class); postDto.setSubmissionDate(post.getSubmissionDate(), userService.getCurrentUser().getPreference().getTimezone()); return postDto; } private Post convertToEntity(PostDto postDto) throws ParseException { Post post = modelMapper.map(postDto, Post.class); post.setSubmissionDate(postDto.getSubmissionDateConverted( userService.getCurrentUser().getPreference().getTimezone())); if (postDto.getId() != null) { Post oldPost = postService.getPostById(postDto.getId()); post.setRedditID(oldPost.getRedditID()); post.setSent(oldPost.isSent()); } return post; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\controller\PostRestController.java
2
请完成以下Java代码
public void Jackson() { for (int i = 0; i < count; i++) { JacksonUtil.bean2Json(p); } } @Setup public void prepare() { List<Person> friends=new ArrayList<Person>(); friends.add(createAPerson("小明",null)); friends.add(createAPerson("Tony",null)); friends.add(createAPerson("陈小二",null)); p=createAPerson("邵同学",friends); } @TearDown public void shutdown() { } private Person createAPerson(String name,List<Person> friends) {
Person newPerson=new Person(); newPerson.setName(name); newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last")); newPerson.setAge(24); List<String> hobbies=new ArrayList<String>(); hobbies.add("篮球"); hobbies.add("游泳"); hobbies.add("coding"); newPerson.setHobbies(hobbies); Map<String,String> clothes=new HashMap<String, String>(); clothes.put("coat", "Nike"); clothes.put("trousers", "adidas"); clothes.put("shoes", "安踏"); newPerson.setClothes(clothes); newPerson.setFriends(friends); return newPerson; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\JsonSerializeBenchmark.java
1
请完成以下Java代码
protected void configure(AuthenticationManagerBuilder auth) { auth.authenticationProvider(authenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http // remove csrf state in session because in jwt do not need them .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //add jwt filters (1. authentication, 2. authorization_) .addFilter(new JwtAuthenticationFilter(authenticationManager())) .addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository)) .authorizeRequests() //configure access rules .antMatchers(HttpMethod.POST, "/login").permitAll() .antMatchers("/api/public/management/*").hasRole("MANAGER")
.antMatchers("/api/public/admin/*").hasRole("ADMIN") .anyRequest().authenticated(); } @Bean DaoAuthenticationProvider authenticationProvider(){ DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); daoAuthenticationProvider.setUserDetailsService((UserDetailsService) this.userPrincipalDetailsService); return daoAuthenticationProvider; } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\11.SpringSecurityJwt\src\main\java\spring\security\security\SecurityConfiguration.java
1
请完成以下Java代码
public String toString() { return new String(value, b, e - b); } @Override public int compareTo(SString anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; }
public char[] toCharArray() { return Arrays.copyOfRange(value, b, e); } public static SString valueOf(char word) { SString s = new SString(new char[]{word}, 0, 1); return s; } public SString add(SString other) { char[] value = new char[length() + other.length()]; System.arraycopy(this.value, b, value, 0, length()); System.arraycopy(other.value, other.b, value, length(), other.length()); b = 0; e = length() + other.length(); this.value = value; return this; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\sequence\SString.java
1
请完成以下Java代码
public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public void setDeleteReason(final String deleteReason) { this.deleteReason = deleteReason; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskId() { return taskId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public void setTaskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTaskState() { return taskState; } public void setTaskState(String taskState) { this.taskState = taskState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; }
@Override public String toString() { return this.getClass().getSimpleName() + "[taskId" + taskId + ", assignee=" + assignee + ", owner=" + owner + ", name=" + name + ", description=" + description + ", dueDate=" + dueDate + ", followUpDate=" + followUpDate + ", priority=" + priority + ", parentTaskId=" + parentTaskId + ", deleteReason=" + deleteReason + ", taskDefinitionKey=" + taskDefinitionKey + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", activityInstanceId=" + activityInstanceId + ", tenantId=" + tenantId + ", taskState=" + taskState + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java
1
请完成以下Java代码
public Object getValue(ELContext context, Object base, Object property) { if (base == null) { VariableContext variableContext = (VariableContext) context.getContext(VariableContext.class); if(variableContext != null) { if(VAR_CTX_KEY.equals(property)) { context.setPropertyResolved(true); return variableContext; } TypedValue typedValue = variableContext.resolve((String) property); if(typedValue != null) { context.setPropertyResolved(true); return unpack(typedValue); } } } return null; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { // read only } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { // always read only return true; } public Class< ? > getCommonPropertyType(ELContext arg0, Object arg1) { return Object.class; }
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext arg0, Object arg1) { return null; } public Class< ? > getType(ELContext arg0, Object arg1, Object arg2) { return Object.class; } protected Object unpack(TypedValue typedValue) { if(typedValue != null) { return typedValue.getValue(); } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\VariableContextElResolver.java
1
请完成以下Java代码
public void setGrow(int grow) { this.grow = grow; } public void grow() { size = size+=(size/grow); rehash(); } public void add(Object o) { if( current == elements.length ) grow(); try { elements[current] = o; current++; } catch(java.lang.ArrayStoreException ase) { } } public void add(int location,Object o) { try { elements[location] = o; } catch(java.lang.ArrayStoreException ase) { } } public void remove(int location) { elements[location] = null; }
public int location(Object o) throws NoSuchObjectException { int loc = -1; for ( int x = 0; x < elements.length; x++ ) { if((elements[x] != null && elements[x] == o )|| (elements[x] != null && elements[x].equals(o))) { loc = x; break; } } if( loc == -1 ) throw new NoSuchObjectException(); return(loc); } public Object get(int location) { return elements[location]; } public java.util.Enumeration elements() { return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Array.java
1
请完成以下Java代码
public List<AuthorityRequirement> getAuthorityRequirements() { return authorityRequirements; } public void setAuthorityRequirements(List<AuthorityRequirement> authorityRequirements) { this.authorityRequirements = authorityRequirements; } public void addAuthorityRequirement(AuthorityRequirement authorityRequirement) { this.authorityRequirements.add(authorityRequirement); } public Expression getExpression() { return expression; } public void setExpression(Expression expression) { this.expression = expression; }
public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } @JsonIgnore public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\Decision.java
1
请完成以下Java代码
public class MyBatisPlusGenerator { public static void main(String[] args) throws SQLException { //1. 全局配置 GlobalConfig config = new GlobalConfig(); config.setActiveRecord(true) // 是否支持AR模式 .setAuthor("yuhao.wang3") // 作者 //.setOutputDir("D:\\workspace_mp\\mp03\\src\\main\\java") // 生成路径 .setOutputDir("D:\\mybatis-plus") // 生成路径 .setFileOverride(true) // 文件覆盖 .setIdType(IdType.AUTO) // 主键策略 .setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I // IEmployeeService .setBaseResultMap(true)//生成基本的resultMap .setEnableCache(false)//是否开启缓存 .setBaseColumnList(true);//生成基本的SQL片段 //2. 数据源配置 DataSourceConfig dsConfig = new DataSourceConfig(); dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型 .setDriverName("com.mysql.jdbc.Driver") .setUrl("jdbc:mysql://host:3306/db") .setUsername("admin") .setPassword("admin"); //3. 策略配置globalConfiguration中 StrategyConfig stConfig = new StrategyConfig(); stConfig.setCapitalMode(true) //全局大写命名 // .setSuperEntityClass("com.wlqq.insurance.claim.pojo.po.base.BaseEntity") .setControllerMappingHyphenStyle(true) .setRestControllerStyle(true) .setEntityLombokModel(true) .setColumnNaming(NamingStrategy.underline_to_camel)
.setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略 // .setTablePrefix("tbl_") .setInclude("fis_record_ext"); // 生成的表 //4. 包名策略配置 PackageConfig pkConfig = new PackageConfig(); pkConfig.setParent("com.wlqq.insurance") .setMapper("mybatis.mapper.withSharding")//dao .setService("service")//servcie .setController("controller")//controller .setEntity("mybatis.domain") .setXml("mapper-xml");//mapper.xml //5. 整合配置 AutoGenerator ag = new AutoGenerator(); ag.setGlobalConfig(config) .setDataSource(dsConfig) .setStrategy(stConfig) .setPackageInfo(pkConfig); //6. 执行 ag.execute(); } }
repos\spring-boot-student-master\spring-boot-student-mybatis-plus\src\main\java\com\xiaolyuh\MyBatisPlusGenerator.java
1
请完成以下Java代码
private List<PackageableRow> retrieveRowsByShipmentScheduleIds(final ViewId viewId, final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return ImmutableList.of(); } return Services.get(IPackagingDAO.class).getByShipmentScheduleIds(shipmentScheduleIds) .stream() .map(packageable -> createPackageableRow(viewId, packageable)) .collect(ImmutableList.toImmutableList()); } private PackageableRow createPackageableRow(final ViewId viewId, final Packageable packageable) { final Quantity qtyPickedOrDelivered = packageable.getQtyPickedOrDelivered(); final Optional<OrderLineId> orderLineId = Optional.ofNullable(packageable.getSalesOrderLineIdOrNull()); return PackageableRow.builder() .shipmentScheduleId(packageable.getShipmentScheduleId()) .salesOrderLineId(orderLineId) .viewId(viewId) // .order(orderLookup.get().findById(packageable.getSalesOrderId())) .product(productLookup.get().findById(packageable.getProductId()))
.bpartner(bpartnerLookup.get().findById(packageable.getCustomerId())) .preparationDate(packageable.getPreparationDate().toZonedDateTime(orgDAO::getTimeZone)) // .qtyOrdered(packageable.getQtyOrdered()) .qtyPicked(qtyPickedOrDelivered) // .build(); } public PackageableRowsData createRowsData( @NonNull final ViewId viewId, @NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return PackageableRowsData.EMPTY; } final Set<ShipmentScheduleId> shipmentScheduleIdsCopy = ImmutableSet.copyOf(shipmentScheduleIds); return PackageableRowsData.ofSupplier(() -> retrieveRowsByShipmentScheduleIds(viewId, shipmentScheduleIdsCopy)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRowsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public R<List<RegionVO>> lazyList(String parentCode, @Parameter(hidden = true) @RequestParam Map<String, Object> menu) { List<RegionVO> list = regionService.lazyList(parentCode, menu); return R.data(RegionWrapper.build().listNodeLazyVO(list)); } /** * 懒加载列表 */ @GetMapping("/lazy-tree") @Parameters({ @Parameter(name = "code", description = "区划编号", in = ParameterIn.QUERY, schema = @Schema(type = "string")), @Parameter(name = "name", description = "区划名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")) }) @ApiOperationSupport(order = 4) @Operation(summary = "懒加载列表", description = "传入menu") public R<List<RegionVO>> lazyTree(String parentCode, @Parameter(hidden = true) @RequestParam Map<String, Object> menu) { List<RegionVO> list = regionService.lazyTree(parentCode, menu); return R.data(RegionWrapper.build().listNodeLazyVO(list)); } /** * 新增 行政区划表 */ @PostMapping("/save") @ApiOperationSupport(order = 5) @Operation(summary = "新增", description = "传入region") public R save(@Valid @RequestBody Region region) { return R.status(regionService.save(region)); } /** * 修改 行政区划表 */ @PostMapping("/update") @ApiOperationSupport(order = 6) @Operation(summary = "修改", description = "传入region") public R update(@Valid @RequestBody Region region) { return R.status(regionService.updateById(region)); } /** * 新增或修改 行政区划表 */ @PostMapping("/submit") @ApiOperationSupport(order = 7) @Operation(summary = "新增或修改", description = "传入region") public R submit(@Valid @RequestBody Region region) { return R.status(regionService.submit(region));
} /** * 删除 行政区划表 */ @PostMapping("/remove") @ApiOperationSupport(order = 8) @Operation(summary = "删除", description = "传入主键") public R remove(@Parameter(description = "主键", required = true) @RequestParam String id) { return R.status(regionService.removeRegion(id)); } /** * 行政区划下拉数据源 */ @GetMapping("/select") @ApiOperationSupport(order = 9) @Operation(summary = "下拉数据源", description = "传入tenant") public R<List<Region>> select(@RequestParam(required = false, defaultValue = "00") String code) { List<Region> list = regionService.list(Wrappers.<Region>query().lambda().eq(Region::getParentCode, code)); return R.data(list); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RegionController.java
2
请完成以下Java代码
protected void removeEntity(TenantId tenantId, DashboardId dashboardId) { deleteDashboard(tenantId, dashboardId); } }; @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findDashboardById(tenantId, new DashboardId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findDashboardByIdAsync(tenantId, new DashboardId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public long countByTenantId(TenantId tenantId) { return dashboardDao.countByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.DASHBOARD; } private class CustomerDashboardsRemover extends PaginatedRemover<Customer, DashboardInfo> { private final Customer customer; CustomerDashboardsRemover(Customer customer) { this.customer = customer; } @Override protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) { return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink); }
@Override protected void removeEntity(TenantId tenantId, DashboardInfo entity) { unassignDashboardFromCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer.getId()); } } private class CustomerDashboardsUpdater extends PaginatedRemover<Customer, DashboardInfo> { private final Customer customer; CustomerDashboardsUpdater(Customer customer) { this.customer = customer; } @Override protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) { return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, DashboardInfo entity) { updateAssignedCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\dashboard\DashboardServiceImpl.java
1
请完成以下Java代码
public void setIsRequireTrolley (final boolean IsRequireTrolley) { set_Value (COLUMNNAME_IsRequireTrolley, IsRequireTrolley); } @Override public boolean isRequireTrolley() { return get_ValueAsBoolean(COLUMNNAME_IsRequireTrolley); } @Override public void setMaxLaunchers (final int MaxLaunchers) { set_Value (COLUMNNAME_MaxLaunchers, MaxLaunchers); } @Override public int getMaxLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxLaunchers); } @Override public void setMaxStartedLaunchers (final int MaxStartedLaunchers) { set_Value (COLUMNNAME_MaxStartedLaunchers, MaxStartedLaunchers); } @Override public int getMaxStartedLaunchers()
{ return get_ValueAsInt(COLUMNNAME_MaxStartedLaunchers); } @Override public void setMobileUI_UserProfile_DD_ID (final int MobileUI_UserProfile_DD_ID) { if (MobileUI_UserProfile_DD_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, MobileUI_UserProfile_DD_ID); } @Override public int getMobileUI_UserProfile_DD_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_DD.java
1
请完成以下Java代码
public WindowId getWindowId() { return windowId; } /** * @return full viewId string (including WindowId, including other parts etc) */ public String getViewId() { return viewId; } @Override @Deprecated public String toString() { return toJson(); } @JsonValue public String toJson() { return viewId; } public String getPart(final int index) { return parts.get(index); } public int getPartAsInt(final int index) { try { final String partStr = getPart(index); return Integer.parseInt(partStr); } catch (final Exception ex) { throw new AdempiereException("Cannot extract part with index " + index + " as integer from " + this, ex); } } /** * @return just the viewId part (without the leading WindowId, without other parts etc) */ public String getViewIdPart()
{ return parts.get(1); } /** * @return other parts (those which come after viewId part) */ @JsonIgnore // IMPORTANT: for some reason, without this annotation the json deserialization does not work even if we have toJson() method annotated with @JsonValue public ImmutableList<String> getOtherParts() { return parts.size() > 2 ? parts.subList(2, parts.size()) : ImmutableList.of(); } public ViewId withWindowId(@NonNull final WindowId newWindowId) { if (windowId.equals(newWindowId)) { return this; } final ImmutableList<String> newParts = ImmutableList.<String>builder() .add(newWindowId.toJson()) .addAll(parts.subList(1, parts.size())) .build(); final String newViewId = JOINER.join(newParts); return new ViewId(newViewId, newParts, newWindowId); } public void assertWindowId(@NonNull final WindowId expectedWindowId) { if (!windowId.equals(expectedWindowId)) { throw new AdempiereException("" + this + " does not have expected windowId: " + expectedWindowId); } } public static boolean equals(@Nullable final ViewId id1, @Nullable final ViewId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewId.java
1
请完成以下Java代码
public static LicenseKeyDataImpl fromRawString(String rawLicense) { String licenseKeyRawString = rawLicense.contains(";") ? rawLicense.split(";", 2)[1] : rawLicense; return new LicenseKeyDataImpl(null, null, null, null, null, licenseKeyRawString); } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValidUntil() { return validUntil; } public void setValidUntil(String validUntil) { this.validUntil = validUntil; } public Boolean isUnlimited() { return isUnlimited;
} public void setUnlimited(Boolean isUnlimited) { this.isUnlimited = isUnlimited; } public Map<String, String> getFeatures() { return features; } public void setFeatures(Map<String, String> features) { this.features = features; } public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\LicenseKeyDataImpl.java
1
请完成以下Java代码
public boolean isFlowable5Job(Job job) { if (job.getProcessDefinitionId() != null) { return Flowable5Util.isFlowable5ProcessDefinitionId(processEngineConfiguration, job.getProcessDefinitionId()); } return false; } @Override public void executeV5Job(Job job) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.executeJob(job); } @Override public void executeV5JobWithLockAndRetry(final Job job) { // Retrieving the compatibility handler needs to be done outside of the executeJobWithLockAndRetry call, // as it shouldn't be wrapped in a transaction. Flowable5CompatibilityHandler compatibilityHandler = processEngineConfiguration.getCommandExecutor().execute(new Command<>() { @Override public Flowable5CompatibilityHandler execute(CommandContext commandContext) { return CommandContextUtil.getProcessEngineConfiguration(commandContext).getFlowable5CompatibilityHandler(); } });
// Note: no transaction (on purpose) compatibilityHandler.executeJobWithLockAndRetry(job); } @Override public void deleteV5Job(String jobId) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.deleteJob(jobId); } @Override public void handleFailedV5Job(AbstractRuntimeJobEntity job, Throwable exception) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.handleFailedJob(job, exception); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\DefaultInternalJobCompatibilityManager.java
1
请完成以下Java代码
public void setIncludeIncidents(Boolean includeClosedIncidents) { this.includeIncidents = includeClosedIncidents; } @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } @CamundaQueryParam(value = "finishedAfter", converter = DateConverter.class) public void setFinishedAfter(Date finishedAfter) { this.finishedAfter = finishedAfter; } @CamundaQueryParam(value = "finishedBefore", converter = DateConverter.class) public void setFinishedBefore(Date finishedBefore) { this.finishedBefore = finishedBefore; } @CamundaQueryParam(value = "processInstanceIdIn", converter = StringArrayConverter.class) public void setProcessInstanceIdIn(String[] processInstanceIdIn) { this.processInstanceIdIn = processInstanceIdIn; } @Override protected boolean isValidSortByValue(String value) { return SORT_ORDER_ACTIVITY_ID.equals(value); } @Override protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId); } @Override protected void applyFilters(HistoricActivityStatisticsQuery query) { if (includeCanceled != null && includeCanceled) { query.includeCanceled(); } if (includeFinished != null && includeFinished) { query.includeFinished(); } if (includeCompleteScope != null && includeCompleteScope) { query.includeCompleteScope();
} if (includeIncidents !=null && includeIncidents) { query.includeIncidents(); } if (startedAfter != null) { query.startedAfter(startedAfter); } if (startedBefore != null) { query.startedBefore(startedBefore); } if (finishedAfter != null) { query.finishedAfter(finishedAfter); } if (finishedBefore != null) { query.finishedBefore(finishedBefore); } if (processInstanceIdIn != null) { query.processInstanceIdIn(processInstanceIdIn); } } @Override protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) { query.orderByActivityId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityStatisticsQueryDto.java
1
请完成以下Java代码
public int getAD_PrinterHW_MediaTray_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaTray_ID); } @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() {
return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_MediaTray.java
1
请在Spring Boot框架中完成以下Java代码
public Object createView() { // 设置视图名 String newViewName = "usersView"; // 设置获取数据的集合名称 String collectionName = "users"; // 定义视图的管道,可是设置视图显示的内容多个筛选条件 List<Bson> pipeline = new ArrayList<>(); // 设置条件,用于筛选集合中的文档数据,只有符合条件的才会映射到视图中 pipeline.add(Document.parse("{\"$match\":{\"sex\":\"女\"}}")); // 执行创建视图 mongoTemplate.getDb().createView(newViewName, collectionName, pipeline); // 检测新的集合是否存在,返回创建结果 return mongoTemplate.collectionExists(newViewName) ? "创建视图成功" : "创建视图失败"; } /** * 删除视图 * * @return 删除视图结果
*/ public Object dropView() { // 设置待删除的视图名称 String viewName = "usersView"; // 检测视图是否存在 if (mongoTemplate.collectionExists(viewName)) { // 删除视图 mongoTemplate.getDb().getCollection(viewName).drop(); return "删除视图成功"; } // 检测新的集合是否存在,返回创建结果 return !mongoTemplate.collectionExists(viewName) ? "删除视图成功" : "删除视图失败"; } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\ViewService.java
2
请在Spring Boot框架中完成以下Java代码
class OAuth2AuthorizationServerWebSecurityConfiguration { @Bean @Order(Ordered.HIGHEST_PRECEDENCE) SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) { OAuth2AuthorizationServerConfigurer authorizationServer = new OAuth2AuthorizationServerConfigurer(); http.securityMatcher(authorizationServer.getEndpointsMatcher()); http.with(authorizationServer, withDefaults()); http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()); http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(withDefaults()); http.oauth2ResourceServer((resourceServer) -> resourceServer.jwt(withDefaults())); http.exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), createRequestMatcher())); return http.build(); }
@Bean @Order(SecurityFilterProperties.BASIC_AUTH_ORDER) SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) { http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()).formLogin(withDefaults()); return http.build(); } private static RequestMatcher createRequestMatcher() { MediaTypeRequestMatcher requestMatcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); requestMatcher.setIgnoredMediaTypes(Set.of(MediaType.ALL)); return requestMatcher; } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-authorization-server\src\main\java\org\springframework\boot\security\oauth2\server\authorization\autoconfigure\servlet\OAuth2AuthorizationServerWebSecurityConfiguration.java
2
请完成以下Java代码
public Result<?> handleSQLException(Exception exception) { String msg = exception.getMessage().toLowerCase(); final String extractvalue = "extractvalue"; final String updatexml = "updatexml"; boolean hasSensitiveInformation = msg.indexOf(extractvalue) >= 0 || msg.indexOf(updatexml) >= 0; if (msg != null && hasSensitiveInformation) { log.error("校验失败,存在SQL注入风险!{}", msg); return Result.error("校验失败,存在SQL注入风险!"); } addSysLog(exception); return Result.error("校验失败,存在SQL注入风险!" + msg); } /** * 添加异常新系统日志 * @param e 异常 * @author chenrui * @date 2024/4/22 17:16 */ private void addSysLog(Throwable e) { LogDTO log = new LogDTO(); log.setLogType(CommonConstant.LOG_TYPE_4); log.setLogContent(e.getClass().getName()+":"+e.getMessage()); log.setRequestParam(ExceptionUtils.getStackTrace(e)); //获取request HttpServletRequest request = null; try { request = SpringContextUtils.getHttpServletRequest(); } catch (NullPointerException | BeansException ignored) { } if (null != request) { //请求的参数 if (!isTooBigException(e)) { // 文件上传过大异常时不能获取参数,否则会报错 Map<String, String[]> parameterMap = request.getParameterMap(); if(!CollectionUtils.isEmpty(parameterMap)) { log.setMethod(oConvertUtils.mapToString(request.getParameterMap())); } } // 请求地址 log.setRequestUrl(request.getRequestURI()); //设置IP地址 log.setIp(IpUtils.getIpAddr(request)); //设置客户端 if(BrowserUtils.isDesktop(request)){ log.setClientType(ClientTerminalTypeEnum.PC.getKey()); }else{ log.setClientType(ClientTerminalTypeEnum.APP.getKey()); } } //获取登录用户信息 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); if(sysUser!=null){ log.setUserid(sysUser.getUsername()); log.setUsername(sysUser.getRealname()); }
baseCommonService.addLog(log); } /** * 是否文件过大异常 * for [QQYUN-11716]上传大图片失败没有精确提示 * @param e * @return * @author chenrui * @date 2025/4/8 20:21 */ private static boolean isTooBigException(Throwable e) { boolean isTooBigException = false; if(e instanceof MultipartException){ Throwable cause = e.getCause(); if (cause instanceof IllegalStateException){ isTooBigException = true; } } if(e instanceof MaxUploadSizeExceededException){ isTooBigException = true; } return isTooBigException; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\exception\JeecgBootExceptionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> dmnProcessEngineConfigurationConfigurer( DmnEngineConfigurator dmnEngineConfigurator ) { return processEngineConfiguration -> processEngineConfiguration.addConfigurator(dmnEngineConfigurator); } @Bean @ConditionalOnMissingBean public DmnEngineConfigurator dmnEngineConfigurator(SpringDmnEngineConfiguration configuration) { SpringDmnEngineConfigurator dmnEngineConfigurator = new SpringDmnEngineConfigurator(); dmnEngineConfigurator.setDmnEngineConfiguration(configuration); invokeConfigurers(configuration); return dmnEngineConfigurator; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(type = { "org.flowable.app.spring.SpringAppEngineConfiguration" }) public static class DmnEngineAppConfiguration extends BaseEngineConfigurationWithConfigurers<SpringDmnEngineConfiguration> { @Bean @ConditionalOnMissingBean(name = "dmnAppEngineConfigurationConfigurer") public EngineConfigurationConfigurer<SpringAppEngineConfiguration> dmnAppEngineConfigurationConfigurer( DmnEngineConfigurator dmnEngineConfigurator ) { return appEngineConfiguration -> appEngineConfiguration.addConfigurator(dmnEngineConfigurator);
} @Bean @ConditionalOnMissingBean public DmnEngineConfigurator dmnEngineConfigurator(SpringDmnEngineConfiguration configuration) { SpringDmnEngineConfigurator dmnEngineConfigurator = new SpringDmnEngineConfigurator(); dmnEngineConfigurator.setDmnEngineConfiguration(configuration); invokeConfigurers(configuration); return dmnEngineConfigurator; } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\dmn\DmnEngineAutoConfiguration.java
2
请完成以下Java代码
private Qualifier parseQualifier(Matcher matcher) { String qualifierSeparator = matcher.group(4); String qualifierId = matcher.group(5); if (StringUtils.hasText(qualifierSeparator) && StringUtils.hasText(qualifierId)) { String versionString = matcher.group(6); return new Qualifier(qualifierId, (versionString != null) ? Integer.valueOf(versionString) : null, qualifierSeparator); } return null; } /** * Parse safely the specified string representation of a {@link Version}. * <p> * Return {@code null} if the text represents an invalid version. * @param text the version text * @return a Version instance for the specified version text * @see #parse(java.lang.String) */ public Version safeParse(String text) { try { return parse(text); } catch (InvalidVersionException ex) { return null; } } /** * Parse the string representation of a {@link VersionRange}. Throws an * {@link InvalidVersionException} if the range could not be parsed. * @param text the range text * @return a VersionRange instance for the specified range text
* @throws InvalidVersionException if the range text could not be parsed */ public VersionRange parseRange(String text) { Assert.notNull(text, "Text must not be null"); Matcher matcher = RANGE_REGEX.matcher(text.trim()); if (!matcher.matches()) { // Try to read it as simple string Version version = parse(text); return new VersionRange(version, true, null, true); } boolean lowerInclusive = matcher.group(1).equals("["); Version lowerVersion = parse(matcher.group(2)); Version higherVersion = parse(matcher.group(3)); boolean higherInclusive = matcher.group(4).equals("]"); return new VersionRange(lowerVersion, lowerInclusive, higherVersion, higherInclusive); } private Version findLatestVersion(Integer major, Integer minor, Version.Qualifier qualifier) { List<Version> matches = this.latestVersions.stream().filter((it) -> { if (major != null && !major.equals(it.getMajor())) { return false; } if (minor != null && !minor.equals(it.getMinor())) { return false; } if (qualifier != null && !qualifier.equals(it.getQualifier())) { return false; } return true; }).toList(); return (matches.size() != 1) ? null : matches.get(0); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionParser.java
1
请完成以下Java代码
default RequestReplyMessageFuture<K, V> sendAndReceive(Message<?> message) { throw new UnsupportedOperationException(); } /** * Send a request message and receive a reply message. * @param message the message to send. * @param replyTimeout the reply timeout; if null, the default will be used. * @return a RequestReplyMessageFuture. * @since 2.7 */ default RequestReplyMessageFuture<K, V> sendAndReceive(Message<?> message, @Nullable Duration replyTimeout) { throw new UnsupportedOperationException(); } /** * Send a request message and receive a reply message. * @param message the message to send. * @param returnType a hint to the message converter for the reply payload type. * @param <P> the reply payload type. * @return a RequestReplyMessageFuture. * @since 2.7 */ default <P> RequestReplyTypedMessageFuture<K, V, P> sendAndReceive(Message<?> message, ParameterizedTypeReference<P> returnType) { throw new UnsupportedOperationException(); } /** * Send a request message and receive a reply message. * @param message the message to send. * @param replyTimeout the reply timeout; if null, the default will be used.
* @param returnType a hint to the message converter for the reply payload type. * @param <P> the reply payload type. * @return a RequestReplyMessageFuture. * @since 2.7 */ default <P> RequestReplyTypedMessageFuture<K, V, P> sendAndReceive(Message<?> message, Duration replyTimeout, @Nullable ParameterizedTypeReference<P> returnType) { throw new UnsupportedOperationException(); } /** * Send a request and receive a reply with the default timeout. * @param record the record to send. * @return a RequestReplyFuture. */ RequestReplyFuture<K, V, R> sendAndReceive(ProducerRecord<K, V> record); /** * Send a request and receive a reply. * @param record the record to send. * @param replyTimeout the reply timeout; if null, the default will be used. * @return a RequestReplyFuture. * @since 2.3 */ RequestReplyFuture<K, V, R> sendAndReceive(ProducerRecord<K, V> record, Duration replyTimeout); }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\ReplyingKafkaOperations.java
1
请完成以下Java代码
public static void writeIncomingElementChild(XMLStreamWriter xtw, SequenceFlow incomingSequence) throws Exception { xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_GATEWAY_INCOMING, BPMN2_NAMESPACE); xtw.writeCharacters(incomingSequence.getId()); xtw.writeEndElement(); } public static void writeOutgoingElementChild(XMLStreamWriter xtw, SequenceFlow outgoingSequence) throws Exception { xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_GATEWAY_OUTGOING, BPMN2_NAMESPACE); xtw.writeCharacters(outgoingSequence.getId()); xtw.writeEndElement(); } /** * 'safe' is here reflecting: * http://activiti.org/userguide/index.html#advanced.safe.bpmn.xml */ public static XMLInputFactory createSafeXmlInputFactory() {
XMLInputFactory xif = XMLInputFactory.newInstance(); if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) { xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); } if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) { xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) { xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); } return xif; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\util\BpmnXMLUtil.java
1
请完成以下Java代码
public JsonAttachmentSourceType toJsonAttachmentSourceType(@NonNull final AttachmentEntryType type) { switch (type) { case Data: return JsonAttachmentSourceType.Data; case URL: return JsonAttachmentSourceType.URL; case LocalFileURL: return JsonAttachmentSourceType.LocalFileURL; default: throw new AdempiereException("Unknown AttachmentEntryType") .appendParametersToMessage() .setParameter("type", type); } }
@NonNull public AttachmentEntryType toAttachmentType(@NonNull final JsonAttachmentSourceType type) { switch (type) { case Data: return AttachmentEntryType.Data; case URL: return AttachmentEntryType.URL; case LocalFileURL: return AttachmentEntryType.LocalFileURL; default: throw new AdempiereException("Unknown JsonAttachmentSourceType") .appendParametersToMessage() .setParameter("type", type); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\util\JsonConverters.java
1
请完成以下Java代码
public MessagePayloadMappingProvider createMessagePayloadMappingProvider( Event bpmnEvent, MessageEventDefinition messageEventDefinition ) { return getMessagePayloadMappingProviderFactory().create( bpmnEvent, messageEventDefinition, getExpressionManager() ); } protected Optional<String> checkClassDelegate(Map<String, List<ExtensionAttribute>> attributes) { return getAttributeValue(attributes, "class"); } protected Optional<String> checkDelegateExpression(Map<String, List<ExtensionAttribute>> attributes) { return getAttributeValue(attributes, "delegateExpression");
} protected Optional<String> getAttributeValue(Map<String, List<ExtensionAttribute>> attributes, String name) { return Optional.ofNullable(attributes) .filter(it -> it.containsKey("activiti")) .map(it -> it.get("activiti")) .flatMap(it -> it .stream() .filter(el -> name.equals(el.getName())) .findAny() ) .map(ExtensionAttribute::getValue); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractHibernateDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> { @Autowired protected SessionFactory sessionFactory; // API @Override public T findOne(final long id) { return (T) getCurrentSession().get(clazz, id); } @Override public List<T> findAll() { return getCurrentSession().createQuery("from " + clazz.getName()).getResultList(); } @Override public void create(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().saveOrUpdate(entity); }
@Override public T update(final T entity) { Preconditions.checkNotNull(entity); return (T) getCurrentSession().merge(entity); } @Override public void delete(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().delete(entity); } @Override public void deleteById(final long entityId) { final T entity = findOne(entityId); Preconditions.checkState(entity != null); delete(entity); } protected Session getCurrentSession() { return sessionFactory.getCurrentSession(); } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\manytomany\dao\common\AbstractHibernateDao.java
2
请在Spring Boot框架中完成以下Java代码
public class ProductRepository { private static final Logger LOGGER = LoggerFactory.getLogger(ProductRepository.class); private final Map<Long, Product> productMap = new HashMap<>(); public Product getProduct(Long productId){ LOGGER.info("Getting Product from Product Repo With Product Id {}", productId); if(!productMap.containsKey(productId)){ LOGGER.error("Product Not Found for Product Id {}", productId); throw new ProductNotFoundException("Product Not Found"); } return productMap.get(productId); } @PostConstruct private void setupRepo() { Product product1 = getProduct(100001, "apple"); productMap.put(100001L, product1);
Product product2 = getProduct(100002, "pears"); productMap.put(100002L, product2); Product product3 = getProduct(100003, "banana"); productMap.put(100003L, product3); Product product4 = getProduct(100004, "mango"); productMap.put(100004L, product4); Product product5 = getProduct(100005, "test"); productMap.put(100005L, product5); } private static Product getProduct(int id, String name) { Product product = new Product(); product.setId(id); product.setName(name); return product; } }
repos\tutorials-master\spring-boot-modules\spring-boot-open-telemetry\spring-boot-open-telemetry1\src\main\java\com\baeldung\opentelemetry\repository\ProductRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void setNumberOfInsured(String numberOfInsured) { this.numberOfInsured = numberOfInsured; } public PatientPayer copaymentFromDate(LocalDate copaymentFromDate) { this.copaymentFromDate = copaymentFromDate; return this; } /** * Zuzahlungsbefreit ab Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung * @return copaymentFromDate **/ @Schema(example = "Mon Jan 01 00:00:00 GMT 2018", description = "Zuzahlungsbefreit ab Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung") public LocalDate getCopaymentFromDate() { return copaymentFromDate; } public void setCopaymentFromDate(LocalDate copaymentFromDate) { this.copaymentFromDate = copaymentFromDate; } public PatientPayer copaymentToDate(LocalDate copaymentToDate) { this.copaymentToDate = copaymentToDate; return this; } /** * Zuzahlungsbefreit bis Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung * @return copaymentToDate **/ @Schema(example = "Wed Jan 31 00:00:00 GMT 2018", description = "Zuzahlungsbefreit bis Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung") public LocalDate getCopaymentToDate() { return copaymentToDate; } public void setCopaymentToDate(LocalDate copaymentToDate) { this.copaymentToDate = copaymentToDate; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientPayer patientPayer = (PatientPayer) o; return Objects.equals(this.payerId, patientPayer.payerId) && Objects.equals(this.payerType, patientPayer.payerType) && Objects.equals(this.numberOfInsured, patientPayer.numberOfInsured) && Objects.equals(this.copaymentFromDate, patientPayer.copaymentFromDate) && Objects.equals(this.copaymentToDate, patientPayer.copaymentToDate);
} @Override public int hashCode() { return Objects.hash(payerId, payerType, numberOfInsured, copaymentFromDate, copaymentToDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientPayer {\n"); sb.append(" payerId: ").append(toIndentedString(payerId)).append("\n"); sb.append(" payerType: ").append(toIndentedString(payerType)).append("\n"); sb.append(" numberOfInsured: ").append(toIndentedString(numberOfInsured)).append("\n"); sb.append(" copaymentFromDate: ").append(toIndentedString(copaymentFromDate)).append("\n"); sb.append(" copaymentToDate: ").append(toIndentedString(copaymentToDate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientPayer.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getResourceUrl() { return resourceUrl; } public void setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; }
public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\EngineInfoResponse.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<CreateServiceInstanceBindingResponse> createServiceInstanceBinding( CreateServiceInstanceBindingRequest request) { return Mono.just(CreateServiceInstanceAppBindingResponse.builder()) .flatMap(responseBuilder -> mailService.serviceBindingExists( request.getServiceInstanceId(), request.getBindingId()) .flatMap(exists -> { if (exists) { return mailService.getServiceBinding( request.getServiceInstanceId(), request.getBindingId()) .flatMap(serviceBinding -> Mono.just(responseBuilder .bindingExisted(true) .credentials(serviceBinding.getCredentials()) .build())); } else { return mailService.createServiceBinding( request.getServiceInstanceId(), request.getBindingId()) .switchIfEmpty(Mono.error( new ServiceInstanceDoesNotExistException( request.getServiceInstanceId()))) .flatMap(mailServiceBinding -> Mono.just(responseBuilder .bindingExisted(false) .credentials(mailServiceBinding.getCredentials()) .build())); } })); } @Override public Mono<GetServiceInstanceBindingResponse> getServiceInstanceBinding(GetServiceInstanceBindingRequest request) { return mailService.getServiceBinding(request.getServiceInstanceId(), request.getBindingId())
.switchIfEmpty(Mono.error(new ServiceInstanceBindingDoesNotExistException(request.getBindingId()))) .flatMap(mailServiceBinding -> Mono.just(GetServiceInstanceAppBindingResponse.builder() .credentials(mailServiceBinding.getCredentials()) .build())); } @Override public Mono<DeleteServiceInstanceBindingResponse> deleteServiceInstanceBinding( DeleteServiceInstanceBindingRequest request) { return mailService.serviceBindingExists(request.getServiceInstanceId(), request.getBindingId()) .flatMap(exists -> { if (exists) { return mailService.deleteServiceBinding(request.getServiceInstanceId()) .thenReturn(DeleteServiceInstanceBindingResponse.builder().build()); } else { return Mono.error(new ServiceInstanceBindingDoesNotExistException(request.getBindingId())); } }); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-open-service-broker\src\main\java\com\baeldung\spring\cloud\openservicebroker\services\MailServiceInstanceBindingService.java
2
请在Spring Boot框架中完成以下Java代码
public class RpUserInfo extends BaseEntity implements Serializable { private String userNo; private String userName; private String accountNo; private static final long serialVersionUID = 1L; private String mobile; private String password; /** 支付密码 */ private String payPwd; public String getPayPwd() { return payPwd; } public void setPayPwd(String payPwd) { this.payPwd = payPwd; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo == null ? null : accountNo.trim(); } public String getStatusDesc() { return PublicStatusEnum.getEnum(this.getStatus()).getDesc(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserInfo.java
2
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "ename") private String name; @OneToOne(cascade = CascadeType.ALL) @JoinTable(name = "emp_workstation", joinColumns = {@JoinColumn(name = "employee_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "workstation_id", referencedColumnName = "id")}) private WorkStation workStation; 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 WorkStation getWorkStation() { return workStation; } public void setWorkStation(WorkStation workStation) { this.workStation = workStation; } }
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\onetoone\jointablebased\Employee.java
2
请完成以下Java代码
public static Optional<String> getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise */ public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS))) .orElse(false); }
/** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the isUserInRole() method in the Servlet API * * @param authority the authority to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) .orElse(false); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\security\SecurityUtils.java
1
请在Spring Boot框架中完成以下Java代码
private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition { PreferGsonOrJacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "gson") static class GsonPreferred { } @Conditional(JacksonAndJsonbUnavailableCondition.class) static class JacksonJsonbUnavailable { } } private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions { JacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnBean(JacksonHttpMessageConvertersConfiguration.JacksonJsonHttpMessageConvertersCustomizer.class) static class JacksonAvailable { }
@SuppressWarnings("removal") @ConditionalOnBean(Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class) static class Jackson2Available { } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\GsonHttpMessageConvertersConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; } @Bean public ViewResolver viewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); resolver.setCharacterEncoding("UTF-8"); return resolver; } @Bean public ISpringTemplateEngine templateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true); engine.setTemplateResolver(templateResolver()); engine.addDialect(new SpringSecurityDialect()); return engine; } private ITemplateResolver templateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/templates/"); resolver.setSuffix(".html"); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } }
repos\tutorials-master\spring-security-modules\spring-security-web-rest-custom\src\main\java\com\baeldung\config\child\WebConfig.java
2
请完成以下Java代码
public String getF_USING() { return F_USING; } public void setF_USING(String f_USING) { F_USING = f_USING; } public String getF_USINGDATE() { return F_USINGDATE; } public void setF_USINGDATE(String f_USINGDATE) { F_USINGDATE = f_USINGDATE; } public Integer getF_LEVEL() { return F_LEVEL; } public void setF_LEVEL(Integer f_LEVEL) { F_LEVEL = f_LEVEL; } public String getF_END() { return F_END; } public void setF_END(String f_END) { F_END = f_END; } public String getF_QRCANTONID() { return F_QRCANTONID; } public void setF_QRCANTONID(String f_QRCANTONID) { F_QRCANTONID = f_QRCANTONID; }
public String getF_DECLARE() { return F_DECLARE; } public void setF_DECLARE(String f_DECLARE) { F_DECLARE = f_DECLARE; } public String getF_DECLAREISEND() { return F_DECLAREISEND; } public void setF_DECLAREISEND(String f_DECLAREISEND) { F_DECLAREISEND = f_DECLAREISEND; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscCanton.java
1
请完成以下Java代码
private int getNumberOfYearsForApproval(final I_C_BP_SupplierApproval bPartnerSupplierApproval) { final SupplierApproval supplierApproval = SupplierApproval.ofNullableCode(bPartnerSupplierApproval.getSupplierApproval()); if (supplierApproval == null) { // the vendor doesn't have a supplier approval return 0; } if (supplierApproval.isOneYear()) { return 1; } else if (supplierApproval.isTwoYears()) { return 2; } else if (supplierApproval.isThreeYears()) { return 3; } // should not happen // the vendor doesn't have a supplier approval return 0; } private boolean supplierApprovalExpired(final LocalDate supplierApprovalDate, final LocalDate datePromised, final int numberOfYears) { return datePromised.minusYears(numberOfYears).isAfter(supplierApprovalDate); } public void notifyUserGroupAboutSupplierApprovalExpiration() { final ImmutableList<I_C_BP_SupplierApproval> bpSupplierApprovals = repo.retrieveBPSupplierApprovalsAboutToExpire(MAX_MONTHS_UNTIL_EXPIRATION_DATE); for (final I_C_BP_SupplierApproval supplierApprovalRecord : bpSupplierApprovals) { notifyUserGroupAboutSupplierApprovalExpiration(supplierApprovalRecord); } } private void notifyUserGroupAboutSupplierApprovalExpiration(@NonNull final I_C_BP_SupplierApproval supplierApprovalRecord) { final UserNotificationRequest.TargetRecordAction targetRecordAction = UserNotificationRequest .TargetRecordAction .of(I_C_BPartner.Table_Name, supplierApprovalRecord.getC_BPartner_ID()); final UserGroupId userGroupId = orgDAO.getSupplierApprovalExpirationNotifyUserGroupID(OrgId.ofRepoId(supplierApprovalRecord.getAD_Org_ID())); if (userGroupId == null) { // nobody to notify return;
} final String partnerName = bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(supplierApprovalRecord.getC_BPartner_ID())); final String supplierApprovalNorm = supplierApprovalRecord.getSupplierApproval_Norm(); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(supplierApprovalRecord.getAD_Org_ID())); final LocalDate expirationDate = TimeUtil.asLocalDate(supplierApprovalRecord.getSupplierApproval_Date(), timeZone) .plusYears(getNumberOfYearsForApproval(supplierApprovalRecord)); userGroupRepository .getByUserGroupId(userGroupId) .streamAssignmentsFor(userGroupId, Instant.now()) .map(UserGroupUserAssignment::getUserId) .map(userId -> UserNotificationRequest.builder() .recipientUserId(userId) .contentADMessage(MSG_Partner_SupplierApproval_ExpirationDate) .contentADMessageParam(partnerName) .contentADMessageParam(supplierApprovalNorm) .contentADMessageParam(expirationDate) .targetAction(targetRecordAction) .build()) .forEach(notificationBL::send); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerSupplierApprovalService.java
1
请完成以下Java代码
private boolean isOnlyOneTourInstanceExpected(final ITourInstanceQueryParams params) { Check.assumeNotNull(params, "params not null"); if (params.getM_ShipperTransportation_ID() > 0) { return true; } return false; } @Override public I_M_Tour_Instance retrieveTourInstance(final Object contextProvider, final ITourInstanceQueryParams params) { Check.assumeNotNull(contextProvider, "contextProvider not null"); final IQueryBuilder<I_M_Tour_Instance> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_M_Tour_Instance.class, contextProvider) // Only active tour instances are relevant for us .addOnlyActiveRecordsFilter() // Matching our params .filter(createTourInstanceMatcher(params)); queryBuilder.orderBy() .addColumn(I_M_Tour_Instance.COLUMNNAME_M_ShipperTransportation_ID, Direction.Descending, Nulls.Last); if (isOnlyOneTourInstanceExpected(params)) { return queryBuilder .create() .firstOnly(I_M_Tour_Instance.class); } else { return queryBuilder .create() .first(I_M_Tour_Instance.class); } } @Override public boolean isTourInstanceMatches(final I_M_Tour_Instance tourInstance, final ITourInstanceQueryParams params)
{ if (tourInstance == null) { return false; } return createTourInstanceMatcher(params) .accept(tourInstance); } @Override public boolean hasDeliveryDays(final I_M_Tour_Instance tourInstance) { Check.assumeNotNull(tourInstance, "tourInstance not null"); final int tourInstanceId = tourInstance.getM_Tour_Instance_ID(); Check.assume(tourInstanceId > 0, "tourInstance shall not be a new/not saved one"); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_DeliveryDay.class, tourInstance) // .addOnlyActiveRecordsFilter() // check all records // Delivery days for our tour instance .addEqualsFilter(I_M_DeliveryDay.COLUMN_M_Tour_Instance_ID, tourInstanceId) .create() .anyMatch(); } public I_M_Tour_Instance retrieveTourInstanceForShipperTransportation(final I_M_ShipperTransportation shipperTransportation) { Check.assumeNotNull(shipperTransportation, "shipperTransportation not null"); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_Tour_Instance.class, shipperTransportation) // .addOnlyActiveRecordsFilter() // Delivery days for our tour instance .addEqualsFilter(I_M_Tour_Instance.COLUMN_M_ShipperTransportation_ID, shipperTransportation.getM_ShipperTransportation_ID()) .create() .firstOnly(I_M_Tour_Instance.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourInstanceDAO.java
1
请在Spring Boot框架中完成以下Java代码
public DirectExchange demo05Exchange() { return new DirectExchange(Demo05Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo05Message.EXCHANGE // Routing key:Demo05Message.ROUTING_KEY // Queue:Demo05Message.QUEUE @Bean public Binding demo05Binding() { return BindingBuilder.bind(demo05Queue()).to(demo05Exchange()).with(Demo05Message.ROUTING_KEY); } } @Bean public BatchingRabbitTemplate batchRabbitTemplate(ConnectionFactory connectionFactory) {
// 创建 BatchingStrategy 对象,代表批量策略 int batchSize = 16384; // 超过收集的消息数量的最大条数。 int bufferLimit = 33554432; // 每次批量发送消息的最大内存 int timeout = 30000; // 超过收集的时间的最大等待时长,单位:毫秒 BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(batchSize, bufferLimit, timeout); // 创建 TaskScheduler 对象,用于实现超时发送的定时器 TaskScheduler taskScheduler = new ConcurrentTaskScheduler(); // 创建 BatchingRabbitTemplate 对象 BatchingRabbitTemplate batchTemplate = new BatchingRabbitTemplate(batchingStrategy, taskScheduler); batchTemplate.setConnectionFactory(connectionFactory); return batchTemplate; } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-batch\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请在Spring Boot框架中完成以下Java代码
public void setAckTimeout(Long ackTimeout) { this.ackTimeout = ackTimeout; } @Override protected DirectMessageListenerContainer createContainerInstance() { return new DirectMessageListenerContainer(); } @Override protected void initializeContainer(DirectMessageListenerContainer instance, @Nullable RabbitListenerEndpoint endpoint) { super.initializeContainer(instance, endpoint); JavaUtils javaUtils = JavaUtils.INSTANCE.acceptIfNotNull(this.taskScheduler, instance::setTaskScheduler) .acceptIfNotNull(this.monitorInterval, instance::setMonitorInterval)
.acceptIfNotNull(this.messagesPerAck, instance::setMessagesPerAck) .acceptIfNotNull(this.ackTimeout, instance::setAckTimeout); if (endpoint != null && endpoint.getConcurrency() != null) { try { instance.setConsumersPerQueue(Integer.parseInt(endpoint.getConcurrency())); } catch (NumberFormatException e) { throw new IllegalStateException("Failed to parse concurrency: " + e.getMessage(), e); } } else { javaUtils.acceptIfNotNull(this.consumersPerQueue, instance::setConsumersPerQueue); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\DirectRabbitListenerContainerFactory.java
2
请完成以下Java代码
private static CostAmountAndQtyDetailed of(final @NonNull CostAmountType type, @NonNull final CostAmountAndQty amtAndQty) { final CostAmountAndQtyDetailed costAmountAndQtyDetailed; switch (type) { case MAIN: costAmountAndQtyDetailed = builder().main(amtAndQty).build(); break; case ADJUSTMENT: costAmountAndQtyDetailed = builder().costAdjustment(amtAndQty).build(); break; case ALREADY_SHIPPED: costAmountAndQtyDetailed = builder().alreadyShipped(amtAndQty).build(); break; default: throw new IllegalArgumentException(); } return costAmountAndQtyDetailed; } public static CostAmountAndQtyDetailed zero(@NonNull final CurrencyId currencyId, @NonNull final UomId uomId) { final CostAmountAndQty zero = CostAmountAndQty.zero(currencyId, uomId); return new CostAmountAndQtyDetailed(zero, zero, zero); } public CostAmountAndQtyDetailed add(@NonNull final CostAmountAndQtyDetailed other) { return builder() .main(main.add(other.main)) .costAdjustment(costAdjustment.add(other.costAdjustment)) .alreadyShipped(alreadyShipped.add(other.alreadyShipped)) .build(); } public CostAmountAndQtyDetailed negateIf(final boolean condition) { return condition ? negate() : this; }
public CostAmountAndQtyDetailed negate() { return builder() .main(main.negate()) .costAdjustment(costAdjustment.negate()) .alreadyShipped(alreadyShipped.negate()) .build(); } public CostAmountAndQty getAmtAndQty(final CostAmountType type) { final CostAmountAndQty costAmountAndQty; switch (type) { case MAIN: costAmountAndQty = main; break; case ADJUSTMENT: costAmountAndQty = costAdjustment; break; case ALREADY_SHIPPED: costAmountAndQty = alreadyShipped; break; default: throw new IllegalArgumentException(); } return costAmountAndQty; } public CostAmountDetailed getAmt() { return CostAmountDetailed.builder() .mainAmt(main.getAmt()) .costAdjustmentAmt(costAdjustment.getAmt()) .alreadyShippedAmt(alreadyShipped.getAmt()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostAmountAndQtyDetailed.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImplementationRef() { return implementationRef; } public void setImplementationRef(String implementationRef) { this.implementationRef = implementationRef; } public List<Operation> getOperations() { return operations; } public void setOperations(List<Operation> operations) { this.operations = operations; } public Interface clone() { Interface clone = new Interface(); clone.setValues(this);
return clone; } public void setValues(Interface otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setImplementationRef(otherElement.getImplementationRef()); operations = new ArrayList<Operation>(); if (otherElement.getOperations() != null && !otherElement.getOperations().isEmpty()) { for (Operation operation : otherElement.getOperations()) { operations.add(operation.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Interface.java
1
请完成以下Java代码
public static String getScheme(HttpServletRequest request){ String scheme = request.getScheme(); String forwardedProto = request.getHeader("x-forwarded-proto"); if (forwardedProto != null) { scheme = forwardedProto; } return scheme; } public static String getDomainName(HttpServletRequest request){ return request.getServerName(); } public static String getDomainNameAndPort(HttpServletRequest request){ String domainName = getDomainName(request); String scheme = getScheme(request); int port = MiscUtils.getPort(request); if (needsPort(scheme, port)) { domainName += ":" + port; } return domainName; } private static boolean needsPort(String scheme, int port) { boolean isHttpDefault = "http".equals(scheme.toLowerCase()) && port == 80; boolean isHttpsDefault = "https".equals(scheme.toLowerCase()) && port == 443; return !isHttpDefault && !isHttpsDefault; } public static int getPort(HttpServletRequest request){ String forwardedProto = request.getHeader("x-forwarded-proto"); int serverPort = request.getServerPort();
if (request.getHeader("x-forwarded-port") != null) { try { serverPort = request.getIntHeader("x-forwarded-port"); } catch (NumberFormatException e) { } } else if (forwardedProto != null) { switch (forwardedProto) { case "http": serverPort = 80; break; case "https": serverPort = 443; break; } } return serverPort; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\utils\MiscUtils.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("name", this.name); persistentState.put("owner", this.owner); persistentState.put("query", this.query); persistentState.put("properties", this.properties); return persistentState; } protected FilterEntity copyFilter() { FilterEntity copy = new FilterEntity(getResourceType()); copy.setName(getName()); copy.setOwner(getOwner()); copy.setQueryInternal(getQueryInternal()); copy.setPropertiesInternal(getPropertiesInternal()); return copy; }
public void postLoad() { if (query != null) { query.addValidator(StoredQueryValidator.get()); } } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\FilterEntity.java
1
请在Spring Boot框架中完成以下Java代码
public static class Config { @NotEmpty private @Nullable String param; private @Nullable String regexp; private @Nullable Predicate<String> predicate; public @Nullable String getParam() { return this.param; } public Config setParam(String param) { this.param = param; return this; } public @Nullable String getRegexp() { return this.regexp; } public Config setRegexp(@Nullable String regexp) { this.regexp = regexp; return this; } public @Nullable Predicate<String> getPredicate() { return this.predicate; }
public Config setPredicate(Predicate<String> predicate) { this.predicate = predicate; return this; } /** * Enforces the validation done on predicate configuration: {@link #regexp} and * {@link #predicate} can't be both set at runtime. * @return <code>false</code> if {@link #regexp} and {@link #predicate} are both * set in this predicate factory configuration */ @AssertTrue public boolean isValid() { return !(StringUtils.hasText(this.regexp) && this.predicate != null); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\QueryRoutePredicateFactory.java
2
请在Spring Boot框架中完成以下Java代码
private void unmarkSalesDefaultContacts(final List<BPartnerContact> contacts) { for (final BPartnerContact contact : contacts) { final BPartnerContactType contactType = contact.getContactType(); if (contactType == null) { continue; } contactType.setSalesDefault(false); } } private void unmarkShipToDefaultContacts(final List<BPartnerContact> contacts) { for (final BPartnerContact contact : contacts) { final BPartnerContactType contactType = contact.getContactType(); if (contactType == null) { continue; } contactType.setShipToDefault(false); }
} private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm) { final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(newTerm.getAD_Org_ID())); return FlatrateTermPricing.builder() .termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID())) .qty(newTerm.getPlannedQtyPerUnit()) .term(newTerm) .priceDate(TimeUtil.asLocalDate(newTerm.getStartDate(), timeZone)) .build() .computeOrThrowEx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\service\OrgChangeCommand.java
2
请完成以下Java代码
public String getCurrentActivityName() { String currentActivityName = null; if (this.activity != null) { currentActivityName = (String) activity.getProperty("name"); } return currentActivityName; } public FlowElement getBpmnModelElementInstance() { throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl"); } public BpmnModelInstance getBpmnModelInstance() { throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl"); } public ProcessEngineServices getProcessEngineServices() { throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl"); }
public ProcessEngine getProcessEngine() { throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl"); } public void forceUpdate() { // nothing to do } public void fireHistoricProcessStartEvent() { // do nothing } protected void removeVariablesLocalInternal(){ // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ExecutionImpl.java
1
请完成以下Java代码
private CapturedHUInfo getCapturedHUInfoOrNull(@NonNull final I_M_HU hu) { return capturedHUInfos.get(HuId.ofRepoId(hu.getM_HU_ID())); } public void updatePackToHU(@NonNull final I_M_HU hu) { updatePackToHUs(ImmutableList.of(hu)); } public void updatePackToHUs(@NonNull final LUTUResult lutu) { updatePackToHUs(lutu.getAllTUOrCURecords()); } public void updatePackToHUs(@NonNull final List<I_M_HU> hus) { if (!isApplicable()) { return; } if (hus.isEmpty()) { return; } if (hus.size() == 1) { final I_M_HU hu = hus.get(0); setWeightNet(hu, weightToTransfer); } else { final Quantity catchWeightToDistribute = weightToTransfer.divide(hus.size()); Quantity distributedCatchWeight = weightToTransfer.toZero(); for (int index = 0; index < hus.size(); index++) { final Quantity actualWeightToDistribute = index + 1 == hus.size() ? weightToTransfer.subtract(distributedCatchWeight) : catchWeightToDistribute;
distributedCatchWeight = distributedCatchWeight.add(actualWeightToDistribute); setWeightNet(hus.get(index), actualWeightToDistribute); } } } private void setWeightNet(@NonNull final I_M_HU hu, @NonNull final Quantity weightNet) { final IAttributeStorage huAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); huAttributes.setSaveOnChange(true); final IWeightable weightable = Weightables.wrap(huAttributes); final Quantity catchWeightConv = uomConversionBL.convertQuantityTo(weightNet, productId, weightable.getWeightNetUOM()); weightable.setWeightNet(catchWeightConv.toBigDecimal()); } // // // @Value @Builder private static class CapturedHUInfo { @NonNull HuId huId; @NonNull Quantity weightNet; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackedHUWeightNetUpdater.java
1