instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static Optional<WritableResource> asWritableResource(@Nullable Resource resource) { return Optional.ofNullable(resource) .filter(WritableResource.class::isInstance) .map(WritableResource.class::cast); } /** * Determines whether the given byte array is {@literal null} or {@literal empty}. * * @param array byte array to evaluate. * @return a boolean value indicating whether the given byte array is {@literal null} or {@literal empty}. */ public static boolean isNotEmpty(@Nullable byte[] array) { return array != null && array.length > 0; } /** * Null-safe operation to determine whether the given {@link Resource} is readable. * * @param resource {@link Resource} to evaluate. * @return a boolean value indicating whether the given {@link Resource} is readable. * @see org.springframework.core.io.Resource#isReadable() * @see org.springframework.core.io.Resource */ public static boolean isReadable(@Nullable Resource resource) { return resource != null && resource.isReadable(); } /** * Null-safe operation to determine whether the given {@link Resource} is writable.
* * @param resource {@link Resource} to evaluate. * @return a boolean value indicating whether the given {@link Resource} is writable. * @see org.springframework.core.io.WritableResource#isWritable() * @see org.springframework.core.io.WritableResource * @see org.springframework.core.io.Resource */ public static boolean isWritable(@Nullable Resource resource) { return resource instanceof WritableResource && ((WritableResource) resource).isWritable(); } /** * Null-safe method to get the {@link Resource#getDescription() description} of the given {@link Resource}. * * @param resource {@link Resource} to describe. * @return a {@link Resource#getDescription() description} of the {@link Resource}, or {@literal null} * if the {@link Resource} handle is {@literal null}. * @see org.springframework.core.io.Resource */ public static @Nullable String nullSafeGetDescription(@Nullable Resource resource) { return resource != null ? resource.getDescription() : null; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\ResourceUtils.java
1
请完成以下Java代码
public T findDeployedDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { T definition = getManager().findDefinitionByDeploymentAndKey(deploymentId, definitionKey); checkInvalidDefinitionByDeploymentAndKey(deploymentId, definitionKey, definition); definition = resolveDefinition(definition); return definition; } public T resolveDefinition(T definition) { String definitionId = definition.getId(); String deploymentId = definition.getDeploymentId(); T cachedDefinition = cache.get(definitionId); if (cachedDefinition == null) { synchronized (this) { cachedDefinition = cache.get(definitionId); if (cachedDefinition == null) { DeploymentEntity deployment = Context .getCommandContext() .getDeploymentManager() .findDeploymentById(deploymentId); deployment.setNew(false); cacheDeployer.deployOnlyGivenResourcesOfDeployment(deployment, definition.getResourceName(), definition.getDiagramResourceName()); cachedDefinition = cache.get(definitionId); } } checkInvalidDefinitionWasCached(deploymentId, definitionId, cachedDefinition); } if (cachedDefinition != null) { cachedDefinition.updateModifiableFieldsFromEntity(definition); } return cachedDefinition; } public void addDefinition(T definition) { cache.put(definition.getId(), definition); } public T getDefinition(String id) { return cache.get(id); } public void removeDefinitionFromCache(String id) { cache.remove(id); }
public void clear() { cache.clear(); } public Cache<String, T> getCache() { return cache; } protected abstract AbstractResourceDefinitionManager<T> getManager(); protected abstract void checkInvalidDefinitionId(String definitionId); protected abstract void checkDefinitionFound(String definitionId, T definition); protected abstract void checkInvalidDefinitionByKey(String definitionKey, T definition); protected abstract void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, T definition); protected abstract void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, T definition); protected abstract void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, T definition); protected abstract void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, T definition); protected abstract void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, T definition); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\ResourceDefinitionCache.java
1
请完成以下Java代码
public Criteria andParentCategoryNameNotIn(List<String> values) { addCriterion("parent_category_name not in", values, "parentCategoryName"); return (Criteria) this; } public Criteria andParentCategoryNameBetween(String value1, String value2) { addCriterion("parent_category_name between", value1, value2, "parentCategoryName"); return (Criteria) this; } public Criteria andParentCategoryNameNotBetween(String value1, String value2) { addCriterion("parent_category_name not between", value1, value2, "parentCategoryName"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler;
} protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponProductCategoryRelationExample.java
1
请完成以下Java代码
public Set<String> getServiceNames(ServiceType type) { String typeName = composeLocalName(type, "*"); ObjectName typeObjectName = getObjectName(typeName); Set<ObjectName> resultNames = getmBeanServer().queryNames(typeObjectName, null); Set<String> result= new HashSet<String>(); for (ObjectName objectName : resultNames) { result.add(objectName.toString()); } return result; } /** * @return the values of all services for a specific {@link ServiceType} */ @SuppressWarnings("unchecked") public <S> List<S> getServiceValuesByType(ServiceType type) { // query the MBeanServer for all services of the given type Set<String> serviceNames = getServiceNames(type); List<S> res = new ArrayList<S>(); for (String serviceName : serviceNames) { PlatformService<S> BpmPlatformService = (PlatformService<S>) servicesByName.get(getObjectName(serviceName)); if (BpmPlatformService != null) { res.add(BpmPlatformService.getValue());
} } return res; } public MBeanServer getmBeanServer() { if (mBeanServer == null) { synchronized (this) { if (mBeanServer == null) { mBeanServer = createOrLookupMbeanServer(); } } } return mBeanServer; } public void setmBeanServer(MBeanServer mBeanServer) { this.mBeanServer = mBeanServer; } protected MBeanServer createOrLookupMbeanServer() { return ManagementFactory.getPlatformMBeanServer(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\MBeanServiceContainer.java
1
请完成以下Java代码
public void setESR_ImportFile_ID (final int ESR_ImportFile_ID) { if (ESR_ImportFile_ID < 1) set_ValueNoCheck (COLUMNNAME_ESR_ImportFile_ID, null); else set_ValueNoCheck (COLUMNNAME_ESR_ImportFile_ID, ESR_ImportFile_ID); } @Override public int getESR_ImportFile_ID() { return get_ValueAsInt(COLUMNNAME_ESR_ImportFile_ID); } @Override public de.metas.payment.esr.model.I_ESR_Import getESR_Import() { return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class); } @Override public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import) { set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import); } @Override public void setESR_Import_ID (final int ESR_Import_ID) { if (ESR_Import_ID < 1) set_Value (COLUMNNAME_ESR_Import_ID, null); else set_Value (COLUMNNAME_ESR_Import_ID, ESR_Import_ID); } @Override public int getESR_Import_ID() { return get_ValueAsInt(COLUMNNAME_ESR_Import_ID); } @Override public void setFileName (final @Nullable java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName);
} @Override public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); } @Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @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.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportFile.java
1
请完成以下Java代码
public OidcUserInfo getUserInfo() { return this.userInfo; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } if (!super.equals(obj)) { return false; } OidcUserAuthority that = (OidcUserAuthority) obj; if (!this.getIdToken().equals(that.getIdToken())) { return false; } return (this.getUserInfo() != null) ? this.getUserInfo().equals(that.getUserInfo()) : that.getUserInfo() == null; }
@Override public int hashCode() { int result = super.hashCode(); result = 31 * result + this.getIdToken().hashCode(); result = 31 * result + ((this.getUserInfo() != null) ? this.getUserInfo().hashCode() : 0); return result; } static Map<String, Object> collectClaims(OidcIdToken idToken, OidcUserInfo userInfo) { Assert.notNull(idToken, "idToken cannot be null"); Map<String, Object> claims = new HashMap<>(); if (userInfo != null) { claims.putAll(userInfo.getClaims()); } claims.putAll(idToken.getClaims()); return claims; } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\user\OidcUserAuthority.java
1
请完成以下Java代码
public int getOverrides_Window_ID() { return get_ValueAsInt(COLUMNNAME_Overrides_Window_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } /** * WindowType AD_Reference_ID=108 * Reference name: AD_Window Types */ public static final int WINDOWTYPE_AD_Reference_ID=108; /** Single Record = S */ public static final String WINDOWTYPE_SingleRecord = "S"; /** Maintain = M */ public static final String WINDOWTYPE_Maintain = "M"; /** Transaktion = T */ public static final String WINDOWTYPE_Transaktion = "T"; /** Query Only = Q */ public static final String WINDOWTYPE_QueryOnly = "Q"; @Override public void setWindowType (final java.lang.String WindowType) { set_Value (COLUMNNAME_WindowType, WindowType); } @Override public java.lang.String getWindowType() { return get_ValueAsString(COLUMNNAME_WindowType); } @Override public void setWinHeight (final int WinHeight) { set_Value (COLUMNNAME_WinHeight, WinHeight); } @Override public int getWinHeight() { return get_ValueAsInt(COLUMNNAME_WinHeight); }
@Override public void setWinWidth (final int WinWidth) { set_Value (COLUMNNAME_WinWidth, WinWidth); } @Override public int getWinWidth() { return get_ValueAsInt(COLUMNNAME_WinWidth); } @Override public void setZoomIntoPriority (final int ZoomIntoPriority) { set_Value (COLUMNNAME_ZoomIntoPriority, ZoomIntoPriority); } @Override public int getZoomIntoPriority() { return get_ValueAsInt(COLUMNNAME_ZoomIntoPriority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window.java
1
请完成以下Java代码
public Response getDefaultResource() throws IOException { return Response.ok(readResource("default-resource.txt")).build(); } @GET @Path("/default-nested") @Produces(MediaType.TEXT_PLAIN) public Response getDefaultNestedResource() throws IOException { return Response.ok(readResource("text/another-resource.txt")).build(); } @GET @Path("/json") @Produces(MediaType.APPLICATION_JSON) public Response getJsonResource() throws IOException { return Response.ok(readResource("resources.json")).build(); }
private String readResource(String resourcePath) throws IOException { LOGGER.info("Reading resource from path: {}", resourcePath); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath)) { if (in == null) { LOGGER.error("Resource not found at path: {}", resourcePath); throw new IOException("Resource not found: " + resourcePath); } LOGGER.info("Successfully read resource: {}", resourcePath); return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)).lines() .collect(Collectors.joining("\n")); } } }
repos\tutorials-master\quarkus-modules\quarkus-resources\src\main\java\com\baeldung\quarkus\resources\ResourceAccessAPI.java
1
请完成以下Java代码
public static ShipmentAllocationBestBeforePolicy ofNullableCode(@Nullable final String code) { return code != null ? ofCode(code) : null; } public static Optional<ShipmentAllocationBestBeforePolicy> optionalOfNullableCode(@Nullable final String code) { return Optional.ofNullable(ofNullableCode(code)); } public static ShipmentAllocationBestBeforePolicy ofCode(@NonNull final String code) { final ShipmentAllocationBestBeforePolicy type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + ShipmentAllocationBestBeforePolicy.class + " found for code: " + code); } return type; } private static final ImmutableMap<String, ShipmentAllocationBestBeforePolicy> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), ShipmentAllocationBestBeforePolicy::getCode); public <T> Comparator<T> comparator(@NonNull final Function<T, LocalDate> bestBeforeDateExtractor) { return (value1, value2) -> { final LocalDate bestBefore1 = bestBeforeDateExtractor.apply(value1); final LocalDate bestBefore2 = bestBeforeDateExtractor.apply(value2); return compareBestBeforeDates(bestBefore1, bestBefore2); }; } private int compareBestBeforeDates(@Nullable final LocalDate bestBefore1, @Nullable final LocalDate bestBefore2) { if (this == Expiring_First) { final LocalDate bestBefore1Effective = CoalesceUtil.coalesceNotNull(bestBefore1, LocalDate.MAX);
final LocalDate bestBefore2Effective = CoalesceUtil.coalesceNotNull(bestBefore2, LocalDate.MAX); return bestBefore1Effective.compareTo(bestBefore2Effective); } else if (this == Newest_First) { final LocalDate bestBefore1Effective = CoalesceUtil.coalesceNotNull(bestBefore1, LocalDate.MIN); final LocalDate bestBefore2Effective = CoalesceUtil.coalesceNotNull(bestBefore2, LocalDate.MIN); return -1 * bestBefore1Effective.compareTo(bestBefore2Effective); } else { throw new AdempiereException("Unknown policy: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\ShipmentAllocationBestBeforePolicy.java
1
请在Spring Boot框架中完成以下Java代码
public class MscManagedProcessApplication implements Service<MscManagedProcessApplication> { protected ProcessApplicationInfo processApplicationInfo; protected ProcessApplicationReference processApplicationReference; public MscManagedProcessApplication(ProcessApplicationInfo processApplicationInfo, ProcessApplicationReference processApplicationReference) { this.processApplicationInfo = processApplicationInfo; this.processApplicationReference = processApplicationReference; } @Override public MscManagedProcessApplication getValue() throws IllegalStateException, IllegalArgumentException { return this; } @Override public void start(StartContext context) throws StartException { // call the process application's
} @Override public void stop(StopContext context) { // Nothing to do } public ProcessApplicationInfo getProcessApplicationInfo() { return processApplicationInfo; } public ProcessApplicationReference getProcessApplicationReference() { return processApplicationReference; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessApplication.java
2
请完成以下Spring Boot application配置
# Make the application available at http://localhost:9000 server: port: 9000 # Configure the public key to use for verifying the incoming JWT tokens security: oauth2: resource: jwt: keyValue: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhiiifKv6Otf5PyqIE+LQ EiJRRh6q8piPY9Okq+RfRu9Bue0D8hq7aFxcgkLZ6Bg9CAS+w1KdaE5MMeOCVVxv rpRETzVpAsh6GL5nBc679jSqMzjr3V4uty46ilL4VHKSxlZh5Nmz5EMHPI5iwpNs 8U5n3QiwsTk514FXad54xPSPH3i/pDzGSZHrVcwDVaO
Kn7gFiIqP86vkJB47JZv8 T6P5RK7Rj06zoG45DMGWG3DQv6o1/Jm4IJQWj0AUD3bSHqzXkPr7qyMYvkE4kyMH 6aVAsAYMxilZFlJMv2b8N883gdi3LEeOJo8zZr5IWyyROfepdeOL7UkAXddAj+dL WQIDAQAB -----END PUBLIC KEY-----
repos\tutorials-master\spring-cloud-modules\spring-cloud-security\auth-resource\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class BizException extends RuntimeException { private static final long serialVersionUID = 1L; protected String errorCode; protected String errorMsg; public BizException() { super(); } public BizException(BaseErrorInfoInterface errorInfoInterface) { super(errorInfoInterface.getResultCode()); this.errorCode = errorInfoInterface.getResultCode(); this.errorMsg = errorInfoInterface.getResultMsg(); } public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) { super(errorInfoInterface.getResultCode(), cause); this.errorCode = errorInfoInterface.getResultCode(); this.errorMsg = errorInfoInterface.getResultMsg(); } public BizException(String errorMsg) { super(errorMsg); this.errorMsg = errorMsg; } public BizException(String errorCode, String errorMsg) { super(errorCode); this.errorCode = errorCode; this.errorMsg = errorMsg; } public BizException(String errorCode, String errorMsg, Throwable cause) { super(errorCode, cause); this.errorCode = errorCode; this.errorMsg = errorMsg;
} public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public String getMessage() { return errorMsg; } @Override public Throwable fillInStackTrace() { return this; } }
repos\springboot-demo-master\Exception\src\main\java\com\et\exception\config\BizException.java
2
请完成以下Java代码
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable) { set_ValueNoCheck (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyBatch (final @Nullable BigDecimal QtyBatch) { set_ValueNoCheck (COLUMNNAME_QtyBatch, QtyBatch); } @Override public BigDecimal getQtyBatch() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatch); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyBatchSize (final @Nullable BigDecimal QtyBatchSize) { set_ValueNoCheck (COLUMNNAME_QtyBatchSize, QtyBatchSize); } @Override public BigDecimal getQtyBatchSize() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatchSize); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyBOM (final @Nullable BigDecimal QtyBOM) { set_ValueNoCheck (COLUMNNAME_QtyBOM, QtyBOM); } @Override
public BigDecimal getQtyBOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyRequiered (final @Nullable BigDecimal QtyRequiered) { set_ValueNoCheck (COLUMNNAME_QtyRequiered, QtyRequiered); } @Override public BigDecimal getQtyRequiered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRequiered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Order_BOMLine.java
1
请完成以下Java代码
public void setCopyVariablesFromHeader(String copyVariablesFromHeader) { this.copyVariablesFromHeader = copyVariablesFromHeader; } public boolean isCopyCamelBodyToBodyAsString() { return copyCamelBodyToBodyAsString; } public void setCopyCamelBodyToBodyAsString(boolean copyCamelBodyToBodyAsString) { this.copyCamelBodyToBodyAsString = copyCamelBodyToBodyAsString; } public boolean isSetProcessInitiator() { return StringUtils.isNotEmpty(getProcessInitiatorHeaderName()); } public Map<String, Object> getReturnVarMap() { return returnVarMap; } public void setReturnVarMap(Map<String, Object> returnVarMap) { this.returnVarMap = returnVarMap; } public String getProcessInitiatorHeaderName() {
return processInitiatorHeaderName; } public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) { this.processInitiatorHeaderName = processInitiatorHeaderName; } @Override public boolean isLenientProperties() { return true; } public long getTimeout() { return timeout; } public int getTimeResolution() { return timeResolution; } }
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java
1
请完成以下Java代码
public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public int getMailServerPort() { return mailServerPort; } public void setMailServerPort(int mailServerPort) { this.mailServerPort = mailServerPort; } public String getMailServerUsername() { return mailServerUsername; } public void setMailServerUsername(String mailServerUsername) { this.mailServerUsername = mailServerUsername; }
public String getMailServerPassword() { return mailServerPassword; } public void setMailServerPassword(String mailServerPassword) { this.mailServerPassword = mailServerPassword; } public boolean isMailServerUseSSL() { return mailServerUseSSL; } public void setMailServerUseSSL(boolean mailServerUseSSL) { this.mailServerUseSSL = mailServerUseSSL; } public boolean isMailServerUseTLS() { return mailServerUseTLS; } public void setMailServerUseTLS(boolean mailServerUseTLS) { this.mailServerUseTLS = mailServerUseTLS; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\cfg\MailServerInfo.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); }
@Override public void setM_Shipper_RoutingCode_ID (final int M_Shipper_RoutingCode_ID) { if (M_Shipper_RoutingCode_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, M_Shipper_RoutingCode_ID); } @Override public int getM_Shipper_RoutingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_ID); } @Override public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_RoutingCode.java
1
请完成以下Java代码
public class DLM_Partition_Config_Add_TableRecord_Lines extends JavaProcess { @Param(parameterName = I_DLM_Partition_Config.COLUMNNAME_DLM_Partition_Config_ID, mandatory = true) private I_DLM_Partition_Config configDB; private final IPartitionerService partitionerService = Services.get(IPartitionerService.class); private final IDLMService dlmService = Services.get(IDLMService.class); @Override protected String doIt() throws Exception { final PartitionConfig config = dlmService.loadPartitionConfig(configDB); final List<TableRecordIdDescriptor> tableRecordReferences = Services.get(ITableRecordIdDAO.class).retrieveAllTableRecordIdReferences(); // get those descriptors whose referencedTableName is the table name of at least one line final List<TableRecordIdDescriptor> descriptors = retainRelevantDescriptors(config, tableRecordReferences); final PartitionConfig augmentedConfig = partitionerService.augmentPartitionerConfig(config, descriptors); dlmService.storePartitionConfig(augmentedConfig);
return MSG_OK; } /** * From the given <code>descriptors</code> list, return those ones that reference of the lines of the given <code>config</code>. * * @param config * @param tableRecordReferences * @return */ @VisibleForTesting /* package */ List<TableRecordIdDescriptor> retainRelevantDescriptors(final PartitionConfig config, final List<TableRecordIdDescriptor> descriptors) { return descriptors.stream() .filter(r -> config.getLine(r.getTargetTableName()).isPresent()) .collect(Collectors.toList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_Partition_Config_Add_TableRecord_Lines.java
1
请完成以下Java代码
public ActivityImpl getSource() { return source; } public void setDestination(ActivityImpl destination) { this.destination = destination; destination.getIncomingTransitions().add(this); } @Deprecated public void addExecutionListener(ExecutionListener executionListener) { super.addListener(ExecutionListener.EVENTNAME_TAKE, executionListener); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Deprecated public List<ExecutionListener> getExecutionListeners() { return (List) super.getListeners(ExecutionListener.EVENTNAME_TAKE); } @Deprecated public void setExecutionListeners(List<ExecutionListener> executionListeners) { for (ExecutionListener executionListener : executionListeners) { addExecutionListener(executionListener); } } public String toString() { return "("+source.getId()+")--"+(id!=null?id+"-->(":">(")+destination.getId()+")"; } // getters and setters ////////////////////////////////////////////////////// public PvmProcessDefinition getProcessDefinition() { return processDefinition; }
protected void setSource(ActivityImpl source) { this.source = source; } public PvmActivity getDestination() { return destination; } public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\TransitionImpl.java
1
请完成以下Java代码
public java.lang.String getPO_Name () { return (java.lang.String)get_Value(COLUMNNAME_PO_Name); } /** Set PO Print name. @param PO_PrintName Print name on PO Screens/Reports */ @Override public void setPO_PrintName (java.lang.String PO_PrintName) { set_Value (COLUMNNAME_PO_PrintName, PO_PrintName); } /** Get PO Print name. @return Print name on PO Screens/Reports */ @Override public java.lang.String getPO_PrintName () { return (java.lang.String)get_Value(COLUMNNAME_PO_PrintName); } /** Set Drucktext. @param PrintName The label text to be printed on a document or correspondence. */ @Override public void setPrintName (java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } /** Get Drucktext. @return The label text to be printed on a document or correspondence. */ @Override public java.lang.String getPrintName () { return (java.lang.String)get_Value(COLUMNNAME_PrintName); } /** Set Browse name. @param WEBUI_NameBrowse Browse name */ @Override public void setWEBUI_NameBrowse (java.lang.String WEBUI_NameBrowse) { set_Value (COLUMNNAME_WEBUI_NameBrowse, WEBUI_NameBrowse); } /** Get Browse name. @return Browse name */ @Override public java.lang.String getWEBUI_NameBrowse () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameBrowse); } /** Set New record name.
@param WEBUI_NameNew New record name */ @Override public void setWEBUI_NameNew (java.lang.String WEBUI_NameNew) { set_Value (COLUMNNAME_WEBUI_NameNew, WEBUI_NameNew); } /** Get New record name. @return New record name */ @Override public java.lang.String getWEBUI_NameNew () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNew); } /** Set New record name (breadcrumb). @param WEBUI_NameNewBreadcrumb New record name (breadcrumb) */ @Override public void setWEBUI_NameNewBreadcrumb (java.lang.String WEBUI_NameNewBreadcrumb) { set_Value (COLUMNNAME_WEBUI_NameNewBreadcrumb, WEBUI_NameNewBreadcrumb); } /** Get New record name (breadcrumb). @return New record name (breadcrumb) */ @Override public java.lang.String getWEBUI_NameNewBreadcrumb () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb); } /** * WidgetSize AD_Reference_ID=540724 * Reference name: WidgetSize_WEBUI */ public static final int WIDGETSIZE_AD_Reference_ID=540724; /** Small = S */ public static final String WIDGETSIZE_Small = "S"; /** Medium = M */ public static final String WIDGETSIZE_Medium = "M"; /** Large = L */ public static final String WIDGETSIZE_Large = "L"; /** Set Widget size. @param WidgetSize Widget size */ @Override public void setWidgetSize (java.lang.String WidgetSize) { set_Value (COLUMNNAME_WidgetSize, WidgetSize); } /** Get Widget size. @return Widget size */ @Override public java.lang.String getWidgetSize () { return (java.lang.String)get_Value(COLUMNNAME_WidgetSize); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element.java
1
请完成以下Java代码
public void iterateUsingListIterator(final List<String> list) { final ListIterator listIterator = list.listIterator(list.size()); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } } /** * Iterate using Java {@link Collections} API. * * @param list the list */ public void iterateUsingCollections(final List<String> list) { Collections.reverse(list); for (final String item : list) { System.out.println(item); } } /** * Iterate using Apache Commons {@link ReverseListIterator}. * * @param list the list */ public void iterateUsingApacheReverseListIterator(final List<String> list) { final ReverseListIterator listIterator = new ReverseListIterator(list); while (listIterator.hasNext()) {
System.out.println(listIterator.next()); } } /** * Iterate using Guava {@link Lists} API. * * @param list the list */ public void iterateUsingGuava(final List<String> list) { final List<String> reversedList = Lists.reverse(list); for (final String item : reversedList) { System.out.println(item); } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\ReverseIterator.java
1
请完成以下Java代码
public boolean applies(final IPricingContext pricingCtx, final IPricingResult result) { return true; } /** * Executes all rules that can be applied. * <p> * Please note that calculation won't stop after first rule that matched. */ @Override public void calculate(@NonNull final IPricingContext pricingCtx, @NonNull final IPricingResult result) { logger.debug("Evaluating pricing rules with pricingContext: {}", pricingCtx); for (final IPricingRule rule : rules) { try (final MDCCloseable ignored = MDC.putCloseable("PricingRule", rule.getClass().getSimpleName())) { // NOTE: we are NOT checking if the pricing result was already calculated, on purpose, because: // * we want to give flexiblity to pricing rules to override the pricing // * we want to support the case of Discount rules which apply on already calculated pricing result // // Preliminary check if there is a chance this pricing rule to be applied if (!rule.applies(pricingCtx, result)) { Loggables.withLogger(logger, Level.DEBUG).addLog("Skipped rule {}, result: {}", rule, result); continue; } //
// Try applying it rule.calculate(pricingCtx, result); // // Add it to applied pricing rules list // FIXME: make sure the rule was really applied (i.e. calculated). Consider asking the calculate() to return a boolean if it really did some changes. // At the moment, there is no way to figure out that a pricing rule which was preliminary considered as appliable // was not actually applied because when "calculate()" method was invoked while retrieving data, // it found out that it cannot be applied. // As a side effect on some pricing results you will get a list of applied rules like: ProductScalePrice, PriceListVersionVB, PriceListVersion, Discount, // which means that ProductScalePrice and PriceListVersionVB were not actually applied because they found out that while doing the "calculate()". result.addPricingRuleApplied(rule); Loggables.withLogger(logger, Level.DEBUG).addLog("Applied rule {}; calculated={}, result: {}", rule, result.isCalculated(), result); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\AggregatedPricingRule.java
1
请完成以下Java代码
public final boolean hasPaymentDocument() { return getC_Payment() != null || getC_CashLine() != null; } public final OrgId getPaymentOrgId() { final I_C_Payment payment = getC_Payment(); if (payment != null) { return OrgId.ofRepoId(payment.getAD_Org_ID()); } final I_C_CashLine cashLine = getC_CashLine(); if (cashLine != null) { return OrgId.ofRepoId(cashLine.getAD_Org_ID()); } return getOrgId(); } public final BPartnerId getPaymentBPartnerId() { final I_C_Payment payment = getC_Payment(); if (payment != null) { return BPartnerId.ofRepoId(payment.getC_BPartner_ID()); } return getBPartnerId(); } @Nullable public final BPartnerLocationId getPaymentBPartnerLocationId()
{ final I_C_Payment payment = getC_Payment(); if (payment != null) { return BPartnerLocationId.ofRepoIdOrNull(payment.getC_BPartner_ID(), payment.getC_BPartner_Location_ID()); } return getBPartnerLocationId(); } public boolean isPaymentReceipt() { Check.assumeNotNull(paymentReceipt, "payment document exists"); return paymentReceipt; } } // DocLine_Allocation
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Allocation.java
1
请在Spring Boot框架中完成以下Java代码
public class SAP_GLJournal { private final SAPGLJournalService glJournalService; public SAP_GLJournal(final SAPGLJournalService glJournalService) {this.glJournalService = glJournalService;} @Init public void init() { CopyRecordFactory.enableForTableName(I_SAP_GLJournal.Table_Name); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void beforeSave(final I_SAP_GLJournal record, final ModelChangeType timing) { if (InterfaceWrapperHelper.isUIAction(record)) { if (isConversionCtxChanged(record, timing)) { glJournalService.updateWhileSaving( record, glJournal -> glJournal.updateLineAcctAmounts(glJournalService.getCurrencyConverter())); } } } private static boolean isConversionCtxChanged(final I_SAP_GLJournal record, final ModelChangeType timing) { if (timing.isNew()) { return true; } final SAPGLJournalCurrencyConversionCtx conversionCtx = SAPGLJournalLoaderAndSaver.extractConversionCtx(record);
final SAPGLJournalCurrencyConversionCtx conversionCtxOld = SAPGLJournalLoaderAndSaver.extractConversionCtx(InterfaceWrapperHelper.createOld(record, I_SAP_GLJournal.class)); return !SAPGLJournalCurrencyConversionCtx.equals(conversionCtx, conversionCtxOld); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_SAP_GLJournal record) { if (InterfaceWrapperHelper.isUIAction(record)) { // shall not happen if (record.isProcessed()) { throw new AdempiereException("Record is processed"); } glJournalService.updateWhileSaving(record, SAPGLJournal::removeAllLines); } } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void afterComplete(final I_SAP_GLJournal record) { glJournalService.fireAfterComplete(record); } @DocValidate(timings = ModelValidator.TIMING_AFTER_REACTIVATE) public void beforeReactivate(final I_SAP_GLJournal record) { glJournalService.fireAfterReactivate(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\interceptor\SAP_GLJournal.java
2
请完成以下Java代码
public boolean isFailed() {return this == POSPaymentProcessingStatus.FAILED;} public boolean isCanceled() {return this == POSPaymentProcessingStatus.CANCELLED;} public boolean isDeleted() {return this == POSPaymentProcessingStatus.DELETED;} public boolean isAllowCheckout() { return isNew() || isCanceled() || isFailed(); } public void assertAllowCheckout() { if (!isAllowCheckout()) { throw new AdempiereException("Payments with status " + this + " cannot be checked out"); } } public BooleanWithReason checkAllowDeleteFromDB() { return isNew() ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted from DB"); } public BooleanWithReason checkAllowDelete(final POSPaymentMethod paymentMethod) { if (checkAllowDeleteFromDB().isTrue()) { return BooleanWithReason.TRUE; } else if (paymentMethod.isCash() && isPending()) { return BooleanWithReason.TRUE; }
else if (isCanceled() || isFailed()) { return BooleanWithReason.TRUE; } else { return BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted"); } } public boolean isAllowRefund() { return isSuccessful(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPaymentProcessingStatus.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { WineQualityRegression wineQualityRegression = new WineQualityRegression(); wineQualityRegression.createDatasets(); wineQualityRegression.createTrainer(); wineQualityRegression.evaluateModels(); wineQualityRegression.saveModel(); } public void createTrainer() { CARTRegressionTrainer subsamplingTree = new CARTRegressionTrainer(Integer.MAX_VALUE, AbstractCARTTrainer.MIN_EXAMPLES, 0.001f, 0.7f, new MeanSquaredError(), Trainer.DEFAULT_SEED); trainer = new RandomForestTrainer<>(subsamplingTree, new AveragingCombiner(), 10); model = trainer.train(trainSet); } public void createDatasets() throws Exception { RegressionFactory regressionFactory = new RegressionFactory(); CSVLoader<Regressor> csvLoader = new CSVLoader<>(';', CSVIterator.QUOTE, regressionFactory); DataSource<Regressor> dataSource = csvLoader.loadDataSource(Paths.get(DATASET_PATH), "quality"); TrainTestSplitter<Regressor> dataSplitter = new TrainTestSplitter<>(dataSource, 0.7, 1L); trainSet = new MutableDataset<>(dataSplitter.getTrain()); log.info(String.format("Train set size = %d, num of features = %d", trainSet.size(), trainSet.getFeatureMap() .size())); testSet = new MutableDataset<>(dataSplitter.getTest()); log.info(String.format("Test set size = %d, num of features = %d", testSet.size(), testSet.getFeatureMap() .size())); } public void evaluateModels() throws Exception { log.info("Training model"); evaluate(model, "trainSet", trainSet); log.info("Testing model"); evaluate(model, "testSet", testSet); log.info("Dataset Provenance: --------------------"); log.info(ProvenanceUtil.formattedProvenanceString(model.getProvenance() .getDatasetProvenance())); log.info("Trainer Provenance: --------------------"); log.info(ProvenanceUtil.formattedProvenanceString(model.getProvenance()
.getTrainerProvenance())); } public void evaluate(Model<Regressor> model, String datasetName, Dataset<Regressor> dataset) { log.info("Results for " + datasetName + "---------------------"); RegressionEvaluator evaluator = new RegressionEvaluator(); RegressionEvaluation evaluation = evaluator.evaluate(model, dataset); Regressor dimension0 = new Regressor("DIM-0", Double.NaN); log.info("MAE: " + evaluation.mae(dimension0)); log.info("RMSE: " + evaluation.rmse(dimension0)); log.info("R^2: " + evaluation.r2(dimension0)); } public void saveModel() throws Exception { File modelFile = new File(MODEL_PATH); try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(modelFile))) { objectOutputStream.writeObject(model); } } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\tribuo\WineQualityRegression.java
1
请完成以下Java代码
public boolean isStorno() { if (storno == null) { return false; } else { return storno; } } /** * Sets the value of the storno property. * * @param value * allowed object is * {@link Boolean } * */ public void setStorno(Boolean value) { this.storno = value; } /** * Gets the value of the copy property. * * @return * possible object is * {@link Boolean } * */ public boolean isCopy() { if (copy == null) { return false; } else { return copy; } } /** * Sets the value of the copy property. * * @param value
* allowed object is * {@link Boolean } * */ public void setCopy(Boolean value) { this.copy = value; } /** * Gets the value of the creditAdvice property. * * @return * possible object is * {@link Boolean } * */ public boolean isCreditAdvice() { if (creditAdvice == null) { return false; } else { return creditAdvice; } } /** * Sets the value of the creditAdvice property. * * @param value * allowed object is * {@link Boolean } * */ public void setCreditAdvice(Boolean value) { this.creditAdvice = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PayloadType.java
1
请完成以下Java代码
public static final class CachesDescriptor implements OperationResponseBody { private final Map<String, CacheManagerDescriptor> cacheManagers; public CachesDescriptor(Map<String, CacheManagerDescriptor> cacheManagers) { this.cacheManagers = cacheManagers; } public Map<String, CacheManagerDescriptor> getCacheManagers() { return this.cacheManagers; } } /** * Description of a {@link CacheManager}. */ public static final class CacheManagerDescriptor { private final Map<String, CacheDescriptor> caches; public CacheManagerDescriptor(Map<String, CacheDescriptor> caches) { this.caches = caches; } public Map<String, CacheDescriptor> getCaches() { return this.caches; } } /** * Description of a {@link Cache}. */ public static class CacheDescriptor implements OperationResponseBody { private final String target; public CacheDescriptor(String target) { this.target = target; } /** * Return the fully qualified name of the native cache. * @return the fully qualified name of the native cache */ public String getTarget() { return this.target; } }
/** * Description of a {@link Cache} entry. */ public static final class CacheEntryDescriptor extends CacheDescriptor { private final String name; private final String cacheManager; public CacheEntryDescriptor(Cache cache, String cacheManager) { super(cache.getNativeCache().getClass().getName()); this.name = cache.getName(); this.cacheManager = cacheManager; } public String getName() { return this.name; } public String getCacheManager() { return this.cacheManager; } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\actuate\endpoint\CachesEndpoint.java
1
请完成以下Java代码
private static boolean _scheduleIfNotPostponed(final IContextAware ctxAware, @Nullable final AsyncBatchId asyncBatchId) { if (shipmentScheduleBL.allMissingSchedsWillBeCreatedLater()) { logger.debug("Not scheduling WP because IShipmentScheduleBL.allMissingSchedsWillBeCreatedLater() returned true: {}", CreateMissingShipmentSchedulesWorkpackageProcessor.class.getSimpleName()); return false; } // don't try to enqueue it if is not active if (!queueDAO.isWorkpackageProcessorEnabled(CreateMissingShipmentSchedulesWorkpackageProcessor.class)) { logger.debug("Not scheduling WP because this workpackage processor is disabled: {}", CreateMissingShipmentSchedulesWorkpackageProcessor.class.getSimpleName()); return false; } final Properties ctx = ctxAware.getCtx(); workPackageQueueFactory.getQueueForEnqueuing(ctx, CreateMissingShipmentSchedulesWorkpackageProcessor.class) .newWorkPackage() .setAsyncBatchId(asyncBatchId) .bindToTrxName(ctxAware.getTrxName()) .buildAndEnqueue(); return true; } // services private final transient IShipmentScheduleHandlerBL inOutCandHandlerBL = Services.get(IShipmentScheduleHandlerBL.class); @Override public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName_NOTUSED) {
final Properties ctx = InterfaceWrapperHelper.getCtx(workpackage); final Set<ShipmentScheduleId> shipmentScheduleIds = inOutCandHandlerBL.createMissingCandidates(ctx); // After shipment schedules where created, invalidate them because we want to make sure they are up2date. final IShipmentScheduleInvalidateBL invalidSchedulesService = Services.get(IShipmentScheduleInvalidateBL.class); final IShipmentSchedulePA shipmentScheduleDAO = Services.get(IShipmentSchedulePA.class); final Collection<I_M_ShipmentSchedule> scheduleRecords = shipmentScheduleDAO.getByIds(shipmentScheduleIds).values(); for (final I_M_ShipmentSchedule scheduleRecord : scheduleRecords) { invalidSchedulesService.notifySegmentChangedForShipmentScheduleInclSched(scheduleRecord); } Loggables.addLog("Created " + shipmentScheduleIds.size() + " candidates"); return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\async\CreateMissingShipmentSchedulesWorkpackageProcessor.java
1
请完成以下Spring Boot application配置
spring.mail.host=localhost spring.mail.port=8025 spring.thymeleaf.cache=false spring.thymeleaf.enabled=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.su
ffix=.html spring.jpa.properties.hibernate.globally_quoted_identifiers=true
repos\tutorials-master\spring-web-modules\spring-mvc-basics-3\src\main\resources\application.properties
2
请完成以下Java代码
public void clear() throws CacheException { redisTemplate.delete(cacheKey); } @Override public int size() { BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey); return hash.size().intValue(); } @Override public Set<K> keys() { BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey); return hash.keys(); }
@Override public Collection<V> values() { BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey); return hash.values(); } protected Object hashKey(K key) { //此处很重要,如果key是登录凭证,那么这是访问用户的授权缓存;将登录凭证转为user对象,返回user的id属性做为hash key,否则会以user对象做为hash key,这样就不好清除指定用户的缓存了 if (key instanceof PrincipalCollection) { PrincipalCollection pc = (PrincipalCollection) key; ShiroUser user = (ShiroUser) pc.getPrimaryPrincipal(); return user.getUserId(); } return key; } } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroRedisCacheManager.java
1
请完成以下Java代码
public class Tea { static final int DEFAULT_TEA_POWDER = 1; // add 1 tbsp tea powder by default private String name; // mandatory private int milk; // ml private boolean herbs; // add herbs or don't private int sugar; // tbsp private int teaPowder; // tbsp public Tea(String name, int milk, boolean herbs, int sugar, int teaPowder) { this.name = name; this.milk = milk; this.herbs = herbs; this.sugar = sugar; this.teaPowder = teaPowder; } // when tea powder is not provided by client, use default value public Tea(String name, int milk, boolean herbs, int sugar) { this(name, milk, herbs, sugar, DEFAULT_TEA_POWDER); } // when sugar is not provided by client, don't add it public Tea(String name, int milk, boolean herbs) { this(name, milk, herbs, 0); } // when herbs is not provided by client, don't add it public Tea(String name, int milk) { this(name, milk, false); } // when milk is not provided by client, don't add it public Tea(String name) {
this(name, 0); } public String getName() { return name; } public int getMilk() { return milk; } public boolean isHerbs() { return herbs; } public int getSugar() { return sugar; } public int getTeaPowder() { return teaPowder; } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\defaultparams\Tea.java
1
请完成以下Java代码
protected Object execute(CommandContext commandContext, TaskEntity task) { if (isLocal) { if (variables != null) { for (String variableName : variables.keySet()) { task.setVariableLocal(variableName, variables.get(variableName), false); } } } else { if (variables != null) { for (String variableName : variables.keySet()) { task.setVariable(variableName, variables.get(variableName), false); } }
} // ACT-1887: Force an update of the task's revision to prevent // simultaneous inserts of the same variable. If not, duplicate variables may occur since optimistic // locking doesn't work on inserts task.forceUpdate(); return null; } @Override protected String getSuspendedTaskExceptionPrefix() { return "Cannot add variables to"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SetTaskVariablesCmd.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("AD_Process_ID", adProcessId) .toString(); } public int getAD_Process_ID() { return adProcessId; } public String getCaption(final String adLanguage) { final ITranslatableString originalProcessCaption = getOriginalProcessCaption(); String caption = getPreconditionsResolution().computeCaption(originalProcessCaption, adLanguage); if (Services.get(IDeveloperModeBL.class).isEnabled()) { final I_AD_Process adProcess = adProcessSupplier.get(); caption += "/" + adProcess.getValue(); } return caption; } private ITranslatableString getOriginalProcessCaption() { final I_AD_Process adProcess = adProcessSupplier.get(); return InterfaceWrapperHelper.getModelTranslationMap(adProcess) .getColumnTrl(I_AD_Process.COLUMNNAME_Name, adProcess.getName()); } public String getDescription(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); String description = adProcessTrl.getDescription(); if (Services.get(IDeveloperModeBL.class).isEnabled()) { if (description == null) { description = ""; } else { description += "\n - "; } description += "Classname:" + adProcess.getClassname() + ", ID=" + adProcess.getAD_Process_ID(); } return description; } public String getHelp(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); return adProcessTrl.getHelp(); } public Icon getIcon() { final I_AD_Process adProcess = adProcessSupplier.get();
final String iconName; if (adProcess.getAD_Form_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WINDOW); } else if (adProcess.getAD_Workflow_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WORKFLOW); } else if (adProcess.isReport()) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_REPORT); } else { iconName = MTreeNode.getIconName(MTreeNode.TYPE_PROCESS); } return Images.getImageIcon2(iconName); } private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get(); } public boolean isEnabled() { return getPreconditionsResolution().isAccepted(); } public boolean isSilentRejection() { return getPreconditionsResolution().isInternal(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\SwingRelatedProcessDescriptor.java
1
请完成以下Java代码
public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getSourceCaseDefinitionId() { return sourceProcessDefinitionId; } public void setSourceCaseDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetCaseDefinitionId() { return targetProcessDefinitionId; } public void setTargetCaseDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public List<CaseInstanceBatchMigrationPartResult> getAllMigrationParts() { return allMigrationParts; } public void addMigrationPart(CaseInstanceBatchMigrationPartResult migrationPart) { if (allMigrationParts == null) { allMigrationParts = new ArrayList<>(); } allMigrationParts.add(migrationPart); if (!STATUS_COMPLETED.equals(migrationPart.getStatus())) { if (waitingMigrationParts == null) { waitingMigrationParts = new ArrayList<>(); } waitingMigrationParts.add(migrationPart);
} else { if (RESULT_SUCCESS.equals(migrationPart.getResult())) { if (succesfulMigrationParts == null) { succesfulMigrationParts = new ArrayList<>(); } succesfulMigrationParts.add(migrationPart); } else { if (failedMigrationParts == null) { failedMigrationParts = new ArrayList<>(); } failedMigrationParts.add(migrationPart); } } } public List<CaseInstanceBatchMigrationPartResult> getSuccessfulMigrationParts() { return succesfulMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getFailedMigrationParts() { return failedMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getWaitingMigrationParts() { return waitingMigrationParts; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationResult.java
1
请在Spring Boot框架中完成以下Java代码
public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); } @Primary @Bean(name = "configFlywayMySql") public FlywayDs1Properties firstFlywayProperties() { return new FlywayDs1Properties(); } @Primary @Bean(name = "dataSourceMySql") @ConfigurationProperties("app.datasource.ds1") public HikariDataSource firstDataSource(@Qualifier("configMySql") DataSourceProperties properties) { return properties.initializeDataSourceBuilder().type(HikariDataSource.class) .build(); } @Primary @FlywayDataSource @Bean(initMethod = "migrate") public Flyway primaryFlyway(@Qualifier("dataSourceMySql") HikariDataSource primaryDataSource, @Qualifier("configFlywayMySql") FlywayDs1Properties properties) { return Flyway.configure() .dataSource(primaryDataSource) .locations(properties.getLocation()) .load(); } // configure PostgreSQL data source and Flyway migration for "booksdb" @Bean(name = "configPostgreSql") @ConfigurationProperties("app.datasource.ds2") public DataSourceProperties secondDataSourceProperties() { return new DataSourceProperties(); } @Bean(name = "configFlywayPostgreSql") public FlywayDs2Properties secondFlywayProperties() { return new FlywayDs2Properties(); }
@Bean(name = "dataSourcePostgreSql") @ConfigurationProperties("app.datasource.ds2") public HikariDataSource secondDataSource(@Qualifier("configPostgreSql") DataSourceProperties properties) { return properties.initializeDataSourceBuilder().type(HikariDataSource.class) .build(); } @FlywayDataSource @Bean(initMethod = "migrate") public Flyway secondFlyway(@Qualifier("dataSourcePostgreSql") HikariDataSource secondDataSource, @Qualifier("configFlywayPostgreSql") FlywayDs2Properties properties) { return Flyway.configure() .dataSource(secondDataSource) .schemas(properties.getSchema()) .locations(properties.getLocation()) .load(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayTwoVendors\src\main\java\com\bookstore\config\ConfigureDataSources.java
2
请完成以下Java代码
private Iterator<ET> getCreateIterator() { assertNotClosed(); if (_iterator == null) { final ILock lock = getOrAcquireLock(); final Object contextProvider = PlainContextAware.newWithThreadInheritedTrx(ctx); _iterator = queryBL.createQueryBuilder(eventTypeClass, contextProvider) .filter(lockManager.getLockedByFilter(eventTypeClass, lock)) .addOnlyActiveRecordsFilter() // .orderBy() .addColumn(InterfaceWrapperHelper.getKeyColumnName(eventTypeClass)) .endOrderBy() // .create() .iterate(eventTypeClass); } return _iterator; } private ILock getOrAcquireLock() { assertNotClosed(); if (_lock == null) { final IQueryFilter<ET> filter = createFilter(); final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName()); _lock = lockManager.lock() .setOwner(lockOwner) .setAutoCleanup(true) .setFailIfNothingLocked(false) .setRecordsByFilter(eventTypeClass, filter) .acquire(); } return _lock; } protected IQueryFilter<ET> createFilter() { return queryBL.createCompositeQueryFilter(eventTypeClass) .addOnlyActiveRecordsFilter() .addOnlyContextClient(ctx) .addEqualsFilter(COLUMNNAME_Processed, false) .addFilter(lockManager.getNotLockedFilter(eventTypeClass)); }
@Override public void close() { // Mark this source as closed if (_closed.getAndSet(true)) { // already closed return; } // // Unlock all if (_lock != null) { _lock.close(); _lock = null; } // // Close iterator if (_iterator != null) { IteratorUtils.closeQuietly(_iterator); _iterator = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\EventSource.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonDeliveryOrderLineContents { @NonNull String shipmentOrderItemId; @NonNull JsonMoney unitPrice; @NonNull JsonMoney totalValue; @NonNull String productName; @NonNull String productValue; @NonNull BigDecimal totalWeightInKg; @NonNull JsonQuantity shippedQuantity; @JsonIgnore public Optional<String> getValue(@NonNull final String attributeValue) { switch (attributeValue) { case DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPPED_QUANTITY: return Optional.of(getShippedQuantity().getValue().toPlainString()); case DeliveryMappingConstants.ATTRIBUTE_VALUE_UOM_CODE:
return Optional.of(getShippedQuantity().getUomCode()); case DeliveryMappingConstants.ATTRIBUTE_VALUE_PRODUCT_NAME: return Optional.of(getProductName()); case DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPMENT_ORDER_ITEM_ID: return Optional.of(getShipmentOrderItemId()); case DeliveryMappingConstants.ATTRIBUTE_VALUE_UNIT_PRICE: return Optional.of(getUnitPrice().getAmount().toPlainString()); case DeliveryMappingConstants.ATTRIBUTE_VALUE_TOTAL_VALUE: return Optional.of(getTotalValue().getAmount().toPlainString()); case DeliveryMappingConstants.ATTRIBUTE_VALUE_CURRENCY_CODE: return Optional.of(getTotalValue().getCurrencyCode()); default: return Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-delivery\src\main\java\de\metas\common\delivery\v1\json\request\JsonDeliveryOrderLineContents.java
2
请完成以下Java代码
private static HUQRCodeGenerateRequest.Attribute toHUQRCodeGenerateRequestAttribute( final JsonQRCodesGenerateRequest.Attribute json, final IAttributeDAO attributeDAO) { final I_M_Attribute attribute = attributeDAO.retrieveAttributeByValue(json.getAttributeCode()); final AttributeId attributeId = AttributeId.ofRepoId(attribute.getM_Attribute_ID()); final HUQRCodeGenerateRequest.Attribute.AttributeBuilder resultBuilder = HUQRCodeGenerateRequest.Attribute.builder() .attributeId(attributeId); return AttributeValueType.ofCode(attribute.getAttributeValueType()) .map(new AttributeValueType.CaseMapper<HUQRCodeGenerateRequest.Attribute>() { @Override public HUQRCodeGenerateRequest.Attribute string() { return resultBuilder.valueString(json.getValue()).build(); } @Override public HUQRCodeGenerateRequest.Attribute number() { final BigDecimal valueNumber = NumberUtils.asBigDecimal(json.getValue()); return resultBuilder.valueNumber(valueNumber).build(); } @Override public HUQRCodeGenerateRequest.Attribute date() {
final LocalDate valueDate = StringUtils.trimBlankToOptional(json.getValue()).map(LocalDate::parse).orElse(null); return resultBuilder.valueDate(valueDate).build(); } @Override public HUQRCodeGenerateRequest.Attribute list() { final String listItemCode = json.getValue(); if (listItemCode != null) { final AttributeListValue listItem = attributeDAO.retrieveAttributeValueOrNull(attributeId, listItemCode); if (listItem == null) { throw new AdempiereException("No M_AttributeValue_ID found for " + attributeId + " and `" + listItemCode + "`"); } return resultBuilder.valueListId(listItem.getId()).build(); } else { return resultBuilder.valueListId(null).build(); } } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\JsonQRCodesGenerateRequestConverters.java
1
请完成以下Java代码
private void refresh() { final Object organization = orgField.getValue(); final Object locator = locatorField.getValue(); final Object product = productField.getValue(); final Object movementType = mtypeField.getValue(); final Timestamp movementDateFrom = dateFField.getValue(); final Timestamp movementDateTo = dateTField.getValue(); final Object bpartnerId = bpartnerField.getValue(); Services.get(IClientUI.class).executeLongOperation(panel, () -> refresh(organization, locator, product, movementType, movementDateFrom, movementDateTo, bpartnerId, statusBar)); } // refresh /** * Zoom */ @Override
public void zoom() { super.zoom(); // Zoom panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); AWindow frame = new AWindow(); if (!frame.initWindow(adWindowId, query)) { panel.setCursor(Cursor.getDefaultCursor()); return; } AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; panel.setCursor(Cursor.getDefaultCursor()); } // zoom } // VTrxMaterial
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTrxMaterial.java
1
请在Spring Boot框架中完成以下Java代码
private TbTimeSeriesSubscription createTsSub(EntityData entityData, int subIdx, boolean latestValues, long startTs, long endTs, Map<String, Long> keyStates, boolean resultToLatestValues) { log.trace("[{}][{}][{}] Creating time-series subscription for [{}] with keys: {}", serviceId, cmdId, subIdx, entityData.getEntityId(), keyStates); return TbTimeSeriesSubscription.builder() .serviceId(serviceId) .sessionId(sessionRef.getSessionId()) .subscriptionId(subIdx) .tenantId(sessionRef.getSecurityCtx().getTenantId()) .entityId(entityData.getEntityId()) .updateProcessor((sub, subscriptionUpdate) -> sendWsMsg(sub.getSessionId(), subscriptionUpdate, EntityKeyType.TIME_SERIES, resultToLatestValues)) .queryTs(createdTime) .allKeys(false) .keyStates(keyStates) .latestValues(latestValues) .startTime(startTs) .endTime(endTs) .build(); } private void sendWsMsg(String sessionId, TelemetrySubscriptionUpdate subscriptionUpdate, EntityKeyType keyType) { sendWsMsg(sessionId, subscriptionUpdate, keyType, true); } private Map<String, Long> buildKeyStats(EntityData entityData, EntityKeyType keysType, List<EntityKey> subKeys, boolean latestValues) { Map<String, Long> keyStates = new HashMap<>(); subKeys.forEach(key -> keyStates.put(key.getKey(), 0L));
if (latestValues && entityData.getLatest() != null) { Map<String, TsValue> currentValues = entityData.getLatest().get(keysType); if (currentValues != null) { currentValues.forEach((k, v) -> { if (subKeys.contains(new EntityKey(keysType, k))) { log.trace("[{}][{}] Updating key: {} with ts: {}", serviceId, cmdId, k, v.getTs()); keyStates.put(k, v.getTs()); } }); } } return keyStates; } abstract void sendWsMsg(String sessionId, TelemetrySubscriptionUpdate subscriptionUpdate, EntityKeyType keyType, boolean resultToLatestValues); protected abstract Aggregation getCurrentAggregation(); }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAbstractDataSubCtx.java
2
请在Spring Boot框架中完成以下Java代码
public class PackingService implements IPackingService { /** * Cannot fully unload: hu. Result is: result */ private static final String ERR_CANNOT_FULLY_UNLOAD_RESULT = "@CannotFullyUnload@ {} @ResultIs@ {}"; @Override public void removeProductQtyFromHU( final Properties ctx, final I_M_HU hu, PackingItemParts parts) { final ITrxManager trxManager = Services.get(ITrxManager.class); trxManager.runInNewTrx((TrxRunnable)localTrxName -> { final IContextAware contextProvider = PlainContextAware.newWithTrxName(ctx, localTrxName); final IMutableHUContext huContext = Services.get(IHandlingUnitsBL.class).createMutableHUContext(contextProvider); for (final PackingItemPart part : parts.toList()) { removeProductQtyFromHU(huContext, hu, part); } }); } private void removeProductQtyFromHU( final IHUContext huContext, final I_M_HU hu, final PackingItemPart part) { final ShipmentScheduleId shipmentScheduleId = part.getShipmentScheduleId(); final I_M_ShipmentSchedule schedule = Services.get(IShipmentSchedulePA.class).getById(shipmentScheduleId); // // Allocation Request final IAllocationRequest request = AllocationUtils.createQtyRequest( huContext, part.getProductId(), part.getQty(),
SystemTime.asZonedDateTime(), schedule, // reference model false // forceQtyAllocation ); // // Allocation Destination final ShipmentScheduleQtyPickedProductStorage shipmentScheduleQtyPickedStorage = new ShipmentScheduleQtyPickedProductStorage(schedule); final IAllocationDestination destination = new GenericAllocationSourceDestination(shipmentScheduleQtyPickedStorage, schedule); // // Allocation Source final IAllocationSource source = HUListAllocationSourceDestination.of(hu); // // Move Qty from HU to shipment schedule (i.e. un-pick) final IAllocationResult result = HULoader.of(source, destination) .load(request); // Make sure result is completed // NOTE: this issue could happen if we want to take out more then we have in our HU if (!result.isCompleted()) { final String errmsg = MessageFormat.format(PackingService.ERR_CANNOT_FULLY_UNLOAD_RESULT, hu, result); throw new AdempiereException(errmsg); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\impl\PackingService.java
2
请完成以下Java代码
public void setAccessTokenResponseClient( OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; } /** * Sets the resolver used for resolving the {@link Jwt} assertion. * @param jwtAssertionResolver the resolver used for resolving the {@link Jwt} * assertion * @since 5.7 */ public void setJwtAssertionResolver(Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver) { Assert.notNull(jwtAssertionResolver, "jwtAssertionResolver cannot be null"); this.jwtAssertionResolver = jwtAssertionResolver; } /** * Sets the maximum acceptable clock skew, which is used when checking the * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is * 60 seconds. * * <p> * An access token is considered expired if * {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew */ public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null"); Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access * token expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\JwtBearerOAuth2AuthorizedClientProvider.java
1
请在Spring Boot框架中完成以下Java代码
public PickingJobAggregationType getAggregationType(@Nullable final BPartnerId customerId, @NonNull PickingJobOptionsCollection pickingJobOptionsCollection) { return getPickingJobOption(customerId, pickingJobOptionsCollection, PickingJobOptions::getAggregationType, PickingJobAggregationType.DEFAULT); } @SuppressWarnings("SameParameterValue") private <T> T getPickingJobOption( @Nullable final BPartnerId customerId, @NonNull final PickingJobOptionsCollection pickingJobOptionsCollection, @NonNull final Function<PickingJobOptions, T> extractOption, @NonNull final T defaultValue) { if (customerId != null) { final PickingJobOptions pickingJobOptions = customerConfigs.getPickingJobOptionsId(customerId) .map(pickingJobOptionsCollection::getById) .orElse(null); if (pickingJobOptions != null) { final T option = extractOption.apply(pickingJobOptions); if (option != null) { return option; } } }
final T option = extractOption.apply(defaultPickingJobOptions); if (option != null) { return option; } return defaultValue; } @NonNull public ImmutableSet<BPartnerId> getPickOnlyCustomerIds() { if (isAllowPickingAnyCustomer) { return ImmutableSet.of(); } return customerConfigs.getCustomerIds(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\MobileUIPickingUserProfile.java
2
请完成以下Java代码
protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_DECISION; } protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { ServiceTask serviceTask = new ServiceTask(); serviceTask.setType(ServiceTask.DMN_TASK); JsonNode decisionTableReferenceNode = getProperty(PROPERTY_DECISIONTABLE_REFERENCE, elementNode); if ( decisionTableReferenceNode != null && decisionTableReferenceNode.has("id") && !(decisionTableReferenceNode.get("id").isNull()) ) { String decisionTableId = decisionTableReferenceNode.get("id").asText(); if (decisionTableMap != null) { String decisionTableKey = decisionTableMap.get(decisionTableId); FieldExtension decisionTableKeyField = new FieldExtension(); decisionTableKeyField.setFieldName(PROPERTY_DECISIONTABLE_REFERENCE_KEY); decisionTableKeyField.setStringValue(decisionTableKey); serviceTask.getFieldExtensions().add(decisionTableKeyField); } } return serviceTask;
} @Override protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {} @Override public void setDecisionTableMap(Map<String, String> decisionTableMap) { this.decisionTableMap = decisionTableMap; } protected void addExtensionAttributeToExtension(ExtensionElement element, String attributeName, String value) { ExtensionAttribute extensionAttribute = new ExtensionAttribute(NAMESPACE, attributeName); extensionAttribute.setNamespacePrefix("modeler"); extensionAttribute.setValue(value); element.addAttribute(extensionAttribute); } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\DecisionTaskJsonConverter.java
1
请完成以下Java代码
protected List<Map<String, String>> collectActivityTrace() { List<Map<String, String>> activityTrace = new ArrayList<Map<String, String>>(); for (AtomicOperationInvocation atomicOperationInvocation : perfromedInvocations) { String activityId = atomicOperationInvocation.getActivityId(); if(activityId == null) { continue; } Map<String, String> activity = new HashMap<String, String>(); activity.put("activityId", activityId); String activityName = atomicOperationInvocation.getActivityName(); if (activityName != null) { activity.put("activityName", activityName); } if(activityTrace.isEmpty() || !activity.get("activityId").equals(activityTrace.get(0).get("activityId"))) { activityTrace.add(0, activity); } } return activityTrace; } public void add(AtomicOperationInvocation atomicOperationInvocation) { perfromedInvocations.add(atomicOperationInvocation); }
protected void writeInvocation(AtomicOperationInvocation invocation, StringWriter writer) { writer.write("\t"); writer.write(invocation.getActivityId()); writer.write(" ("); writer.write(invocation.getOperation().getCanonicalName()); writer.write(", "); writer.write(invocation.getExecution().toString()); if(invocation.isPerformAsync()) { writer.write(", ASYNC"); } if(invocation.getApplicationContextName() != null) { writer.write(", pa="); writer.write(invocation.getApplicationContextName()); } writer.write(")\n"); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\BpmnStackTrace.java
1
请在Spring Boot框架中完成以下Java代码
private void processLabels(final List<Label> labelList, @NonNull final ImportIssueInfo.ImportIssueInfoBuilder importIssueInfoBuilder, @NonNull final OrgId orgId) { final ImmutableList<ProcessedLabel> processedLabels = labelService.processLabels(labelList); final List<IssueLabel> issueLabelList = new ArrayList<>(); final List<String> deliveryPlatformList = new ArrayList<>(); BigDecimal budget = BigDecimal.ZERO; BigDecimal estimation = BigDecimal.ZERO; BigDecimal roughEstimation = BigDecimal.ZERO; Optional<Status> status = Optional.empty(); Optional<LocalDate> plannedUATDate = Optional.empty(); Optional<LocalDate> deliveredDate = Optional.empty(); for (final ProcessedLabel label : processedLabels) { switch (label.getLabelType()) { case ESTIMATION: estimation = estimation.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO)); break; case ROUGH_EST: roughEstimation = roughEstimation.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO)); break; case BUDGET: budget = budget.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO)); break; case STATUS: status = status.isPresent() ? status : Status.ofCodeOptional(label.getExtractedValue()); break; case DELIVERY_PLATFORM: deliveryPlatformList.add(label.getExtractedValue()); break; case PLANNED_UAT: plannedUATDate = plannedUATDate.isPresent() ? plannedUATDate : getDateFromLabel(label.getExtractedValue()); break; case DELIVERED_DATE: deliveredDate = deliveredDate.isPresent() ? deliveredDate : getDateFromLabel(label.getExtractedValue()); break; default: // nothing to do for UNKNOWN label types }
issueLabelList.add(IssueLabel.builder().value(label.getLabel()).orgId(orgId).build()); } importIssueInfoBuilder.budget(budget); importIssueInfoBuilder.estimation(estimation); importIssueInfoBuilder.roughEstimation(roughEstimation); importIssueInfoBuilder.issueLabels(ImmutableList.copyOf(issueLabelList)); status.ifPresent(importIssueInfoBuilder::status); plannedUATDate.ifPresent(importIssueInfoBuilder::plannedUATDate); deliveredDate.ifPresent(importIssueInfoBuilder::deliveredDate); if (!deliveryPlatformList.isEmpty()) { importIssueInfoBuilder.deliveryPlatform(Joiner.on(",").join(deliveryPlatformList)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\GithubImporterService.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isEnableChangeDetection() { return enableChangeDetection; } public void setEnableChangeDetection(boolean enableChangeDetection) { this.enableChangeDetection = enableChangeDetection; } public Duration getChangeDetectionInitialDelay() { return changeDetectionInitialDelay; } public void setChangeDetectionInitialDelay(Duration changeDetectionInitialDelay) { this.changeDetectionInitialDelay = changeDetectionInitialDelay; } public Duration getChangeDetectionDelay() { return changeDetectionDelay; }
public void setChangeDetectionDelay(Duration changeDetectionDelay) { this.changeDetectionDelay = changeDetectionDelay; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\FlowableEventRegistryProperties.java
2
请在Spring Boot框架中完成以下Java代码
final class Jsr250MethodSecurityConfiguration implements ImportAware, AopInfrastructureBean { private static final Pointcut pointcut = AuthorizationManagerBeforeMethodInterceptor.jsr250().getPointcut(); private final Jsr250AuthorizationManager authorizationManager = new Jsr250AuthorizationManager(); private final AuthorizationManagerBeforeMethodInterceptor methodInterceptor; Jsr250MethodSecurityConfiguration( ObjectProvider<ObjectPostProcessor<AuthorizationManager<MethodInvocation>>> postProcessors) { ObjectPostProcessor<AuthorizationManager<MethodInvocation>> postProcessor = postProcessors .getIfUnique(ObjectPostProcessor::identity); AuthorizationManager<MethodInvocation> manager = postProcessor.postProcess(this.authorizationManager); this.methodInterceptor = AuthorizationManagerBeforeMethodInterceptor.jsr250(manager); } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static MethodInterceptor jsr250AuthorizationMethodInterceptor( ObjectProvider<Jsr250MethodSecurityConfiguration> _jsr250MethodSecurityConfiguration) { Supplier<AuthorizationManagerBeforeMethodInterceptor> supplier = () -> { Jsr250MethodSecurityConfiguration configuration = _jsr250MethodSecurityConfiguration.getObject(); return configuration.methodInterceptor; }; return new DeferringMethodInterceptor<>(pointcut, supplier); } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { EnableMethodSecurity annotation = importMetadata.getAnnotations().get(EnableMethodSecurity.class).synthesize(); this.methodInterceptor.setOrder(this.methodInterceptor.getOrder() + annotation.offset()); } @Autowired(required = false)
void setGrantedAuthorityDefaults(GrantedAuthorityDefaults defaults) { this.authorizationManager.setRolePrefix(defaults.getRolePrefix()); } @Autowired(required = false) void setRoleHierarchy(RoleHierarchy roleHierarchy) { AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); authoritiesAuthorizationManager.setRoleHierarchy(roleHierarchy); this.authorizationManager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); } @Autowired(required = false) void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { this.methodInterceptor.setSecurityContextHolderStrategy(securityContextHolderStrategy); } @Autowired(required = false) void setEventPublisher(AuthorizationEventPublisher eventPublisher) { this.methodInterceptor.setAuthorizationEventPublisher(eventPublisher); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\Jsr250MethodSecurityConfiguration.java
2
请完成以下Java代码
public void setPA_Goal_ID (int PA_Goal_ID) { if (PA_Goal_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Goal_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */ public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Goal getPA_GoalParent() throws RuntimeException { return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name) .getPO(getPA_GoalParent_ID(), get_TrxName()); } /** Set Parent Goal. @param PA_GoalParent_ID Parent Goal */ public void setPA_GoalParent_ID (int PA_GoalParent_ID) { if (PA_GoalParent_ID < 1) set_Value (COLUMNNAME_PA_GoalParent_ID, null); else set_Value (COLUMNNAME_PA_GoalParent_ID, Integer.valueOf(PA_GoalParent_ID)); } /** Get Parent Goal. @return Parent Goal */ public int getPA_GoalParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_GoalParent_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Measure getPA_Measure() throws RuntimeException { return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name) .getPO(getPA_Measure_ID(), get_TrxName()); } /** Set Measure. @param PA_Measure_ID Concrete Performance Measurement */ public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_Value (COLUMNNAME_PA_Measure_ID, null); else set_Value (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Relative Weight. @param RelativeWeight Relative weight of this step (0 = ignored) */ public void setRelativeWeight (BigDecimal RelativeWeight) { set_Value (COLUMNNAME_RelativeWeight, RelativeWeight); } /** Get Relative Weight. @return Relative weight of this step (0 = ignored) */ public BigDecimal getRelativeWeight () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight); if (bd == null) return Env.ZERO; return bd; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Goal.java
1
请完成以下Java代码
public abstract class HistoryCleanupHandler implements TransactionListener { /** * Maximum allowed batch size. */ public final static int MAX_BATCH_SIZE = 500; protected HistoryCleanupJobHandlerConfiguration configuration; protected String jobId; protected CommandExecutor commandExecutor; public void execute(CommandContext commandContext) { // passed commandContext may be in an inconsistent state commandExecutor.execute(new HistoryCleanupHandlerCmd()); } abstract void performCleanup(); abstract Map<String, Long> reportMetrics(); abstract boolean shouldRescheduleNow(); public HistoryCleanupJobHandlerConfiguration getConfiguration() { return configuration; } public HistoryCleanupHandler setConfiguration(HistoryCleanupJobHandlerConfiguration configuration) { this.configuration = configuration; return this; } public HistoryCleanupHandler setJobId(String jobId) { this.jobId = jobId; return this; }
public HistoryCleanupHandler setCommandExecutor(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; return this; } protected class HistoryCleanupHandlerCmd implements Command<Void> { @Override public Void execute(CommandContext commandContext) { Map<String, Long> report = reportMetrics(); boolean isRescheduleNow = shouldRescheduleNow(); new HistoryCleanupSchedulerCmd(isRescheduleNow, report, configuration, jobId).execute(commandContext); return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupHandler.java
1
请完成以下Java代码
public String getCnname() { return cnname; } public void setCnname(String cnname) { this.cnname = cnname; } public String getUsername() { return username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getRePassword() { return rePassword; } public void setRePassword(String rePassword) { this.rePassword = rePassword; } public String getHistoryPassword() { return historyPassword; }
public void setHistoryPassword(String historyPassword) { this.historyPassword = historyPassword; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @Override public String toString() { return "User{" + "id=" + id + ", cnname=" + cnname + ", username=" + username + ", password=" + password + ", email=" + email + ", telephone=" + telephone + ", mobilePhone=" + mobilePhone + '}'; } }
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\User.java
1
请完成以下Java代码
public class IntegerListFilter { private List<Integer> jdkIntList; private MutableList<Integer> ecMutableList; private IntList ecIntList; private ExecutorService executor; @Setup public void setup() { PrimitiveIterator.OfInt iterator = new Random(1L).ints(-10000, 10000).iterator(); ecMutableList = FastList.newWithNValues(1_000_000, iterator::nextInt); jdkIntList = new ArrayList<>(1_000_000); jdkIntList.addAll(ecMutableList); ecIntList = ecMutableList.collectInt(i -> i, new IntArrayList(1_000_000)); executor = Executors.newWorkStealingPool(); } @Benchmark public List<Integer> jdkList() { return jdkIntList.stream().filter(i -> i % 5 == 0).collect(Collectors.toList()); } @Benchmark public MutableList<Integer> ecMutableList() {
return ecMutableList.select(i -> i % 5 == 0); } @Benchmark public List<Integer> jdkListParallel() { return jdkIntList.parallelStream().filter(i -> i % 5 == 0).collect(Collectors.toList()); } @Benchmark public MutableList<Integer> ecMutableListParallel() { return ecMutableList.asParallel(executor, 100_000).select(i -> i % 5 == 0).toList(); } @Benchmark public IntList ecPrimitive() { return this.ecIntList.select(i -> i % 5 == 0); } @Benchmark public IntList ecPrimitiveParallel() { return this.ecIntList.primitiveParallelStream().filter(i -> i % 5 == 0).collect(IntLists.mutable::empty, MutableIntList::add, MutableIntList::addAll); } }
repos\tutorials-master\core-java-modules\core-java-11\src\main\java\com\baeldung\benchmark\IntegerListFilter.java
1
请完成以下Java代码
public void setReversalLine(final org.compiere.model.I_M_InventoryLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class, ReversalLine); } @Override public void setReversalLine_ID (final int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID); } @Override public int getReversalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReversalLine_ID); } @Override public void setUPC (final @Nullable java.lang.String UPC) { throw new IllegalArgumentException ("UPC is virtual column"); }
@Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setValue (final @Nullable java.lang.String Value) { throw new IllegalArgumentException ("Value is virtual column"); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLine.java
1
请完成以下Java代码
public void setHasStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } public boolean isGraphicalNotationDefined() { return isGraphicalNotationDefined; } public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) { this.isGraphicalNotationDefined = isGraphicalNotationDefined; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public String getEngineVersion() {
return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public IOSpecification getIoSpecification() { return ioSpecification; } public void setIoSpecification(IOSpecification ioSpecification) { this.ioSpecification = ioSpecification; } public String toString() { return "ProcessDefinitionEntity[" + id + "]"; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public Integer getAppVersion() { return this.appVersion; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantIdLike() { return tenantIdLike; } @ApiParam("Only return jobs with a tenantId like the given value") public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } @ApiParam("Only return jobs without a tenantId") public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public boolean isLocked() { return locked; } @ApiParam("Only return jobs that are locked") public void setLocked(boolean locked) { this.locked = locked; }
public boolean isUnlocked() { return unlocked; } @ApiParam("Only return jobs that are unlocked") public void setUnlocked(boolean unlocked) { this.unlocked = unlocked; } public boolean isWithoutScopeType() { return withoutScopeType; } @ApiParam("Only return jobs without a scope type") public void setWithoutScopeType(boolean withoutScopeType) { this.withoutScopeType = withoutScopeType; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public void setBuyerEANCU(String value) { this.buyerEANCU = value; } /** * Gets the value of the supplierGTINCU property. * * @return * possible object is * {@link String } * */ public String getSupplierGTINCU() { return supplierGTINCU; } /** * Sets the value of the supplierGTINCU property. * * @param value * allowed object is * {@link String } * */ public void setSupplierGTINCU(String value) { this.supplierGTINCU = value; } /** * Gets the value of the invoicableQtyBasedOn property. * * @return * possible object is * {@link InvoicableQtyBasedOnEnum } * */ public InvoicableQtyBasedOnEnum getInvoicableQtyBasedOn() { return invoicableQtyBasedOn; } /** * Sets the value of the invoicableQtyBasedOn property. * * @param value * allowed object is * {@link InvoicableQtyBasedOnEnum } * */ public void setInvoicableQtyBasedOn(InvoicableQtyBasedOnEnum value) { this.invoicableQtyBasedOn = value; } /** * Gets the value of the cuombPartnerID property. * * @return * possible object is * {@link EDIExpCUOMType } * */ public EDIExpCUOMType getCUOMBPartnerID() { return cuombPartnerID; } /** * Sets the value of the cuombPartnerID property. * * @param value * allowed object is * {@link EDIExpCUOMType } * */ public void setCUOMBPartnerID(EDIExpCUOMType value) { this.cuombPartnerID = value; }
/** * Gets the value of the qtyEnteredInBPartnerUOM property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getQtyEnteredInBPartnerUOM() { return qtyEnteredInBPartnerUOM; } /** * Sets the value of the qtyEnteredInBPartnerUOM property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setQtyEnteredInBPartnerUOM(BigDecimal value) { this.qtyEnteredInBPartnerUOM = value; } /** * Gets the value of the externalSeqNo property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getExternalSeqNo() { return externalSeqNo; } /** * Sets the value of the externalSeqNo property. * * @param value * allowed object is * {@link BigInteger } * */ public void setExternalSeqNo(BigInteger value) { this.externalSeqNo = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctopInvoic500VType.java
2
请在Spring Boot框架中完成以下Java代码
private void reply(LocalRequestMetaData rpcRequest, TbMsg response) { DeferredResult<ResponseEntity> responseWriter = rpcRequest.responseWriter(); if (response == null) { logRuleEngineCall(rpcRequest, null, new TimeoutException("Processing timeout detected!")); responseWriter.setResult(new ResponseEntity<>(HttpStatus.REQUEST_TIMEOUT)); } else { String responseData = response.getData(); if (!StringUtils.isEmpty(responseData)) { try { logRuleEngineCall(rpcRequest, response, null); responseWriter.setResult(new ResponseEntity<>(JacksonUtil.toJsonNode(responseData), HttpStatus.OK)); } catch (IllegalArgumentException e) { log.debug("Failed to decode device response: {}", responseData, e); logRuleEngineCall(rpcRequest, response, e); responseWriter.setResult(new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE)); } } else { logRuleEngineCall(rpcRequest, response, null); responseWriter.setResult(new ResponseEntity<>(HttpStatus.OK)); } } } private void logRuleEngineCall(LocalRequestMetaData rpcRequest, TbMsg response, Throwable e) { logRuleEngineCall(rpcRequest.user(), rpcRequest.request().getOriginator(), rpcRequest.request().getData(), response, e); }
private void logRuleEngineCall(SecurityUser user, EntityId entityId, String request, TbMsg response, Throwable e) { auditLogService.logEntityAction( user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), entityId, null, ActionType.REST_API_RULE_ENGINE_CALL, BaseController.toException(e), request, response != null ? response.getData() : ""); } private record LocalRequestMetaData(TbMsg request, SecurityUser user, DeferredResult<ResponseEntity> responseWriter) {} }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\RuleEngineController.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final DhlShipmentOrderId shipmentOrderId = DhlShipmentOrderId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (shipmentOrderId == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No shipment order selected"); } final DhlCustomDeliveryDataDetail dhlShipmentOrder = dhlShipmentOrderDAO.getByIdOrNull(shipmentOrderId); if (dhlShipmentOrder == null || dhlShipmentOrder.getPdfLabelData() == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No label available"); } return ProcessPreconditionsResolution.accept();
} @Override protected String doIt() { final DhlShipmentOrderId shipmentOrderId = DhlShipmentOrderId.ofRepoIdOrNull(getRecord_ID()); if (shipmentOrderId == null) { return MSG_OK; } final DhlCustomDeliveryDataDetail dhlShipmentOrder = dhlShipmentOrderDAO.getByIdOrNull(shipmentOrderId); if (dhlShipmentOrder == null || dhlShipmentOrder.getPdfLabelData() == null) { return MSG_OK; } getResult().setReportData(new ByteArrayResource(dhlShipmentOrder.getPdfLabelData()), "Dhl_Awb_" + dhlShipmentOrder.getAwb(), MimeType.TYPE_PDF); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\process\DHL_ShipmentOrder_DhlLabel_Download.java
1
请完成以下Java代码
private static final File[] retrieveChildren(final IFileRef fileRef) { final File file = fileRef.getFile(); if (file == null) { return new File[] {}; } if (!file.isDirectory()) { return new File[] {}; } final File[] children = file.listFiles(); if (children == null) { return new File[] {}; } Arrays.sort(children); // make sure the files are sorted lexicographically return children; } @Override protected IScriptScanner retrieveNextChildScriptScanner() { while (currentIndex < children.length - 1) { currentIndex++; final File child = children[currentIndex];
final IScriptScanner childScanner = createScriptScanner(child); if (childScanner != null) { return childScanner; } } return null; } private IScriptScanner createScriptScanner(final File file) { final FileRef fileRef = new FileRef(this, rootFileRef, file); final IScriptScanner scanner = getScriptScannerFactoryToUse().createScriptScanner(fileRef); return scanner; } @Override public String toString() { return "DirectoryScriptScanner [rootFileRef=" + rootFileRef + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\DirectoryScriptScanner.java
1
请完成以下Java代码
public <T> T newInstance(final Class<T> modelClass, final Object contextProvider) { final SaveDecoupledHUStorageDAO delegate = getDelegate(contextProvider); return delegate.newInstance(modelClass, contextProvider); } @Override public void initHUStorages(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); delegate.initHUStorages(hu); } @Override public void initHUItemStorages(final I_M_HU_Item item) { final SaveDecoupledHUStorageDAO delegate = getDelegate(item); delegate.initHUItemStorages(item); } @Override public I_M_HU_Storage retrieveStorage(final I_M_HU hu, final ProductId productId) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.retrieveStorage(hu, productId); } @Override public void save(final I_M_HU_Storage storage) { final SaveDecoupledHUStorageDAO delegate = getDelegate(storage); delegate.save(storage); } @Override public List<I_M_HU_Storage> retrieveStorages(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.retrieveStorages(hu); } @Override public void save(final I_M_HU_Item_Storage storageLine) { final SaveDecoupledHUStorageDAO delegate = getDelegate(storageLine); delegate.save(storageLine); } @Override public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item item) { final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
return delegate.retrieveItemStorages(item); } @Override public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item item, @NonNull final ProductId productId) { final SaveDecoupledHUStorageDAO delegate = getDelegate(item); return delegate.retrieveItemStorage(item, productId); } @Override public void save(final I_M_HU_Item item) { final SaveDecoupledHUStorageDAO delegate = getDelegate(item); delegate.save(item); } @Override public I_C_UOM getC_UOMOrNull(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.getC_UOMOrNull(hu); } @Override public UOMType getC_UOMTypeOrNull(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.getC_UOMTypeOrNull(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\SaveOnCommitHUStorageDAO.java
1
请完成以下Java代码
public static PaymentId ofRepoId(final int repoId) {return new PaymentId(repoId);} @Nullable public static PaymentId ofRepoIdOrNull(final int repoId) {return repoId > 0 ? new PaymentId(repoId) : null;} public static Optional<PaymentId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static int toRepoId(final PaymentId id) { return id != null ? id.getRepoId() : -1; } public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<PaymentId> ids) { if (ids.isEmpty()) { return ImmutableSet.of(); } return ids.stream().map(PaymentId::getRepoId).collect(ImmutableSet.toImmutableSet()); }
int repoId; private PaymentId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Payment_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable PaymentId id1, @Nullable PaymentId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\PaymentId.java
1
请完成以下Java代码
protected String encodeNonNullPassword(String rawPassword) { String salt = getSalt(); return BCrypt.hashpw(rawPassword.toString(), salt); } private String getSalt() { if (this.random != null) { return BCrypt.gensalt(this.version.getVersion(), this.strength, this.random); } return BCrypt.gensalt(this.version.getVersion(), this.strength); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) { this.logger.warn("Encoded password does not look like BCrypt"); return false; } return BCrypt.checkpw(rawPassword.toString(), encodedPassword); } @Override protected boolean upgradeEncodingNonNull(String encodedPassword) { Matcher matcher = this.BCRYPT_PATTERN.matcher(encodedPassword); if (!matcher.matches()) { throw new IllegalArgumentException("Encoded password does not look like BCrypt: " + encodedPassword); } int strength = Integer.parseInt(matcher.group(2)); return strength < this.strength; } /** * Stores the default bcrypt version for use in configuration. * * @author Lin Feng
*/ public enum BCryptVersion { $2A("$2a"), $2Y("$2y"), $2B("$2b"); private final String version; BCryptVersion(String version) { this.version = version; } public String getVersion() { return this.version; } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\bcrypt\BCryptPasswordEncoder.java
1
请完成以下Java代码
public static void handleExceptionWhenSendingEmail() { try { sendPlainTextEmail(); System.out.println("Email sent successfully!"); } catch (MailException e) { System.err.println("Error: " + e.getMessage()); } } public static void setCustomHeaderWhenSendingEmail() { Email email = EmailBuilder.startingBlank() .from("sender@example.com") .to("recipient@example.com") .withSubject("Email with Custom Header") .withPlainText("This is an important message.") .withHeader("X-Priority", "1") .buildEmail(); sendEmail(email); } private static void sendEmailWithDeliveryReadRecipient() { Email email = EmailBuilder.startingBlank() .from("sender@example.com") .to("recipient@example.com") .withSubject("Email with Delivery/Read Receipt Configured!")
.withPlainText("This is an email sending with delivery/read receipt.") .withDispositionNotificationTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO)) .withReturnReceiptTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO)) .buildEmail(); sendEmail(email); } private static void sendEmail(Email email) { Mailer mailer = MailerBuilder.withSMTPServer("smtp.example.com", 25, "username", "password") .withMaximumEmailSize(1024 * 1024 * 5) // 5 Megabytes .buildMailer(); boolean validate = mailer.validate(email); if (validate) { mailer.sendMail(email); } else { System.out.println("Invalid email address."); } } }
repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\simplemail\SimpleMailExample.java
1
请完成以下Java代码
public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class); } @Override public void setC_DocType(org.compiere.model.I_C_DocType C_DocType) { set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType); } /** Set Belegart. @param C_DocType_ID Belegart oder Verarbeitungsvorgaben */ @Override public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Belegart oder Verarbeitungsvorgaben */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document Type Sequence assignment. @param C_DocType_Sequence_ID Document Type Sequence assignment */ @Override public void setC_DocType_Sequence_ID (int C_DocType_Sequence_ID) { if (C_DocType_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocType_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_Sequence_ID, Integer.valueOf(C_DocType_Sequence_ID)); } /** Get Document Type Sequence assignment. @return Document Type Sequence assignment */ @Override public int getC_DocType_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Sequence getDocNoSequence() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override
public void setDocNoSequence(org.compiere.model.I_AD_Sequence DocNoSequence) { set_ValueFromPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class, DocNoSequence); } /** Set Nummernfolgen für Belege. @param DocNoSequence_ID Document sequence determines the numbering of documents */ @Override public void setDocNoSequence_ID (int DocNoSequence_ID) { if (DocNoSequence_ID < 1) set_Value (COLUMNNAME_DocNoSequence_ID, null); else set_Value (COLUMNNAME_DocNoSequence_ID, Integer.valueOf(DocNoSequence_ID)); } /** Get Nummernfolgen für Belege. @return Document sequence determines the numbering of documents */ @Override public int getDocNoSequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DocNoSequence_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Sequence.java
1
请完成以下Java代码
public ResourceEntity createDiagramForProcessDefinition(ProcessDefinitionEntity processDefinition, BpmnParse bpmnParse) { if (StringUtils.isEmpty(processDefinition.getKey()) || StringUtils.isEmpty(processDefinition.getResourceName())) { throw new IllegalStateException("Provided process definition must have both key and resource name set."); } ResourceEntity resource = createResourceEntity(); ProcessEngineConfiguration processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(); try { byte[] diagramBytes = IoUtil.readInputStream( processEngineConfiguration.getProcessDiagramGenerator().generateDiagram(bpmnParse.getBpmnModel(), "png", processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(), processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(),processEngineConfiguration.isDrawSequenceFlowNameWithNoLabelDI()), null); String diagramResourceName = ResourceNameUtil.getProcessDiagramResourceName( processDefinition.getResourceName(), processDefinition.getKey(), "png"); resource.setName(diagramResourceName); resource.setBytes(diagramBytes); resource.setDeploymentId(processDefinition.getDeploymentId()); // Mark the resource as 'generated' resource.setGenerated(true);
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable). LOGGER.warn("Error while generating process diagram, image will not be stored in repository", t); resource = null; } return resource; } protected ResourceEntity createResourceEntity() { return CommandContextUtil.getProcessEngineConfiguration().getResourceEntityManager().create(); } public boolean shouldCreateDiagram(ProcessDefinitionEntity processDefinition, DeploymentEntity deployment) { if (deployment.isNew() && processDefinition.isGraphicalNotationDefined() && CommandContextUtil.getProcessEngineConfiguration().isCreateDiagramOnDeploy()) { // If the 'getProcessDiagramResourceNameFromDeployment' call returns null, it means // no diagram image for the process definition was provided in the deployment resources. return ResourceNameUtil.getProcessDiagramResourceNameFromDeployment(processDefinition, deployment.getResources()) == null; } return false; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\deployer\ProcessDefinitionDiagramHelper.java
1
请完成以下Spring Boot application配置
spring: kafka: security: protocol: "SSL" bootstrap-servers: localhost:9093 ssl: trust-store-location: classpath:/client-certs/kafka.client.truststore.jks trust-store-password: password key-store-location: classpath:/client-certs/kafka.client.keystore.jks key-store-password: password consumer: group-id: demo-group-id auto-offset-reset: earliest key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apach
e.kafka.common.serialization.StringDeserializer producer: key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
repos\tutorials-master\spring-kafka\src\main\resources\application-ssl.yml
2
请完成以下Java代码
public class Msv3FaultInfo { @XmlElement(name = "ErrorCode", required = true) protected String errorCode; @XmlElement(name = "EndanwenderFehlertext", required = true) protected String endanwenderFehlertext; @XmlElement(name = "TechnischerFehlertext", required = true) protected String technischerFehlertext; /** * Gets the value of the errorCode property. * * @return * possible object is * {@link String } * */ public String getErrorCode() { return errorCode; } /** * Sets the value of the errorCode property. * * @param value * allowed object is * {@link String } * */ public void setErrorCode(String value) { this.errorCode = value; } /** * Gets the value of the endanwenderFehlertext property. * * @return * possible object is * {@link String } * */ public String getEndanwenderFehlertext() { return endanwenderFehlertext; } /** * Sets the value of the endanwenderFehlertext property.
* * @param value * allowed object is * {@link String } * */ public void setEndanwenderFehlertext(String value) { this.endanwenderFehlertext = value; } /** * Gets the value of the technischerFehlertext property. * * @return * possible object is * {@link String } * */ public String getTechnischerFehlertext() { return technischerFehlertext; } /** * Sets the value of the technischerFehlertext property. * * @param value * allowed object is * {@link String } * */ public void setTechnischerFehlertext(String value) { this.technischerFehlertext = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\Msv3FaultInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private long status; private String name; private String email; public User(){} public User(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } public void setStatus(long status) { this.status = status; } public long getStatus() { return status; } @Override public String toString() { return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\springbootdatasourceconfig\application\entities\User.java
2
请在Spring Boot框架中完成以下Java代码
public class CopyRecordService { @NonNull public PO copyRecord(@NonNull final CopyRecordRequest copyRecordRequest) { final TableRecordReference fromRecordRef = copyRecordRequest.getTableRecordReference(); final PO fromPO = fromRecordRef.getModel(PlainContextAware.newWithThreadInheritedTrx(), PO.class); final String tableName = fromPO.get_TableName(); if (!CopyRecordFactory.isEnabledForTableName(tableName)) { throw newCloneNotAllowedException(copyRecordRequest.getCustomErrorIfCloneNotAllowed(), tableName); } return CopyRecordFactory.getCopyRecordSupport(tableName) .setAdWindowId(copyRecordRequest.getFromAdWindowId())
.copyToNew(fromPO) .orElseThrow(() -> newCloneNotAllowedException(copyRecordRequest.getCustomErrorIfCloneNotAllowed(), tableName)); } private static AdempiereException newCloneNotAllowedException(@Nullable final AdMessageKey customErrorIfCloneNotAllowed, final @NonNull String tableName) { if (customErrorIfCloneNotAllowed != null) { return new AdempiereException(customErrorIfCloneNotAllowed); } else { return new AdempiereException("Clone is not enabled for table=" + tableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\CopyRecordService.java
2
请完成以下Java代码
default void afterTrxProcessed(IReference<I_M_HU_Trx_Hdr> trxHdrRef, List<I_M_HU_Trx_Line> trxLines) { // nothing } /** * Method called when a whole HU Load is completed. This default implementation does nothing. * * NOTE: this is the last method which is called, right before the final result is returned. * * @param huContext * @param loadResults */ default void afterLoad(IHUContext huContext, List<IAllocationResult> loadResults) { // nothing } /** * This default implementation does nothing. * * @param hu handling unit (never null) * @param parentHUItemOld (might be null) */ // TODO: we shall have a proper transaction for this case default void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld) { // nothing } /** * Called by {@link HULoader} each time a single unload/load transaction was performed. This default implementation does nothing. *
* @param huContext * @param unloadTrx * @param loadTrx */ default void onUnloadLoadTransaction(IHUContext huContext, IHUTransactionCandidate unloadTrx, IHUTransactionCandidate loadTrx) { // nothing } /** * Called when a split is performed. This default implementation does nothing. * * @param huContext * @param unloadTrx transaction on source HU * @param loadTrx transaction on destination HU */ default void onSplitTransaction(IHUContext huContext, IHUTransactionCandidate unloadTrx, IHUTransactionCandidate loadTrx) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\IHUTrxListener.java
1
请在Spring Boot框架中完成以下Java代码
protected static class CookieStoreConfiguration { /** * Creates a default {@link PerInstanceCookieStore} that should be used. * @return the cookie store */ @Bean @ConditionalOnMissingBean public PerInstanceCookieStore cookieStore() { return new JdkPerInstanceCookieStore(CookiePolicy.ACCEPT_ORIGINAL_SERVER); } /** * Creates a default trigger to cleanup the cookie store on deregistering of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance}.
* @param publisher publisher of {@link InstanceEvent}s events * @param cookieStore the store to inform about deregistration of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance} * @return a new trigger */ @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public CookieStoreCleanupTrigger cookieStoreCleanupTrigger(final Publisher<InstanceEvent> publisher, final PerInstanceCookieStore cookieStore) { return new CookieStoreCleanupTrigger(publisher, cookieStore); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerInstanceWebClientConfiguration.java
2
请完成以下Java代码
protected String getProcessDefinitionId(IdentityLinkEntity identityLink) { String processDefinitionId = null; if (identityLink.getProcessInstanceId() != null) { ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(identityLink.getProcessInstanceId()); if (execution != null) { processDefinitionId = execution.getProcessDefinitionId(); } } else if (identityLink.getTaskId() != null) { TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(identityLink.getTaskId()); if (task != null) { processDefinitionId = task.getProcessDefinitionId(); } } return processDefinitionId; } @Override public boolean isHistoryEnabledForEntityLink(EntityLinkEntity entityLink) { String processDefinitionId = getProcessDefinitionId(entityLink); return isHistoryEnabled(processDefinitionId); } @Override public boolean isHistoryEnabledForVariables(HistoricTaskInstance historicTaskInstance) { return processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY); } protected String getProcessDefinitionId(EntityLinkEntity entityLink) {
String processDefinitionId = null; if (ScopeTypes.BPMN.equals(entityLink.getScopeType()) && entityLink.getScopeId() != null) { ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(entityLink.getScopeId()); if (execution != null) { processDefinitionId = execution.getProcessDefinitionId(); } } else if (ScopeTypes.TASK.equals(entityLink.getScopeType()) && entityLink.getScopeId() != null) { TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(entityLink.getScopeId()); if (task != null) { processDefinitionId = task.getProcessDefinitionId(); } } return processDefinitionId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\DefaultHistoryConfigurationSettings.java
1
请完成以下Java代码
private BaeldungArticle latestArticle() { List<BaeldungArticle> articleList = website.getArticleList(); int latestArticleIndex = articleList.size() - 1; return articleList.get(latestArticleIndex); } public Baeldung getWebsite() { return website; } } public static class Baeldung { private List<BaeldungArticle> articleList; public void setArticleList(List<BaeldungArticle> articleList) { this.articleList = articleList; } public List<BaeldungArticle> getArticleList() { return this.articleList; } }
public static class BaeldungArticle { private String title; private String content; public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\sax\SaxParserMain.java
1
请完成以下Java代码
public String getTray() { return tray; } /** * @param tray the tray to set */ public void setTray(String tray) { this.tray = tray; } public int getPageFrom() { return pageFrom; } /** * @param pageFrom the pageFrom to set */ public void setPageFrom(int pageFrom) { this.pageFrom = pageFrom; } public int getPageTo() { return pageTo; } /** * @param pageTo the pageTo to set */ public void setPageTo(int pageTo) { this.pageTo = pageTo; } @Override public String toString() { return "PrintPackageInfo [printService=" + printService + ", tray=" + tray + ", pageFrom=" + pageFrom + ", pageTo=" + pageTo + ", calX=" + calX + ", calY=" + calY + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + calX; result = prime * result + calY; result = prime * result + pageFrom; result = prime * result + pageTo; result = prime * result + ((printService == null) ? 0 : printService.hashCode()); result = prime * result + ((tray == null) ? 0 : tray.hashCode()); result = prime * result + trayNumber; return result; } @Override public boolean equals(Object obj) {
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrintPackageInfo other = (PrintPackageInfo)obj; if (calX != other.calX) return false; if (calY != other.calY) return false; if (pageFrom != other.pageFrom) return false; if (pageTo != other.pageTo) return false; if (printService == null) { if (other.printService != null) return false; } else if (!printService.equals(other.printService)) return false; if (tray == null) { if (other.tray != null) return false; } else if (!tray.equals(other.tray)) return false; if (trayNumber != other.trayNumber) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackageInfo.java
1
请完成以下Java代码
private static Quantity extractQtyInvoiced(final I_C_Invoice_Line_Alloc ila) { final UomId uomId = UomId.ofRepoIdOrNull(ila.getC_UOM_ID()); return uomId != null ? Quantitys.of(ila.getQtyInvoicedInUOM(), uomId) : null; } private RawData loadRawData() { final List<I_C_Invoice_Line_Alloc> ilaRecords = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Line_Alloc.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_Invoice_Line_Alloc.COLUMN_C_Invoice_Candidate_ID, invoiceCandidateIds) .create() .list(); final ImmutableListMultimap<Integer, I_C_Invoice_Line_Alloc> invoiceCandidateId2IlaRecords = Multimaps.index(ilaRecords, I_C_Invoice_Line_Alloc::getC_Invoice_Candidate_ID); final ImmutableList<Integer> invoiceLineRepoIds = ilaRecords.stream() .map(ilaRecord -> ilaRecord.getC_InvoiceLine_ID()) .distinct() .collect(ImmutableList.toImmutableList()); final List<I_C_InvoiceLine> invoiceLineRecords = Services.get(IQueryBL.class) .createQueryBuilder(I_C_InvoiceLine.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_InvoiceLine.COLUMN_C_InvoiceLine_ID, invoiceLineRepoIds) .create() .list(); final ImmutableMap<Integer, I_C_InvoiceLine> invoiceLineId2InvoiceLineRecord = Maps.uniqueIndex(invoiceLineRecords, I_C_InvoiceLine::getC_InvoiceLine_ID); final ImmutableList<Integer> invoiceRepoIds = invoiceLineRecords.stream() .map(I_C_InvoiceLine::getC_Invoice_ID) .distinct() .collect(ImmutableList.toImmutableList()); final List<I_C_Invoice> invoiceRecords = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_Invoice.COLUMN_C_Invoice_ID, invoiceRepoIds) .create() .list(); final ImmutableMap<Integer, I_C_Invoice> invoiceId2InvoiceRecord = Maps.uniqueIndex(invoiceRecords, I_C_Invoice::getC_Invoice_ID); return new RawData(invoiceId2InvoiceRecord, invoiceLineId2InvoiceLineRecord, invoiceCandidateId2IlaRecords); } @Value private static class RawData { ImmutableMap<Integer, I_C_Invoice> invoiceId2InvoiceRecord; ImmutableMap<Integer, I_C_InvoiceLine> invoiceLineId2InvoiceLineRecord; ImmutableListMultimap<Integer, I_C_Invoice_Line_Alloc> invoiceCandidateId2IlaRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\InvoicedDataLoader.java
1
请完成以下Java代码
public int getRevisionNext() { return revision+1; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.newPassword = password; } public String getSalt() { return this.salt; } public void setSalt(String salt) { this.salt = salt; } /** * Special setter for MyBatis. */ public void setDbPassword(String password) { this.password = password; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public int getAttempts() { return attempts; } public void setAttempts(int attempts) { this.attempts = attempts; } public void encryptPassword() { if (newPassword != null) { salt = generateSalt(); setDbPassword(encryptPassword(newPassword, salt));
} } protected String encryptPassword(String password, String salt) { if (password == null) { return null; } else { String saltedPassword = saltPassword(password, salt); return Context.getProcessEngineConfiguration() .getPasswordManager() .encrypt(saltedPassword); } } protected String generateSalt() { return Context.getProcessEngineConfiguration() .getSaltGenerator() .generateSalt(); } public boolean checkPasswordAgainstPolicy() { PasswordPolicyResult result = Context.getProcessEngineConfiguration() .getIdentityService() .checkPasswordAgainstPolicy(newPassword, this); return result.isValid(); } public boolean hasNewPassword() { return newPassword != null; } public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", password=******" // sensitive for logging + ", salt=******" // sensitive for logging + ", lockExpirationTime=" + lockExpirationTime + ", attempts=" + attempts + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserEntity.java
1
请完成以下Java代码
public void reportStringCompressed() { getCounter("stringsCompressed").increment(); } @Override public void reportStringUncompressed() { getCounter("stringsUncompressed").increment(); } private void checkTiming(TenantId tenantId, EntityCountQuery query, long timingNanos) { double timingMs = timingNanos / 1000_000.0; String queryType = query instanceof EntityDataQuery ? "data" : "count"; if (timingMs < slowQueryThreshold) { log.debug("[{}] Executed " + queryType + " query in {} ms: {}", tenantId, timingMs, query); } else { log.warn("[{}] Executed slow " + queryType + " query in {} ms: {}", tenantId, timingMs, query); }
} private StatsTimer getTimer(String name) { return timers.computeIfAbsent(name, __ -> statsFactory.createStatsTimer("edqsTimers", name)); } private StatsCounter getCounter(String name) { return counters.computeIfAbsent(name, __ -> statsFactory.createStatsCounter("edqsCounters", name)); } private AtomicInteger getObjectGauge(ObjectType objectType) { return objectCounters.computeIfAbsent(objectType, type -> statsFactory.createGauge("edqsGauges", "objectsCount", new AtomicInteger(), "objectType", type.name())); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\stats\DefaultEdqsStatsService.java
1
请完成以下Java代码
public final class CrossOriginEmbedderPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; private @Nullable ServerHttpHeadersWriter delegate; /** * Sets the {@link CrossOriginEmbedderPolicy} value to be used in the * {@code Cross-Origin-Embedder-Policy} header * @param embedderPolicy the {@link CrossOriginEmbedderPolicy} to use */ public void setPolicy(CrossOriginEmbedderPolicy embedderPolicy) { Assert.notNull(embedderPolicy, "embedderPolicy cannot be null"); this.delegate = createDelegate(embedderPolicy); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(CrossOriginEmbedderPolicy embedderPolicy) { StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(EMBEDDER_POLICY, embedderPolicy.getPolicy()); return builder.build(); } public enum CrossOriginEmbedderPolicy { UNSAFE_NONE("unsafe-none"), REQUIRE_CORP("require-corp"),
CREDENTIALLESS("credentialless"); private final String policy; CrossOriginEmbedderPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\CrossOriginEmbedderPolicyServerHttpHeadersWriter.java
1
请完成以下Java代码
public class TelecomAddressType { @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice", required = true) protected List<String> phone; @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") protected List<String> fax; /** * Gets the value of the phone 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 phone property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPhone().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getPhone() { if (phone == null) { phone = new ArrayList<String>(); } return this.phone; } /** * Gets the value of the fax 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 fax property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFax().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getFax() { if (fax == null) { fax = new ArrayList<String>(); } return this.fax; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TelecomAddressType.java
1
请在Spring Boot框架中完成以下Java代码
public class DataScopeCache { private static final String SCOPE_CACHE_CODE = "dataScope:code:"; private static final String SCOPE_CACHE_CLASS = "dataScope:class:"; private static final String DEPT_CACHE_ANCESTORS = "dept:ancestors:"; private static IDataScopeClient dataScopeClient; private static IDataScopeClient getDataScopeClient() { if (dataScopeClient == null) { dataScopeClient = SpringUtil.getBean(IDataScopeClient.class); } return dataScopeClient; } /** * 获取数据权限 * * @param mapperId 数据权限mapperId * @param roleId 用户角色集合 * @return DataScopeModel */ public static DataScopeModel getDataScopeByMapper(String mapperId, String roleId) { DataScopeModel dataScope = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_CLASS, mapperId + StringPool.COLON + roleId, DataScopeModel.class); if (dataScope == null || !dataScope.getSearched()) { dataScope = getDataScopeClient().getDataScopeByMapper(mapperId, roleId); CacheUtil.put(SYS_CACHE, SCOPE_CACHE_CLASS, mapperId + StringPool.COLON + roleId, dataScope); } return StringUtil.isNotBlank(dataScope.getResourceCode()) ? dataScope : null; } /** * 获取数据权限 * * @param code 数据权限资源编号 * @return DataScopeModel */ public static DataScopeModel getDataScopeByCode(String code) { DataScopeModel dataScope = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_CODE, code, DataScopeModel.class); if (dataScope == null || !dataScope.getSearched()) {
dataScope = getDataScopeClient().getDataScopeByCode(code); CacheUtil.put(SYS_CACHE, SCOPE_CACHE_CODE, code, dataScope); } return StringUtil.isNotBlank(dataScope.getResourceCode()) ? dataScope : null; } /** * 获取部门子级 * * @param deptId 部门id * @return deptIds */ public static List<Long> getDeptAncestors(Long deptId) { List ancestors = CacheUtil.get(SYS_CACHE, DEPT_CACHE_ANCESTORS, deptId, List.class); if (CollectionUtil.isEmpty(ancestors)) { ancestors = getDataScopeClient().getDeptAncestors(deptId); CacheUtil.put(SYS_CACHE, DEPT_CACHE_ANCESTORS, deptId, ancestors); } return ancestors; } }
repos\SpringBlade-master\blade-service-api\blade-scope-api\src\main\java\org\springblade\system\cache\DataScopeCache.java
2
请完成以下Java代码
public class DD_Order_Candidate_EnqueueToProcess extends ViewBasedProcessTemplate implements IProcessPrecondition { @NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class); @NonNull private final DDOrderCandidateService ddOrderCandidateService = SpringContextHolder.instance.getBean(DDOrderCandidateService.class); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final PInstanceId selectionId = createSelection(); ddOrderCandidateService.enqueueToProcess(selectionId); return MSG_OK; } protected PInstanceId createSelection() { final IQueryBuilder<I_DD_Order_Candidate> queryBuilder = selectionQueryBuilder(); final PInstanceId adPInstanceId = Check.assumeNotNull(getPinstanceId(), "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
final int count = queryBuilder .create() .setRequiredAccess(Access.READ) .createSelection(adPInstanceId); if (count <= 0) { throw new AdempiereException("@NoSelection@"); } return adPInstanceId; } protected IQueryBuilder<I_DD_Order_Candidate> selectionQueryBuilder() { final IQueryFilter<I_DD_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_DD_Order_Candidate.class) .addEqualsFilter(I_DD_Order_Candidate.COLUMNNAME_Processed, false) .addCompareFilter(I_DD_Order_Candidate.COLUMNNAME_QtyToProcess, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .filter(userSelectionFilter) .addOnlyActiveRecordsFilter() .orderBy(I_DD_Order_Candidate.COLUMNNAME_DD_Order_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.webui\src\main\java\de\metas\distribution\webui\process\DD_Order_Candidate_EnqueueToProcess.java
1
请完成以下Java代码
public HUQueryBuilder setExcludeAfterPickingLocator(final boolean excludeAfterPickingLocator) { locators.setExcludeAfterPickingLocator(excludeAfterPickingLocator); return this; } @Override public HUQueryBuilder setIncludeAfterPickingLocator(final boolean includeAfterPickingLocator) { locators.setIncludeAfterPickingLocator(includeAfterPickingLocator); return this; } @Override public HUQueryBuilder setExcludeHUsOnPickingSlot(final boolean excludeHUsOnPickingSlot) { _excludeHUsOnPickingSlot = excludeHUsOnPickingSlot; return this; } @Override public IHUQueryBuilder setExcludeReservedToOtherThan(@Nullable final HUReservationDocRef documentRef)
{ _excludeReservedToOtherThanRef = documentRef; return this; } @Override public IHUQueryBuilder setExcludeReserved() { _excludeReserved = true; return this; } @Override public IHUQueryBuilder setIgnoreHUsScheduledInDDOrder(final boolean ignoreHUsScheduledInDDOrder) { this.ignoreHUsScheduledInDDOrder = ignoreHUsScheduledInDDOrder; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder.java
1
请完成以下Java代码
public LDAPGroupCacheListener getLdapCacheListener() { return ldapCacheListener; } public void setLdapCacheListener(LDAPGroupCacheListener ldapCacheListener) { this.ldapCacheListener = ldapCacheListener; } // Helper classes //////////////////////////////////// static class LDAPGroupCacheEntry { protected Date timestamp; protected List<Group> groups; public LDAPGroupCacheEntry() { } public LDAPGroupCacheEntry(Date timestamp, List<Group> groups) { this.timestamp = timestamp; this.groups = groups; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; }
public List<Group> getGroups() { return groups; } public void setGroups(List<Group> groups) { this.groups = groups; } } // Cache listeners. Currently not yet exposed (only programmatically for the // moment) // Experimental stuff! public static interface LDAPGroupCacheListener { void cacheHit(String userId); void cacheMiss(String userId); void cacheEviction(String userId); void cacheExpired(String userId); } }
repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\LDAPGroupCache.java
1
请完成以下Java代码
public String getZip() { return super.getZip(); } @Schema(description = "Phone number", example = "+1(415)777-7777") @Override public String getPhone() { return super.getPhone(); } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Email", example = "example@company.com") @Override public String getEmail() { return super.getEmail(); } @Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class) @Override public JsonNode getAdditionalInfo() { return super.getAdditionalInfo(); } @JsonIgnore public boolean isPublic() { if (getAdditionalInfo() != null && getAdditionalInfo().has("isPublic")) { return getAdditionalInfo().get("isPublic").asBoolean(); } return false; } @JsonIgnore public ShortCustomerInfo toShortCustomerInfo() { return new ShortCustomerInfo(id, title, isPublic()); } @Override @JsonProperty(access = Access.READ_ONLY) @Schema(description = "Name of the customer. Read-only, duplicated from title for backward compatibility", example = "Company A", accessMode = Schema.AccessMode.READ_ONLY) public String getName() { return title; }
@Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [title="); builder.append(title); builder.append(", tenantId="); builder.append(tenantId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", country="); builder.append(country); builder.append(", state="); builder.append(state); builder.append(", city="); builder.append(city); builder.append(", address="); builder.append(address); builder.append(", address2="); builder.append(address2); builder.append(", zip="); builder.append(zip); builder.append(", phone="); builder.append(phone); builder.append(", email="); builder.append(email); 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\Customer.java
1
请完成以下Java代码
public void invalidateCandidatesFor(final Object model) { final I_M_InOut inout = InterfaceWrapperHelper.create(model, I_M_InOut.class); invalidateCandidatesForInOut(inout); invalidateFreightCostCandidateIfNeeded(inout); } private void invalidateFreightCostCandidateIfNeeded(final I_M_InOut inout) { final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); final OrderId orderId = OrderId.ofRepoIdOrNull(inout.getC_Order_ID()); if (orderId == null) { // nothing to do return; } invoiceCandDAO.invalidateUninvoicedFreightCostCandidate(orderId); } private void invalidateCandidatesForInOut(final I_M_InOut inout) { // // Retrieve inout line handlers final Properties ctx = InterfaceWrapperHelper.getCtx(inout); final List<IInvoiceCandidateHandler> inoutLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, org.compiere.model.I_M_InOutLine.Table_Name); for (final IInvoiceCandidateHandler handler : inoutLineHandlers) { for (final org.compiere.model.I_M_InOutLine line : inOutDAO.retrieveLines(inout)) { handler.invalidateCandidatesFor(line); } } } @Override public String getSourceTable() { return org.compiere.model.I_M_InOut.Table_Name; } @Override public boolean isUserInChargeUserEditable() { return false; }
@Override public void setOrderedData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic) { throw new UnsupportedOperationException(); } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOut_Handler.java
1
请完成以下Java代码
public class GetRenderedTaskFormCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected String formEngineName; public GetRenderedTaskFormCmd(String taskId, String formEngineName) { this.taskId = taskId; this.formEngineName = formEngineName; } @Override public Object execute(CommandContext commandContext) { if (taskId == null) { throw new FlowableIllegalArgumentException("Task id should not be null"); } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId); if (task == null) { throw new FlowableObjectNotFoundException("Task '" + taskId + "' not found", Task.class); } FormHandlerHelper formHandlerHelper = processEngineConfiguration.getFormHandlerHelper(); TaskFormHandler taskFormHandler = formHandlerHelper.getTaskFormHandlder(task);
if (taskFormHandler != null) { FormEngine formEngine = processEngineConfiguration.getFormEngines().get(formEngineName); if (formEngine == null) { throw new FlowableException("No formEngine '" + formEngineName + "' defined process engine configuration"); } TaskFormData taskForm = taskFormHandler.createTaskForm(task); return formEngine.renderTaskForm(taskForm); } return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetRenderedTaskFormCmd.java
1
请完成以下Java代码
final class LdapEncoder { private static final String[] NAME_ESCAPE_TABLE = new String[96]; static { // all below 0x20 (control chars) for (char c = 0; c < ' '; c++) { NAME_ESCAPE_TABLE[c] = "\\" + toTwoCharHex(c); } NAME_ESCAPE_TABLE['#'] = "\\#"; NAME_ESCAPE_TABLE[','] = "\\,"; NAME_ESCAPE_TABLE[';'] = "\\;"; NAME_ESCAPE_TABLE['='] = "\\="; NAME_ESCAPE_TABLE['+'] = "\\+"; NAME_ESCAPE_TABLE['<'] = "\\<"; NAME_ESCAPE_TABLE['>'] = "\\>"; NAME_ESCAPE_TABLE['\"'] = "\\\""; NAME_ESCAPE_TABLE['\\'] = "\\\\"; } /** * All static methods - not to be instantiated. */ private LdapEncoder() { } static String toTwoCharHex(char c) { String raw = Integer.toHexString(c).toUpperCase(Locale.ENGLISH); return (raw.length() > 1) ? raw : "0" + raw; } /** * LDAP Encodes a value for use with a DN. Escapes for LDAP, not JNDI! <br/> * Escapes:<br/> * ' ' [space] - "\ " [if first or last] <br/> * '#' [hash] - "\#" <br/> * ',' [comma] - "\," <br/> * ';' [semicolon] - "\;" <br/> * '= [equals] - "\=" <br/> * '+' [plus] - "\+" <br/> * '&lt;' [less than] - "\&lt;" <br/> * '&gt;' [greater than] - "\&gt;" <br/> * '"' [double quote] - "\"" <br/> * '\' [backslash] - "\\" <br/> * @param value the value to escape. * @return The escaped value. */ static String nameEncode(String value) { if (value == null) { return null; } StringBuilder encodedValue = new StringBuilder(value.length() * 2); int length = value.length();
int last = length - 1; for (int i = 0; i < length; i++) { char c = value.charAt(i); // space first or last if (c == ' ' && (i == 0 || i == last)) { encodedValue.append("\\ "); continue; } // check in table for escapes if (c < NAME_ESCAPE_TABLE.length) { String esc = NAME_ESCAPE_TABLE[c]; if (esc != null) { encodedValue.append(esc); continue; } } // default: add the char encodedValue.append(c); } return encodedValue.toString(); } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\LdapEncoder.java
1
请完成以下Java代码
public void importRecord(@NonNull final BPartnerImportContext context) { final I_I_BPartner importRecord = context.getCurrentImportRecord(); if (importRecord.getAD_PrintFormat_ID() <= 0 && Check.isBlank(importRecord.getPrintFormat_DocBaseType())) { return; } final PrintFormatId printFormatId = PrintFormatId.ofRepoIdOrNull(importRecord.getAD_PrintFormat_ID()); final DocBaseType docBaseType; if(!Check.isBlank(importRecord.getPrintFormat_DocBaseType())) { docBaseType = DocBaseType.ofCode(importRecord.getPrintFormat_DocBaseType()); } // for vendors we have print format for purchase order else if (importRecord.isVendor()) { docBaseType = DocBaseType.PurchaseOrder; } // for customer we have print format for delivery else { docBaseType = DocBaseType.Shipment; } final DocTypeId docTypeId = docTypeDAO.getDocTypeId(DocTypeQuery.builder() .docBaseType(docBaseType) .adClientId(importRecord.getAD_Client_ID()) .adOrgId(importRecord.getAD_Org_ID()) .build()); final AdTableId adTableId = AdTableId.ofRepoId(tableDAO.retrieveTableId(docBaseType.getTableName())); final BPartnerId bPartnerId = BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()); final BPartnerLocationId bPartnerLocationId = importRecord.isSetPrintFormat_C_BPartner_Location() ? BPartnerLocationId.ofRepoIdOrNull(bPartnerId, importRecord.getC_BPartner_Location_ID()) : null; final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder() .printFormatId(printFormatId) .docTypeId(docTypeId)
.adTableId(adTableId) .bPartnerLocationId(bPartnerLocationId) .bpartnerId(bPartnerId) .isExactMatch(true) .build(); BPPrintFormat bpPrintFormat = bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery); if (bpPrintFormat == null) { bpPrintFormat = BPPrintFormat.builder() .adTableId(adTableId) .docTypeId(docTypeId) .printFormatId(printFormatId) .bpartnerId(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID())) .bPartnerLocationId(bPartnerLocationId) .printCopies(PrintCopies.ofInt(importRecord.getPrintFormat_DocumentCopies_Override())) .build(); } bpPrintFormat = bPartnerPrintFormatRepository.save(bpPrintFormat); importRecord.setC_BP_PrintFormat_ID(bpPrintFormat.getBpPrintFormatId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerPrintFormatImportHelper.java
1
请完成以下Java代码
public class BpmnModelInstanceCache extends ModelInstanceCache<BpmnModelInstance, ProcessDefinitionEntity> { public BpmnModelInstanceCache(CacheFactory factory, int cacheCapacity, ResourceDefinitionCache<ProcessDefinitionEntity> definitionCache) { super(factory, cacheCapacity, definitionCache); } @Override protected void throwLoadModelException(String definitionId, Exception e) { throw LOG.loadModelException("BPMN", "process", definitionId, e); } @Override protected BpmnModelInstance readModelFromStream(InputStream bpmnResourceInputStream) { return Bpmn.readModelFromStream(bpmnResourceInputStream); } @Override
protected void logRemoveEntryFromDeploymentCacheFailure(String definitionId, Exception e) { LOG.removeEntryFromDeploymentCacheFailure("process", definitionId, e); } @Override protected List<ProcessDefinition> getAllDefinitionsForDeployment(final String deploymentId) { final CommandContext commandContext = Context.getCommandContext(); List<ProcessDefinition> allDefinitionsForDeployment = commandContext.runWithoutAuthorization(new Callable<List<ProcessDefinition>>() { public List<ProcessDefinition> call() throws Exception { return new ProcessDefinitionQueryImpl() .deploymentId(deploymentId) .list(); } }); return allDefinitionsForDeployment; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\BpmnModelInstanceCache.java
1
请完成以下Java代码
public boolean isLocked(final Class<?> modelClass, final int recordId, final LockOwner lockOwner) { return getLockDatabase().isLocked(modelClass, recordId, lockOwner); } @Override public boolean isLocked(final Object model) { return getLockDatabase().isLocked(model, LockOwner.ANY); } @Override public final <T> T retrieveAndLock(final IQuery<T> query, final Class<T> clazz) { return getLockDatabase().retrieveAndLock(query, clazz); } @Override public final String getNotLockedWhereClause(final String tableName, final String joinColumnNameFQ) { return getLockDatabase().getNotLockedWhereClause(tableName, joinColumnNameFQ); } @Override public final <T> IQueryFilter<T> getNotLockedFilter(final Class<T> modelClass) { return getLockDatabase().getNotLockedFilter(modelClass); } @Override public String getLockedWhereClause(final Class<?> modelClass, final String joinColumnNameFQ, final LockOwner lockOwner) { return getLockDatabase().getLockedWhereClause(modelClass, joinColumnNameFQ, lockOwner); } @Override public final <T> IQueryFilter<T> getLockedByFilter(final Class<T> modelClass, final LockOwner lockOwner) { return getLockDatabase().getLockedByFilter(modelClass, lockOwner); } @Override public ILock getExistingLockForOwner(final LockOwner lockOwner) { return getLockDatabase().retrieveLockForOwner(lockOwner); } @Override public <T> IQueryFilter<T> getNotLockedFilter(@NonNull String modelTableName, @NonNull String joinColumnNameFQ) { return getLockDatabase().getNotLockedFilter(modelTableName, joinColumnNameFQ); } @Override public <T> IQueryBuilder<T> getLockedRecordsQueryBuilder(final Class<T> modelClass, final Object contextProvider) {
return getLockDatabase().getLockedRecordsQueryBuilder(modelClass, contextProvider); } @Override public int removeAutoCleanupLocks() { return getLockDatabase().removeAutoCleanupLocks(); } @Override public <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz) { return getLockDatabase().retrieveAndLockMultipleRecords(query, clazz); } @Override public <T> IQuery<T> addNotLockedClause(final IQuery<T> query) { return getLockDatabase().addNotLockedClause(query); } @Override public ExistingLockInfo getLockInfo(final TableRecordReference tableRecordReference, final LockOwner lockOwner) { return getLockDatabase().getLockInfo(tableRecordReference, lockOwner); } @Override public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(final @NonNull TableRecordReferenceSet recordRefs) { return getLockDatabase().getLockInfosByRecordIds(recordRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockManager.java
1
请完成以下Java代码
public PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { final PPOrderId ppOrderIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getPpOrderId() : null; final PPOrderBOMLineId lineIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getLineId() : null; return PPOrderId.equals(this.ppOrderId, ppOrderIdNew) && PPOrderBOMLineId.equals(this.ppOrderBOMLineId, lineIdNew) ? this : toBuilder().ppOrderId(ppOrderIdNew).ppOrderBOMLineId(lineIdNew).build(); } public PPOrderRef withPPOrderId(@Nullable final PPOrderId ppOrderId) { if (PPOrderId.equals(this.ppOrderId, ppOrderId)) { return this; } return toBuilder().ppOrderId(ppOrderId).build(); } @Nullable public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderId(newPPOrderId); } else if (newPPOrderId != null) { return ofPPOrderId(newPPOrderId);
} else { return null; } } @Nullable public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId); } else if (newPPOrderAndBOMLineId != null) { return ofPPOrderBOMLineId(newPPOrderAndBOMLineId); } else { return null; } } @Nullable public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java
1
请在Spring Boot框架中完成以下Java代码
protected String executeToStringTransform(JsonNode result) { if (result.isTextual()) { return result.asText(); } throw wrongResultType(result); } @Override protected JsonNode convertResult(Object result) { return JacksonUtil.toJsonNode(result != null ? result.toString() : null); } private static TbMsg unbindMsg(JsonNode msgData, TbMsg msg) { String data = null; Map<String, String> metadata = null; String messageType = null; if (msgData.has(RuleNodeScriptFactory.MSG)) { JsonNode msgPayload = msgData.get(RuleNodeScriptFactory.MSG); data = JacksonUtil.toString(msgPayload); } if (msgData.has(RuleNodeScriptFactory.METADATA)) { JsonNode msgMetadata = msgData.get(RuleNodeScriptFactory.METADATA); metadata = JacksonUtil.convertValue(msgMetadata, new TypeReference<>() {});
} if (msgData.has(RuleNodeScriptFactory.MSG_TYPE)) { messageType = msgData.get(RuleNodeScriptFactory.MSG_TYPE).asText(); } String newData = data != null ? data : msg.getData(); TbMsgMetaData newMetadata = metadata != null ? new TbMsgMetaData(metadata) : msg.getMetaData().copy(); String newMessageType = StringUtils.isNotEmpty(messageType) ? messageType : msg.getType(); return msg.transform() .type(newMessageType) .metaData(newMetadata) .data(newData) .build(); } private TbScriptException wrongResultType(JsonNode result) { return new TbScriptException(scriptId, TbScriptException.ErrorCode.RUNTIME, null, new ClassCastException("Wrong result type: " + result.getNodeType())); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\script\RuleNodeJsScriptEngine.java
2
请在Spring Boot框架中完成以下Java代码
public Object buildTree(List<DeptDto> deptDtos) { Set<DeptDto> trees = new LinkedHashSet<>(); Set<DeptDto> depts= new LinkedHashSet<>(); List<String> deptNames = deptDtos.stream().map(DeptDto::getName).collect(Collectors.toList()); boolean isChild; for (DeptDto deptDTO : deptDtos) { isChild = false; if (deptDTO.getPid() == null) { trees.add(deptDTO); } for (DeptDto it : deptDtos) { if (it.getPid() != null && deptDTO.getId().equals(it.getPid())) { isChild = true; if (deptDTO.getChildren() == null) { deptDTO.setChildren(new ArrayList<>()); } deptDTO.getChildren().add(it); } } if(isChild) { depts.add(deptDTO); } else if(deptDTO.getPid() != null && !deptNames.contains(findById(deptDTO.getPid()).getName())) { depts.add(deptDTO); } } if (CollectionUtil.isEmpty(trees)) { trees = depts; } Map<String,Object> map = new HashMap<>(2); map.put("totalElements",deptDtos.size()); map.put("content",CollectionUtil.isEmpty(trees)? deptDtos :trees); return map; } @Override public void verification(Set<DeptDto> deptDtos) { Set<Long> deptIds = deptDtos.stream().map(DeptDto::getId).collect(Collectors.toSet()); if(userRepository.countByDepts(deptIds) > 0){ throw new BadRequestException("所选部门存在用户关联,请解除后再试!"); } if(roleRepository.countByDepts(deptIds) > 0){ throw new BadRequestException("所选部门存在角色关联,请解除后再试!");
} } private void updateSubCnt(Long deptId){ if(deptId != null){ int count = deptRepository.countByPid(deptId); deptRepository.updateSubCntById(count, deptId); } } private List<DeptDto> deduplication(List<DeptDto> list) { List<DeptDto> deptDtos = new ArrayList<>(); for (DeptDto deptDto : list) { boolean flag = true; for (DeptDto dto : list) { if (dto.getId().equals(deptDto.getPid())) { flag = false; break; } } if (flag){ deptDtos.add(deptDto); } } return deptDtos; } /** * 清理缓存 * @param id / */ public void delCaches(Long id){ List<User> users = userRepository.findByRoleDeptId(id); // 删除数据权限 redisUtils.delByKeys(CacheKey.DATA_USER, users.stream().map(User::getId).collect(Collectors.toSet())); redisUtils.del(CacheKey.DEPT_ID + id); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DeptServiceImpl.java
2
请完成以下Java代码
public String toString() { return "TrxCallableWithTrxName-wrapper[" + trxRunnable + "]"; } @Override public Void call(final String localTrxName) throws Exception { trxRunnable.run(localTrxName); return null; } @Override public Void call() throws Exception { throw new IllegalStateException("This method shall not be called"); } @Override public boolean doCatch(final Throwable e) throws Throwable { throw e; } @Override public void doFinally() { // nothing } }; } public static TrxCallableWithTrxName<Void> wrapIfNeeded(final TrxRunnable2 trxRunnable) { if (trxRunnable == null) { return null; } return new TrxCallableWithTrxName<Void>() { @Override public String toString() { return "TrxCallableWithTrxName-wrapper[" + trxRunnable + "]"; } @Override public Void call(final String localTrxName) throws Exception { trxRunnable.run(localTrxName); return null; } @Override public Void call() throws Exception { throw new IllegalStateException("This method shall not be called"); } @Override public boolean doCatch(final Throwable e) throws Throwable { return trxRunnable.doCatch(e); } @Override public void doFinally() { trxRunnable.doFinally(); } }; } public static <T> TrxCallable<T> wrapIfNeeded(final Callable<T> callable) { if (callable == null) { return null; }
if (callable instanceof TrxCallable) { final TrxCallable<T> trxCallable = (TrxCallable<T>)callable; return trxCallable; } return new TrxCallableAdapter<T>() { @Override public String toString() { return "TrxCallableWrappers[" + callable + "]"; } @Override public T call() throws Exception { return callable.call(); } }; } public static <T> TrxCallableWithTrxName<T> wrapAsTrxCallableWithTrxNameIfNeeded(final TrxCallable<T> callable) { if (callable == null) { return null; } if (callable instanceof TrxCallableWithTrxName) { final TrxCallableWithTrxName<T> callableWithTrxName = (TrxCallableWithTrxName<T>)callable; return callableWithTrxName; } return new TrxCallableWithTrxName<T>() { @Override public String toString() { return "TrxCallableWithTrxName-wrapper[" + callable + "]"; } @Override public T call(final String localTrxName) throws Exception { return callable.call(); } @Override public T call() throws Exception { throw new IllegalStateException("This method shall not be called"); } @Override public boolean doCatch(final Throwable e) throws Throwable { return callable.doCatch(e); } @Override public void doFinally() { callable.doFinally(); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxCallableWrappers.java
1
请完成以下Java代码
protected Optional<String> getSwiftCode() { return Optional.ofNullable(accountStatement2.getAcct().getSvcr()) .map(branchAndFinancialInstitutionIdentification4 -> branchAndFinancialInstitutionIdentification4.getFinInstnId().getBIC()) .filter(Check::isNotBlank); } @Override @NonNull protected Optional<String> getAccountNo() { return Optional.ofNullable(accountStatement2.getAcct().getId().getOthr()) .map(GenericAccountIdentification1::getId); } @NonNull private IStatementLineWrapper buildBatchReportEntryWrapper(@NonNull final ReportEntry2 reportEntry) { return BatchReportEntry2Wrapper.builder() .currencyRepository(getCurrencyRepository()) .entry(reportEntry) .build(); } @NonNull private Optional<CashBalance3> findOPBDCashBalance() { return accountStatement2.getBal() .stream() .filter(AccountStatement2Wrapper::isOPBDCashBalance) .findFirst(); } @NonNull private Optional<CashBalance3> findPRCDCashBalance() {
return accountStatement2.getBal() .stream() .filter(AccountStatement2Wrapper::isPRCDCashBalance) .findFirst(); } private static boolean isPRCDCashBalance(@NonNull final CashBalance3 cashBalance) { final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd(); return BalanceType12Code.PRCD.equals(balanceTypeCode); } private static boolean isOPBDCashBalance(@NonNull final CashBalance3 cashBalance) { final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd(); return BalanceType12Code.OPBD.equals(balanceTypeCode); } private static boolean isCRDTCashBalance(@NonNull final CashBalance3 cashBalance) { return CRDT.equals(cashBalance.getCdtDbtInd()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\AccountStatement2Wrapper.java
1
请完成以下Java代码
private static String buildMessage(final I_M_PriceList_Version plv, final int productId) { final StringBuilder sb = new StringBuilder("@NotFound@ @M_ProductPrice_ID@"); // // Product final I_M_Product product = productId > 0 ? loadOutOfTrx(productId, I_M_Product.class) : null; sb.append("\n@M_Product_ID@: ").append(product == null ? "<" + productId + ">" : product.getName()); // // Price List Version sb.append("\n@M_PriceList_Version_ID@: ").append(plv == null ? "-" : plv.getName()); // // Price List
final I_M_PriceList priceList = plv == null ? null : Services.get(IPriceListDAO.class).getById(PriceListId.ofRepoId(plv.getM_PriceList_ID())); sb.append("\n@M_PriceList_ID@: ").append(priceList == null ? "-" : priceList.getName()); // // Pricing System final PricingSystemId pricingSystemId = priceList != null ? PricingSystemId.ofRepoIdOrNull(priceList.getM_PricingSystem_ID()) : null; final String pricingSystemName = pricingSystemId != null ? Services.get(IPriceListDAO.class).getPricingSystemName(pricingSystemId) : "-"; sb.append("\n@M_PricingSystem_ID@: ").append(pricingSystemName); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\pricing\exceptions\ProductNotOnPriceListException.java
1
请完成以下Java代码
public void setStrategy(Integer strategy) { this.strategy = strategy; } public String getRefResource() { return refResource; } public void setRefResource(String refResource) { this.refResource = refResource; } public Integer getControlBehavior() { return controlBehavior; } public void setControlBehavior(Integer controlBehavior) { this.controlBehavior = controlBehavior; } public Integer getWarmUpPeriodSec() { return warmUpPeriodSec; } public void setWarmUpPeriodSec(Integer warmUpPeriodSec) { this.warmUpPeriodSec = warmUpPeriodSec; } public Integer getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public void setMaxQueueingTimeMs(Integer maxQueueingTimeMs) { this.maxQueueingTimeMs = maxQueueingTimeMs; } public boolean isClusterMode() { return clusterMode; } public FlowRuleEntity setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; return this; } public ClusterFlowConfig getClusterConfig() { return clusterConfig; } public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) { this.clusterConfig = clusterConfig; return this; }
@Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public FlowRule toRule() { FlowRule flowRule = new FlowRule(); flowRule.setCount(this.count); flowRule.setGrade(this.grade); flowRule.setResource(this.resource); flowRule.setLimitApp(this.limitApp); flowRule.setRefResource(this.refResource); flowRule.setStrategy(this.strategy); if (this.controlBehavior != null) { flowRule.setControlBehavior(controlBehavior); } if (this.warmUpPeriodSec != null) { flowRule.setWarmUpPeriodSec(warmUpPeriodSec); } if (this.maxQueueingTimeMs != null) { flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); } flowRule.setClusterMode(clusterMode); flowRule.setClusterConfig(clusterConfig); return flowRule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java
1
请在Spring Boot框架中完成以下Java代码
protected void applyToResource(ClassPathResource resource, RuntimeHints hints) { super.applyToResource(resource, hints); BpmnXMLConverter xmlConverter = new BpmnXMLConverter(); BpmnModel bpmnModel = xmlConverter.convertToBpmnModel(() -> { try { return resource.getInputStream(); } catch (IOException e) { throw new UncheckedIOException("Failed to read resource " + resource, e); } }, false, false); Collection<ServiceTask> serviceTasks = bpmnModel.getMainProcess().findFlowElementsOfType(ServiceTask.class); for (ServiceTask serviceTask : serviceTasks) { if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType())) { String expression = serviceTask.getImplementation(); String expressionWithoutDelimiters = expression.substring(2); expressionWithoutDelimiters = expressionWithoutDelimiters.substring(0, expressionWithoutDelimiters.length() - 1); String beanName = expressionWithoutDelimiters; try { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); String beanClassName = beanDefinition.getBeanClassName(); if (StringUtils.isNotEmpty(beanClassName)) {
hints.reflection().registerType(TypeReference.of(beanClassName), MemberCategory.values()); logger.debug("Registering hint for bean name [{}] for service task {} in {}", beanName, serviceTask.getId(), resource); } else { logger.debug("No bean class name for bean name [{}] for service task {} in {}", beanName, serviceTask.getId(), resource); } } catch (Throwable throwable) { logger.error("Couldn't find bean named [{}] for service task {} in {}", beanName, serviceTask.getId(), resource); } } } } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\aot\process\FlowableProcessAutoDeployBeanFactoryInitializationAotProcessor.java
2
请完成以下Java代码
public class Interval { int start; int end; Interval(int start, int end) { this.start = start; this.end = end; } public void setEnd(int end) { this.end = end; } @Override public String toString() { return "Interval{" + "start=" + start + ", end=" + end + '}'; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Interval interval = (Interval) o; return start == interval.start && end == interval.end; } @Override public int hashCode() { return Objects.hash(start, end); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\mergeintervals\Interval.java
1
请完成以下Java代码
public class SparkplugTopicService { private static final Map<String, SparkplugTopic> SPLIT_TOPIC_CACHE = new HashMap<>(); public static final String TOPIC_ROOT_SPB_V_1_0 = "spBv1.0"; public static final String TOPIC_ROOT_CERT_SP = "$sparkplug/certificates/"; public static final String TOPIC_SPLIT_REGEXP = "/"; public static final String TOPIC_STATE_REGEXP = TOPIC_ROOT_SPB_V_1_0 + TOPIC_SPLIT_REGEXP + STATE.name() + TOPIC_SPLIT_REGEXP; public static SparkplugTopic getSplitTopic(String topic) throws ThingsboardException { SparkplugTopic sparkplugTopic = SPLIT_TOPIC_CACHE.get(topic); if (sparkplugTopic == null) { // validation topic sparkplugTopic = parseTopic(topic); SPLIT_TOPIC_CACHE.put(topic, sparkplugTopic); } return sparkplugTopic; }
/** * all ID Element MUST be a UTF-8 string * and with the exception of the reserved characters of + (plus), / (forward slash). * Publish: $sparkplug/certificates/spBv1.0/G1/NBIRTH/E1 * Publish: spBv1.0/G1/NBIRTH/E1 * Publish: $sparkplug/certificates/spBv1.0/G1/DBIRTH/E1/D1 * Publish: spBv1.0/G1/DBIRTH/E1/D1 * @param topic * @return * @throws ThingsboardException */ public static SparkplugTopic parseTopicPublish(String topic) throws ThingsboardException { topic = topic.startsWith(TOPIC_ROOT_CERT_SP) ? topic.substring(TOPIC_ROOT_CERT_SP.length()) : topic; topic = topic.indexOf("+") > 0 ? topic.substring(0, topic.indexOf("+")): topic; return getSplitTopic(topic); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugTopicService.java
1