instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class JsonErrorItem { String message; @JsonInclude(Include.NON_EMPTY) @Nullable String errorCode; boolean userFriendlyError; @JsonInclude(Include.NON_EMPTY) String detail; @JsonInclude(Include.NON_EMPTY) String stackTrace; Map<String, String> parameters; @JsonInclude(Include.NON_EMPTY) JsonMetasfreshId adIssueId; @Nullable String orgCode; @Nullable String sourceClassName; @Nullable String sourceMethodName; @Nullable String issueCategory; /** * Local exception. * It won't be serialized. It's just used for local troubleshooting. */ @JsonIgnore transient Throwable throwable; @JsonCreator @Builder private JsonErrorItem( @JsonProperty("message") @Nullable final String message, @JsonProperty("errorCode") @Nullable final String errorCode, @JsonProperty("userFriendlyError") final boolean userFriendlyError, @JsonProperty("detail") @Nullable final String detail, @JsonProperty("stackTrace") @Nullable final String stackTrace, @JsonProperty("parameters") @Nullable @Singular final Map<String, String> parameters,
@JsonProperty("adIssueId") @Nullable final JsonMetasfreshId adIssueId, @JsonProperty("orgCode") @Nullable final String orgCode, @JsonProperty("sourceClassName") @Nullable final String sourceClassName, @JsonProperty("sourceMethodName") @Nullable final String sourceMethodName, @JsonProperty("issueCategory") @Nullable final String issueCategory, @Nullable final Throwable throwable) { this.message = message; this.errorCode = errorCode; this.userFriendlyError = userFriendlyError; this.detail = detail; this.stackTrace = stackTrace; this.parameters = CoalesceUtil.coalesce(parameters, ImmutableMap.of()); this.adIssueId = adIssueId; this.sourceClassName = sourceClassName; this.sourceMethodName = sourceMethodName; this.issueCategory = issueCategory; this.orgCode = orgCode; this.throwable = throwable; } @JsonPOJOBuilder(withPrefix = "") public static class JsonErrorItemBuilder { } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\JsonErrorItem.java
2
请完成以下Java代码
public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setSiteName (final @Nullable java.lang.String SiteName) { set_ValueNoCheck (COLUMNNAME_SiteName, SiteName); } @Override public java.lang.String getSiteName() { return get_ValueAsString(COLUMNNAME_SiteName); } @Override public void setValue (final @Nullable java.lang.String Value) {
set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_119_v.java
1
请在Spring Boot框架中完成以下Java代码
protected void initClient() throws Exception { if (mqttClient == null || !mqttClient.isConnected()) { String clientId = MqttAsyncClient.generateClientId(); String accessToken = target.getDevice().getCredentials().getCredentialsId(); mqttClient = new MqttClient(target.getBaseUrl(), clientId, new MemoryPersistence()); mqttClient.setTimeToWait(config.getRequestTimeoutMs()); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(accessToken); options.setConnectionTimeout(config.getRequestTimeoutMs() / 1000); IMqttToken result = mqttClient.connectWithResult(options); if (result.getException() != null) { throw result.getException(); } log.debug("Initialized MQTT client for URI {}", mqttClient.getServerURI()); } } @Override protected void sendTestPayload(String payload) throws Exception {
MqttMessage message = new MqttMessage(); message.setPayload(payload.getBytes()); message.setQos(config.getQos()); mqttClient.publish(DEVICE_TELEMETRY_TOPIC, message); } @Override protected void destroyClient() throws Exception { if (mqttClient != null) { mqttClient.disconnect(); mqttClient = null; log.info("Disconnected MQTT client"); } } @Override protected TransportType getTransportType() { return TransportType.MQTT; } }
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\transport\impl\MqttTransportHealthChecker.java
2
请完成以下Java代码
private ManagedChannel createChannel() { Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); URI requestURI = Objects.requireNonNull(route, "Route not found in exchange attributes").getUri(); return createChannelChannel(requestURI.getHost(), requestURI.getPort()); } private Function<JsonNode, DynamicMessage> callGRPCServer() { return jsonRequest -> { try { DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor); JsonFormat.parser().merge(jsonRequest.toString(), builder); return ClientCalls.blockingUnaryCall(clientCall, builder.build()); } catch (IOException e) { throw new RuntimeException(e); } }; } private Function<DynamicMessage, Object> serialiseGRPCResponse() { return gRPCResponse -> { try { return objectReader .readValue(JsonFormat.printer().omittingInsignificantWhitespace().print(gRPCResponse)); } catch (IOException e) { throw new RuntimeException(e); } }; } private Flux<JsonNode> deserializeJSONRequest() { return exchange.getRequest().getBody().mapNotNull(dataBufferBody -> { if (dataBufferBody.capacity() == 0) {
return objectNode; } ResolvableType targetType = ResolvableType.forType(JsonNode.class); return new JacksonJsonDecoder().decode(dataBufferBody, targetType, null, null); }).cast(JsonNode.class); } private Function<Object, DataBuffer> wrapGRPCResponse() { return jsonResponse -> new NettyDataBufferFactory(new PooledByteBufAllocator()) .wrap(Objects.requireNonNull(new ObjectMapper().writeValueAsBytes(jsonResponse))); } // We are creating this on every call, should optimize? private ManagedChannel createChannelChannel(String host, int port) { NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port); try { return grpcSslConfigurer.configureSsl(nettyChannelBuilder); } catch (SSLException e) { throw new RuntimeException(e); } } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\JsonToGrpcGatewayFilterFactory.java
1
请完成以下Java代码
public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getCalledProcessInstanceId() { return calledProcessInstanceId; }
public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } @Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Date getTime() { return getStartTime(); } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "HistoricActivityInstanceEntity[activityId=" + activityId + ", activityName=" + activityName + "]"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricActivityInstanceEntity.java
1
请完成以下Java代码
public static DocumentLocation ofBPartnerLocationId(@NonNull final BPartnerLocationId bpartnerLocationId) { return builder() .bpartnerId(bpartnerLocationId.getBpartnerId()) .bpartnerLocationId(bpartnerLocationId) .contactId(null) .locationId(null) .bpartnerAddress(null) .build(); } public DocumentLocation withLocationId(@Nullable final LocationId locationId) { return !Objects.equals(this.locationId, locationId) ? toBuilder().locationId(locationId).build() : this; } public DocumentLocation withRenderedAddress(@NonNull final RenderedAddressAndCapturedLocation renderedAddress) { return toBuilder() .locationId(renderedAddress.getCapturedLocationId()) .bpartnerAddress(renderedAddress.getRenderedAddress()) .build(); } private DocumentLocation withoutRenderedAddress() {
return bpartnerAddress != null ? toBuilder().bpartnerAddress(null).build() : this; } public boolean equalsIgnoringRenderedAddress(@NonNull final DocumentLocation other) { return Objects.equals(this.withoutRenderedAddress(), other.withoutRenderedAddress()); } public BPartnerLocationAndCaptureId toBPartnerLocationAndCaptureId() { if (bpartnerLocationId == null) { throw new AdempiereException("Cannot convert " + this + " to " + BPartnerLocationAndCaptureId.class.getSimpleName() + " because bpartnerLocationId is null"); } return BPartnerLocationAndCaptureId.of(bpartnerLocationId, locationId); } public DocumentLocation withContactId(@Nullable final BPartnerContactId contactId) { return !Objects.equals(this.contactId, contactId) ? toBuilder().contactId(contactId).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\DocumentLocation.java
1
请完成以下Java代码
public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVersion (final int Version) { set_Value (COLUMNNAME_Version, Version); } @Override public int getVersion() { return get_ValueAsInt(COLUMNNAME_Version); } @Override public void setWaitingTime (final int WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public int getWaitingTime() { return get_ValueAsInt(COLUMNNAME_WaitingTime); } /** * WorkflowType AD_Reference_ID=328 * Reference name: AD_Workflow Type */ public static final int WORKFLOWTYPE_AD_Reference_ID=328; /** General = G */ public static final String WORKFLOWTYPE_General = "G"; /** Document Process = P */ public static final String WORKFLOWTYPE_DocumentProcess = "P"; /** Document Value = V */ public static final String WORKFLOWTYPE_DocumentValue = "V"; /** Manufacturing = M */ public static final String WORKFLOWTYPE_Manufacturing = "M"; /** Quality = Q */ public static final String WORKFLOWTYPE_Quality = "Q"; /** Repair = R */ public static final String WORKFLOWTYPE_Repair = "R"; @Override public void setWorkflowType (final java.lang.String WorkflowType) { set_Value (COLUMNNAME_WorkflowType, WorkflowType);
} @Override public java.lang.String getWorkflowType() { return get_ValueAsString(COLUMNNAME_WorkflowType); } @Override public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() { return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow.java
1
请完成以下Java代码
public DeliveryOrderId getDeliveryOrderRepoId() { final int repoId = getParameters().getParameterAsInt(PARAM_DeliveryOrderRepoId, -1); return DeliveryOrderId.ofRepoId(repoId); } public void printLabels( @NonNull final DeliveryOrder deliveryOrder, @NonNull final List<PackageLabels> packageLabels, @NonNull final DeliveryOrderService deliveryOrderRepo, @Nullable final AsyncBatchId asyncBatchId) { for (final PackageLabels packageLabel : packageLabels) { final PackageLabel defaultPackageLabel = packageLabel.getDefaultPackageLabel(); printLabel(deliveryOrder, defaultPackageLabel, deliveryOrderRepo, asyncBatchId); } } private void printLabel( final DeliveryOrder deliveryOrder, final PackageLabel packageLabel, @NonNull final DeliveryOrderService deliveryOrderRepo, @Nullable final AsyncBatchId asyncBatchId) { final IArchiveStorageFactory archiveStorageFactory = Services.get(IArchiveStorageFactory.class); final String fileExtWithDot = MimeType.getExtensionByType(packageLabel.getContentType()); final String fileName = CoalesceUtil.firstNotEmptyTrimmed(packageLabel.getFileName(), packageLabel.getType().toString()) + fileExtWithDot; final byte[] labelData = packageLabel.getLabelData();
final Properties ctx = Env.getCtx(); final IArchiveStorage archiveStorage = archiveStorageFactory.getArchiveStorage(ctx); final I_AD_Archive archive = InterfaceWrapperHelper.create(archiveStorage.newArchive(ctx, ITrx.TRXNAME_ThreadInherited), I_AD_Archive.class); final ITableRecordReference deliveryOrderRef = deliveryOrderRepo.toTableRecordReference(deliveryOrder); archive.setAD_Table_ID(deliveryOrderRef.getAD_Table_ID()); archive.setRecord_ID(deliveryOrderRef.getRecord_ID()); archive.setC_BPartner_ID(deliveryOrder.getDeliveryAddress().getBpartnerId()); // archive.setAD_Org_ID(); // TODO: do we need to orgId too? archive.setName(fileName); archiveStorage.setBinaryData(archive, labelData); archive.setIsReport(false); archive.setIsDirectEnqueue(true); archive.setIsDirectProcessQueueItem(true); archive.setC_Async_Batch_ID(AsyncBatchId.toRepoId(asyncBatchId)); InterfaceWrapperHelper.save(archive); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\async\DeliveryOrderWorkpackageProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public FilterRegistrationBean<TrustHostFilter> getTrustHostFilter() { Set<String> filterUri = new HashSet<>(); filterUri.add("/onlinePreview"); filterUri.add("/picturesPreview"); filterUri.add("/getCorsFile"); TrustHostFilter filter = new TrustHostFilter(); FilterRegistrationBean<TrustHostFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); return registrationBean; } @Bean public FilterRegistrationBean<TrustDirFilter> getTrustDirFilter() { Set<String> filterUri = new HashSet<>(); filterUri.add("/onlinePreview"); filterUri.add("/picturesPreview"); filterUri.add("/getCorsFile"); TrustDirFilter filter = new TrustDirFilter(); FilterRegistrationBean<TrustDirFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); return registrationBean; } @Bean public FilterRegistrationBean<BaseUrlFilter> getBaseUrlFilter() { Set<String> filterUri = new HashSet<>(); BaseUrlFilter filter = new BaseUrlFilter(); FilterRegistrationBean<BaseUrlFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); registrationBean.setOrder(20); return registrationBean;
} @Bean public FilterRegistrationBean<UrlCheckFilter> getUrlCheckFilter() { UrlCheckFilter filter = new UrlCheckFilter(); FilterRegistrationBean<UrlCheckFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setOrder(30); return registrationBean; } @Bean public FilterRegistrationBean<AttributeSetFilter> getWatermarkConfigFilter() { Set<String> filterUri = new HashSet<>(); filterUri.add("/index"); filterUri.add("/"); filterUri.add("/onlinePreview"); filterUri.add("/picturesPreview"); AttributeSetFilter filter = new AttributeSetFilter(); FilterRegistrationBean<AttributeSetFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); return registrationBean; } }
repos\kkFileView-master\server\src\main\java\cn\keking\config\WebConfig.java
2
请在Spring Boot框架中完成以下Java代码
public Set<String> getActivePlanItemDefinitionIds() { return activePlanItemDefinitionIds; } public void setActivePlanItemDefinitionIds(Set<String> activePlanItemDefinitionIds) { this.activePlanItemDefinitionIds = activePlanItemDefinitionIds; } public Boolean getIncludeCaseVariables() { return includeCaseVariables; } public void setIncludeCaseVariables(Boolean includeCaseVariables) { this.includeCaseVariables = includeCaseVariables; } public Collection<String> getIncludeCaseVariablesNames() { return includeCaseVariablesNames; } public void setIncludeCaseVariablesNames(Collection<String> includeCaseVariablesNames) { this.includeCaseVariablesNames = includeCaseVariablesNames; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId; } public Boolean getWithoutCaseInstanceParentId() { return withoutCaseInstanceParentId; } public void setWithoutCaseInstanceParentId(Boolean withoutCaseInstanceParentId) { this.withoutCaseInstanceParentId = withoutCaseInstanceParentId; } public Boolean getWithoutCaseInstanceCallbackId() { return withoutCaseInstanceCallbackId; } public void setWithoutCaseInstanceCallbackId(Boolean withoutCaseInstanceCallbackId) { this.withoutCaseInstanceCallbackId = withoutCaseInstanceCallbackId; } public Set<String> getCaseInstanceCallbackIds() { return caseInstanceCallbackIds; } public void setCaseInstanceCallbackIds(Set<String> caseInstanceCallbackIds) { this.caseInstanceCallbackIds = caseInstanceCallbackIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceQueryRequest.java
2
请完成以下Java代码
public String getSummary() { StringBuffer sb = new StringBuffer(); sb.append(getDocumentNo()); // : Total Lines = 123.00 (#1) sb.append(": "). append(Msg.translate(getCtx(),"Amt")).append("=").append(getAmt()) .append(" (#").append(getLines(false).length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) sb.append(" - ").append(getDescription()); return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getCreated()); } /** * Retrieves all the charge lines that is present on the document * @return Charge Lines */ public MRMALine[] getChargeLines() { StringBuffer whereClause = new StringBuffer(); whereClause.append("IsActive='Y' AND M_RMA_ID="); whereClause.append(get_ID()); whereClause.append(" AND C_Charge_ID IS NOT null"); int rmaLineIds[] = MRMALine.getAllIDs(MRMALine.Table_Name, whereClause.toString(), get_TrxName()); ArrayList<MRMALine> chargeLineList = new ArrayList<>(); for (int rmaLineId : rmaLineIds) { MRMALine rmaLine = new MRMALine(getCtx(), rmaLineId, get_TrxName()); chargeLineList.add(rmaLine); } MRMALine lines[] = new MRMALine[chargeLineList.size()]; chargeLineList.toArray(lines); return lines; } /** * Get whether Tax is included (based on the original order) * @return True if tax is included */ public boolean isTaxIncluded(final I_C_Tax tax) { final I_C_Order order = getOriginalOrder(); if (order != null && order.getC_Order_ID() > 0) { return Services.get(IOrderBL.class).isTaxIncluded(order, TaxUtils.from(tax)); } return true; } /** * Get Process Message * @return clear text error message
*/ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * @return AD_User_ID */ @Override public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID /** * Get Document Approval Amount * @return amount */ @Override public BigDecimal getApprovalAmt() { return getAmt(); } // getApprovalAmt /** * Document Status is Complete or Closed * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MRMA
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMA.java
1
请在Spring Boot框架中完成以下Java代码
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { customizeSpringfoxHandlerMappings(getHandlerMappings(bean)); } return bean; } private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) { List<T> copy = mappings.stream() .filter(mapping -> mapping.getPatternParser() == null) .collect(Collectors.toList()); mappings.clear(); mappings.addAll(copy); } @SuppressWarnings("unchecked") private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try { Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings"); field.setAccessible(true); return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } }; } /** * 自定义Swagger配置 */ public abstract SwaggerProperties swaggerProperties(); }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\config\BaseSwaggerConfig.java
2
请完成以下Java代码
public void setC_CompensationGroup_Schema_Category_ID (final int C_CompensationGroup_Schema_Category_ID) { if (C_CompensationGroup_Schema_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_Category_ID, C_CompensationGroup_Schema_Category_ID); } @Override public int getC_CompensationGroup_Schema_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_Category_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CompensationGroup_Schema_Category.java
1
请完成以下Java代码
public void checkSetLicenseKey() { getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM); } @Override public void checkReadLicenseKey() { getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM); } @Override public void checkRegisterProcessApplication() { getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM); } @Override public void checkUnregisterProcessApplication() { getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM); } @Override public void checkReadRegisteredDeployments() { getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM); } @Override public void checkReadProcessApplicationForDeployment() { getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM); } @Override public void checkRegisterDeployment() { getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM); } @Override public void checkUnregisterDeployment() { getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM); }
@Override public void checkDeleteMetrics() { getAuthorizationManager().checkAuthorization(SystemPermissions.DELETE, Resources.SYSTEM); } @Override public void checkDeleteTaskMetrics() { getAuthorizationManager().checkAuthorization(SystemPermissions.DELETE, Resources.SYSTEM); } @Override public void checkReadSchemaLog() { getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM); } // helper //////////////////////////////////////// protected AuthorizationManager getAuthorizationManager() { return Context.getCommandContext().getAuthorizationManager(); } protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) { return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); } protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) { return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId); } protected ExecutionEntity findExecutionById(String processInstanceId) { return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\auth\AuthorizationCommandChecker.java
1
请完成以下Java代码
public List<I_M_HU> retrieveHUs(final org.compiere.model.I_M_Package mpackage) { Check.assumeNotNull(mpackage, "mpackage not null"); return queryBL.createQueryBuilder(I_M_Package_HU.class, mpackage) .addEqualsFilter(I_M_Package_HU.COLUMN_M_Package_ID, mpackage.getM_Package_ID()) .addOnlyActiveRecordsFilter() .andCollect(I_M_Package_HU.COLUMN_M_HU_ID) .addOnlyActiveRecordsFilter() .create() .list(I_M_HU.class); } @Override public List<I_M_Package> retrievePackages(final Collection<PackageId> packageIds) { if (packageIds == null || packageIds.isEmpty()) { return Collections.emptyList(); } return queryBL .createQueryBuilder(I_M_Package.class) .addInArrayOrAllFilter(org.compiere.model.I_M_Package.COLUMNNAME_M_Package_ID, packageIds) .create() .list(I_M_Package.class); } @Override public boolean isHUAssignedToPackage(final I_M_HU hu) { return queryBL .createQueryBuilder(I_M_Package_HU.class, hu) .addEqualsFilter(I_M_Package_HU.COLUMN_M_HU_ID, hu.getM_HU_ID()) .create() .anyMatch(); } @Override public List<I_M_Package> retrievePackages(final I_M_HU hu, final String trxName) { final Properties ctx = InterfaceWrapperHelper.getCtx(hu); return queryBL.createQueryBuilder(I_M_Package_HU.class, ctx, trxName) .addEqualsFilter(I_M_Package_HU.COLUMN_M_HU_ID, hu.getM_HU_ID()) .addOnlyActiveRecordsFilter() .andCollect(I_M_Package_HU.COLUMN_M_Package_ID) .addOnlyActiveRecordsFilter() .create() .list(I_M_Package.class); } @Override public List<I_M_Package> retrievePackagesForShipment(final I_M_InOut shipment) { Check.assumeNotNull(shipment, "shipment not null"); return queryBL.createQueryBuilder(I_M_Package.class, shipment) .addEqualsFilter(org.compiere.model.I_M_Package.COLUMNNAME_M_InOut_ID, shipment.getM_InOut_ID())
.create() .list(I_M_Package.class); } @Override public Collection<PackageId> retainPackageIdsWithHUs(final Collection<PackageId> packageIds) { if (Check.isEmpty(packageIds)) { return Collections.emptyList(); } return queryBL.createQueryBuilder(I_M_Package_HU.class) .addInArrayFilter(I_M_Package_HU.COLUMNNAME_M_Package_ID, packageIds) .create() .listDistinct(I_M_Package_HU.COLUMNNAME_M_Package_ID, PackageId.class); } @Override public I_M_Package retrievePackage(final I_M_HU hu) { final List<I_M_Package> mpackages = retrievePackages(hu, ITrx.TRXNAME_ThreadInherited); if (mpackages.isEmpty()) { return null; } else if (mpackages.size() > 1) { Check.errorIf(true, HUException.class, "More than one package was found for HU." + "\n@M_HU_ID@: {}" + "\n@M_Package_ID@: {}", hu, mpackages); return mpackages.get(0); // in case the system is configured to just log } else { return mpackages.get(0); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPackageDAO.java
1
请在Spring Boot框架中完成以下Java代码
public String createMailWithAttachment(Model model, @ModelAttribute("mailObject") @Valid MailObject mailObject, Errors errors) { if (errors.hasErrors()) { return "mail/send"; } emailService.sendMessageWithAttachment( mailObject.getTo(), mailObject.getSubject(), mailObject.getText(), attachmentPath ); return "redirect:/mail"; } @RequestMapping(value = {"/sendHtml"}, method = RequestMethod.GET) public String getHtmlMailView(Model model, HttpServletRequest request) { Map<String, String> templateEngines = new HashMap<>(); templateEngines.put("Thymeleaf", "Thymeleaf"); templateEngines.put("Freemarker", "Freemarker"); model.addAttribute("mailObject", new MailObject()); model.addAttribute("templateEngines", templateEngines); return "mail/sendHtml"; } @RequestMapping(value = "/sendHtml", method = RequestMethod.POST) public String createHtmlMail(Model model, @ModelAttribute("mailObject") @Valid MailObject mailObject, Errors errors) throws IOException, MessagingException, TemplateException { if (errors.hasErrors()) { return "mail/send"; }
Map<String, Object> templateModel = new HashMap<>(); templateModel.put("recipientName", mailObject.getRecipientName()); templateModel.put("text", mailObject.getText()); templateModel.put("senderName", mailObject.getSenderName()); if (mailObject.getTemplateEngine().equalsIgnoreCase("thymeleaf")) { emailService.sendMessageUsingThymeleafTemplate( mailObject.getTo(), mailObject.getSubject(), templateModel); } else { emailService.sendMessageUsingFreemarkerTemplate( mailObject.getTo(), mailObject.getSubject(), templateModel); } return "redirect:/mail"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\MailController.java
2
请完成以下Java代码
public Optional<UserDashboardId> getUserDashboardId(@NonNull final UserDashboardKey userDashboardKey) { return userDashboardRepository.getUserDashboardId(userDashboardKey); } public Optional<UserDashboardDataProvider> getData(@NonNull final UserDashboardKey userDashboardKey) { return userDashboardRepository.getUserDashboardId(userDashboardKey) .map(this::getData); } public UserDashboardDataProvider getData(@NonNull final UserDashboardId dashboardId) { return providers.getOrLoad(dashboardId, this::createDashboardDataProvider); } private UserDashboardDataProvider createDashboardDataProvider(@NonNull final UserDashboardId dashboardId) { return UserDashboardDataProvider.builder() .userDashboardRepository(userDashboardRepository) .kpiDataProvider(kpiDataProvider)
.dashboardId(dashboardId) .build(); } public KPIDataResult getKPIData(@NonNull final KPIId kpiId, @NonNull final KPIDataContext kpiDataContext) { return kpiDataProvider.getKPIData(KPIDataRequest.builder() .kpiId(kpiId) .timeRangeDefaults(KPITimeRangeDefaults.DEFAULT) .context(kpiDataContext) .maxStaleAccepted(Duration.ofDays(100)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardDataService.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * ValidationType AD_Reference_ID=2 * Reference name: AD_Reference Validation Types */ public static final int VALIDATIONTYPE_AD_Reference_ID=2; /** ListValidation = L */ public static final String VALIDATIONTYPE_ListValidation = "L"; /** DataType = D */ public static final String VALIDATIONTYPE_DataType = "D"; /** TableValidation = T */ public static final String VALIDATIONTYPE_TableValidation = "T"; /** Set Validation type. @param ValidationType Different method of validating data */ @Override public void setValidationType (java.lang.String ValidationType) {
set_Value (COLUMNNAME_ValidationType, ValidationType); } /** Get Validation type. @return Different method of validating data */ @Override public java.lang.String getValidationType () { return (java.lang.String)get_Value(COLUMNNAME_ValidationType); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public void setVFormat (java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public java.lang.String getVFormat () { return (java.lang.String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Reference.java
1
请在Spring Boot框架中完成以下Java代码
public Order deliver(long id) { Order order = orders.get(id); System.out.println(" try to deliver,order no:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEventEnum.DELIVERY) .setHeader("order", order).build())) { System.out.println(" deliver fail,error,order no:" + id); } return orders.get(id); } @Override public Order receive(long id) { Order order = orders.get(id); System.out.println(" try to receiver,order no:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEventEnum.RECEIVED) .setHeader("order", order).build())) { System.out.println(" deliver fail,error,order no:" + id); } return orders.get(id); } @Override public Map<Long, Order> getOrders() { return orders;
} /** * send transient event * @param message * @return */ private synchronized boolean sendEvent(Message<OrderStatusChangeEventEnum> message) { boolean result = false; try { orderStateMachine.start(); result = orderStateMachine.sendEvent(message); } catch (Exception e) { e.printStackTrace(); } finally { if (Objects.nonNull(message)) { Order order = (Order) message.getHeaders().get("order"); if (Objects.nonNull(order) && Objects.equals(order.getOrderStatus(), OrderStatusEnum.FINISH)) { orderStateMachine.stop(); } } } return result; } }
repos\springboot-demo-master\Statemachine\src\main\java\com\et\statemachine\service\OrderServiceImpl.java
2
请完成以下Java代码
public Set<TableRecordReference> toSet() {return recordRefs;} public Set<Integer> toIntSet() { // just to make sure that our records are from a single table getSingleTableName(); return recordRefs.stream() .map(TableRecordReference::getRecord_ID) .collect(ImmutableSet.toImmutableSet()); } public int size() { return recordRefs.size(); } @NonNull public AdTableId getSingleTableId() { final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() == 1) { return tableIds.iterator().next(); } else { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public void assertSingleTableName()
{ final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() != 1) { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public Stream<TableRecordReference> streamReferences() { return recordRefs.stream(); } @NonNull private ImmutableSet<AdTableId> getTableIds() { return recordRefs.stream() .map(TableRecordReference::getAD_Table_ID) .map(AdTableId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReferenceSet.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { ensureNotNull("executionId", executionId); EventSubscriptionManager eventSubscriptionManager = commandContext.getEventSubscriptionManager(); List<EventSubscriptionEntity> eventSubscriptions = null; if (messageName != null) { eventSubscriptions = eventSubscriptionManager.findEventSubscriptionsByNameAndExecution( EventType.MESSAGE.name(), messageName, executionId, exclusive); } else { eventSubscriptions = eventSubscriptionManager.findEventSubscriptionsByExecutionAndType( executionId, EventType.MESSAGE.name(), exclusive); } ensureNotEmpty("Execution with id '" + executionId + "' does not have a subscription to a message event with name '" + messageName + "'", "eventSubscriptions", eventSubscriptions); ensureNumberOfElements("More than one matching message subscription found for execution " + executionId, "eventSubscriptions", eventSubscriptions, 1); // there can be only one:
EventSubscriptionEntity eventSubscriptionEntity = eventSubscriptions.get(0); // check authorization String processInstanceId = eventSubscriptionEntity.getProcessInstanceId(); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessInstanceById(processInstanceId); } eventSubscriptionEntity.eventReceived(processVariables, processVariablesLocal, processVariablesToTriggeredScope, null, false); return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\MessageEventReceivedCmd.java
1
请在Spring Boot框架中完成以下Java代码
public void show() { try { String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } view("product", p); render("_product"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void destroy() { try { String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; }
p.delete(); view("message", "Successfully deleted product id " + id, "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } @Override protected String getContentType() { return "application/json"; } @Override protected String getLayout() { return null; } }
repos\tutorials-master\web-modules\java-lite\src\main\java\app\controllers\ProductsController.java
2
请完成以下Java代码
public int getDIM_Dimension_Spec_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1)
set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_AttributeValue.java
1
请在Spring Boot框架中完成以下Java代码
private JsonRequestBPartnerUpsertItem getJsonRequestBPartnerUpsertItemForDoctor( @NonNull final String doctorId, @NonNull final DoctorApi doctorApi, @NonNull final AlbertaConnectionDetails connectionDetails, @NonNull final String orgCode) { try { final Doctor doctor = doctorApi.getDoctor(connectionDetails.getApiKey(), doctorId); return DataMapper.mapDoctorToUpsertRequest(doctor, orgCode); } catch (final ApiException e) { throw new RuntimeException("Unexpected exception when retrieving doctor information", e); } }
@NonNull private JsonRequestBPartnerUpsertItem getJsonRequestBPartnerUpsertItemForPharmacy( @NonNull final String pharmacyId, @NonNull final PharmacyApi pharmacyApi, @NonNull final AlbertaConnectionDetails connectionDetails, @NonNull final String orgCode) { try { final Pharmacy pharmacy = pharmacyApi.getPharmacy(connectionDetails.getApiKey(), pharmacyId); return DataMapper.mapPharmacyToUpsertRequest(pharmacy, orgCode); } catch (final ApiException e) { throw new RuntimeException("Unexpected exception when retrieving pharmacy information", e); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\CreateMissingBPartnerProcessor.java
2
请完成以下Java代码
public int getM_Product_ID() { return ProductId.toRepoId(olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand)); } @Override public void setM_Product_ID(final int productId) { olCand.setM_Product_Override_ID(productId); values.setProductId(ProductId.ofRepoIdOrNull(productId)); } @Override public void setQty(final BigDecimal qty) { olCand.setQtyEntered_Override(qty); values.setQty(qty); } @Override public BigDecimal getQty() { return olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand); } @Override public int getM_HU_PI_Item_Product_ID() { final Integer valueOverrideOrValue = getValueOverrideOrValue(olCand, I_C_OLCand.COLUMNNAME_M_HU_PI_Item_Product_ID); return valueOverrideOrValue == null ? 0 : valueOverrideOrValue; } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { olCand.setM_HU_PI_Item_Product_Override_ID(huPiItemProductId); values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return olCand.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return olCandEffectiveValuesBL.getEffectiveUomId(olCand).getRepoId(); } @Override public void setC_UOM_ID(final int uomId) { values.setUomId(UomId.ofRepoIdOrNull(uomId)); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { olCand.setPrice_UOM_Internal_ID(uomId); } }
@Override public BigDecimal getQtyTU() { return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand)); } @Override public void setQtyTU(final BigDecimal qtyPacks) { values.setQtyTU(qtyPacks); } @Override public int getC_BPartner_ID() { final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand); return BPartnerId.toRepoId(bpartnerId); } @Override public void setC_BPartner_ID(final int partnerId) { olCand.setC_BPartner_Override_ID(partnerId); values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId)); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public boolean isWithIncident() { return withIncident; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } public String getCaseInstanceId() { return caseInstanceId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isRootProcessInstances() { return isRootProcessInstances; } public boolean isProcessDefinitionWithoutTenantId() { return isProcessDefinitionWithoutTenantId; } public boolean isLeafProcessInstances() {
return isLeafProcessInstances; } public String[] getTenantIds() { return tenantIds; } @Override public ProcessInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public ProcessInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public LogLevel getLevel() { Assert.state(this.logLevel != null, () -> "Unable to provide LogLevel for '" + this.name + "'"); return this.logLevel; } /** * Return if this is a custom level and cannot be represented by {@link LogLevel}. * @return if this is a custom level */ public boolean isCustom() { return this.logLevel == null; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } LevelConfiguration other = (LevelConfiguration) obj; return this.logLevel == other.logLevel && ObjectUtils.nullSafeEquals(this.name, other.name); } @Override public int hashCode() { return Objects.hash(this.logLevel, this.name); } @Override public String toString() { return "LevelConfiguration [name=" + this.name + ", logLevel=" + this.logLevel + "]";
} /** * Create a new {@link LevelConfiguration} instance of the given {@link LogLevel}. * @param logLevel the log level * @return a new {@link LevelConfiguration} instance */ public static LevelConfiguration of(LogLevel logLevel) { Assert.notNull(logLevel, "'logLevel' must not be null"); return new LevelConfiguration(logLevel.name(), logLevel); } /** * Create a new {@link LevelConfiguration} instance for a custom level name. * @param name the log level name * @return a new {@link LevelConfiguration} instance */ public static LevelConfiguration ofCustom(String name) { Assert.hasText(name, "'name' must not be empty"); return new LevelConfiguration(name, null); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggerConfiguration.java
1
请完成以下Java代码
public RefreshTokenGrantBuilder accessTokenResponseClient( OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) { this.accessTokenResponseClient = accessTokenResponseClient; return this; } /** * Sets the {@link ApplicationEventPublisher} used when an access token is * refreshed. * @param eventPublisher the {@link ApplicationEventPublisher} * @return the {@link RefreshTokenGrantBuilder} * @since 6.5 */ public RefreshTokenGrantBuilder eventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; return this; } /** * Sets the maximum acceptable clock skew, which is used when checking the access * token expiry. An access token is considered expired if * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link RefreshTokenGrantBuilder} * @see RefreshTokenOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; return this; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the * access token expiry. * @param clock the clock * @return the {@link RefreshTokenGrantBuilder} */
public RefreshTokenGrantBuilder clock(Clock clock) { this.clock = clock; return this; } /** * Builds an instance of {@link RefreshTokenOAuth2AuthorizedClientProvider}. * @return the {@link RefreshTokenOAuth2AuthorizedClientProvider} */ @Override public OAuth2AuthorizedClientProvider build() { RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider(); if (this.accessTokenResponseClient != null) { authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient); } if (this.eventPublisher != null) { authorizedClientProvider.setApplicationEventPublisher(this.eventPublisher); } if (this.clockSkew != null) { authorizedClientProvider.setClockSkew(this.clockSkew); } if (this.clock != null) { authorizedClientProvider.setClock(this.clock); } return authorizedClientProvider; } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizedClientProviderBuilder.java
1
请完成以下Java代码
public void setDataEntry_TargetWindow_ID (final int DataEntry_TargetWindow_ID) { if (DataEntry_TargetWindow_ID < 1) set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, null); else set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, DataEntry_TargetWindow_ID); } @Override public int getDataEntry_TargetWindow_ID() { return get_ValueAsInt(COLUMNNAME_DataEntry_TargetWindow_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSeqNo (final int SeqNo)
{ set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTabName (final java.lang.String TabName) { set_Value (COLUMNNAME_TabName, TabName); } @Override public java.lang.String getTabName() { return get_ValueAsString(COLUMNNAME_TabName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Tab.java
1
请完成以下Java代码
public String getF_OFFICEID() { return F_OFFICEID; } public void setF_OFFICEID(String f_OFFICEID) { F_OFFICEID = f_OFFICEID; } public String getF_TOLLID() { return F_TOLLID; } public void setF_TOLLID(String f_TOLLID) { F_TOLLID = f_TOLLID; } public Integer getF_ORDER() { return F_ORDER; } public void setF_ORDER(Integer f_ORDER) { F_ORDER = f_ORDER; } public BigDecimal getF_SHARE() { return F_SHARE; } public void setF_SHARE(BigDecimal f_SHARE) { F_SHARE = f_SHARE; } public String getF_ISRATION() { return F_ISRATION; } public void setF_ISRATION(String f_ISRATION) { F_ISRATION = f_ISRATION; } public String getF_INCANTONID() { return F_INCANTONID; } public void setF_INCANTONID(String f_INCANTONID) { F_INCANTONID = f_INCANTONID; } public String getF_INOFFICEID() { return F_INOFFICEID; } public void setF_INOFFICEID(String f_INOFFICEID) { F_INOFFICEID = f_INOFFICEID; } public Integer getF_INACCOUNTTYPE() { return F_INACCOUNTTYPE; } public void setF_INACCOUNTTYPE(Integer f_INACCOUNTTYPE) { F_INACCOUNTTYPE = f_INACCOUNTTYPE; } public String getF_INACCOUNTID() { return F_INACCOUNTID; } public void setF_INACCOUNTID(String f_INACCOUNTID) { F_INACCOUNTID = f_INACCOUNTID; } public String getF_STARTDATE() { return F_STARTDATE; } public void setF_STARTDATE(String f_STARTDATE) { F_STARTDATE = f_STARTDATE; } public String getF_ENDDATE() { return F_ENDDATE; } public void setF_ENDDATE(String f_ENDDATE) { F_ENDDATE = f_ENDDATE; }
public String getF_MEMO() { return F_MEMO; } public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; } public String getF_AUDITTIME() { return F_AUDITTIME; } public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_VERSION() { return F_VERSION; } public void setF_VERSION(String f_VERSION) { F_VERSION = f_VERSION; } public String getF_BUDGETCODE() { return F_BUDGETCODE; } public void setF_BUDGETCODE(String f_BUDGETCODE) { F_BUDGETCODE = f_BUDGETCODE; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollSpecialShare.java
1
请完成以下Spring Boot application配置
spring: # datasource 数据源配置内容 datasource: url: jdbc:mysql://127.0.0.1:3306/lab-39-mysql?useSSL=false&useUnicode=true&characterEncoding=UTF-8 drive
r-class-name: com.mysql.jdbc.Driver username: root password:
repos\SpringBoot-Labs-master\lab-42\lab-42-demo01\src\main\resources\application.yaml
2
请完成以下Spring Boot application配置
spring: # RabbitMQ 配置项,对应 RabbitProperties 配置类 rabbitmq: host: 127.0.0.1 # RabbitMQ 服务的地址 port: 5672 # RabbitMQ 服务的端口 username: guest # RabbitMQ 服务的账号 password: guest # RabbitMQ 服务的密码 pub
lisher-confirm-type: correlated # 设置 Confirm 类型为 CORRELATED 。 publisher-returns: true #
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-confirm-async\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public Optional<User> findById(String id) { return Optional.ofNullable(userMapper.findById(id)); } @Override public Optional<User> findByUsername(String username) { return Optional.ofNullable(userMapper.findByUsername(username)); } @Override public Optional<User> findByEmail(String email) { return Optional.ofNullable(userMapper.findByEmail(email)); } @Override public void saveRelation(FollowRelation followRelation) {
if (!findRelation(followRelation.getUserId(), followRelation.getTargetId()).isPresent()) { userMapper.saveRelation(followRelation); } } @Override public Optional<FollowRelation> findRelation(String userId, String targetId) { return Optional.ofNullable(userMapper.findRelation(userId, targetId)); } @Override public void removeRelation(FollowRelation followRelation) { userMapper.deleteRelation(followRelation); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\infrastructure\repository\MyBatisUserRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } /** * Type AD_Reference_ID=541243 * Reference name: C_Project_Repair_Task_Type */ public static final int TYPE_AD_Reference_ID=541243;
/** ServiceRepairOrder = W */ public static final String TYPE_ServiceRepairOrder = "W"; /** SpareParts = P */ public static final String TYPE_SpareParts = "P"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java
2
请完成以下Java代码
public void updateAfterReplacement() { // do nothing } /** * Removes all reference to this. */ private void unlinkAllReferences() { Collection<Attribute<?>> attributes = elementType.getAllAttributes(); for (Attribute<?> attribute : attributes) { Object identifier = attribute.getValue(this); if (identifier != null) { ((AttributeImpl<?>) attribute).unlinkReference(this, identifier); } } } /** * Removes every reference to children of this. */ private void unlinkAllChildReferences() { List<ModelElementType> childElementTypes = elementType.getAllChildElementTypes(); for (ModelElementType type : childElementTypes) { Collection<ModelElementInstance> childElementsForType = getChildElementsByType(type); for (ModelElementInstance childElement : childElementsForType) { ((ModelElementInstanceImpl) childElement).unlinkAllReferences(); } } } protected <T> Set<T> asSet(T element, Set<T> elements){ Set<T> result = new HashSet<T>(); result.add(element); if (elements != null) { result.addAll(elements); } return result; }
@Override public int hashCode() { return domElement.hashCode(); } @Override public boolean equals(Object obj) { if(obj == null) { return false; } else if(obj == this) { return true; } else if(!(obj instanceof ModelElementInstanceImpl)) { return false; } else { ModelElementInstanceImpl other = (ModelElementInstanceImpl) obj; return other.domElement.equals(domElement); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\ModelElementInstanceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class GatewayClassPathWarningAutoConfiguration { private static final Log log = LogFactory.getLog(GatewayClassPathWarningAutoConfiguration.class); private static final String BORDER = "\n\n**********************************************************\n\n"; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet") @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) protected static class SpringMvcFoundOnClasspathConfiguration { public SpringMvcFoundOnClasspathConfiguration() { throw new MvcFoundOnClasspathException(); }
} @Configuration(proxyBeanMethods = false) @ConditionalOnMissingClass("org.springframework.web.reactive.DispatcherHandler") protected static class WebfluxMissingFromClasspathConfiguration { public WebfluxMissingFromClasspathConfiguration() { log.warn(BORDER + "Spring Webflux is missing from the classpath, " + "which is required for Spring Cloud Gateway at this time. " + "Please add spring-boot-starter-webflux dependency." + BORDER); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayClassPathWarningAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setS_Milestone_ID (final int S_Milestone_ID) { if (S_Milestone_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, null); else
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, S_Milestone_ID); } @Override public int getS_Milestone_ID() { return get_ValueAsInt(COLUMNNAME_S_Milestone_ID); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Milestone.java
2
请完成以下Java代码
public Object getConfig() { return config; } @Override public String toString() { return String.format("Query: param=%s regexp=%s", config.getParam(), config.getRegexp()); } }; } 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
1
请在Spring Boot框架中完成以下Java代码
public PatientNote patientId(String patientId) { this.patientId = patientId; return this; } /** * Id des Patienten in Alberta * @return patientId **/ @Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Id des Patienten in Alberta") public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId; } public PatientNote archived(Boolean archived) { this.archived = archived; return this; } /** * Kennzeichen, ob die Notiz vom Benutzer archiviert wurde * @return archived **/ @Schema(example = "false", description = "Kennzeichen, ob die Notiz vom Benutzer archiviert wurde") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientNote patientNote = (PatientNote) o; return Objects.equals(this.status, patientNote.status) && Objects.equals(this.noteText, patientNote.noteText) && Objects.equals(this.patientId, patientNote.patientId) && Objects.equals(this.archived, patientNote.archived); } @Override public int hashCode() { return Objects.hash(status, noteText, patientId, archived); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientNote {\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).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\PatientNote.java
2
请在Spring Boot框架中完成以下Java代码
public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId; } public PatientNote archived(Boolean archived) { this.archived = archived; return this; } /** * Kennzeichen, ob die Notiz vom Benutzer archiviert wurde * @return archived **/ @Schema(example = "false", description = "Kennzeichen, ob die Notiz vom Benutzer archiviert wurde") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientNote patientNote = (PatientNote) o;
return Objects.equals(this.status, patientNote.status) && Objects.equals(this.noteText, patientNote.noteText) && Objects.equals(this.patientId, patientNote.patientId) && Objects.equals(this.archived, patientNote.archived); } @Override public int hashCode() { return Objects.hash(status, noteText, patientId, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientNote {\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).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\PatientNote.java
2
请完成以下Java代码
public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getSummary() { return this.summary;
} public void setSummary(String summary) { this.summary = summary; } @Override public String toString() { return "Message{" + "id=" + id + ", text='" + text + '\'' + ", summary='" + summary + '\'' + ", createDate=" + createDate + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\model\Message.java
1
请完成以下Java代码
public boolean isLogged(final int AD_Table_ID) { final List<Integer> changeLogAllowedTableIds = retrieveChangeLogAllowedTableIds(); return Collections.binarySearch(changeLogAllowedTableIds, AD_Table_ID) >= 0; } // trackChanges /** * Fill Log with tables to be logged */ @Cached(cacheName = I_AD_Table.Table_Name + "#IsChangeLog") public List<Integer> retrieveChangeLogAllowedTableIds() { final ImmutableList.Builder<Integer> list = ImmutableList.builder(); final String sql = "SELECT t.AD_Table_ID FROM AD_Table t " + "WHERE t.IsChangeLog='Y'" // also inactive + " OR EXISTS (SELECT * FROM AD_Column c " + "WHERE t.AD_Table_ID=c.AD_Table_ID AND c.ColumnName='EntityType') " + "ORDER BY t.AD_Table_ID"; PreparedStatement pstmt = null; ResultSet rs = null; try
{ pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); while (rs.next()) { list.add(rs.getInt(1)); } } catch (final Exception e) { logger.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return list.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\impl\SessionDAO.java
1
请完成以下Java代码
public boolean accept( @NonNull final IValidationContext evalCtx, final NamePair item) { if (null == item) { // Should never happen. return false; } final String docType = evalCtx.get_ValueAsString(COLUMNNAME_C_DocType_ID); final String docTypeTarget = evalCtx.get_ValueAsString(COLUMNNAME_C_DocTypeTarget_ID); final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(StringUtils.toIntegerOrZero(docType)); final DocTypeId docTypeTargetId = DocTypeId.ofRepoIdOrNull(StringUtils.toIntegerOrZero(docTypeTarget)); if (docTypeId == null && docTypeTargetId == null) { // Not a document. All warehouses available. return true; } final WarehouseId warehouseId = WarehouseId.ofRepoIdOrNull(NumberUtils.asInt(item.getID(), -1)); Check.assumeNotNull(warehouseId, "Invalid warehouse {}", item.getID()); // Check if we have any available doc types assigned to our warehouse. // If not, we shall accept this warehouse right away (task 09301). // As soon as there is assigned at least on doc type, we will enforce the restrictions. final IWarehouseDAO warehousesRepo = Services.get(IWarehouseDAO.class);
if (warehousesRepo.isAllowAnyDocType(warehouseId)) { return true; // no restrictions defined => accept this warehouse } // First check for doc type. if (docTypeId != null) { final String docBaseType = Services.get(IDocTypeDAO.class).getById(docTypeId).getDocBaseType(); return warehousesRepo.isDocTypeAllowed(warehouseId, docBaseType); } // For orders, also check doc type target if (docTypeTargetId != null) { final String docBaseType = Services.get(IDocTypeDAO.class).getById(docTypeTargetId).getDocBaseType(); return warehousesRepo.isDocTypeAllowed(warehouseId, docBaseType); } return false; } @Override public Set<String> getParameters(@Nullable final String contextTableName) { return PARAMS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\validationrule\FilterWarehouseByDocTypeValidationRule.java
1
请完成以下Java代码
public long getCreatedTime() { return super.getCreatedTime(); } @Schema(description = "JSON object with Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY) public TenantId getTenantId() { return tenantId; } public void setTenantId(TenantId tenantId) { this.tenantId = tenantId; } @Schema(description = "The Administration Settings key, (e.g. 'general' or 'mail')", example = "mail") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Schema(description = "JSON representation of the Administration Settings value") public JsonNode getJsonValue() { return jsonValue; } public void setJsonValue(JsonNode jsonValue) { this.jsonValue = jsonValue; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((jsonValue == null) ? 0 : jsonValue.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; AdminSettings other = (AdminSettings) obj; if (jsonValue == null) { if (other.jsonValue != null) return false; } else if (!jsonValue.equals(other.jsonValue)) return false;
if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AdminSettings [key="); builder.append(key); builder.append(", jsonValue="); builder.append(jsonValue); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\AdminSettings.java
1
请在Spring Boot框架中完成以下Java代码
public static ClientEMailConfig toClientEMailConfig(@NonNull final I_AD_Client client) { return ClientEMailConfig.builder() .clientId(ClientId.ofRepoId(client.getAD_Client_ID())) .mailbox(extractMailbox(client)) .build(); } private static ExplainedOptional<Mailbox> extractMailbox(@NonNull final I_AD_Client client) { final EMailAddress email = EMailAddress.ofNullableString(client.getRequestEMail()); if (email == null) { return ExplainedOptional.emptyBecause("AD_Client.RequestEMail not set"); } return ExplainedOptional.of( Mailbox.builder() .type(MailboxType.SMTP) .email(email) .smtpConfig(extractSMTPConfig(client)) .build() ); } private static SMTPConfig extractSMTPConfig(@NonNull final I_AD_Client client) { return SMTPConfig.builder() .smtpHost(client.getSMTPHost()) .smtpPort(client.getSMTPPort()) .smtpAuthorization(client.isSmtpAuthorization()) .username(client.getRequestUser()) .password(client.getRequestUserPW()) .startTLS(client.isStartTLS()) .build(); } @Override public ClientMailTemplates getClientMailTemplatesById(final ClientId clientId) { return emailTemplatesCache.getOrLoad(clientId, this::retrieveClientMailTemplatesById); } private ClientMailTemplates retrieveClientMailTemplatesById(final ClientId clientId) {
final I_AD_Client record = getById(clientId); return toClientMailTemplates(record); } private static ClientMailTemplates toClientMailTemplates(@NonNull final I_AD_Client record) { return ClientMailTemplates.builder() .passwordResetMailTemplateId(MailTemplateId.optionalOfRepoId(record.getPasswordReset_MailText_ID())) .build(); } @Override public boolean isMultilingualDocumentsEnabled(@NonNull final ClientId adClientId) { final I_AD_Client client = getById(adClientId); return client.isMultiLingualDocument(); } @Override public String getClientNameById(@NonNull final ClientId clientId) { return getById(clientId).getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ClientDAO.java
2
请在Spring Boot框架中完成以下Java代码
public class TodoService implements ITodoService { @Autowired private TodoRepository todoRepository; @Override public List<Todo> getTodoByUser(String user) { return todoRepository.findByUserName(user); } @Override public Optional<Todo> getTodoById(long id) { return todoRepository.findById(id); } @Override public void updateTodo(Todo todo) { todoRepository.save(todo); } @Override public void addTodo(String name, String desc, Date targetDate, boolean isDone) { todoRepository.save(new Todo(name, desc, targetDate, isDone)); } @Override public void deleteTodo(long id) {
Optional<Todo> todo = todoRepository.findById(id); if(todo.isPresent()) { todoRepository.delete(todo.get()); } } @Override public void saveTodo(Todo todo) { todoRepository.save(todo); } @Override public Object getTodosByUser(String name) { return null; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDB\src\main\java\spring\hibernate\service\TodoService.java
2
请完成以下Java代码
public OptionalBoolean getNumericKey() { return _numericKey; } public Builder setKeyColumn(final boolean keyColumn) { this.keyColumn = keyColumn; return this; } public Builder setEncrypted(final boolean encrypted) { this.encrypted = encrypted; return this; } /** * Sets ORDER BY priority and direction (ascending/descending)
* * @param priority priority; if positive then direction will be ascending; if negative then direction will be descending */ public Builder setDefaultOrderBy(final int priority) { if (priority >= 0) { orderByPriority = priority; orderByAscending = true; } else { orderByPriority = -priority; orderByAscending = false; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public PrintOptions createPrintOptions() { return new PrintOptions(); } /** * Create an instance of {@link Printer } * */ public Printer createPrinter() { return new Printer(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link StoreOrders }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link StoreOrders }{@code >} */ @XmlElementDecl(namespace = "http://dpd.com/common/service/types/ShipmentService/3.2", name = "storeOrders") public JAXBElement<StoreOrders> createStoreOrders(StoreOrders value) { return new JAXBElement<StoreOrders>(_StoreOrders_QNAME, StoreOrders.class, null, value); }
/** * Create an instance of {@link JAXBElement }{@code <}{@link StoreOrdersResponse }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link StoreOrdersResponse }{@code >} */ @XmlElementDecl(namespace = "http://dpd.com/common/service/types/ShipmentService/3.2", name = "storeOrdersResponse") public JAXBElement<StoreOrdersResponse> createStoreOrdersResponse(StoreOrdersResponse value) { return new JAXBElement<StoreOrdersResponse>(_StoreOrdersResponse_QNAME, StoreOrdersResponse.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ObjectFactory.java
2
请完成以下Java代码
public int getDATEV_Export_ID() { return get_ValueAsInt(COLUMNNAME_DATEV_Export_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsExcludeAlreadyExported (final boolean IsExcludeAlreadyExported) { set_Value (COLUMNNAME_IsExcludeAlreadyExported, IsExcludeAlreadyExported); } @Override public boolean isExcludeAlreadyExported() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeAlreadyExported); } @Override public void setIsNegateInboundAmounts (final boolean IsNegateInboundAmounts) { set_Value (COLUMNNAME_IsNegateInboundAmounts, IsNegateInboundAmounts); } @Override public boolean isNegateInboundAmounts() { return get_ValueAsBoolean(COLUMNNAME_IsNegateInboundAmounts); } @Override public void setIsPlaceBPAccountsOnCredit (final boolean IsPlaceBPAccountsOnCredit) { set_Value (COLUMNNAME_IsPlaceBPAccountsOnCredit, IsPlaceBPAccountsOnCredit); } @Override public boolean isPlaceBPAccountsOnCredit() { return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit); } /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx)
{ set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); } @Override public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo) { set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo); } @Override public boolean isSwitchCreditMemo() { return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
1
请在Spring Boot框架中完成以下Java代码
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource, @Qualifier("primaryJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) { return builder // 设置数据源 .dataSource(primaryDataSource) // 设置jpa配置 .properties(jpaProperties.getProperties()) // 设置实体包名 .packages(ENTITY_PACKAGE) // 设置持久化单元名,用于@PersistenceContext注解获取EntityManager时指定数据源 .persistenceUnit("primaryPersistenceUnit").build(); } /** * 获取实体管理对象 * * @param factory 注入名为primaryEntityManagerFactory的bean * @return 实体管理对象 */ @Primary @Bean(name = "primaryEntityManager") public EntityManager entityManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
return factory.createEntityManager(); } /** * 获取主库事务管理对象 * * @param factory 注入名为primaryEntityManagerFactory的bean * @return 事务管理对象 */ @Primary @Bean(name = "primaryTransactionManager") public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) { return new JpaTransactionManager(factory); } }
repos\spring-boot-demo-master\demo-multi-datasource-jpa\src\main\java\com\xkcoding\multi\datasource\jpa\config\PrimaryJpaConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class PricingConditionsBreakId { public static final PricingConditionsBreakId of(final int discountSchemaId, final int discountSchemaBreakId) { return new PricingConditionsBreakId(PricingConditionsId.ofRepoId(discountSchemaId), discountSchemaBreakId); } public static final PricingConditionsBreakId ofOrNull(final int discountSchemaId, final int discountSchemaBreakId) { if (discountSchemaId > 0 && discountSchemaBreakId > 0) { return of(discountSchemaId, discountSchemaBreakId); } else { return null; } } public static final boolean matching(final PricingConditionsId id, PricingConditionsBreakId breakId) { if (id == null) { return breakId == null; } else if (breakId == null) { return true; } else { return Objects.equals(id, breakId.getPricingConditionsId()); } } public static final void assertMatching(final PricingConditionsId id, PricingConditionsBreakId breakId) { if (!matching(id, breakId)) { throw new AdempiereException("" + id + " and " + breakId + " are not matching")
.setParameter("pricingConditionsId", id) .setParameter("pricingConditionsBreakId", breakId); } } private final PricingConditionsId pricingConditionsId; private final int discountSchemaBreakId; private PricingConditionsBreakId(@NonNull final PricingConditionsId pricingConditionsId, final int discountSchemaBreakId) { Check.assumeGreaterThanZero(discountSchemaBreakId, "discountSchemaBreakId"); this.pricingConditionsId = pricingConditionsId; this.discountSchemaBreakId = discountSchemaBreakId; } public boolean matchingDiscountSchemaId(final int discountSchemaId) { return pricingConditionsId.getRepoId() == discountSchemaId; } public int getDiscountSchemaId() { return pricingConditionsId.getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakId.java
2
请在Spring Boot框架中完成以下Java代码
public class ImageController { @Autowired private ServletContext servletContext; @RequestMapping(value = "/image-view", method = RequestMethod.GET) public String imageView() throws IOException { return "image-download"; } @RequestMapping(value = "/image-manual-response", method = RequestMethod.GET) public void getImageAsByteArray(HttpServletResponse response) throws IOException { final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg"); response.setContentType(MediaType.IMAGE_JPEG_VALUE); IOUtils.copy(in, response.getOutputStream()); } @RequestMapping(value = "/image-byte-array", method = RequestMethod.GET) @ResponseBody public byte[] getImageAsByteArray() throws IOException { final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg"); return IOUtils.toByteArray(in); } @RequestMapping(value = "/image-response-entity", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageAsResponseEntity() throws IOException { ResponseEntity<byte[]> responseEntity; final HttpHeaders headers = new HttpHeaders(); final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg"); byte[] media = IOUtils.toByteArray(in); headers.setCacheControl(CacheControl.noCache().getHeaderValue()); responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK); return responseEntity; } @RequestMapping(value = "/image-resource", method = RequestMethod.GET) @ResponseBody public ResponseEntity<Resource> getImageAsResource() { final HttpHeaders headers = new HttpHeaders(); Resource resource = new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg"); return new ResponseEntity<>(resource, headers, HttpStatus.OK); } }
repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\controller\ImageController.java
2
请完成以下Java代码
public void stop() { stopped = true; } @Override public void unsubscribe() { log.info("Unsubscribing and stopping consumer for {}", partitions); stopped = true; consumerLock.lock(); try { if (subscribed) { doUnsubscribe(); } } finally { consumerLock.unlock(); } } @Override public boolean isStopped() { return stopped; } abstract protected List<R> doPoll(long durationInMillis); abstract protected T decode(R record) throws IOException; abstract protected void doSubscribe(Set<TopicPartitionInfo> partitions);
abstract protected void doCommit(); abstract protected void doUnsubscribe(); @Override public Set<TopicPartitionInfo> getPartitions() { return partitions; } @Override public List<String> getFullTopicNames() { if (partitions == null) { return Collections.emptyList(); } return partitions.stream() .map(TopicPartitionInfo::getFullTopicName) .toList(); } protected boolean isLongPollingSupported() { return false; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\AbstractTbQueueConsumerTemplate.java
1
请完成以下Java代码
public boolean isSuspended() { return executionEntity.isSuspended(); } @Override public String getId() { return executionEntity.getId(); } @Override public String getRootProcessInstanceId() { return executionEntity.getRootProcessInstanceId(); } @Override public boolean isEnded() { return executionEntity.isEnded(); }
@Override public String getProcessInstanceId() { return executionEntity.getProcessInstanceId(); } @Override public String getTenantId() { return executionEntity.getTenantId(); } @Override public String getProcessDefinitionKey() { return executionEntity.getProcessDefinitionKey(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessInstanceWithVariablesImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WFActivity { @NonNull WFActivityId id; @NonNull ITranslatableString caption; @NonNull WFActivityType wfActivityType; @With @NonNull WFActivityStatus status; @NonNull WFActivityAlwaysAvailableToUser alwaysAvailableToUser; @Nullable String userInstructions; @Builder private WFActivity( @NonNull final WFActivityId id, @NonNull final ITranslatableString caption, @NonNull final WFActivityType wfActivityType, @Nullable final WFActivityStatus status,
@Nullable final WFActivityAlwaysAvailableToUser alwaysAvailableToUser, @Nullable final String userInstructions) { this.id = id; this.caption = caption; this.wfActivityType = wfActivityType; this.status = status != null ? status : WFActivityStatus.NOT_STARTED; this.alwaysAvailableToUser = CoalesceUtil.coalesceNotNull(alwaysAvailableToUser, WFActivityAlwaysAvailableToUser.DEFAULT); this.userInstructions = userInstructions; } public boolean isCompleted() { return getStatus().isCompleted(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFActivity.java
2
请完成以下Java代码
private void insertUserEntity(PublicKeyCredentialUserEntity userEntity) { List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity); PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray()); this.jdbcOperations.update(SAVE_USER_SQL, pss); } private int updateUserEntity(PublicKeyCredentialUserEntity userEntity) { List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity); SqlParameterValue userEntityId = parameters.remove(0); parameters.add(userEntityId); PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray()); return this.jdbcOperations.update(UPDATE_USER_SQL, pss); } @Override public void delete(Bytes id) { Assert.notNull(id, "id cannot be null"); SqlParameterValue[] parameters = new SqlParameterValue[] { new SqlParameterValue(Types.VARCHAR, id.toBase64UrlString()), }; PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters); this.jdbcOperations.update(DELETE_USER_SQL, pss); } private static class UserEntityParametersMapper implements Function<PublicKeyCredentialUserEntity, List<SqlParameterValue>> { @Override public List<SqlParameterValue> apply(PublicKeyCredentialUserEntity userEntity) { List<SqlParameterValue> parameters = new ArrayList<>(); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getId().toBase64UrlString()));
parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getName())); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getDisplayName())); return parameters; } } private static class UserEntityRecordRowMapper implements RowMapper<PublicKeyCredentialUserEntity> { @Override public PublicKeyCredentialUserEntity mapRow(ResultSet rs, int rowNum) throws SQLException { Bytes id = Bytes.fromBase64(new String(rs.getString("id").getBytes())); String name = rs.getString("name"); String displayName = rs.getString("display_name"); return ImmutablePublicKeyCredentialUserEntity.builder().id(id).name(name).displayName(displayName).build(); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\JdbcPublicKeyCredentialUserEntityRepository.java
1
请完成以下Java代码
public int hashCode() { int hash = 7; hash = 67 * hash + (this.timestamp != null ? this.timestamp.hashCode() : 0); hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 67 * hash + (this.reporter != null ? this.reporter.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) {
return false; } final MetricIntervalEntity other = (MetricIntervalEntity) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.reporter == null) ? (other.reporter != null) : !this.reporter.equals(other.reporter)) { return false; } if (this.timestamp != other.timestamp && (this.timestamp == null || !this.timestamp.equals(other.timestamp))) { return false; } return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MetricIntervalEntity.java
1
请完成以下Java代码
class QueueProcessorDescriptor { @NonNull @Getter private final I_C_Queue_Processor queueProcessor; @NonNull private final Map<QueuePackageProcessorId, I_C_Queue_PackageProcessor> packageProcessors; public QueueProcessorDescriptor( @NonNull final I_C_Queue_Processor queueProcessor, @NonNull final List<I_C_Queue_PackageProcessor> packageProcessorList) { this.queueProcessor = queueProcessor; this.packageProcessors = Maps.uniqueIndex(packageProcessorList, (packageProcessor) -> QueuePackageProcessorId.ofRepoId(packageProcessor.getC_Queue_PackageProcessor_ID())); } @NonNull public QueueProcessorId getQueueProcessorId() { return QueueProcessorId.ofRepoId(queueProcessor.getC_Queue_Processor_ID()); } @NonNull
public ImmutableSet<QueuePackageProcessorId> getQueuePackageProcessorIds() { return ImmutableSet.copyOf(packageProcessors.keySet()); } public boolean hasPackageProcessor(@NonNull final QueuePackageProcessorId packageProcessorId) { return packageProcessors.get(packageProcessorId) != null; } public Optional<I_C_Queue_PackageProcessor> getPackageProcessor(@NonNull final QueuePackageProcessorId packageProcessorId) { return Optional.ofNullable(packageProcessors.get(packageProcessorId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName().replace("EntityImpl", "")).append("[") .append("id=").append(id) .append(", eventType=").append(eventType); if (activityId != null) { sb.append(", activityId=").append(activityId); } if (executionId != null) { sb.append(", processInstanceId=").append(processInstanceId) .append(", executionId=").append(executionId); } else if (scopeId != null) { sb.append(", scopeId=").append(scopeId) .append(", subScopeId=").append(subScopeId) .append(", scopeType=").append(scopeType) .append(", scopeDefinitionId=").append(scopeDefinitionId); } if (processDefinitionId != null) { sb.append(", processDefinitionId=").append(processDefinitionId); } else if (scopeDefinitionId != null) { if (scopeId == null) { sb.append(", scopeType=").append(scopeType); } sb.append(", scopeDefinitionId=").append(scopeDefinitionId); } if (scopeDefinitionKey != null) { sb.append(", scopeDefinitionKey=").append(scopeDefinitionKey); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\entity\EventSubscriptionEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String createMailWithTemplate(Model model, @ModelAttribute("mailObject") @Valid MailObject mailObject, Errors errors) { if (errors.hasErrors()) { return "mail/send"; } emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(), mailObject.getSubject(), mailObject.getText()); return "redirect:/mail"; } @RequestMapping(value = "/sendAttachment", method = RequestMethod.POST) public String createMailWithAttachment(Model model, @ModelAttribute("mailObject") @Valid MailObject mailObject, Errors errors) { if (errors.hasErrors()) { return "mail/send"; } emailService.sendMessageWithAttachment( mailObject.getTo(), mailObject.getSubject(), mailObject.getText(), attachmentPath ); return "redirect:/mail"; } @RequestMapping(value = {"/sendHtml"}, method = RequestMethod.GET) public String getHtmlMailView(Model model, HttpServletRequest request) { Map<String, String> templateEngines = new HashMap<>(); templateEngines.put("Thymeleaf", "Thymeleaf"); templateEngines.put("Freemarker", "Freemarker"); model.addAttribute("mailObject", new MailObject()); model.addAttribute("templateEngines", templateEngines); return "mail/sendHtml"; } @RequestMapping(value = "/sendHtml", method = RequestMethod.POST) public String createHtmlMail(Model model, @ModelAttribute("mailObject") @Valid MailObject mailObject, Errors errors) throws IOException, MessagingException, TemplateException { if (errors.hasErrors()) {
return "mail/send"; } Map<String, Object> templateModel = new HashMap<>(); templateModel.put("recipientName", mailObject.getRecipientName()); templateModel.put("text", mailObject.getText()); templateModel.put("senderName", mailObject.getSenderName()); if (mailObject.getTemplateEngine().equalsIgnoreCase("thymeleaf")) { emailService.sendMessageUsingThymeleafTemplate( mailObject.getTo(), mailObject.getSubject(), templateModel); } else { emailService.sendMessageUsingFreemarkerTemplate( mailObject.getTo(), mailObject.getSubject(), templateModel); } return "redirect:/mail"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\MailController.java
2
请完成以下Java代码
public Void execute(CommandContext context) { checkAuthorization(context); ensureNotNull(BadUserRequestException.class, "processDefinitionId", processDefinitionId); if (historyTimeToLive != null) { ensureGreaterThanOrEqual(BadUserRequestException.class, "", "historyTimeToLive", historyTimeToLive, 0); } HistoryTimeToLiveParser parser = HistoryTimeToLiveParser.create(context); parser.validate(historyTimeToLive); ProcessDefinitionEntity processDefinitionEntity = context.getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); logUserOperation(context, processDefinitionEntity); processDefinitionEntity.setHistoryTimeToLive(historyTimeToLive);
return null; } protected void checkAuthorization(CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessDefinitionById(processDefinitionId); } } protected void logUserOperation(CommandContext commandContext, ProcessDefinitionEntity processDefinitionEntity) { PropertyChange propertyChange = new PropertyChange("historyTimeToLive", processDefinitionEntity.getHistoryTimeToLive(), historyTimeToLive); commandContext.getOperationLogManager() .logProcessDefinitionOperation(UserOperationLogEntry.OPERATION_TYPE_UPDATE_HISTORY_TIME_TO_LIVE, processDefinitionId, processDefinitionEntity.getKey(), propertyChange); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateProcessDefinitionHistoryTimeToLiveCmd.java
1
请完成以下Java代码
public FileType getType() { return type; } public void setType(FileType type) { this.type = type; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getCompressFileKey() { return compressFileKey; } public void setCompressFileKey(String compressFileKey) { this.compressFileKey = compressFileKey; } public String getName() { return name; } public String getCacheName() { return cacheName; } public String getCacheListName() { return cacheListName; } public String getOutFilePath() { return outFilePath; } public String getOriginFilePath() { return originFilePath; } public boolean isHtmlView() { return isHtmlView; } public void setCacheName(String cacheName) { this.cacheName = cacheName; } public void setCacheListName(String cacheListName) { this.cacheListName = cacheListName; } public void setOutFilePath(String outFilePath) { this.outFilePath = outFilePath; } public void setOriginFilePath(String originFilePath) { this.originFilePath = originFilePath; } public void setHtmlView(boolean isHtmlView) { this.isHtmlView = isHtmlView;
} public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Boolean getSkipDownLoad() { return skipDownLoad; } public void setSkipDownLoad(Boolean skipDownLoad) { this.skipDownLoad = skipDownLoad; } public String getTifPreviewType() { return tifPreviewType; } public void setTifPreviewType(String previewType) { this.tifPreviewType = previewType; } public Boolean forceUpdatedCache() { return forceUpdatedCache; } public void setForceUpdatedCache(Boolean forceUpdatedCache) { this.forceUpdatedCache = forceUpdatedCache; } public String getKkProxyAuthorization() { return kkProxyAuthorization; } public void setKkProxyAuthorization(String kkProxyAuthorization) { this.kkProxyAuthorization = kkProxyAuthorization; } }
repos\kkFileView-master\server\src\main\java\cn\keking\model\FileAttribute.java
1
请完成以下Java代码
public BigDecimal getQty() { return ddOrderLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { return ddOrderLine.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { ddOrderLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return ddOrderLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return ddOrderLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { values.setC_UOM_ID(uomId); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0)
{ ddOrderLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return ddOrderLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { ddOrderLine.setQtyEnteredTU(qtyPacks); values.setQtyTU(qtyPacks); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public void setC_BPartner_ID(final int partnerId) { // nothing } @Override public int getC_BPartner_ID() { return ddOrderLine.getDD_Order().getC_BPartner_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\lowlevel\model\DDOrderLineHUPackingAware.java
1
请完成以下Java代码
public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; } /** * 验证token是否还有效 * * @param token 客户端传入的token * @param userDetails 从数据库中查询出来的用户信息 */ public boolean validateToken(String token, UserDetails userDetails) { String username = getUserNameFromToken(token); return username.equals(userDetails.getUsername()) && !isTokenExpired(token); } /** * 判断token是否已经失效 */ private boolean isTokenExpired(String token) { Date expiredDate = getExpiredDateFromToken(token); return expiredDate.before(new Date()); } /** * 从token中获取过期时间 */ private Date getExpiredDateFromToken(String token) { Claims claims = getClaimsFromToken(token); return claims.getExpiration(); } /** * 根据用户信息生成token */ public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } /** * 当原来的token没过期时是可以刷新的 * * @param oldToken 带tokenHead的token
*/ public String refreshHeadToken(String oldToken) { if(StrUtil.isEmpty(oldToken)){ return null; } String token = oldToken.substring(tokenHead.length()); if(StrUtil.isEmpty(token)){ return null; } //token校验不通过 Claims claims = getClaimsFromToken(token); if(claims==null){ return null; } //如果token已经过期,不支持刷新 if(isTokenExpired(token)){ return null; } //如果token在30分钟之内刚刷新过,返回原token if(tokenRefreshJustBefore(token,30*60)){ return token; }else{ claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } } /** * 判断token在指定时间内是否刚刚刷新过 * @param token 原token * @param time 指定时间(秒) */ private boolean tokenRefreshJustBefore(String token, int time) { Claims claims = getClaimsFromToken(token); Date created = claims.get(CLAIM_KEY_CREATED, Date.class); Date refreshDate = new Date(); //刷新时间在创建时间的指定时间内 if(refreshDate.after(created)&&refreshDate.before(DateUtil.offsetSecond(created,time))){ return true; } return false; } }
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\util\JwtTokenUtil.java
1
请完成以下Java代码
public void afterCreate(EntryEvent<K, V> event) { processEntryEvent(event, EntryEventType.CREATE); } @Override public void afterDestroy(EntryEvent<K, V> event) { processEntryEvent(event, EntryEventType.DESTROY); } @Override public void afterInvalidate(EntryEvent<K, V> event) { processEntryEvent(event, EntryEventType.INVALIDATE); } @Override public void afterUpdate(EntryEvent<K, V> event) { processEntryEvent(event, EntryEventType.UPDATE); } protected void processEntryEvent(EntryEvent<K, V> event, EntryEventType eventType) { } @Override public void afterRegionClear(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.CLEAR); } @Override public void afterRegionCreate(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.CREATE); } @Override public void afterRegionDestroy(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.DESTROY); } @Override public void afterRegionInvalidate(RegionEvent<K, V> event) {
processRegionEvent(event, RegionEventType.INVALIDATE); } @Override public void afterRegionLive(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.LIVE); } protected void processRegionEvent(RegionEvent<K, V> event, RegionEventType eventType) { } public enum EntryEventType { CREATE, DESTROY, INVALIDATE, UPDATE; } public enum RegionEventType { CLEAR, CREATE, DESTROY, INVALIDATE, LIVE; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\cache\AbstractCommonEventProcessingCacheListener.java
1
请完成以下Java代码
private final class FactAcctLogIterable implements IFactAcctLogIterable { @ToStringBuilder(skip = true) private final Properties ctx; private final String processingTag; public FactAcctLogIterable(final Properties ctx, final String processingTag) { super(); this.ctx = ctx; this.processingTag = processingTag; } @Override public String toString() { return ObjectUtils.toString(this); } @Override public Properties getCtx() { return ctx; } @Override public String getProcessingTag() { return processingTag; } @Override
public void close() { releaseTag(ctx, processingTag); } @Override @NonNull public Iterator<I_Fact_Acct_Log> iterator() { return retrieveForTag(ctx, processingTag); } @Override public void deleteAll() { deleteAllForTag(ctx, processingTag); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\legacy\impl\LegacyFactAcctLogDAO.java
1
请完成以下Java代码
public void setAD_PrinterHW_ID (int AD_PrinterHW_ID) { if (AD_PrinterHW_ID < 1) set_Value (COLUMNNAME_AD_PrinterHW_ID, null); else set_Value (COLUMNNAME_AD_PrinterHW_ID, Integer.valueOf(AD_PrinterHW_ID)); } @Override public int getAD_PrinterHW_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_ID); } @Override public void setAD_PrinterHW_MediaTray_ID (int AD_PrinterHW_MediaTray_ID) { if (AD_PrinterHW_MediaTray_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaTray_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaTray_ID, Integer.valueOf(AD_PrinterHW_MediaTray_ID)); } @Override 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 String getTradeStatus() { return tradeStatus; } public void setTradeStatus(String tradeStatus) { this.tradeStatus = tradeStatus == null ? null : tradeStatus.trim(); } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public Date getBankTradeTime() { return bankTradeTime; } public void setBankTradeTime(Date bankTradeTime) { this.bankTradeTime = bankTradeTime; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo == null ? null : bankOrderNo.trim(); } public String getBankTrxNo() { return bankTrxNo; } public void setBankTrxNo(String bankTrxNo) { this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim(); } public String getBankTradeStatus() { return bankTradeStatus; } public void setBankTradeStatus(String bankTradeStatus) { this.bankTradeStatus = bankTradeStatus == null ? null : bankTradeStatus.trim(); } public BigDecimal getBankAmount() { return bankAmount; } public void setBankAmount(BigDecimal bankAmount) { this.bankAmount = bankAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; } public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } public String getErrType() { return errType; } public void setErrType(String errType) { this.errType = errType == null ? null : errType.trim(); } public String getHandleStatus() { return handleStatus; }
public void setHandleStatus(String handleStatus) { this.handleStatus = handleStatus == null ? null : handleStatus.trim(); } public String getHandleValue() { return handleValue; } public void setHandleValue(String handleValue) { this.handleValue = handleValue == null ? null : handleValue.trim(); } public String getHandleRemark() { return handleRemark; } public void setHandleRemark(String handleRemark) { this.handleRemark = handleRemark == null ? null : handleRemark.trim(); } public String getOperatorName() { return operatorName; } public void setOperatorName(String operatorName) { this.operatorName = operatorName == null ? null : operatorName.trim(); } public String getOperatorAccountNo() { return operatorAccountNo; } public void setOperatorAccountNo(String operatorAccountNo) { this.operatorAccountNo = operatorAccountNo == null ? null : operatorAccountNo.trim(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistake.java
2
请完成以下Java代码
public class JobDto { protected String id; protected String jobDefinitionId; protected String processInstanceId; protected String processDefinitionId; protected String processDefinitionKey; protected String executionId; protected String exceptionMessage; protected String failedActivityId; protected int retries; protected Date dueDate; protected boolean suspended; protected long priority; protected String tenantId; protected Date createTime; protected String batchId; public static JobDto fromJob(Job job) { JobDto dto = new JobDto(); dto.id = job.getId(); dto.jobDefinitionId = job.getJobDefinitionId(); dto.processInstanceId = job.getProcessInstanceId(); dto.processDefinitionId = job.getProcessDefinitionId(); dto.processDefinitionKey = job.getProcessDefinitionKey(); dto.executionId = job.getExecutionId(); dto.exceptionMessage = job.getExceptionMessage(); dto.failedActivityId = job.getFailedActivityId(); dto.retries = job.getRetries(); dto.dueDate = job.getDuedate(); dto.suspended = job.isSuspended(); dto.priority = job.getPriority(); dto.tenantId = job.getTenantId(); dto.createTime = job.getCreateTime(); dto.batchId = job.getBatchId(); return dto; } public String getId() { return id; } public String getJobDefinitionId() { return jobDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId;
} public String getExceptionMessage() { return exceptionMessage; } public String getFailedActivityId() { return failedActivityId; } public int getRetries() { return retries; } public Date getDueDate() { return dueDate; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public boolean isSuspended() { return suspended; } public long getPriority() { return priority; } public String getTenantId() { return tenantId; } public Date getCreateTime() { return createTime; } public String getBatchId() { return batchId; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobDto.java
1
请完成以下Java代码
public void cleanup(long systemTtl) { log.info("Going to cleanup old timeseries data using ttl: {}s", systemTtl); try (Connection connection = dataSource.getConnection(); PreparedStatement stmt = connection.prepareStatement("call cleanup_timeseries_by_ttl(?,?,?)")) { stmt.setObject(1, ModelConstants.NULL_UUID); stmt.setLong(2, systemTtl); stmt.setLong(3, 0); stmt.setQueryTimeout((int) TimeUnit.HOURS.toSeconds(1)); stmt.execute(); printWarnings(stmt); try (ResultSet resultSet = stmt.getResultSet()) { resultSet.next(); log.info("Total telemetry removed stats by TTL for entities: [{}]", resultSet.getLong(1)); } } catch (SQLException e) { log.error("SQLException occurred during timeseries TTL task execution ", e); } } protected ListenableFuture<List<ReadTsKvQueryResult>> processFindAllAsync(TenantId tenantId, EntityId entityId, List<ReadTsKvQuery> queries) { List<ListenableFuture<ReadTsKvQueryResult>> futures = queries .stream() .map(query -> findAllAsync(tenantId, entityId, query)) .collect(Collectors.toList()); return Futures.transform(Futures.allAsList(futures), new Function<>() { @Nullable @Override public List<ReadTsKvQueryResult> apply(@Nullable List<ReadTsKvQueryResult> results) { if (results == null || results.isEmpty()) { return null; } return results.stream().filter(Objects::nonNull).collect(Collectors.toList()); } }, service); }
protected long computeTtl(long ttl) { if (systemTtl > 0) { if (ttl == 0) { ttl = systemTtl; } else { ttl = Math.min(systemTtl, ttl); } } return ttl; } protected int getDataPointDays(TsKvEntry tsKvEntry, long ttl) { return tsKvEntry.getDataPoints() * Math.max(1, (int) (ttl / SECONDS_IN_DAY)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\AbstractSqlTimeseriesDao.java
1
请完成以下Java代码
private List<String> getGrantedAuthorities(Authentication authentication) { return this.roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities()) .stream() .map(GrantedAuthority::getAuthority) .toList(); } /** * Creates an instance of {@link AllAuthoritiesReactiveAuthorizationManager} with the * provided authorities. * @param roles the authorities to check for prefixed with "ROLE_". Each role should * not start with "ROLE_" since it is automatically prepended already. * @param <T> the type of object being authorized * @return the new instance */ public static <T> AllAuthoritiesReactiveAuthorizationManager<T> hasAllRoles(String... roles) { return hasAllPrefixedAuthorities(ROLE_PREFIX, roles); } /** * Creates an instance of {@link AllAuthoritiesReactiveAuthorizationManager} with the * provided authorities. * @param prefix the prefix for <code>authorities</code> * @param authorities the authorities to check for prefixed with <code>prefix</code> * @param <T> the type of object being authorized * @return the new instance */ public static <T> AllAuthoritiesReactiveAuthorizationManager<T> hasAllPrefixedAuthorities(String prefix, String... authorities) { Assert.notNull(prefix, "rolePrefix cannot be null"); Assert.notEmpty(authorities, "roles cannot be empty"); Assert.noNullElements(authorities, "roles cannot contain null values"); return hasAllAuthorities(toNamedRolesArray(prefix, authorities)); } /** * Creates an instance of {@link AllAuthoritiesReactiveAuthorizationManager} with the * provided authorities.
* @param authorities the authorities to check for * @param <T> the type of object being authorized * @return the new instance */ public static <T> AllAuthoritiesReactiveAuthorizationManager<T> hasAllAuthorities(String... authorities) { Assert.notEmpty(authorities, "authorities cannot be empty"); Assert.noNullElements(authorities, "authorities cannot contain null values"); return new AllAuthoritiesReactiveAuthorizationManager<>(authorities); } private static String[] toNamedRolesArray(String rolePrefix, String[] roles) { String[] result = new String[roles.length]; for (int i = 0; i < roles.length; i++) { String role = roles[i]; Assert.isTrue(rolePrefix.isEmpty() || !role.startsWith(rolePrefix), () -> role + " should not start with " + rolePrefix + " since " + rolePrefix + " is automatically prepended when using hasAnyRole. Consider using hasAnyAuthority instead."); result[i] = rolePrefix + role; } return result; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AllAuthoritiesReactiveAuthorizationManager.java
1
请完成以下Spring Boot application配置
# custom path for swagger-ui springdoc.swagger-ui.path=/swagger-ui-custom.html # custom path for api docs springdoc.api-docs.path=/api-docs # H2 Related Configurations spring.datasource.url=jdbc:h2:mem:springdoc ## for com.baeldung.restdocopenapi ## springdoc.version=@springdoc.version@ spring.jpa.hibernate.ddl-auto=none ## for com.baeldung.jwt ## jwt.private.key=classpath:app.key jwt.public.key=classpath:app.pub api.version=1.0-SNAPSHOT tos.uri=terms-of-service api.server.url=https://www.baeldung.com api.description=The User API is used to create, update, and delete users. Users can be created with or without an associated account. If an account
is created, the user will be granted the <strong>ROLE_USER</strong> role. If an account is not created, the user will be granted the <b>ROLE_USER</b> role. springdoc.swagger-ui.operationsSorter=alpha ##springdoc.swagger-ui.tagsSorter=alpha ##springdoc.writer-with-order-by-keys=true
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\resources\application.properties
2
请完成以下Java代码
public void deleteHistoricDetailsByTaskId(String taskId) { if (isHistoryEnabled()) { // delete entries in DB List<HistoricDetail> historicDetails = findHistoricDetailsByTaskId(taskId); for (HistoricDetail historicDetail : historicDetails) { ((HistoricDetailEventEntity) historicDetail).delete(); } //delete entries in Cache List<HistoricDetailEventEntity> cachedHistoricDetails = getDbEntityManager().getCachedEntitiesByType(HistoricDetailEventEntity.class); for (HistoricDetailEventEntity historicDetail : cachedHistoricDetails) { // make sure we only delete the right ones (as we cannot make a proper query in the cache) if (taskId.equals(historicDetail.getTaskId())) { historicDetail.delete(); } } } } @SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByTaskId(String taskId) { return getDbEntityManager().selectList("selectHistoricDetailsByTaskId", taskId); } protected void configureQuery(HistoricDetailQueryImpl query) { getAuthorizationManager().configureHistoricDetailQuery(query); getTenantManager().configureQuery(query); } public DbOperation addRemovalTimeToDetailsByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricDetailEventEntity.class, "updateHistoricDetailsByRootProcessInstanceId", parameters); } public DbOperation addRemovalTimeToDetailsByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricDetailEventEntity.class, "updateHistoricDetailsByProcessInstanceId", parameters); } public DbOperation deleteHistoricDetailsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricDetailEventEntity.class, "deleteHistoricDetailsByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailManager.java
1
请完成以下Java代码
public class LTrimRTrim { private String src; private static String ltrimResult; private static String rtrimResult; private static Pattern LTRIM = Pattern.compile("^\\s+"); private static Pattern RTRIM = Pattern.compile("\\s+$"); public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); } @Setup public void setup() { src = " White spaces left and right "; ltrimResult = "White spaces left and right "; rtrimResult = " White spaces left and right"; } public static String whileLtrim(String s) { int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } return s.substring(i); } public static String whileRtrim(String s) { int i = s.length() - 1; while (i >= 0 && Character.isWhitespace(s.charAt(i))) { i--; } return s.substring(0, i + 1); } private static boolean checkStrings(String ltrim, String rtrim) { boolean result = false; if (ltrimResult.equalsIgnoreCase(ltrim) && rtrimResult.equalsIgnoreCase(rtrim)) result = true; return result; } // Going through the String detecting Whitespaces @Benchmark public boolean whileCharacters() { String ltrim = whileLtrim(src); String rtrim = whileRtrim(src); return checkStrings(ltrim, rtrim); } // replaceAll() and Regular Expressions @Benchmark public boolean replaceAllRegularExpression() { String ltrim = src.replaceAll("^\\s+", "");
String rtrim = src.replaceAll("\\s+$", ""); return checkStrings(ltrim, rtrim); } public static String patternLtrim(String s) { return LTRIM.matcher(s) .replaceAll(""); } public static String patternRtrim(String s) { return RTRIM.matcher(s) .replaceAll(""); } // Pattern matches() with replaceAll @Benchmark public boolean patternMatchesLTtrimRTrim() { String ltrim = patternLtrim(src); String rtrim = patternRtrim(src); return checkStrings(ltrim, rtrim); } // Guava CharMatcher trimLeadingFrom / trimTrailingFrom @Benchmark public boolean guavaCharMatcher() { String ltrim = CharMatcher.whitespace().trimLeadingFrom(src); String rtrim = CharMatcher.whitespace().trimTrailingFrom(src); return checkStrings(ltrim, rtrim); } // Apache Commons StringUtils containsIgnoreCase @Benchmark public boolean apacheCommonsStringUtils() { String ltrim = StringUtils.stripStart(src, null); String rtrim = StringUtils.stripEnd(src, null); return checkStrings(ltrim, rtrim); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\trim\LTrimRTrim.java
1
请完成以下Java代码
public String getTheme() { return theme; } /** * Set the theme. * * @param theme theme */ public void setTheme(String theme) { this.theme = theme; } /** * Get the checks if is ldap. *
* @return the checks if is ldap */ public Integer getIsLdap() { return isLdap; } /** * Set the checks if is ldap. * * @param isLdap the checks if is ldap */ public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } }
repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java
1
请完成以下Java代码
public PartyIdentificationSEPA1 getUltmtCdtr() { return ultmtCdtr; } /** * Sets the value of the ultmtCdtr property. * * @param value * allowed object is * {@link PartyIdentificationSEPA1 } * */ public void setUltmtCdtr(PartyIdentificationSEPA1 value) { this.ultmtCdtr = value; } /** * Gets the value of the chrgBr property. * * @return * possible object is * {@link ChargeBearerTypeSEPACode } * */ public ChargeBearerTypeSEPACode getChrgBr() { return chrgBr; } /** * Sets the value of the chrgBr property. * * @param value * allowed object is * {@link ChargeBearerTypeSEPACode } * */ public void setChrgBr(ChargeBearerTypeSEPACode value) { this.chrgBr = value; } /** * Gets the value of the cdtrSchmeId property. * * @return * possible object is * {@link PartyIdentificationSEPA3 } *
*/ public PartyIdentificationSEPA3 getCdtrSchmeId() { return cdtrSchmeId; } /** * Sets the value of the cdtrSchmeId property. * * @param value * allowed object is * {@link PartyIdentificationSEPA3 } * */ public void setCdtrSchmeId(PartyIdentificationSEPA3 value) { this.cdtrSchmeId = value; } /** * Gets the value of the drctDbtTxInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the drctDbtTxInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDrctDbtTxInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DirectDebitTransactionInformationSDD } * * */ public List<DirectDebitTransactionInformationSDD> getDrctDbtTxInf() { if (drctDbtTxInf == null) { drctDbtTxInf = new ArrayList<DirectDebitTransactionInformationSDD>(); } return this.drctDbtTxInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentInstructionInformationSDD.java
1
请完成以下Java代码
public Class<Address> returnedClass() { return Address.class; } @Override public boolean equals(Address x, Address y) { if (x == y) { return true; } if (Objects.isNull(x) || Objects.isNull(y)) { return false; } return x.equals(y); } @Override public int hashCode(Address x) { return x.hashCode(); } @Override public Address deepCopy(Address value) { if (Objects.isNull(value)) { return null; } Address newEmpAdd = new Address(); newEmpAdd.setAddressLine1(value.getAddressLine1()); newEmpAdd.setAddressLine2(value.getAddressLine2()); newEmpAdd.setCity(value.getCity()); newEmpAdd.setCountry(value.getCountry()); newEmpAdd.setZipCode(value.getZipCode()); return newEmpAdd; } @Override
public boolean isMutable() { return true; } @Override public Serializable disassemble(Address value) { return (Serializable) deepCopy(value); } @Override public Address assemble(Serializable cached, Object owner) { return deepCopy((Address) cached); } @Override public Address replace(Address detached, Address managed, Object owner) { return detached; } @Override public boolean isInstance(Object object) { return CompositeUserType.super.isInstance(object); } @Override public boolean isSameClass(Object object) { return CompositeUserType.super.isSameClass(object); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\AddressType.java
1
请完成以下Java代码
public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_EventAudit.java
1
请完成以下Java代码
protected MContainerElement[] getAllElements() { int elements[] = MContainerElement.getAllIDs("CM_Container_Element", "CM_Container_ID=" + get_ID(), get_TrxName()); if (elements.length>0) { MContainerElement[] containerElements = new MContainerElement[elements.length]; for (int i=0;i<elements.length;i++) { containerElements[i] = new MContainerElement(getCtx(), elements[i], get_TrxName()); } return containerElements; } else { return null; } } @Override protected boolean beforeDelete() { // Clean own index MIndex.cleanUp(get_TrxName(), getAD_Client_ID(), get_Table_ID(), get_ID()); // Clean ElementIndex MContainerElement[] theseElements = getAllElements(); if (theseElements!=null) { for (int i=0;i<theseElements.length;i++) { theseElements[i].delete(false); } } // StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_ID ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString (), get_TrxName ()); if (no > 0) log.debug("#" + no + " - TreeType=CMC"); else log.warn("#" + no + " - TreeType=CMC"); return no > 0; } /** * After Delete
* * @param success * @return deleted */ @Override protected boolean afterDelete (boolean success) { if (!success) return success; // StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_IDOld ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString (), get_TrxName ()); // If 0 than there is nothing to delete which is okay. if (no > 0) log.debug("#" + no + " - TreeType=CMC"); else log.warn("#" + no + " - TreeType=CMC"); return true; } // afterDelete /** * reIndex * @param newRecord */ public void reIndex(boolean newRecord) { String [] toBeIndexed = new String[8]; toBeIndexed[0] = this.getName(); toBeIndexed[1] = this.getDescription(); toBeIndexed[2] = this.getRelativeURL(); toBeIndexed[3] = this.getMeta_Author(); toBeIndexed[4] = this.getMeta_Copyright(); toBeIndexed[5] = this.getMeta_Description(); toBeIndexed[6] = this.getMeta_Keywords(); toBeIndexed[7] = this.getMeta_Publisher(); MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), getCM_WebProject_ID(), this.getUpdated()); MContainerElement[] theseElements = getAllElements(); if (theseElements!=null) for (int i=0;i<theseElements.length;i++) theseElements[i].reIndex (false); } // reIndex } // MContainer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContainer.java
1
请完成以下Java代码
protected TreePath[] getChildrenPath(TreePath path) { Object node = path.getLastPathComponent(); int childrenNumber = this.model.getChildCount(node); TreePath[] childrenPath = new TreePath[childrenNumber]; for (int childIndex = 0; childIndex < childrenNumber; childIndex++) { childrenPath[childIndex] = path.pathByAddingChild(this.model.getChild(node, childIndex)); } return childrenPath; } @Override public TreeModel getTreeModel() { return this.model; } /** * Sets the specified tree model. The current cheking is cleared. */ @Override public void setTreeModel(TreeModel newModel) { TreeModel oldModel = this.model; if (oldModel != null) { oldModel.removeTreeModelListener(this.propagateCheckingListener); } this.model = newModel; if (newModel != null) { newModel.addTreeModelListener(this.propagateCheckingListener); } clearChecking(); } /** * Return a string that describes the tree model including the values of * checking, enabling, greying. */ @Override public String toString() { return toString(new TreePath(this.model.getRoot())); } /** * Convenience method for getting a string that describes the tree * starting at path. *
* @param path the treepath root of the tree */ private String toString(TreePath path) { String checkString = "n"; String greyString = "n"; String enableString = "n"; if (isPathChecked(path)) { checkString = "y"; } if (isPathEnabled(path)) { enableString = "y"; } if (isPathGreyed(path)) { greyString = "y"; } String description = "Path checked: " + checkString + " greyed: " + greyString + " enabled: " + enableString + " Name: " + path.toString() + "\n"; for (TreePath childPath : getChildrenPath(path)) { description += toString(childPath); } return description; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultTreeCheckingModel.java
1
请完成以下Java代码
public class FetchAndLockBuilderImpl implements FetchAndLockBuilder { protected final CommandExecutor commandExecutor; protected String workerId; protected int maxTasks; protected boolean usePriority; protected List<QueryOrderingProperty> orderingProperties = new ArrayList<>(); public FetchAndLockBuilderImpl(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; } public FetchAndLockBuilderImpl workerId(String workerId) { this.workerId = workerId; return this; } public FetchAndLockBuilderImpl maxTasks(int maxTasks) { this.maxTasks = maxTasks; return this; } public FetchAndLockBuilderImpl usePriority(boolean usePriority) { this.usePriority = usePriority; return this; } public FetchAndLockBuilderImpl orderByCreateTime() { orderingProperties.add(new QueryOrderingProperty(CREATE_TIME, null)); return this; } public FetchAndLockBuilderImpl asc() throws NotValidException { configureLastOrderingPropertyDirection(ASCENDING); return this; } public FetchAndLockBuilderImpl desc() throws NotValidException { configureLastOrderingPropertyDirection(DESCENDING); return this; } @Override
public ExternalTaskQueryTopicBuilder subscribe() { checkQueryOk(); return new ExternalTaskQueryTopicBuilderImpl(commandExecutor, workerId, maxTasks, usePriority, orderingProperties); } protected void configureLastOrderingPropertyDirection(Direction direction) { QueryOrderingProperty lastProperty = !orderingProperties.isEmpty() ? getLastElement(orderingProperties) : null; ensureNotNull(NotValidException.class, "You should call any of the orderBy methods first before specifying a direction", "currentOrderingProperty", lastProperty); if (lastProperty.getDirection() != null) { ensureNull(NotValidException.class, "Invalid query: can specify only one direction desc() or asc() for an ordering constraint", "direction", direction); } lastProperty.setDirection(direction); } protected void checkQueryOk() { for (QueryOrderingProperty orderingProperty : orderingProperties) { ensureNotNull(NotValidException.class, "Invalid query: call asc() or desc() after using orderByXX()", "direction", orderingProperty.getDirection()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\FetchAndLockBuilderImpl.java
1
请完成以下Java代码
public List<GridTabVO> getChildTabs(final int tabNo) { final GridTabVO masterTab = _tabs.get(tabNo); final int masterTabLevel = masterTab.getTabLevel(); final int childTabLevelExpected = masterTabLevel + 1; final int tabsCount = _tabs.size(); final List<GridTabVO> childTabs = new ArrayList<>(); for (int childTabNo = tabNo + 1; childTabNo < tabsCount; childTabNo++) { final GridTabVO childTab = _tabs.get(childTabNo); final int childTabLevel = childTab.getTabLevel(); if(childTabLevel == masterTabLevel) { // we just moved to another master tab. Stop here. break; } else if (childTabLevel == childTabLevelExpected) { // we found a child tab. Collect it. childTabs.add(childTab); } else // childTabLevel > childTabLevelExpected { // we found a child of a child tab. Ignore it. continue; } } return childTabs; } public String getName() { return name; } public Map<String, String> getNameTrls() { return nameTrls; } private void setName(final String adLanguage, final String nameTrl) { Check.assumeNotEmpty(adLanguage, "adLanguage is not empty"); if(nameTrl == null) { return; } if(nameTrls == null) { nameTrls = new HashMap<>(); } nameTrls.put(adLanguage, nameTrl); } public String getDescription() { return description; } public Map<String, String> getDescriptionTrls() { return descriptionTrls; } private void setDescription(final String adLanguage, final String descriptionTrl) { Check.assumeNotEmpty(adLanguage, "adLanguage is not empty"); if(descriptionTrl == null) { return; } if(descriptionTrls == null) { descriptionTrls = new HashMap<>(); } descriptionTrls.put(adLanguage, descriptionTrl); } public String getHelp() { return help; } public Map<String, String> getHelpTrls() { return helpTrls; }
private void setHelp(final String adLanguage, final String helpTrl) { Check.assumeNotEmpty(adLanguage, "adLanguage is not empty"); if(helpTrl == null) { return; } if(helpTrls == null) { helpTrls = new HashMap<>(); } helpTrls.put(adLanguage, helpTrl); } void setReadWrite(final boolean readWrite) { this._isReadWrite = readWrite; } public boolean isReadWrite() { return Boolean.TRUE.equals(_isReadWrite); } private void setIsSOTrx(final boolean isSOTrx) { this._isSOTrx = isSOTrx; } public boolean isSOTrx() { return _isSOTrx; } public int getAD_Color_ID() { return AD_Color_ID; } public int getAD_Image_ID() { return AD_Image_ID; } public int getWinWidth() { return WinWidth; } public int getWinHeight() { return WinHeight; } public String getWindowType() { return WindowType; } private int getBaseTable_ID() { return _BaseTable_ID; } boolean isLoadAllLanguages() { return loadAllLanguages; } boolean isApplyRolePermissions() { return applyRolePermissions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindowVO.java
1
请完成以下Java代码
public String getTargetProcessDefinitionId() { return targetProcessDefinitionId; } public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public List<MigrationInstructionDto> getInstructions() { return instructions; } public void setInstructions(List<MigrationInstructionDto> instructions) { this.instructions = instructions; } public Map<String, VariableValueDto> getVariables() { return variables; } public void setVariables(Map<String, VariableValueDto> variables) { this.variables = variables; } public static MigrationPlanDto from(MigrationPlan migrationPlan) { MigrationPlanDto dto = new MigrationPlanDto(); VariableMap variables = migrationPlan.getVariables(); if (variables != null) { dto.setVariables(VariableValueDto.fromMap(variables)); } dto.setSourceProcessDefinitionId(migrationPlan.getSourceProcessDefinitionId()); dto.setTargetProcessDefinitionId(migrationPlan.getTargetProcessDefinitionId()); ArrayList<MigrationInstructionDto> instructionDtos = new ArrayList<MigrationInstructionDto>(); if (migrationPlan.getInstructions() != null) { for (MigrationInstruction migrationInstruction : migrationPlan.getInstructions()) { MigrationInstructionDto migrationInstructionDto = MigrationInstructionDto.from(migrationInstruction); instructionDtos.add(migrationInstructionDto); } } dto.setInstructions(instructionDtos); return dto; } public static MigrationPlan toMigrationPlan(ProcessEngine processEngine,
ObjectMapper objectMapper, MigrationPlanDto migrationPlanDto) { MigrationPlanBuilder migrationPlanBuilder = processEngine.getRuntimeService().createMigrationPlan(migrationPlanDto.getSourceProcessDefinitionId(), migrationPlanDto.getTargetProcessDefinitionId()); Map<String, VariableValueDto> variableDtos = migrationPlanDto.getVariables(); if (variableDtos != null) { Map<String, Object> variables = VariableValueDto.toMap(variableDtos, processEngine, objectMapper); migrationPlanBuilder.setVariables(variables); } if (migrationPlanDto.getInstructions() != null) { for (MigrationInstructionDto migrationInstructionDto : migrationPlanDto.getInstructions()) { MigrationInstructionBuilder migrationInstructionBuilder = migrationPlanBuilder.mapActivities(migrationInstructionDto.getSourceActivityIds().get(0), migrationInstructionDto.getTargetActivityIds().get(0)); if (Boolean.TRUE.equals(migrationInstructionDto.isUpdateEventTrigger())) { migrationInstructionBuilder = migrationInstructionBuilder.updateEventTrigger(); } migrationPlanBuilder = migrationInstructionBuilder; } } return migrationPlanBuilder.build(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationPlanDto.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Role_ID (final int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, AD_Role_ID); } @Override public int getAD_Role_ID() { return get_ValueAsInt(COLUMNNAME_AD_Role_ID); } @Override public void setIsAllowAllActions (final boolean IsAllowAllActions) { set_Value (COLUMNNAME_IsAllowAllActions, IsAllowAllActions); } @Override public boolean isAllowAllActions() { return get_ValueAsBoolean(COLUMNNAME_IsAllowAllActions); }
@Override public void setMobile_Application_Access_ID (final int Mobile_Application_Access_ID) { if (Mobile_Application_Access_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_Access_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_Access_ID, Mobile_Application_Access_ID); } @Override public int getMobile_Application_Access_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_Access_ID); } @Override public void setMobile_Application_ID (final int Mobile_Application_ID) { if (Mobile_Application_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID); } @Override public int getMobile_Application_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Access.java
1
请完成以下Java代码
private void listProcessVariables(ProcessInstance processInstance) { logger.info(">>> Process variables:"); List<VariableInstance> variables = processRuntime.variables( ProcessPayloadBuilder.variables().withProcessInstance(processInstance).build() ); variables.forEach(variableInstance -> logger.info("\t> " + variableInstance.getName() + " -> " + variableInstance.getValue()) ); } private ProcessInstance startProcess() { ProcessInstance processInstance = processRuntime.start( ProcessPayloadBuilder.start() .withProcessDefinitionKey("RankMovieId") .withName("myProcess") .withVariable("movieToRank", "Lord of the rings") .build() ); logger.info(">>> Created Process Instance: " + processInstance); return processInstance; } private void listAvailableProcesses() { Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10)); logger.info("> Available Process definitions: " + processDefinitionPage.getTotalItems()); for (ProcessDefinition pd : processDefinitionPage.getContent()) { logger.info("\t > Process definition: " + pd); } } @Bean("Movies.getMovieDesc") public Connector getMovieDesc() { return getConnector(); } @Bean("MoviesWithUUIDs.getMovieDesc") public Connector getMovieDescUUIDs() { return getConnector(); }
private Connector getConnector() { return integrationContext -> { Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables(); logger.info(">>inbound: " + inBoundVariables); integrationContext.addOutBoundVariable( "movieDescription", "The Lord of the Rings is an epic high fantasy novel written by English author and scholar J. R. R. Tolkien" ); return integrationContext; }; } @Bean public VariableEventListener<VariableCreatedEvent> variableCreatedEventListener() { return variableCreatedEvent -> variableCreatedEvents.add(variableCreatedEvent); } @Bean public ProcessRuntimeEventListener<ProcessCompletedEvent> processCompletedEventListener() { return processCompletedEvent -> processCompletedEvents.add(processCompletedEvent); } }
repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\DemoApplication.java
1
请在Spring Boot框架中完成以下Java代码
public class CompleteWFActivityHandler implements WFActivityHandler, UserConfirmationSupport { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("inventory.complete"); @NonNull private final IMsgBL msgBL = Services.get(IMsgBL.class); @NonNull private final InventoryJobService jobService; @Override public WFActivityType getHandledActivityType() {return HANDLED_ACTIVITY_TYPE;} @Override public UIComponent getUIComponent(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(msgBL.getMsg(jsonOpts.getAdLanguage(), ARE_YOU_SURE)) .build()); }
@Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return computeActivityState(getInventory(wfProcess)); } public static WFActivityStatus computeActivityState(final Inventory inventory) { return InventoryJobWFActivityHandler.computeActivityState(inventory); } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.assertActivityType(HANDLED_ACTIVITY_TYPE); return InventoryMobileApplication.mapJob(request.getWfProcess(), jobService::complete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\CompleteWFActivityHandler.java
2
请完成以下Java代码
public boolean dbNeedsMigration() { final Version dbVersion = Version.valueOf(dbVersionStr); logger.info("AD_System.DBVersion is {}", dbVersion); final Version rolloutVersion = Version.valueOf(rolloutVersionStr); logger.info("Our own version is {}", rolloutVersion); final int comp = dbVersion.compareTo(rolloutVersion); if (comp == 0) { logger.info("AD_System.DBVersion is equal to our version. Nothing to do."); return false; } else if (comp < 0) { // dbVersion is lower than rolloutVersion // => we need to do the migration to "elevate" it logger.info("The DB version is lower than our own version. Going to migrate"); return true; } // Check if we have the special case of issue https://github.com/metasfresh/metasfresh/issues/2260 final boolean sameMajorVersion = dbVersion.getMajorVersion() == rolloutVersion.getMajorVersion(); final boolean sameMinorVersion = dbVersion.getMinorVersion() == rolloutVersion.getMinorVersion(); final boolean patchVersionSwitchBetweenOneAndTwo = // dbVersion.getPatchVersion() == 1 && rolloutVersion.getPatchVersion() == 2 // || dbVersion.getPatchVersion() == 2 && rolloutVersion.getPatchVersion() == 1; if (sameMajorVersion && sameMinorVersion && patchVersionSwitchBetweenOneAndTwo) { logger.info("Detected a version switch between master (=> patchVersion=1) and release, issue etc (=> patchVersion=2). Assuming that the DB needs migration. Also see https://github.com/metasfresh/metasfresh/issues/2260"); return true; } // check if we have a switch between two non-master branches if(!Objects.equals(dbVersion.getBuildMetadata(), rolloutVersion.getBuildMetadata())) { logger.info("Detected a version switch between \"branches\" dbVersion={} and rolloutVersion={}. Assuming that the DB needs migration. Also see https://github.com/metasfresh/metasfresh/issues/2260", dbVersion.getPreReleaseVersion(), rolloutVersion.getPreReleaseVersion()); return true; } // Issue https://github.com/metasfresh/metasfresh/issues/2260 does not apply..
// dbVersion higher....uh-ooh final String msg = "The code has version " + rolloutVersionStr + " but the DB already has version " + dbVersionStr; if (!failIfRolloutIsGreaterThanDB) { // let's ignore the problem logger.info(msg + ". *Not* throwing exception because of the +" + CommandlineParams.OPTION_DoNotFailIfRolloutIsGreaterThanDB + " parameter; but not going to attempt migration either."); return false; } throw new InconsistentVersionsException(msg); } public static final class InconsistentVersionsException extends RuntimeException { private static final long serialVersionUID = -5089487300354591676L; private InconsistentVersionsException(final String msg) { super(msg); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\VersionChecker.java
1
请完成以下Java代码
public UserInterface2Code getDispTp() { return dispTp; } /** * Sets the value of the dispTp property. * * @param value * allowed object is * {@link UserInterface2Code } * */ public void setDispTp(UserInterface2Code value) { this.dispTp = value; } /** * Gets the value of the nbOfLines property. * * @return * possible object is * {@link String } * */ public String getNbOfLines() { return nbOfLines; } /** * Sets the value of the nbOfLines property. * * @param value * allowed object is * {@link String } * */ public void setNbOfLines(String value) { this.nbOfLines = value; }
/** * Gets the value of the lineWidth property. * * @return * possible object is * {@link String } * */ public String getLineWidth() { return lineWidth; } /** * Sets the value of the lineWidth property. * * @param value * allowed object is * {@link String } * */ public void setLineWidth(String value) { this.lineWidth = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\DisplayCapabilities1.java
1
请完成以下Java代码
public List<POSOrder> list(@NonNull final POSOrderQuery query) { final List<I_C_POS_Order> orderRecords = toSqlQuery(query) .create() .list(); return newLoaderAndSaver().loadFromRecords(orderRecords); } public Optional<POSOrder> firstOnly(@NonNull final POSOrderQuery query) { return toSqlQuery(query) .create() .firstOnlyOptional(I_C_POS_Order.class) .map(record -> newLoaderAndSaver().loadFromRecord(record)); } private IQueryBuilder<I_C_POS_Order> toSqlQuery(final POSOrderQuery query) { final IQueryBuilder<I_C_POS_Order> sqlQueryBuilder = queryBL.createQueryBuilder(I_C_POS_Order.class) .addEqualsFilter(I_C_POS_Order.COLUMNNAME_C_POS_ID, query.getPosTerminalId()) .addEqualsFilter(I_C_POS_Order.COLUMNNAME_Cashier_ID, query.getCashierId()); if (query.isOpen()) { sqlQueryBuilder.addInArrayFilter(I_C_POS_Order.COLUMNNAME_Status, POSOrderStatus.OPEN_STATUSES); } final Set<POSOrderExternalId> onlyOrderExternalIds = query.getOnlyOrderExternalIds(); if (onlyOrderExternalIds != null && !onlyOrderExternalIds.isEmpty()) { sqlQueryBuilder.addInArrayFilter(I_C_POS_Order.COLUMNNAME_ExternalId, POSOrderExternalId.toStringSet(onlyOrderExternalIds)); } return sqlQueryBuilder; } public POSOrder getById(@NonNull final POSOrderId posOrderId) { return newLoaderAndSaver().getById(posOrderId); } public POSOrder updateByExternalId(final @NonNull POSOrderExternalId externalId, final @NonNull Consumer<POSOrder> updater) { return createOrUpdateByExternalId(
externalId, externalId0 -> { throw new AdempiereException("No order found for external id " + externalId); }, updater); } public POSOrder createOrUpdateByExternalId( @NonNull final POSOrderExternalId externalId, @NonNull final Function<POSOrderExternalId, POSOrder> factory, @NonNull final Consumer<POSOrder> updater) { return trxManager.callInThreadInheritedTrx(() -> newLoaderAndSaver().createOrUpdateByExternalId(externalId, factory, updater)); } public void updateById(@NonNull final POSOrderId id, @NonNull final Consumer<POSOrder> updater) { trxManager.callInThreadInheritedTrx(() -> newLoaderAndSaver().updateById(id, updater)); } public void updatePaymentById(@NonNull final POSOrderAndPaymentId orderAndPaymentId, @NonNull final BiFunction<POSOrder, POSPayment, POSPayment> updater) { updateById(orderAndPaymentId.getOrderId(), order -> order.updatePaymentById(orderAndPaymentId.getPaymentId(), payment -> updater.apply(order, payment))); } public POSOrderId getIdByExternalId(final @NonNull POSOrderExternalId externalId) { return newLoaderAndSaver().getIdByExternalId(externalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrdersRepository.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(AuthenticationManagerBuilder auth) { String[] beanNames = InitializeUserDetailsBeanManagerConfigurer.this.context .getBeanNamesForType(UserDetailsService.class); if (auth.isConfigured()) { if (beanNames.length > 0) { this.logger.warn("Global AuthenticationManager configured with an AuthenticationProvider bean. " + "UserDetailsService beans will not be used by Spring Security for automatically configuring username/password login. " + "Consider removing the AuthenticationProvider bean. " + "Alternatively, consider using the UserDetailsService in a manually instantiated DaoAuthenticationProvider. " + "If the current configuration is intentional, to turn off this warning, " + "increase the logging level of 'org.springframework.security.config.annotation.authentication.configuration.InitializeUserDetailsBeanManagerConfigurer' to ERROR"); } return; } if (beanNames.length == 0) { return; } else if (beanNames.length > 1) { this.logger.warn(LogMessage.format("Found %s UserDetailsService beans, with names %s. " + "Global Authentication Manager will not use a UserDetailsService for username/password login. " + "Consider publishing a single UserDetailsService bean.", beanNames.length, Arrays.toString(beanNames))); return; } UserDetailsService userDetailsService = InitializeUserDetailsBeanManagerConfigurer.this.context .getBean(beanNames[0], UserDetailsService.class); PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class); UserDetailsPasswordService passwordManager = getBeanOrNull(UserDetailsPasswordService.class); CompromisedPasswordChecker passwordChecker = getBeanOrNull(CompromisedPasswordChecker.class); DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService); if (passwordEncoder != null) {
provider.setPasswordEncoder(passwordEncoder); } if (passwordManager != null) { provider.setUserDetailsPasswordService(passwordManager); } if (passwordChecker != null) { provider.setCompromisedPasswordChecker(passwordChecker); } provider.afterPropertiesSet(); auth.authenticationProvider(provider); this.logger.info(LogMessage.format( "Global AuthenticationManager configured with UserDetailsService bean with name %s", beanNames[0])); } /** * @return a bean of the requested class if there's just a single registered * component, null otherwise. */ private <T> T getBeanOrNull(Class<T> type) { return InitializeUserDetailsBeanManagerConfigurer.this.context.getBeanProvider(type).getIfUnique(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configuration\InitializeUserDetailsBeanManagerConfigurer.java
2
请完成以下Java代码
public boolean isCreateDiagramOnDeploy() { return isCreateDiagramOnDeploy; } public DmnEngineConfiguration setCreateDiagramOnDeploy(boolean isCreateDiagramOnDeploy) { this.isCreateDiagramOnDeploy = isCreateDiagramOnDeploy; return this; } public String getDecisionFontName() { return decisionFontName; } public DmnEngineConfiguration setDecisionFontName(String decisionFontName) { this.decisionFontName = decisionFontName; return this; } public String getLabelFontName() {
return labelFontName; } public DmnEngineConfiguration setLabelFontName(String labelFontName) { this.labelFontName = labelFontName; return this; } public String getAnnotationFontName() { return annotationFontName; } public DmnEngineConfiguration setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; return this; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngineConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
class SomeClass { private SomeDependency someDependency; public SomeClass(SomeDependency someDependency) { super(); this.someDependency = someDependency; System.out.println("All dependencies are ready!"); } @PostConstruct public void initialize() { someDependency.getReady(); } @PreDestroy public void cleanup() { System.out.println("Cleanup"); } } @Component class SomeDependency { public void getReady() {
System.out.println("Some logic using SomeDependency"); } } @Configuration @ComponentScan public class PrePostAnnotationsContextLauncherApplication { public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext (PrePostAnnotationsContextLauncherApplication.class)) { Arrays.stream(context.getBeanDefinitionNames()) .forEach(System.out::println); } } }
repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\f1\PrePostAnnotationsContextLauncherApplication.java
2
请完成以下Java代码
public class APIProcessInstanceConverter extends ListConverter<org.activiti.engine.runtime.ProcessInstance, ProcessInstance> implements ModelConverter<org.activiti.engine.runtime.ProcessInstance, ProcessInstance> { @Override public ProcessInstance from(org.activiti.engine.runtime.ProcessInstance internalProcessInstance) { ProcessInstanceImpl processInstance = new ProcessInstanceImpl(); processInstance.setId(internalProcessInstance.getId()); processInstance.setParentId(internalProcessInstance.getParentProcessInstanceId()); processInstance.setName(internalProcessInstance.getName()); processInstance.setProcessDefinitionId(internalProcessInstance.getProcessDefinitionId()); processInstance.setProcessDefinitionKey(internalProcessInstance.getProcessDefinitionKey()); processInstance.setProcessDefinitionVersion(internalProcessInstance.getProcessDefinitionVersion()); processInstance.setInitiator(internalProcessInstance.getStartUserId()); processInstance.setStartDate(internalProcessInstance.getStartTime()); processInstance.setProcessDefinitionKey(internalProcessInstance.getProcessDefinitionKey()); processInstance.setBusinessKey(internalProcessInstance.getBusinessKey()); processInstance.setStatus(calculateStatus(internalProcessInstance)); processInstance.setProcessDefinitionVersion(internalProcessInstance.getProcessDefinitionVersion());
processInstance.setAppVersion(Objects.toString(internalProcessInstance.getAppVersion(), null)); processInstance.setProcessDefinitionName(internalProcessInstance.getProcessDefinitionName()); processInstance.setRootProcessInstanceId(internalProcessInstance.getRootProcessInstanceId()); return processInstance; } private ProcessInstance.ProcessInstanceStatus calculateStatus( org.activiti.engine.runtime.ProcessInstance internalProcessInstance ) { if (internalProcessInstance.isSuspended()) { return ProcessInstance.ProcessInstanceStatus.SUSPENDED; } else if (internalProcessInstance.isEnded()) { return ProcessInstance.ProcessInstanceStatus.COMPLETED; } else if (internalProcessInstance.getStartTime() == null) { return ProcessInstance.ProcessInstanceStatus.CREATED; } return ProcessInstance.ProcessInstanceStatus.RUNNING; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\model\impl\APIProcessInstanceConverter.java
1
请完成以下Java代码
public void setPriceActual (BigDecimal PriceActual) { set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ public BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return Env.ZERO; return bd; } /** Set Verarbeitet. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge.
@param QtyEntered Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public void setQtyEntered (BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Menge. @return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity Invoiced. @param QtyInvoiced Invoiced Quantity */ public void setQtyInvoiced (BigDecimal QtyInvoiced) { set_ValueNoCheck (COLUMNNAME_QtyInvoiced, QtyInvoiced); } /** Get Quantity Invoiced. @return Invoiced Quantity */ public BigDecimal getQtyInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_InvoiceLine_Overview.java
1
请完成以下Spring Boot application配置
# =================================================================== # Activate this profile to enable TLS and HTTP/2. # # JHipster has generated a self-signed certificate, which will be used to encrypt traffic. # As your browser will not understand this certificate, you will need to import it. # # Another (easiest) solution with Chrome is to enable the "allow-insecure-localhost" flag # at chrome://flags/#allow-insecure-localhost # =================================================================== server: ssl: key-store: classpath:config/tls/keystore.p12 key-store-password: password key-store-type: PKCS12 key-alias: selfsigned ciphers: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_EC
DHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 enabled-protocols: TLSv1.2 jhipster: http: version: V_2_0
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\resources\config\application-tls.yml
2
请在Spring Boot框架中完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (applicationContext instanceof ConfigurableApplicationContext) { ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext; DubboLifecycleComponentApplicationListener dubboLifecycleComponentApplicationListener = new DubboLifecycleComponentApplicationListener(applicationContext); context.addApplicationListener(dubboLifecycleComponentApplicationListener); DubboBootstrapApplicationListener dubboBootstrapApplicationListener = new DubboBootstrapApplicationListener(applicationContext); context.addApplicationListener(dubboBootstrapApplicationListener); } } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { // Remove the BeanDefinitions of ApplicationListener from DubboBeanUtils#registerCommonBeans(BeanDefinitionRegistry)
// TODO Refactoring in Dubbo 2.7.9 removeBeanDefinition(registry, DubboLifecycleComponentApplicationListener.BEAN_NAME); removeBeanDefinition(registry, DubboBootstrapApplicationListener.BEAN_NAME); } private void removeBeanDefinition(BeanDefinitionRegistry registry, String beanName) { if (registry.containsBeanDefinition(beanName)) { registry.removeBeanDefinition(beanName); } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // DO NOTHING } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class DownloadsFolderConfiguration implements WebMvcConfigurer { private static final Logger logger = LogManager.getLogger(DownloadsFolderConfiguration.class); @Nullable @Value("${metasfresh.serverRoot.downloads:}") private String downloadsPath; @Override public void addResourceHandlers(final @NonNull ResourceHandlerRegistry registry) { if (Check.isEmpty(downloadsPath, true)) { downloadsPath = defaultDownloadsPath(); } // Make sure the path ends with separator // see https://jira.spring.io/browse/SPR-14063 if (downloadsPath != null && !downloadsPath.endsWith(File.separator)) { downloadsPath += File.separator; } if (!Check.isEmpty(downloadsPath, true)) { logger.info("Serving static content from " + downloadsPath); registry.addResourceHandler("/download/**").addResourceLocations("file:" + downloadsPath); // the "binaries" download path is about to be removed soon! registry.addResourceHandler("/binaries/**").addResourceLocations("file:" + downloadsPath); } }
@Nullable private String defaultDownloadsPath() { try { final File cwd = new File(".").getCanonicalFile(); final File downloadsFile = new File(cwd, "download"); return downloadsFile.getCanonicalPath(); } catch (final IOException ex) { logger.warn("Failed finding the default downloads path", ex); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\home_page\DownloadsFolderConfiguration.java
2
请完成以下Java代码
public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } @Override public de.metas.aggregation.model.I_C_Aggregation getIncluded_Aggregation() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Included_Aggregation_ID, de.metas.aggregation.model.I_C_Aggregation.class); } @Override public void setIncluded_Aggregation(de.metas.aggregation.model.I_C_Aggregation Included_Aggregation) { set_ValueFromPO(COLUMNNAME_Included_Aggregation_ID, de.metas.aggregation.model.I_C_Aggregation.class, Included_Aggregation); } /** Set Included Aggregation. @param Included_Aggregation_ID Included Aggregation */ @Override public void setIncluded_Aggregation_ID (int Included_Aggregation_ID) { if (Included_Aggregation_ID < 1) set_Value (COLUMNNAME_Included_Aggregation_ID, null); else set_Value (COLUMNNAME_Included_Aggregation_ID, Integer.valueOf(Included_Aggregation_ID)); } /** Get Included Aggregation. @return Included Aggregation */ @Override public int getIncluded_Aggregation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Included_Aggregation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Include Logic. @param IncludeLogic If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded. */ @Override public void setIncludeLogic (java.lang.String IncludeLogic) { set_Value (COLUMNNAME_IncludeLogic, IncludeLogic); } /** Get Include Logic. @return If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded. */ @Override public java.lang.String getIncludeLogic () { return (java.lang.String)get_Value(COLUMNNAME_IncludeLogic); }
/** * Type AD_Reference_ID=540532 * Reference name: C_AggregationItem_Type */ public static final int TYPE_AD_Reference_ID=540532; /** Column = COL */ public static final String TYPE_Column = "COL"; /** IncludedAggregation = INC */ public static final String TYPE_IncludedAggregation = "INC"; /** Attribute = ATR */ public static final String TYPE_Attribute = "ATR"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_AggregationItem.java
1
请完成以下Java代码
public class PMM_GenerateOrders extends WorkpackageProcessorAdapter { public static PMM_GenerateOrdersEnqueuer prepareEnqueuing() { return new PMM_GenerateOrdersEnqueuer(); } @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName) { final List<I_PMM_PurchaseCandidate> candidates = retrieveItems(); if (candidates.isEmpty()) { throw new AdempiereException("@NotFound@ @PMM_PurchaseCandidate_ID@"); } OrdersGenerator.newInstance() .setCandidates(candidates) .generate();
return Result.SUCCESS; } private List<I_PMM_PurchaseCandidate> retrieveItems() { final I_C_Queue_WorkPackage workpackage = getC_Queue_WorkPackage(); return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(workpackage, I_PMM_PurchaseCandidate.class); } @Override public boolean isAllowRetryOnError() { // no, mainly because we want to prevent: if something fails and user will re-enqueue the candidates, nothing will happen because they were enqueued here. return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\async\PMM_GenerateOrders.java
1
请在Spring Boot框架中完成以下Java代码
public class POReference extends AbstractModelInterceptor { // services private static final Logger logger = LogManager.getLogger(POReference.class); private final IFactAcctDAO factAcctDAO = Services.get(IFactAcctDAO.class); private final AcctDocRegistry acctDocRegistry; private static final String COLUMNNAME_POReference = I_Fact_Acct.COLUMNNAME_POReference; public POReference(final AcctDocRegistry acctDocRegistry) {this.acctDocRegistry = acctDocRegistry;} @Override protected void onInit(final IModelValidationEngine engine, final I_AD_Client client) { final Set<String> tableNamesToWatch = getTableNamesToWatch(); tableNamesToWatch.forEach(tableName -> engine.addModelChange(tableName, this)); logger.info("Watching POReference changes on {}", tableNamesToWatch); } private Set<String> getTableNamesToWatch() { return acctDocRegistry.getDocTableNames() .stream()
.filter(tableName -> POInfo.getPOInfoNotNull(tableName).hasColumnName(COLUMNNAME_POReference)) .collect(ImmutableSet.toImmutableSet()); } @Override public void onModelChange(final Object model, final ModelChangeType changeType) { if (changeType.isAfter() && changeType.isChange() && InterfaceWrapperHelper.isValueChanged(model, COLUMNNAME_POReference)) { final TableRecordReference recordRef = TableRecordReference.of(model); final String poReference = InterfaceWrapperHelper.getValueOptional(model, COLUMNNAME_POReference) .map(Object::toString) .orElse(null); factAcctDAO.updatePOReference(recordRef, poReference); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\POReference.java
2