instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class WEBUI_M_InOut_Shipment_SelectHUs extends JavaProcess implements IProcessPrecondition { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final I_M_InOut shipment = context.getSelectedModel(I_M_InOut.class); // guard against null (might happen if the selected ID is not valid) if (shipment == null) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return checkEligibleForHUsSelection(shipment); } /** * @return true if given shipment is eligible for HU selection */ public static ProcessPreconditionsResolution checkEligibleForHUsSelection(final I_M_InOut shipment) { // shipment must be completed or closed closed final String docStatus = shipment.getDocStatus(); if (!(docStatus.equals(X_M_InOut.DOCSTATUS_Completed) || docStatus.equals(X_M_InOut.DOCSTATUS_Closed))) { return ProcessPreconditionsResolution.reject("shipment not completed"); } final List<I_M_HU> shipmentHandlingUnits = Services.get(IHUInOutDAO.class).retrieveShippedHandlingUnits(shipment);
if (shipmentHandlingUnits.isEmpty()) { return ProcessPreconditionsResolution.reject("shipment has no handling units assigned"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final I_M_InOut shipment = getRecord(I_M_InOut.class); final List<I_M_HU> shipmentHandlingUnits = Services.get(IHUInOutDAO.class).retrieveShippedHandlingUnits(shipment); getResult().setRecordToOpen(RecordsToOpen.builder() .records(TableRecordReference.ofCollection(shipmentHandlingUnits)) .adWindowId(null) .target(RecordsToOpen.OpenTarget.GridView) .targetTab(RecordsToOpen.TargetTab.SAME_TAB_OVERLAY) .automaticallySetReferencingDocumentPaths(true) .useAutoFilters(false) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_InOut_Shipment_SelectHUs.java
1
请在Spring Boot框架中完成以下Java代码
public class PaginationFormatting { private PaginationMultiTypeValuesHelper multiValue = new PaginationMultiTypeValuesHelper(); private Map<String, PaginationMultiTypeValuesHelper> results = new HashMap<>(); public Map<String, PaginationMultiTypeValuesHelper> filterQuery(String sex, String email, Pageable pageable) { Types typeInstance; if (sex.length() == 0 && email.length() == 0) { typeInstance = new AllType(sex, email, pageable); } else if (sex.length() > 0 && email.length() > 0) { typeInstance = new SexEmailType(sex, email, pageable); } else { typeInstance = new SexType(sex, email, pageable);
} this.multiValue.setCount(typeInstance.getCount()); this.multiValue.setPage(typeInstance.getPageNumber() + 1); this.multiValue.setResults(typeInstance.getContent()); this.multiValue.setTotal(typeInstance.getTotal()); this.results.put("data", this.multiValue); return results; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\controller\pagination\PaginationFormatting.java
2
请在Spring Boot框架中完成以下Java代码
public class EncryptionConfig { @Value("${com.baeldung.csfle.master-key-path}") private String masterKeyPath; @Value("${com.baeldung.csfle.key-vault.namespace}") private String keyVaultNamespace; @Value("${com.baeldung.csfle.key-vault.alias}") private String keyVaultAlias; @Value("${com.baeldung.csfle.auto-decryption:false}") private boolean autoDecryption; @Value("${com.baeldung.csfle.auto-encryption:false}") private boolean autoEncryption; @Value("${com.baeldung.csfle.auto-encryption-lib:#{null}}") private File autoEncryptionLib; private BsonBinary dataKeyId; public void setDataKeyId(BsonBinary dataKeyId) { this.dataKeyId = dataKeyId; } public BsonBinary getDataKeyId() { return dataKeyId; } public String getKeyVaultNamespace() { return keyVaultNamespace; } public String getKeyVaultAlias() { return keyVaultAlias; } public String getMasterKeyPath() {
return masterKeyPath; } public boolean isAutoDecryption() { return autoDecryption; } public boolean isAutoEncryption() { return autoEncryption; } public File getAutoEncryptionLib() { return autoEncryptionLib; } public String dataKeyIdUuid() { if (dataKeyId == null) throw new IllegalStateException("data key not initialized"); return dataKeyId.asUuid() .toString(); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-3\src\main\java\com\baeldung\boot\csfle\config\EncryptionConfig.java
2
请完成以下Java代码
public BigDecimal getSum() { return sum; } /** * Sets the value of the sum property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSum(BigDecimal value) { this.sum = value; } /** * Gets the value of the ttlNetNtry property. * * @return * possible object is * {@link AmountAndDirection35 } * */
public AmountAndDirection35 getTtlNetNtry() { return ttlNetNtry; } /** * Sets the value of the ttlNetNtry property. * * @param value * allowed object is * {@link AmountAndDirection35 } * */ public void setTtlNetNtry(AmountAndDirection35 value) { this.ttlNetNtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\NumberAndSumOfTransactions4.java
1
请在Spring Boot框架中完成以下Java代码
class InfluxPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<InfluxProperties> implements InfluxConfig { InfluxPropertiesConfigAdapter(InfluxProperties properties) { super(properties); } @Override public String prefix() { return "management.influx.metrics.export"; } @Override public String db() { return obtain(InfluxProperties::getDb, InfluxConfig.super::db); } @Override public InfluxConsistency consistency() { return obtain(InfluxProperties::getConsistency, InfluxConfig.super::consistency); } @Override public @Nullable String userName() { return get(InfluxProperties::getUserName, InfluxConfig.super::userName); } @Override public @Nullable String password() { return get(InfluxProperties::getPassword, InfluxConfig.super::password); } @Override public @Nullable String retentionPolicy() { return get(InfluxProperties::getRetentionPolicy, InfluxConfig.super::retentionPolicy); } @Override public @Nullable Integer retentionReplicationFactor() { return get(InfluxProperties::getRetentionReplicationFactor, InfluxConfig.super::retentionReplicationFactor); } @Override public @Nullable String retentionDuration() { return get(InfluxProperties::getRetentionDuration, InfluxConfig.super::retentionDuration);
} @Override public @Nullable String retentionShardDuration() { return get(InfluxProperties::getRetentionShardDuration, InfluxConfig.super::retentionShardDuration); } @Override public String uri() { return obtain(InfluxProperties::getUri, InfluxConfig.super::uri); } @Override public boolean compressed() { return obtain(InfluxProperties::isCompressed, InfluxConfig.super::compressed); } @Override public boolean autoCreateDb() { return obtain(InfluxProperties::isAutoCreateDb, InfluxConfig.super::autoCreateDb); } @Override public InfluxApiVersion apiVersion() { return obtain(InfluxProperties::getApiVersion, InfluxConfig.super::apiVersion); } @Override public @Nullable String org() { return get(InfluxProperties::getOrg, InfluxConfig.super::org); } @Override public String bucket() { return obtain(InfluxProperties::getBucket, InfluxConfig.super::bucket); } @Override public @Nullable String token() { return get(InfluxProperties::getToken, InfluxConfig.super::token); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxPropertiesConfigAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public class AssignableInvoiceCandidateRepository { private AssignableInvoiceCandidateFactory assignableInvoiceCandidateFactory; public AssignableInvoiceCandidateRepository( @NonNull final AssignableInvoiceCandidateFactory assignableInvoiceCandidateFactory) { this.assignableInvoiceCandidateFactory = assignableInvoiceCandidateFactory; } public AssignableInvoiceCandidate getById(@NonNull final InvoiceCandidateId id) { final I_C_Invoice_Candidate invoiceCandidateRecord = load(id.getRepoId(), I_C_Invoice_Candidate.class); return assignableInvoiceCandidateFactory.ofRecord(invoiceCandidateRecord); } public AssignableInvoiceCandidate ofRecord(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return assignableInvoiceCandidateFactory.ofRecord(invoiceCandidateRecord); } public Iterator<AssignableInvoiceCandidate> getAllAssigned( @NonNull final RefundInvoiceCandidate refundInvoiceCandidate) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Candidate_Assignment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Term_ID, refundInvoiceCandidate.getId().getRepoId()) .andCollect( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Assigned_ID, I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .create()
.stream() .map(assignableInvoiceCandidateFactory::ofRecord) .iterator(); } /** * In production, assignable invoice candidates are created elsewhere and are only loaded if they are relevant for refund contracts. * That's why this method is intended only for (unit-)testing. */ @VisibleForTesting public AssignableInvoiceCandidate saveNew(@NonNull final AssignableInvoiceCandidate assignableCandidate) { final I_C_Invoice_Candidate assignableCandidateRecord = newInstance(I_C_Invoice_Candidate.class); saveRecord(assignableCandidateRecord); return assignableCandidate .toBuilder() .id(InvoiceCandidateId.ofRepoId(assignableCandidateRecord.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidateRepository.java
2
请完成以下Java代码
public static String getDataScopeType() { List<Long> dataScopes = getCurrentUserDataScope(); if(CollUtil.isEmpty(dataScopes)){ return ""; } return DataScopeEnum.ALL.getValue(); } /** * 获取用户ID * @return 系统用户ID */ public static Long getCurrentUserId() { return getCurrentUserId(getToken()); } /** * 获取用户ID * @return 系统用户ID */ public static Long getCurrentUserId(String token) { JWT jwt = JWTUtil.parseToken(token); return Long.valueOf(jwt.getPayload("userId").toString()); } /** * 获取系统用户名称 * * @return 系统用户名称 */ public static String getCurrentUsername() { return getCurrentUsername(getToken()); } /** * 获取系统用户名称 *
* @return 系统用户名称 */ public static String getCurrentUsername(String token) { JWT jwt = JWTUtil.parseToken(token); return jwt.getPayload("sub").toString(); } /** * 获取Token * @return / */ public static String getToken() { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder .getRequestAttributes())).getRequest(); String bearerToken = request.getHeader(header); if (bearerToken != null && bearerToken.startsWith(tokenStartWith)) { // 去掉令牌前缀 return bearerToken.replace(tokenStartWith, ""); } else { log.debug("非法Token:{}", bearerToken); } return null; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SecurityUtils.java
1
请完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getZone() { return zone; } public void setZone(String zone) { this.zone = zone; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\entities\Persons.java
1
请在Spring Boot框架中完成以下Java代码
public String getGLN() { return gln; } /** * Sets the value of the gln property. * * @param value * allowed object is * {@link String } * */ public void setGLN(String value) { this.gln = value; } /** * Gets the value of the storeGLN property. * * @return * possible object is * {@link String } * */ public String getStoreGLN() { return storeGLN; } /** * Sets the value of the storeGLN property. * * @param value * allowed object is * {@link String } * */ public void setStoreGLN(String value) {
this.storeGLN = value; } /** * Gets the value of the lookupLabel property. * * @return * possible object is * {@link String } * */ public String getLookupLabel() { return lookupLabel; } /** * Sets the value of the lookupLabel property. * * @param value * allowed object is * {@link String } * */ public void setLookupLabel(String value) { this.lookupLabel = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EDICBPartnerLookupBPLGLNVType.java
2
请在Spring Boot框架中完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" salesId: ").append(toIndentedString(salesId)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" rootId: ").append(toIndentedString(rootId)).append("\n"); sb.append(" creationDate: ").append(toIndentedString(creationDate)).append("\n"); sb.append(" deliveryDate: ").append(toIndentedString(deliveryDate)).append("\n"); sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); sb.append(" dayOfDelivery: ").append(toIndentedString(dayOfDelivery)).append("\n"); sb.append(" nextDelivery: ").append(toIndentedString(nextDelivery)).append("\n"); sb.append(" deliveryAddress: ").append(toIndentedString(deliveryAddress)).append("\n"); sb.append(" doctorId: ").append(toIndentedString(doctorId)).append("\n"); sb.append(" hospitalId: ").append(toIndentedString(hospitalId)).append("\n"); sb.append(" pharmacyId: ").append(toIndentedString(pharmacyId)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeIds: ").append(toIndentedString(therapyTypeIds)).append("\n"); sb.append(" isInitialCare: ").append(toIndentedString(isInitialCare)).append("\n"); sb.append(" orderedArticleLines: ").append(toIndentedString(orderedArticleLines)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" isSeriesOrder: ").append(toIndentedString(isSeriesOrder)).append("\n"); sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n"); sb.append(" deliveryInformation: ").append(toIndentedString(deliveryInformation)).append("\n"); sb.append(" deliveryNote: ").append(toIndentedString(deliveryNote)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\Order.java
2
请在Spring Boot框架中完成以下Java代码
public class QuarkusProcessEngineConfiguration extends CdiJtaProcessEngineConfiguration { /** * Default values. */ public QuarkusProcessEngineConfiguration() { setJobExecutorActivate(true); setJdbcUrl(null); setJdbcUsername(null); setJdbcPassword(null); setJdbcDriver(null); setDatabaseSchemaUpdate(DB_SCHEMA_UPDATE_TRUE); // automatic schema update setTransactionsExternallyManaged(true); setIdGenerator(new StrongUuidGenerator()); setHistory(HistoryLevel.HISTORY_LEVEL_FULL.getName()); // Cockpit needs it } /** * We need to make sure, that the root command always calls {@link TransactionManager#begin} in its interceptor chain * since Agroal does not support deferred/lazy enlistment. This is why we override this method to add * the {@link JakartaTransactionInterceptor} to the interceptor chain.
*/ @Override protected void initCommandExecutorDbSchemaOperations() { if (commandExecutorSchemaOperations == null) { List<CommandInterceptor> commandInterceptorsDbSchemaOperations = new ArrayList<>(); commandInterceptorsDbSchemaOperations.add(new LogInterceptor()); commandInterceptorsDbSchemaOperations.add(new CommandCounterInterceptor(this)); commandInterceptorsDbSchemaOperations.add(new JakartaTransactionInterceptor(transactionManager, false, this)); commandInterceptorsDbSchemaOperations.add(new CommandContextInterceptor(dbSchemaOperationsCommandContextFactory, this)); commandInterceptorsDbSchemaOperations.add(actualCommandExecutor); commandExecutorSchemaOperations = initInterceptorChain(commandInterceptorsDbSchemaOperations); } } }
repos\camunda-bpm-platform-master\quarkus-extension\engine\runtime\src\main\java\org\camunda\bpm\quarkus\engine\extension\QuarkusProcessEngineConfiguration.java
2
请完成以下Java代码
public GroupQuery createGroupQuery() { return new DbGroupQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutorTxRequired()); } public GroupQuery createGroupQuery(CommandContext commandContext) { return new DbGroupQueryImpl(); } public long findGroupCountByQueryCriteria(DbGroupQueryImpl query) { configureQuery(query, Resources.GROUP); return (Long) getDbEntityManager().selectOne("selectGroupCountByQueryCriteria", query); } public List<Group> findGroupByQueryCriteria(DbGroupQueryImpl query) { configureQuery(query, Resources.GROUP); return getDbEntityManager().selectList("selectGroupByQueryCriteria", query); } //tenants ////////////////////////////////////////// public TenantEntity findTenantById(String tenantId) { checkAuthorization(Permissions.READ, Resources.TENANT, tenantId); return getDbEntityManager().selectById(TenantEntity.class, tenantId); } public TenantQuery createTenantQuery() { return new DbTenantQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutorTxRequired()); } public TenantQuery createTenantQuery(CommandContext commandContext) { return new DbTenantQueryImpl(); } public long findTenantCountByQueryCriteria(DbTenantQueryImpl query) { configureQuery(query, Resources.TENANT); return (Long) getDbEntityManager().selectOne("selectTenantCountByQueryCriteria", query); } public List<Tenant> findTenantByQueryCriteria(DbTenantQueryImpl query) { configureQuery(query, Resources.TENANT); return getDbEntityManager().selectList("selectTenantByQueryCriteria", query); } //memberships ////////////////////////////////////////// protected boolean existsMembership(String userId, String groupId) { Map<String, String> key = new HashMap<>(); key.put("userId", userId); key.put("groupId", groupId); return ((Long) getDbEntityManager().selectOne("selectMembershipCount", key)) > 0; } protected boolean existsTenantMembership(String tenantId, String userId, String groupId) { Map<String, String> key = new HashMap<>();
key.put("tenantId", tenantId); if (userId != null) { key.put("userId", userId); } if (groupId != null) { key.put("groupId", groupId); } return ((Long) getDbEntityManager().selectOne("selectTenantMembershipCount", key)) > 0; } //authorizations //////////////////////////////////////////////////// @Override protected void configureQuery(@SuppressWarnings("rawtypes") AbstractQuery query, Resource resource) { Context.getCommandContext() .getAuthorizationManager() .configureQuery(query, resource); } @Override protected void checkAuthorization(Permission permission, Resource resource, String resourceId) { Context.getCommandContext() .getAuthorizationManager() .checkAuthorization(permission, resource, resourceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbReadOnlyIdentityServiceProvider.java
1
请完成以下Java代码
public CmmnModelInstance getCmmnModelInstance() { if(caseDefinitionId != null) { return Context.getProcessEngineConfiguration() .getDeploymentCache() .findCmmnModelInstanceForCaseDefinition(caseDefinitionId); } else { return null; } } public CmmnElement getCmmnModelElementInstance() { CmmnModelInstance cmmnModelInstance = getCmmnModelInstance(); if(cmmnModelInstance != null) { ModelElementInstance modelElementInstance = cmmnModelInstance.getModelElementById(activityId); try { return (CmmnElement) modelElementInstance; } catch(ClassCastException e) { ModelElementType elementType = modelElementInstance.getElementType(); throw new ProcessEngineException("Cannot cast "+modelElementInstance+" to CmmnElement. " + "Is of type "+elementType.getTypeName() + " Namespace " + elementType.getTypeNamespace(), e); }
} else { return null; } } public ProcessEngineServices getProcessEngineServices() { return Context .getProcessEngineConfiguration() .getProcessEngine(); } public ProcessEngine getProcessEngine() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public String getCaseDefinitionTenantId() { CaseDefinitionEntity caseDefinition = (CaseDefinitionEntity) getCaseDefinition(); return caseDefinition.getTenantId(); } public <T extends CoreExecution> void performOperation(CoreAtomicOperation<T> operation) { Context.getCommandContext() .performOperation((CmmnAtomicOperation) operation, this); } public <T extends CoreExecution> void performOperationSync(CoreAtomicOperation<T> operation) { Context.getCommandContext() .performOperation((CmmnAtomicOperation) operation, this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionEntity.java
1
请在Spring Boot框架中完成以下Java代码
private Instant now() {return SystemTime.asInstant();} /** * Return a cached access token or fetch one and assume that it's going to be valid for {@link #EXPIRING_DURATION}. * We can later use the actual validity-duration from the API response when we come across a case where that info is actually provided. */ public OAuthAccessToken getAccessToken(@NonNull OAuthAccessTokenRequest request) { final OAuthAccessToken cachedToken = accessTokensCache.getIfPresent(request.getIdentity()); if (cachedToken != null && !cachedToken.isExpired(now())) { return cachedToken; } // Fetch new token final OAuthAccessToken newToken = fetchNewAccessToken(request); accessTokensCache.put(request.getIdentity(), newToken); return newToken; } /** * If a token is known to be invalid, it can be removed from the cache with this method */ public void invalidateToken(@NonNull OAuthIdentity identity) { accessTokensCache.invalidate(identity); accessTokensCache.cleanUp(); } private OAuthAccessToken fetchNewAccessToken(@NonNull final OAuthAccessTokenRequest request) { try { final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON)); httpHeaders.setContentType(MediaType.APPLICATION_JSON); final Map<String, String> formData = createFormData(request); final ResponseEntity<String> response = restTemplate.postForEntity( request.getIdentity().getTokenUrl(), new HttpEntity<>(jsonObjectMapper.writeValueAsString(formData), httpHeaders), String.class); final JsonNode jsonNode = jsonObjectMapper.readTree(response.getBody()); final String accessToken = jsonNode.get("bearer").asText(); return OAuthAccessToken.of(accessToken, now().plus(EXPIRING_DURATION)); } catch (final JsonProcessingException e) { throw new RuntimeCamelException("Failed to parse OAuth token response", e); } } @NonNull private static Map<String, String> createFormData(@NonNull final OAuthAccessTokenRequest request) { final Map<String, String> formData = new HashMap<>(); if (Check.isNotBlank(request.getIdentity().getClientId()))
{ formData.put("client_id", request.getIdentity().getClientId()); } if (Check.isNotBlank(request.getClientSecret())) { formData.put("client_secret", request.getClientSecret()); } if (Check.isNotBlank(request.getIdentity().getUsername())) { formData.put("email", request.getIdentity().getUsername()); } if (Check.isNotBlank(request.getPassword())) { formData.put("password", request.getPassword()); } return formData; } @Value @Builder private static class CacheKey { @NonNull String tokenUrl; @Nullable String clientId; @Nullable String username; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\oauth\OAuthTokenManager.java
2
请完成以下Java代码
void heapifyFromLastLeafsParent() { int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length); while (lastLeafsParentIndex >= 0) { heapify(lastLeafsParentIndex); lastLeafsParentIndex--; } } void heapify(int index) { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { smallestElementIndex = leftNodeIndex; } if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { smallestElementIndex = rightNodeIndex; } if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); } } int getParentNodeIndex(int index) { return (index - 1) / 2; } int getLeftNodeIndex(int index) { return (2 * index + 1); } int getRightNodeIndex(int index) { return (2 * index + 2); } HeapNode getRootNode() { return heapNodes[0]; } void heapifyFromRoot() { heapify(0); } void swap(int i, int j) { HeapNode temp = heapNodes[i];
heapNodes[i] = heapNodes[j]; heapNodes[j] = temp; } static int[] merge(int[][] array) { HeapNode[] heapNodes = new HeapNode[array.length]; int resultingArraySize = 0; for (int i = 0; i < array.length; i++) { HeapNode node = new HeapNode(array[i][0], i); heapNodes[i] = node; resultingArraySize += array[i].length; } MinHeap minHeap = new MinHeap(heapNodes); int[] resultingArray = new int[resultingArraySize]; for (int i = 0; i < resultingArraySize; i++) { HeapNode root = minHeap.getRootNode(); resultingArray[i] = root.element; if (root.nextElementIndex < array[root.arrayIndex].length) { root.element = array[root.arrayIndex][root.nextElementIndex++]; } else { root.element = Integer.MAX_VALUE; } minHeap.heapifyFromRoot(); } return resultingArray; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\minheapmerge\MinHeap.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() {
return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
repos\tutorials-master\persistence-modules\deltaspike\src\main\java\baeldung\model\Member.java
1
请完成以下Java代码
public class MigrationInstructionJsonConverter extends JsonObjectConverter<MigrationInstruction> { public static final MigrationInstructionJsonConverter INSTANCE = new MigrationInstructionJsonConverter(); public static final String SOURCE_ACTIVITY_IDS = "sourceActivityIds"; public static final String TARGET_ACTIVITY_IDS = "targetActivityIds"; public static final String UPDATE_EVENT_TRIGGER = "updateEventTrigger"; public JsonObject toJsonObject(MigrationInstruction instruction) { JsonObject json = JsonUtil.createObject(); JsonUtil.addArrayField(json, SOURCE_ACTIVITY_IDS, new String[]{instruction.getSourceActivityId()}); JsonUtil.addArrayField(json, TARGET_ACTIVITY_IDS, new String[]{instruction.getTargetActivityId()}); JsonUtil.addField(json, UPDATE_EVENT_TRIGGER, instruction.isUpdateEventTrigger()); return json; } public MigrationInstruction toObject(JsonObject json) { return new MigrationInstructionImpl( readSourceActivityId(json),
readTargetActivityId(json), JsonUtil.getBoolean(json, UPDATE_EVENT_TRIGGER) ); } protected String readSourceActivityId(JsonObject json) { return JsonUtil.getString(JsonUtil.getArray(json, SOURCE_ACTIVITY_IDS)); } protected String readTargetActivityId(JsonObject json) { return JsonUtil.getString(JsonUtil.getArray(json, TARGET_ACTIVITY_IDS)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\json\MigrationInstructionJsonConverter.java
1
请完成以下Java代码
public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; } /** * Gets the value of the ccy property. * * @return * possible object is
* {@link ActiveOrHistoricCurrencyCodeEUR } * */ public ActiveOrHistoricCurrencyCodeEUR getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyCodeEUR } * */ public void setCcy(ActiveOrHistoricCurrencyCodeEUR value) { this.ccy = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\ActiveOrHistoricCurrencyAndAmountSEPA.java
1
请完成以下Java代码
public void setRef_M_PackagingTreeItem_ID (int Ref_M_PackagingTreeItem_ID) { if (Ref_M_PackagingTreeItem_ID < 1) set_Value (COLUMNNAME_Ref_M_PackagingTreeItem_ID, null); else set_Value (COLUMNNAME_Ref_M_PackagingTreeItem_ID, Integer.valueOf(Ref_M_PackagingTreeItem_ID)); } /** Get Ref Packaging Tree Item. @return Ref Packaging Tree Item */ @Override public int getRef_M_PackagingTreeItem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_M_PackagingTreeItem_ID); if (ii == null) return 0; return ii.intValue(); } /** Status AD_Reference_ID=540165 */ public static final int STATUS_AD_Reference_ID=540165; /** Ready = R */ public static final String STATUS_Ready = "R"; /** Packed = P */ public static final String STATUS_Packed = "P"; /** Partially Packed = PP */ public static final String STATUS_PartiallyPacked = "PP"; /** UnPacked = UP */ public static final String STATUS_UnPacked = "UP"; /** Open = O */ public static final String STATUS_Open = "O"; /** Set Status. @param Status Status */ @Override public void setStatus (String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status */ @Override public String getStatus () { return (String)get_Value(COLUMNNAME_Status); } /** Type AD_Reference_ID=540166 */ public static final int TYPE_AD_Reference_ID=540166; /** Box = B */ public static final String TYPE_Box = "B"; /** PackedItem = PI */ public static final String TYPE_PackedItem = "PI"; /** UnPackedItem = UI */ public static final String TYPE_UnPackedItem = "UI"; /** AvailableBox = AB */
public static final String TYPE_AvailableBox = "AB"; /** NonItem = NI */ public static final String TYPE_NonItem = "NI"; /** Set Art. @param Type Art */ @Override public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public String getType () { return (String)get_Value(COLUMNNAME_Type); } /** Set Gewicht. @param Weight Gewicht eines Produktes */ @Override public void setWeight (BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } /** Get Gewicht. @return Gewicht eines Produktes */ @Override public BigDecimal getWeight () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Weight); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTreeItem.java
1
请完成以下Java代码
public class PaymentData { private String paymentReference; private String type; private BigDecimal amount; private Currency currency; public String getPaymentReference() { return paymentReference; } public void setPaymentReference(String paymentReference) { this.paymentReference = paymentReference; } public String getType() { return type; } public void setType(String type) { this.type = type; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) {
this.amount = amount; } public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } @Override public String toString() { return new StringJoiner(", ", PaymentData.class.getSimpleName() + "[", "]") .add("paymentReference='" + paymentReference + "'") .add("type='" + type + "'") .add("amount=" + amount) .add("currency=" + currency) .toString(); } }
repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\multipletopics\PaymentData.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){ Result<List<Map<String,Object>>> res = new Result<>(); try { // 当前文件系统类 FileSystemView fsv = FileSystemView.getFileSystemView(); // 列出所有windows 磁盘 File[] fs = File.listRoots(); log.info("查询磁盘信息:"+fs.length+"个"); List<Map<String,Object>> list = new ArrayList<>(); for (int i = 0; i < fs.length; i++) { if(fs[i].getTotalSpace()==0) { continue; } Map<String,Object> map = new HashMap(5);
map.put("name", fsv.getSystemDisplayName(fs[i])); map.put("max", fs[i].getTotalSpace()); map.put("rest", fs[i].getFreeSpace()); map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace()); list.add(map); log.info(map.toString()); } res.setResult(list); res.success("查询成功"); } catch (Exception e) { res.error500("查询失败"+e.getMessage()); } return res; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\controller\ActuatorRedisController.java
2
请在Spring Boot框架中完成以下Java代码
public class BankAccountAcct { @NonNull BankAccountId bankAccountId; @NonNull AcctSchemaId acctSchemaId; @NonNull Account B_Asset_Acct; @NonNull Account B_UnallocatedCash_Acct; @NonNull Account B_InTransit_Acct; @NonNull Account B_PaymentSelect_Acct; @NonNull Account B_InterestRev_Acct; @NonNull Account B_InterestExp_Acct; @NonNull Account PayBankFee_Acct; @NonNull Account RealizedGain_Acct; @NonNull Account RealizedLoss_Acct; @NonNull Optional<Account> Payment_WriteOff_Acct; @NonNull public Optional<Account> getAccount(@NonNull final BankAccountAcctType acctType) { switch (acctType) { // // Account Type - Payment case B_UnallocatedCash_Acct: return Optional.of(B_UnallocatedCash_Acct);
case B_InTransit_Acct: return Optional.of(B_InTransit_Acct); case B_PaymentSelect_Acct: return Optional.of(B_PaymentSelect_Acct); case PayBankFee_Acct: return Optional.of(PayBankFee_Acct); // // Account Type - Bank Statement case B_Asset_Acct: return Optional.of(B_Asset_Acct); case B_InterestRev_Acct: return Optional.of(B_InterestRev_Acct); case B_InterestExp_Acct: return Optional.of(B_InterestExp_Acct); case RealizedGain_Acct: return Optional.of(RealizedGain_Acct); case RealizedLoss_Acct: return Optional.of(RealizedLoss_Acct); case Payment_WriteOff_Acct: return Payment_WriteOff_Acct; // default: throw new AdempiereException("Unknown account type: " + acctType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\accounting\BankAccountAcct.java
2
请完成以下Java代码
private UserNotificationRequest createUserNotification(@NonNull final I_M_InOut inout) { final I_C_BPartner bpartner = InterfaceWrapperHelper.load(inout.getC_BPartner_ID(), I_C_BPartner.class); final String bpValue = bpartner.getValue(); final String bpName = bpartner.getName(); final AdMessageKey adMessage = getNotificationAD_Message(inout); final UserId recipientUserId = getNotificationRecipientUserId(inout); final TableRecordReference inoutRef = TableRecordReference.of(inout); return newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(adMessage) .contentADMessageParam(inoutRef) .contentADMessageParam(bpValue) .contentADMessageParam(bpName) .targetAction(TargetRecordAction.ofRecordAndWindow(inoutRef, getWindowId(inout))) .build(); } private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC); } private AdWindowId getWindowId(final I_M_InOut inout) { return inout.isSOTrx() ? WINDOW_RETURN_FROM_CUSTOMER : WINDOW_RETURN_TO_VENDOR; } private AdMessageKey getNotificationAD_Message(final I_M_InOut inout) {return inout.isSOTrx() ? MSG_Event_RETURN_FROM_CUSTOMER_Generated : MSG_Event_RETURN_TO_VENDOR_Generated;} private UserId getNotificationRecipientUserId(final I_M_InOut inout) { //
// In case of reversal i think we shall notify the current user too final DocStatus docStatus = DocStatus.ofCode(inout.getDocStatus()); if (docStatus.isReversedOrVoided()) { final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user if (currentUserId > 0) { return UserId.ofRepoId(currentUserId); } return UserId.ofRepoId(inout.getUpdatedBy()); // last updated } // // Fallback: notify only the creator else { return UserId.ofRepoId(inout.getCreatedBy()); } } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\ReturnInOutUserNotificationsProducer.java
1
请在Spring Boot框架中完成以下Java代码
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (conflictedBeanNames.contains(beanName) && bean instanceof ServiceConfig) { ServiceConfig serviceConfig = (ServiceConfig) bean; if (isConflictedServiceConfig(serviceConfig)) { // Set id as the bean name serviceConfig.setId(beanName); } } return bean; } private boolean isConflictedServiceConfig(ServiceConfig serviceConfig) { return Objects.equals(serviceConfig.getId(), serviceConfig.getInterface()); } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } /**
* Keep the order being higher than {@link CommonAnnotationBeanPostProcessor#getOrder()} that is * {@link Ordered#LOWEST_PRECEDENCE} * * @return {@link Ordered#LOWEST_PRECEDENCE} +1 */ @Override public int getOrder() { return LOWEST_PRECEDENCE + 1; } @Override public void destroy() throws Exception { interfaceNamesToBeanNames.clear(); conflictedBeanNames.clear(); } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\beans\factory\config\ServiceBeanIdConflictProcessor.java
2
请完成以下Java代码
public style addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public style addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public style addElement(Element element) { addElementToRegistry(element); return(this); }
/** Adds an Element to the element. @param element Adds an Element to the element. */ public style addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public style removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\style.java
1
请完成以下Java代码
public Criteria andAttendTypeNotIn(List<String> values) { addCriterion("attend_type not in", values, "attendType"); return (Criteria) this; } public Criteria andAttendTypeBetween(String value1, String value2) { addCriterion("attend_type between", value1, value2, "attendType"); return (Criteria) this; } public Criteria andAttendTypeNotBetween(String value1, String value2) { addCriterion("attend_type not between", value1, value2, "attendType"); 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\CmsTopicExample.java
1
请在Spring Boot框架中完成以下Java代码
public class NotificationService { private final List<NotificationChannel> notificationChannels; private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(); @Value("${monitoring.notifications.message_prefix}") private String messagePrefix; public List<? extends Future<?>> sendNotification(Notification notification) { String message; if (StringUtils.isEmpty(messagePrefix)) { message = notification.getText(); } else { message = messagePrefix + " " + notification.getText(); } return notificationChannels.stream().map(notificationChannel -> notificationExecutor.submit(() -> { try { notificationChannel.sendNotification(message); } catch (Exception e) { log.error("Failed to send notification to {}", notificationChannel.getClass().getSimpleName(), e);
} }) ).toList(); } @PreDestroy public void shutdownExecutor() { try { notificationExecutor.shutdown(); if (!notificationExecutor.awaitTermination(10, TimeUnit.SECONDS)) { var dropped = notificationExecutor.shutdownNow(); log.warn("Notification executor did not terminate in time. Forced shutdown; {} task(s) will not be executed.", dropped.size()); } } catch (InterruptedException e) { var dropped = notificationExecutor.shutdownNow(); Thread.currentThread().interrupt(); log.warn("Interrupted during notification executor shutdown. Forced shutdown; {} task(s) will not be executed.", dropped.size()); } catch (Exception e) { log.warn("Unexpected error while shutting down notification executor", e); } } }
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\notification\NotificationService.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isEnableAutoRegionLookup() { return this.enableAutoRegionLookup; } public void setEnableAutoRegionLookup(boolean enableAutoRegionLookup) { this.enableAutoRegionLookup = enableAutoRegionLookup; } public float getEvictionHeapPercentage() { return this.evictionHeapPercentage; } public void setEvictionHeapPercentage(float evictionHeapPercentage) { this.evictionHeapPercentage = evictionHeapPercentage; } public float getEvictionOffHeapPercentage() { return this.evictionOffHeapPercentage; } public void setEvictionOffHeapPercentage(float evictionOffHeapPercentage) { this.evictionOffHeapPercentage = evictionOffHeapPercentage; } public String getLogLevel() { return this.logLevel; } public void setLogLevel(String logLevel) { this.logLevel = logLevel; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public OffHeapProperties getOffHeap() { return this.offHeap; } public PeerCacheProperties getPeer() { return this.peer; } public CacheServerProperties getServer() { return this.server; } public static class CompressionProperties { private String compressorBeanName; private String[] regionNames = {}; public String getCompressorBeanName() { return this.compressorBeanName; } public void setCompressorBeanName(String compressorBeanName) { this.compressorBeanName = compressorBeanName; } public String[] getRegionNames() {
return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } public static class OffHeapProperties { private String memorySize; private String[] regionNames = {}; public String getMemorySize() { return this.memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class JsonOrderLineGroup { @ApiModelProperty(value = "All JsonOLCandCreateRequests with the same ExternalHeaderId and the same groupId shall belong to the same bundle (compensation-group)") @JsonInclude(NON_NULL) String groupKey; @ApiModelProperty(value = "If true, marks the associated as the \"main\" product. Should only be set to true for non-stocked products.") @JsonInclude(NON_NULL) boolean isGroupMainItem; @ApiModelProperty( // value = "Translates to C_OLCand.GroupCompensationDiscountPercentage") @JsonInclude(NON_NULL) BigDecimal discount; @ApiModelProperty( // value = "It is taken into consideration when C_OLCand.Line is renumbered. Translates to C_OLCand.CompensationGroupOrderBy") @JsonInclude(NON_NULL) JsonGroupCompensationOrderBy ordering;
@Builder public JsonOrderLineGroup(@JsonProperty("groupKey") final @Nullable String groupKey, @JsonProperty("groupMainItem") final boolean isGroupMainItem, @JsonProperty("discount") final @Nullable BigDecimal discount, @JsonProperty("ordering") final @Nullable JsonGroupCompensationOrderBy ordering) { if (!isGroupMainItem && discount != null) { throw new RuntimeException("Discount can only be set for the group's main item! (i.e. groupMainItem = true ) "); } this.groupKey = groupKey; this.isGroupMainItem = isGroupMainItem; this.discount = discount; this.ordering = ordering; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v2\request\JsonOrderLineGroup.java
2
请完成以下Java代码
public int getAD_BusinessRule_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID); } @Override public void setAD_Record_Warning_ID (final int AD_Record_Warning_ID) { if (AD_Record_Warning_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Record_Warning_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Record_Warning_ID, AD_Record_Warning_ID); } @Override public int getAD_Record_Warning_ID() { return get_ValueAsInt(COLUMNNAME_AD_Record_Warning_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setIsAcknowledged (final boolean IsAcknowledged) { set_Value (COLUMNNAME_IsAcknowledged, IsAcknowledged); } @Override public boolean isAcknowledged() { return get_ValueAsBoolean(COLUMNNAME_IsAcknowledged); } @Override public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() {
return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRoot_AD_Table_ID (final int Root_AD_Table_ID) { if (Root_AD_Table_ID < 1) set_Value (COLUMNNAME_Root_AD_Table_ID, null); else set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID); } @Override public int getRoot_AD_Table_ID() { return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID); } @Override public void setRoot_Record_ID (final int Root_Record_ID) { if (Root_Record_ID < 1) set_Value (COLUMNNAME_Root_Record_ID, null); else set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID); } @Override public int getRoot_Record_ID() { return get_ValueAsInt(COLUMNNAME_Root_Record_ID); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity) { set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
1
请完成以下Java代码
public void addMigratingDependentInstance(MigratingInstance migratingInstance) { } @Override public ExecutionEntity resolveRepresentativeExecution() { return null; } @Override public void attachState(MigratingScopeInstance targetActivityInstance) { setParent(targetActivityInstance); ExecutionEntity representativeExecution = targetActivityInstance.resolveRepresentativeExecution(); eventSubscription.setExecution(representativeExecution); } @Override
public void setParent(MigratingScopeInstance parentInstance) { if (this.parentInstance != null) { this.parentInstance.removeChild(this); } this.parentInstance = parentInstance; if (parentInstance != null) { parentInstance.addChild(this); } } public void remove() { eventSubscription.delete(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingCompensationEventSubscriptionInstance.java
1
请在Spring Boot框架中完成以下Java代码
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepositoryBean( B builder) { Map<String, OAuth2AuthorizedClientRepository> authorizedClientRepositoryMap = BeanFactoryUtils .beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientRepository.class); if (authorizedClientRepositoryMap.size() > 1) { throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientRepository.class, authorizedClientRepositoryMap.size(), "Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName() + "' but found " + authorizedClientRepositoryMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientRepositoryMap.keySet())); } return (!authorizedClientRepositoryMap.isEmpty() ? authorizedClientRepositoryMap.values().iterator().next() : null); } private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientService( B builder) { OAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientServiceBean(builder); if (authorizedClientService == null) { authorizedClientService = new InMemoryOAuth2AuthorizedClientService( getClientRegistrationRepository(builder)); } return authorizedClientService; } private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean( B builder) { Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils .beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientService.class); if (authorizedClientServiceMap.size() > 1) { throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class, authorizedClientServiceMap.size(), "Expected single matching bean of type '" + OAuth2AuthorizedClientService.class.getName()
+ "' but found " + authorizedClientServiceMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientServiceMap.keySet())); } return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null); } static <B extends HttpSecurityBuilder<B>> OidcSessionRegistry getOidcSessionRegistry(B builder) { OidcSessionRegistry sessionRegistry = builder.getSharedObject(OidcSessionRegistry.class); if (sessionRegistry != null) { return sessionRegistry; } ApplicationContext context = builder.getSharedObject(ApplicationContext.class); if (context.getBeanNamesForType(OidcSessionRegistry.class).length == 1) { sessionRegistry = context.getBean(OidcSessionRegistry.class); } else { sessionRegistry = new InMemoryOidcSessionRegistry(); } builder.setSharedObject(OidcSessionRegistry.class, sessionRegistry); return sessionRegistry; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OAuth2ClientConfigurerUtils.java
2
请完成以下Java代码
public class BitMaskUtil { // First 8 masks as constant to prevent having to math.pow() every time a // bit needs flipping. private static final int FLAG_BIT_1 = 1; // 000...00000001 private static final int FLAG_BIT_2 = 2; // 000...00000010 private static final int FLAG_BIT_3 = 4; // 000...00000100 private static final int FLAG_BIT_4 = 8; // 000...00001000 private static final int FLAG_BIT_5 = 16; // 000...00010000 private static final int FLAG_BIT_6 = 32; // 000...00100000 private static final int FLAG_BIT_7 = 64; // 000...01000000 private static final int FLAG_BIT_8 = 128; // 000...10000000 private static int[] MASKS = { FLAG_BIT_1, FLAG_BIT_2, FLAG_BIT_3, FLAG_BIT_4, FLAG_BIT_5, FLAG_BIT_6, FLAG_BIT_7, FLAG_BIT_8, }; /** * Set bit to '1' in the given int. * * @param current * integer value * @param bitNumber * number of the bit to set to '1' (right first bit starting at 1). */ public static int setBitOn(int value, int bitNumber) { if (bitNumber <= 0 || bitNumber > 8) { throw new IllegalArgumentException("Only bits 1 through 8 are supported"); } // To turn on, OR with the correct mask return value | MASKS[bitNumber - 1]; } /** * Set bit to '0' in the given int. * * @param current * integer value * @param bitNumber * number of the bit to set to '0' (right first bit starting at 1). */ public static int setBitOff(int value, int bitNumber) { if (bitNumber <= 0 || bitNumber > 8) { throw new IllegalArgumentException("Only bits 1 through 8 are supported"); } // To turn on, OR with the correct mask return value & ~MASKS[bitNumber - 1]; } /** * Check if the bit is set to '1'
* * @param value * integer to check bit * @param number * of bit to check (right first bit starting at 1) */ public static boolean isBitOn(int value, int bitNumber) { if (bitNumber <= 0 || bitNumber > 8) { throw new IllegalArgumentException("Only bits 1 through 8 are supported"); } return ((value & MASKS[bitNumber - 1]) == MASKS[bitNumber - 1]); } /** * Set bit to '0' or '1' in the given int. * * @param current * integer value * @param bitNumber * number of the bit to set to '0' or '1' (right first bit starting at 1). * @param bitValue * if true, bit set to '1'. If false, '0'. */ public static int setBit(int value, int bitNumber, boolean bitValue) { if (bitValue) { return setBitOn(value, bitNumber); } else { return setBitOff(value, bitNumber); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\BitMaskUtil.java
1
请完成以下Java代码
public void setAttributes2 (final java.lang.String Attributes2) { set_Value (COLUMNNAME_Attributes2, Attributes2); } @Override public java.lang.String getAttributes2() { return get_ValueAsString(COLUMNNAME_Attributes2); } @Override public void setC_BPartner_QuickInput_Attributes2_ID (final int C_BPartner_QuickInput_Attributes2_ID) { if (C_BPartner_QuickInput_Attributes2_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID, C_BPartner_QuickInput_Attributes2_ID); } @Override public int getC_BPartner_QuickInput_Attributes2_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID); }
@Override public org.compiere.model.I_C_BPartner_QuickInput getC_BPartner_QuickInput() { return get_ValueAsPO(COLUMNNAME_C_BPartner_QuickInput_ID, org.compiere.model.I_C_BPartner_QuickInput.class); } @Override public void setC_BPartner_QuickInput(final org.compiere.model.I_C_BPartner_QuickInput C_BPartner_QuickInput) { set_ValueFromPO(COLUMNNAME_C_BPartner_QuickInput_ID, org.compiere.model.I_C_BPartner_QuickInput.class, C_BPartner_QuickInput); } @Override public void setC_BPartner_QuickInput_ID (final int C_BPartner_QuickInput_ID) { if (C_BPartner_QuickInput_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_ID, C_BPartner_QuickInput_ID); } @Override public int getC_BPartner_QuickInput_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput_Attributes2.java
1
请完成以下Java代码
public CacheGetException setTargetObject(final Object targetObject) { this.targetObject = targetObject; resetMessageBuilt(); return this; } public CacheGetException setMethodArguments(final Object[] methodArgs) { this.methodArgs = methodArgs; resetMessageBuilt(); return this; } public CacheGetException setInvalidParameter(final int parameterIndex, final Object parameter) { this.parameterIndex = parameterIndex; this.parameter = parameter; this.parameterSet = true;
resetMessageBuilt(); return this; } public CacheGetException setAnnotation(final Class<? extends Annotation> annotation) { this.annotationType = annotation; return this; } public CacheGetException addSuppressIfNotNull(final Throwable exception) { if(exception != null) { addSuppressed(exception); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheGetException.java
1
请在Spring Boot框架中完成以下Java代码
public class JmxManagedThreadPool extends SeExecutorService implements JmxManagedThreadPoolMBean, PlatformService<JmxManagedThreadPool> { private final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER; protected final BlockingQueue<Runnable> threadPoolQueue; public JmxManagedThreadPool(BlockingQueue<Runnable> queue, ThreadPoolExecutor executor) { super(executor); threadPoolQueue = queue; } public void start(PlatformServiceContainer mBeanServiceContainer) { // nothing to do } public void stop(PlatformServiceContainer mBeanServiceContainer) { // clear the queue threadPoolQueue.clear(); // Ask the thread pool to finish and exit threadPoolExecutor.shutdown(); // Waits for 1 minute to finish all currently executing jobs try { if(!threadPoolExecutor.awaitTermination(60L, TimeUnit.SECONDS)) { LOG.timeoutDuringShutdownOfThreadPool(60, TimeUnit.SECONDS); } } catch (InterruptedException e) { LOG.interruptedWhileShuttingDownThreadPool(e); } } public JmxManagedThreadPool getValue() { return this; } public void setCorePoolSize(int corePoolSize) { threadPoolExecutor.setCorePoolSize(corePoolSize); } public void setMaximumPoolSize(int maximumPoolSize) { threadPoolExecutor.setMaximumPoolSize(maximumPoolSize); }
public int getMaximumPoolSize() { return threadPoolExecutor.getMaximumPoolSize(); } public void setKeepAliveTime(long time, TimeUnit unit) { threadPoolExecutor.setKeepAliveTime(time, unit); } public void purgeThreadPool() { threadPoolExecutor.purge(); } public int getPoolSize() { return threadPoolExecutor.getPoolSize(); } public int getActiveCount() { return threadPoolExecutor.getActiveCount(); } public int getLargestPoolSize() { return threadPoolExecutor.getLargestPoolSize(); } public long getTaskCount() { return threadPoolExecutor.getTaskCount(); } public long getCompletedTaskCount() { return threadPoolExecutor.getCompletedTaskCount(); } public int getQueueCount() { return threadPoolQueue.size(); } public int getQueueAddlCapacity() { return threadPoolQueue.remainingCapacity(); } public ThreadPoolExecutor getThreadPoolExecutor() { return threadPoolExecutor; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedThreadPool.java
2
请完成以下Java代码
protected String doIt() throws Exception { final HUEditorRow row = getSingleSelectedRow(); final I_M_HU sourceLUorTU = row.getM_HU(); final HUsToNewTUsRequest request = HUsToNewTUsRequest.forSourceHuAndQty(sourceLUorTU, qtyTUs); final List<I_M_HU> extractedTUs = HUTransformService.newInstance().husToNewTUs(request).toHURecords(); if (extractedTUs.isEmpty()) { throw new AdempiereException("@NoSelection@"); } final PPOrderLinesView ppOrderView = getPPOrderView().get(); final PPOrderId ppOrderId = ppOrderView.getPpOrderId(); final HUPPOrderIssueProducer issueProducer = huPPOrderBL.createIssueProducer(ppOrderId);
final PPOrderBOMLineId selectedOrderBOMLineId = getSelectedOrderBOMLineId(); if (selectedOrderBOMLineId != null) { issueProducer.targetOrderBOMLine(selectedOrderBOMLineId); } issueProducer.createIssues(extractedTUs); getView().invalidateAll(); ppOrderView.invalidateAll(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_HUEditor_IssueTUs.java
1
请在Spring Boot框架中完成以下Java代码
private static class AmountSourceAndAcct { @NonNull CurrencyAndRate currencyAndRate; @NonNull BigDecimal amtSource; @NonNull BigDecimal amtAcct; public static AmountSourceAndAcct zero(@NonNull final CurrencyAndRate currencyAndRate) { return builder().currencyAndRate(currencyAndRate).amtSource(BigDecimal.ZERO).amtAcct(BigDecimal.ZERO).build(); } public boolean isZero() { return amtSource.signum() == 0 && amtAcct.signum() == 0; } public boolean isZeroAmtSource() { return amtSource.signum() == 0; } public AmountSourceAndAcct negate() { return isZero() ? this : toBuilder().amtSource(this.amtSource.negate()).amtAcct(this.amtAcct.negate()).build(); } public AmountSourceAndAcct add(@NonNull final AmountSourceAndAcct other) { assertCurrencyAndRateMatching(other); if (other.isZero())
{ return this; } else if (this.isZero()) { return other; } else { return toBuilder() .amtSource(this.amtSource.add(other.amtSource)) .amtAcct(this.amtAcct.add(other.amtAcct)) .build(); } } public AmountSourceAndAcct subtract(@NonNull final AmountSourceAndAcct other) { return add(other.negate()); } private void assertCurrencyAndRateMatching(@NonNull final AmountSourceAndAcct other) { if (!Objects.equals(this.currencyAndRate, other.currencyAndRate)) { throw new AdempiereException("Currency rate not matching: " + this.currencyAndRate + ", " + other.currencyAndRate); } } } } // Doc_Bank
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\Doc_BankStatement.java
2
请完成以下Java代码
public <ID extends RepoIdAware> ImmutableSet<ID> getRecordIdsToRefresh( @NonNull final DocumentIdsSelection rowIds, @NonNull final Function<DocumentId, ID> idMapper) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } else if (rowIds.isAll()) { return Stream.concat(this.rowIds.stream(), this.initialRowIds.stream()) .map(idMapper) .collect(ImmutableSet.toImmutableSet()); } else {
return rowIds.stream() .filter(this::isRelevantForRefreshing) .map(idMapper) .collect(ImmutableSet.toImmutableSet()); } } public Stream<T> stream() {return rowsById.values().stream();} public Stream<T> stream(final Predicate<T> predicate) {return rowsById.values().stream().filter(predicate);} public long count(final Predicate<T> predicate) {return rowsById.values().stream().filter(predicate).count();} public boolean anyMatch(final Predicate<T> predicate) {return rowsById.values().stream().anyMatch(predicate);} public List<T> list() {return rowIds.stream().map(rowsById::get).collect(ImmutableList.toImmutableList());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\ImmutableRowsIndex.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerNameAndGreetingStrategies { private static final Logger logger = LogManager.getLogger(BPartnerNameAndGreetingStrategies.class); private final ImmutableMap<BPartnerNameAndGreetingStrategyId, BPartnerNameAndGreetingStrategy> strategiesById; public BPartnerNameAndGreetingStrategies( @NonNull final Optional<List<BPartnerNameAndGreetingStrategy>> strategies) { this.strategiesById = strategies .map(list -> Maps.uniqueIndex(list, BPartnerNameAndGreetingStrategy::getId)) .orElseGet(ImmutableMap::of); logger.info("Strategies: {}", this.strategiesById); } public ExplainedOptional<NameAndGreeting> compute( @NonNull final BPartnerNameAndGreetingStrategyId strategyId,
@NonNull final ComputeNameAndGreetingRequest request) { return getStrategyById(strategyId).compute(request); } private BPartnerNameAndGreetingStrategy getStrategyById(@NonNull final BPartnerNameAndGreetingStrategyId strategyId) { final BPartnerNameAndGreetingStrategy strategy = strategiesById.get(strategyId); if (strategy == null) { throw new AdempiereException("No strategy found for ID=" + strategyId); } return strategy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\name\strategy\BPartnerNameAndGreetingStrategies.java
2
请完成以下Java代码
public Object getOldValue() { return oldValue; } public Object getNewValue() { return newValue; } public String getEventType() { return eventType; } public int getAD_User_ID() { return AD_User_ID; } public PInstanceId getAD_PInstance_ID() { return AD_PInstance_ID; } public static final class Builder { private int AD_Session_ID; private String trxName; private int AD_Table_ID; private int AD_Column_ID; private int record_ID; private int AD_Client_ID; private int AD_Org_ID; private Object oldValue; private Object newValue; private String eventType; private int AD_User_ID; private PInstanceId AD_PInstance_ID; private Builder() { super(); } public ChangeLogRecord build() { return new ChangeLogRecord(this); } public Builder setAD_Session_ID(final int AD_Session_ID) { this.AD_Session_ID = AD_Session_ID; return this; } public Builder setTrxName(final String trxName) { this.trxName = trxName; return this; } public Builder setAD_Table_ID(final int AD_Table_ID) { this.AD_Table_ID = AD_Table_ID; return this; } public Builder setAD_Column_ID(final int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public Builder setRecord_ID(final int record_ID) { this.record_ID = record_ID; return this; }
public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) { this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请完成以下Java代码
public class SplitFloatingPointNumbers { public static void main(String[] args) { double doubleNumber = 24.04; splitUsingFloatingTypes(doubleNumber); splitUsingString(doubleNumber); splitUsingBigDecimal(doubleNumber); } private static void splitUsingFloatingTypes(double doubleNumber) { System.out.println("Using Floating Point Arithmetics:"); int intPart = (int) doubleNumber; System.out.println("Double Number: "+doubleNumber); System.out.println("Integer Part: "+ intPart); System.out.println("Decimal Part: "+ (doubleNumber - intPart)); }
private static void splitUsingString(double doubleNumber) { System.out.println("Using String Operations:"); String doubleAsString = String.valueOf(doubleNumber); int indexOfDecimal = doubleAsString.indexOf("."); System.out.println("Double Number: "+doubleNumber); System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal)); System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal)); } private static void splitUsingBigDecimal(double doubleNumber) { System.out.println("Using BigDecimal Operations:"); BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber)); int intValue = bigDecimal.intValue(); System.out.println("Double Number: "+bigDecimal.toPlainString()); System.out.println("Integer Part: "+intValue); System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString()); } }
repos\tutorials-master\core-java-modules\core-java-lang-math\src\main\java\com\baeldung\doubles\SplitFloatingPointNumbers.java
1
请完成以下Java代码
public TimerEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new TimerEventDefinitionImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); timeDateChild = sequenceBuilder.element(TimeDate.class) .build(); timeDurationChild = sequenceBuilder.element(TimeDuration.class) .build(); timeCycleChild = sequenceBuilder.element(TimeCycle.class) .build(); typeBuilder.build(); } public TimerEventDefinitionImpl(ModelTypeInstanceContext context) { super(context); } public TimeDate getTimeDate() { return timeDateChild.getChild(this); }
public void setTimeDate(TimeDate timeDate) { timeDateChild.setChild(this, timeDate); } public TimeDuration getTimeDuration() { return timeDurationChild.getChild(this); } public void setTimeDuration(TimeDuration timeDuration) { timeDurationChild.setChild(this, timeDuration); } public TimeCycle getTimeCycle() { return timeCycleChild.getChild(this); } public void setTimeCycle(TimeCycle timeCycle) { timeCycleChild.setChild(this, timeCycle); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TimerEventDefinitionImpl.java
1
请完成以下Java代码
private static DateTimeTranslatableString ofTime(@NonNull final LocalTime time) { final Instant instant = LocalDate.now() .atTime(time) .atZone(SystemTime.zoneId()) .toInstant(); return new DateTimeTranslatableString(instant, DisplayType.Time); } static DateTimeTranslatableString ofObject(@NonNull final Object obj) { return ofObject(obj, -1); } static DateTimeTranslatableString ofObject(@NonNull final Object obj, final int displayType) { if (obj instanceof java.util.Date) { final java.util.Date date = (java.util.Date)obj; if (displayType == DisplayType.Date) { return ofDate(date); } else if (displayType == DisplayType.DateTime) { return ofDateTime(date); } else // default: { return ofDateTime(date); } } else if (obj instanceof LocalDate) { return ofDate((LocalDate)obj); } else if (obj instanceof LocalTime) { return ofTime((LocalTime)obj); } else if (obj instanceof LocalDateTime) { return ofDateTime((LocalDateTime)obj); } else if (obj instanceof Instant) { return ofDateTime((Instant)obj); } else if (obj instanceof ZonedDateTime) { return ofDateTime((ZonedDateTime)obj); } else if (obj instanceof InstantAndOrgId) { return ofDateTime(((InstantAndOrgId)obj).toInstant()); } else if (obj instanceof LocalDateAndOrgId) { return ofDate(((LocalDateAndOrgId)obj).toLocalDate()); } else { throw new AdempiereException("Cannot create " + DateTimeTranslatableString.class + " from " + obj + " (" + obj.getClass() + ")"); } } private final Instant instant; private final int displayType; private DateTimeTranslatableString(@NonNull final Instant instant, final boolean dateTime) { this(instant, dateTime ? DisplayType.DateTime : DisplayType.Date); } private DateTimeTranslatableString(@NonNull final Instant instant, final int displayType) {
this.instant = instant; this.displayType = displayType; } @Override @Deprecated public String toString() { return getDefaultValue(); } @Override public String translate(final String adLanguage) { final Language language = Language.getLanguage(adLanguage); final SimpleDateFormat dateFormat = DisplayType.getDateFormat(displayType, language); dateFormat.setTimeZone(TimeZone.getTimeZone(SystemTime.zoneId())); return dateFormat.format(toDate()); } private java.util.Date toDate() { return java.util.Date.from(instant); } @Override public String getDefaultValue() { final SimpleDateFormat dateFormat = DisplayType.getDateFormat(displayType); dateFormat.setTimeZone(TimeZone.getTimeZone(SystemTime.zoneId())); return dateFormat.format(toDate()); } @Override public Set<String> getAD_Languages() { return ImmutableSet.of(); } @Override public boolean isTranslatedTo(final String adLanguage) { return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\DateTimeTranslatableString.java
1
请完成以下Java代码
abstract class AggregateBinder<T> { private final Context context; AggregateBinder(Context context) { this.context = context; } /** * Determine if recursive binding is supported. * @param source the configuration property source or {@code null} for all sources. * @return if recursive binding is supported */ protected abstract boolean isAllowRecursiveBinding(@Nullable ConfigurationPropertySource source); /** * Perform binding for the aggregate. * @param name the configuration property name to bind * @param target the target to bind * @param elementBinder an element binder * @return the bound aggregate or null */ @SuppressWarnings("unchecked") final @Nullable Object bind(ConfigurationPropertyName name, Bindable<?> target, AggregateElementBinder elementBinder) { Object result = bindAggregate(name, target, elementBinder); Supplier<?> value = target.getValue(); if (result == null || value == null) { return result; } return merge((Supplier<T>) value, (T) result); } /** * Perform the actual aggregate binding. * @param name the configuration property name to bind * @param target the target to bind * @param elementBinder an element binder * @return the bound result */ protected abstract @Nullable Object bindAggregate(ConfigurationPropertyName name, Bindable<?> target, AggregateElementBinder elementBinder); /** * Merge any additional elements into the existing aggregate. * @param existing the supplier for the existing value * @param additional the additional elements to merge * @return the merged result */ protected abstract T merge(Supplier<T> existing, T additional); /** * Return the context being used by this binder. * @return the context */ protected final Context getContext() { return this.context; } /**
* Internal class used to supply the aggregate and cache the value. * * @param <T> the aggregate type */ protected static class AggregateSupplier<T> { private final Supplier<T> supplier; private @Nullable T supplied; public AggregateSupplier(Supplier<T> supplier) { this.supplier = supplier; } public T get() { if (this.supplied == null) { this.supplied = this.supplier.get(); } return this.supplied; } public boolean wasSupplied() { return this.supplied != null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\AggregateBinder.java
1
请完成以下Java代码
private static void setDaysOfWeek(@NonNull final I_C_BP_PurchaseSchedule scheduleRecord, @NonNull final ImmutableSet<DayOfWeek> daysOfWeek) { if (daysOfWeek.contains(DayOfWeek.MONDAY)) { scheduleRecord.setOnMonday(true); } if (daysOfWeek.contains(DayOfWeek.TUESDAY)) { scheduleRecord.setOnTuesday(true); } if (daysOfWeek.contains(DayOfWeek.WEDNESDAY)) { scheduleRecord.setOnWednesday(true); } if (daysOfWeek.contains(DayOfWeek.THURSDAY)) { scheduleRecord.setOnThursday(true);
} if (daysOfWeek.contains(DayOfWeek.FRIDAY)) { scheduleRecord.setOnFriday(true); } if (daysOfWeek.contains(DayOfWeek.SATURDAY)) { scheduleRecord.setOnSaturday(true); } if (daysOfWeek.contains(DayOfWeek.SUNDAY)) { scheduleRecord.setOnSunday(true); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\BPPurchaseScheduleRepository.java
1
请在Spring Boot框架中完成以下Java代码
public boolean monthBetween(final int monthOneBased, final Date dateStart, final Date dateEnd) { if (monthOneBased < 1 || monthOneBased > 12) { throw new IllegalArgumentException("Invalid month value '" + monthOneBased + "'. It shall be between 1 and 12."); } // convert the "one based" month (i.e. Jan=1) to "zero based" (i.e. Jan=0) final int month = monthOneBased - 1; logger.trace("Evaluating monthBetween: month(zero based)={}, date={} -> {}", month, dateStart, dateEnd); @SuppressWarnings("deprecation") final int fromMonth = dateStart == null ? Calendar.JANUARY : dateStart.getMonth(); if (month < fromMonth) { logger.trace("Not between because month is before start date"); return false; } @SuppressWarnings("deprecation") final int toMonth = dateEnd == null ? Calendar.DECEMBER : dateEnd.getMonth(); if (month > toMonth) { logger.trace("Not between because month is after end date"); return false; } logger.trace("Returning true because month is between given dates"); return true; } /** * @param month month (1-Jan, 2-Feb ... 12-Dec) * @param year year (2000, ... 2016) * @param dateStart date or null; null will be ignored * @param dateEnd date or null; null will be ignored * @return true if given <code>month</code> and <code>year</code> is between given dates */ public boolean monthBetween(final int monthOneBased, final int year, final Date dateStart, final Date dateEnd) { if (monthOneBased < 1 || monthOneBased > 12) { throw new IllegalArgumentException( "Invalid month value '" + monthOneBased + "'. It shall be between 1 and 12."); } final int yearFrom = dateStart == null ? year : TimeUtil.getYearFromTimestamp(dateStart); final int yearTo = dateEnd == null ? year : TimeUtil.getYearFromTimestamp(dateEnd); // if year is after endDate, false if (year > yearTo) { logger.trace("Not between because year is after endDate"); return false; } // if year is before startDate, false if (year < yearFrom) { logger.trace("Not between because year is before startDate");
return false; } // convert the "one based" month (i.e. Jan=1) to "zero based" (i.e. Jan=0) final int month = monthOneBased - 1; logger.trace("Evaluating monthBetween: month(zero based)={}, date={} -> {}", month, dateStart, dateEnd); @SuppressWarnings("deprecation") final int fromMonth = dateStart == null ? Calendar.JANUARY : dateStart.getMonth(); if ((month < fromMonth) && (year == yearFrom)) { logger.trace("Not between because month is before start date"); return false; } @SuppressWarnings("deprecation") final int toMonth = dateEnd == null ? Calendar.DECEMBER : dateEnd.getMonth(); if ((month > toMonth) && (year == yearTo)) { logger.trace("Not between because month is after end date"); return false; } logger.trace("Returning true because month is between given dates"); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JexlCustomFunctions.java
2
请完成以下Java代码
public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { if (!StringUtils.isEmpty(responseMsg.getError())) { throw new AdaptorException(responseMsg.getError()); } else { TransportApiProtos.GatewayAttributeResponseMsg.Builder responseMsgBuilder = TransportApiProtos.GatewayAttributeResponseMsg.newBuilder(); responseMsgBuilder.setDeviceName(deviceName); responseMsgBuilder.setResponseMsg(responseMsg); byte[] payloadBytes = responseMsgBuilder.build().toByteArray(); return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, payloadBytes)); } } @Override public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.AttributeUpdateNotificationMsg notificationMsg) { TransportApiProtos.GatewayAttributeUpdateNotificationMsg.Builder builder = TransportApiProtos.GatewayAttributeUpdateNotificationMsg.newBuilder(); builder.setDeviceName(deviceName); builder.setNotificationMsg(notificationMsg); byte[] payloadBytes = builder.build().toByteArray(); return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, payloadBytes)); }
@Override public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) { TransportApiProtos.GatewayDeviceRpcRequestMsg.Builder builder = TransportApiProtos.GatewayDeviceRpcRequestMsg.newBuilder(); builder.setDeviceName(deviceName); builder.setRpcRequestMsg(rpcRequest); byte[] payloadBytes = builder.build().toByteArray(); return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_RPC_TOPIC, payloadBytes)); } public static byte[] toBytes(ByteBuf inbound) { byte[] bytes = new byte[inbound.readableBytes()]; int readerIndex = inbound.readerIndex(); inbound.getBytes(readerIndex, bytes); return bytes; } private int getRequestId(String topicName, String topic) { return Integer.parseInt(topicName.substring(topic.length())); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\adaptors\ProtoMqttAdaptor.java
1
请完成以下Java代码
public int getAttributeInvoice(String pConcept) { MHRConcept concept = MHRConcept.forValue(getCtx(), pConcept); if (concept == null) { return 0; } ArrayList<Object> params = new ArrayList<>(); StringBuffer whereClause = new StringBuffer(); // check ValidFrom: whereClause.append(MHRAttribute.COLUMNNAME_ValidFrom + "<=?"); params.add(m_dateFrom); // check client whereClause.append(" AND AD_Client_ID = ?"); params.add(getAD_Client_ID()); // check concept whereClause.append(" AND EXISTS (SELECT 1 FROM HR_Concept c WHERE c.HR_Concept_ID=HR_Attribute.HR_Concept_ID" + " AND c.Value = ?)"); params.add(pConcept); // if (!MHRConcept.TYPE_Information.equals(concept.getType())) { whereClause.append(" AND " + MHRAttribute.COLUMNNAME_C_BPartner_ID + " = ?"); params.add(m_C_BPartner_ID); } MHRAttribute attribute = new Query(getCtx(), MHRAttribute.Table_Name, whereClause.toString(), get_TrxName()) .setParameters(params) .setOrderBy(MHRAttribute.COLUMNNAME_ValidFrom + " DESC") .first(); if (attribute != null) { return (Integer)attribute.get_Value("C_Invoice_ID"); } else { return 0; } } // getAttributeInvoice /** * Helper Method : Get AttributeDocType * * @param pConcept - Value to Concept * @return C_DocType_ID, 0 if does't */ public int getAttributeDocType(String pConcept) { MHRConcept concept = MHRConcept.forValue(getCtx(), pConcept); if (concept == null) { return 0; } ArrayList<Object> params = new ArrayList<>(); StringBuffer whereClause = new StringBuffer(); // check ValidFrom: whereClause.append(MHRAttribute.COLUMNNAME_ValidFrom + "<=?"); params.add(m_dateFrom); // check client whereClause.append(" AND AD_Client_ID = ?"); params.add(getAD_Client_ID()); // check concept whereClause.append(" AND EXISTS (SELECT 1 FROM HR_Concept c WHERE c.HR_Concept_ID=HR_Attribute.HR_Concept_ID" + " AND c.Value = ?)"); params.add(pConcept);
// if (!MHRConcept.TYPE_Information.equals(concept.getType())) { whereClause.append(" AND " + MHRAttribute.COLUMNNAME_C_BPartner_ID + " = ?"); params.add(m_C_BPartner_ID); } MHRAttribute attribute = new Query(getCtx(), MHRAttribute.Table_Name, whereClause.toString(), get_TrxName()) .setParameters(params) .setOrderBy(MHRAttribute.COLUMNNAME_ValidFrom + " DESC") .first(); if (attribute != null) { return (Integer)attribute.get_Value("C_DocType_ID"); } else { return 0; } } // getAttributeDocType /** * Helper Method : get days from specific period * * @param period * @return no. of days */ public double getDays(int period) { return Env.getContextAsInt(getCtx(), "_DaysPeriod") + 1; } // getDays } // MHRProcess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRProcess.java
1
请完成以下Java代码
public void assertPickedFrom() { if (!isPickedFrom()) {throw new AdempiereException("Pick from required first");} } public void assertInTransit() { assertNotDroppedTo(); assertPickedFrom(); } public void removePickedHUs() { this.pickedHUs = null; this.qtyNotPickedReason = null; updateStatus(); } public void markAsPickedFrom( @Nullable final QtyRejectedReasonCode qtyNotPickedReason, @NonNull final DDOrderMoveSchedulePickedHUs pickedHUs) { assertNotPickedFrom(); final Quantity qtyPicked = pickedHUs.getQtyPicked(); Quantity.assertSameUOM(this.qtyToPick, qtyPicked); if (qtyPicked.signum() <= 0) { throw new AdempiereException("QtyPicked must be greater than zero"); } if (!this.qtyToPick.qtyAndUomCompareToEquals(qtyPicked)) { if (qtyNotPickedReason == null) { throw new AdempiereException("Reason must be provided when not picking the whole scheduled qty"); } this.qtyNotPickedReason = qtyNotPickedReason; } else { this.qtyNotPickedReason = null; } this.pickedHUs = pickedHUs; updateStatus(); } public boolean isDropTo() { return pickedHUs != null && pickedHUs.isDroppedTo(); } public void assertNotDroppedTo() { if (isDropTo()) { throw new AdempiereException("Already Dropped To"); } } public void markAsDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{ assertInTransit(); final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this); pickedHUs.setDroppedTo(dropToLocatorId, dropToMovementId); updateStatus(); } private void updateStatus() { this.status = computeStatus(); } private DDOrderMoveScheduleStatus computeStatus() { if (isDropTo()) { return DDOrderMoveScheduleStatus.COMPLETED; } else if (isPickedFrom()) { return DDOrderMoveScheduleStatus.IN_PROGRESS; } else { return DDOrderMoveScheduleStatus.NOT_STARTED; } } @NonNull public ExplainedOptional<LocatorId> getInTransitLocatorId() { if (pickedHUs == null) { return ExplainedOptional.emptyBecause("Schedule is not picked yet"); } return pickedHUs.getInTransitLocatorId(); } @NonNull public ImmutableSet<HuId> getPickedHUIds() { final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this); return pickedHUs.getActualHUIdsPicked(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ProcessTask.class, CMMN_ELEMENT_PROCESS_TASK) .namespaceUri(CMMN11_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<ProcessTask>() { public ProcessTask newInstance(ModelTypeInstanceContext instanceContext) { return new ProcessTaskImpl(instanceContext); } }); processRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PROCESS_REF) .build(); /** camunda extensions */ camundaProcessBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_BINDING) .namespace(CAMUNDA_NS) .build(); camundaProcessVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_VERSION) .namespace(CAMUNDA_NS) .build();
camundaProcessTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_TENANT_ID) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class) .build(); processRefExpressionChild = sequenceBuilder.element(ProcessRefExpression.class) .minOccurs(0) .maxOccurs(1) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessTaskImpl.java
1
请完成以下Java代码
public void setCurrentLUTUConfiguration(final I_M_ReceiptSchedule documentLine, final I_M_HU_LUTU_Configuration lutuConfiguration) { documentLine.setM_HU_LUTU_Configuration(lutuConfiguration); } @Override public I_M_HU_LUTU_Configuration createNewLUTUConfiguration(final I_M_ReceiptSchedule documentLine) { final I_M_HU_PI_Item_Product tuPIItemProduct = getM_HU_PI_Item_Product(documentLine); final ProductId cuProductId = ProductId.ofRepoId(documentLine.getM_Product_ID()); final UomId cuUOMId = UomId.ofRepoId(documentLine.getC_UOM_ID()); final BPartnerId bpartnerId = receiptScheduleBL.getBPartnerEffectiveId(documentLine); final I_C_OrderLine orderLine = orderDAO.getOrderLineById(OrderLineId.ofRepoId(documentLine.getC_OrderLine_ID()), I_C_OrderLine.class); final I_M_HU_LUTU_Configuration lutuConfiguration = lutuFactory.createLUTUConfiguration( tuPIItemProduct, cuProductId, cuUOMId, bpartnerId, false, // noLUForVirtualTU == false => allow placing the CU (e.g. a packing material product) directly on the LU); HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID()), orderLine.getQtyLU()); // Update LU/TU configuration updateLUTUConfigurationFromDocumentLine(lutuConfiguration, documentLine); // NOTE: don't save it...we might use it as "in-memory POJO" return lutuConfiguration; } @Override public void updateLUTUConfigurationFromDocumentLine(final I_M_HU_LUTU_Configuration lutuConfiguration, final I_M_ReceiptSchedule documentLine) { Check.assumeNotNull(lutuConfiguration, "lutuConfiguration not null"); Check.assumeNotNull(documentLine, "documentLine not null"); //
// Set BPartner / Location to be used final int bpartnerId = receiptScheduleBL.getC_BPartner_Effective_ID(documentLine); final int bpartnerLocationId = receiptScheduleBL.getC_BPartner_Location_Effective_ID(documentLine); lutuConfiguration.setC_BPartner_ID(bpartnerId); lutuConfiguration.setC_BPartner_Location_ID(bpartnerLocationId); // // Set Locator final LocatorId locatorId = receiptScheduleBL.getLocatorEffectiveId(documentLine); lutuConfiguration.setM_Locator_ID(locatorId.getRepoId()); // // Set HUStatus=Planning because receipt schedules are always about planning lutuConfiguration.setHUStatus(X_M_HU.HUSTATUS_Planning); } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product(final I_M_ReceiptSchedule receiptSchedule) { final I_M_HU_PI_Item_Product tuPIItemProduct = receiptSchedule.getM_HU_PI_Item_Product(); if (tuPIItemProduct != null && tuPIItemProduct.getM_HU_PI_Item_Product_ID() > 0) { return tuPIItemProduct; } // // Fallback: return Virtual PI item final Properties ctx = InterfaceWrapperHelper.getCtx(receiptSchedule); return hupiItemProductDAO.retrieveVirtualPIMaterialItemProduct(ctx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleDocumentLUTUConfigurationHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { @Autowired private BookstoreService bookstoreService; public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { System.out.println("\n\n Fetch authors read-only entities:"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsReadOnlyEntities(); System.out.println("\n\n Fetch authors as array of objects"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsArrayOfObject(); System.out.println("\n\n Fetch authors as array of objects by specifying columns"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsArrayOfObjectColumns(); System.out.println("\n\n Fetch authors as array of objects via native query"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsArrayOfObjectNative(); System.out.println("\n\n Fetch authors as array of objects via query builder mechanism"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsArrayOfObjectQueryBuilderMechanism();
System.out.println("\n\n Fetch authors as Spring projection (DTO):"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsDtoClass(); System.out.println("\n\n Fetch authors as Spring projection (DTO) by specifying columns:"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsDtoClassColumns(); System.out.println("\n\n Fetch authors as Spring projection (DTO) and native query:"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorAsDtoClassNative(); System.out.println("\n\n Fetch authors as Spring projection (DTO) via query builder mechanism:"); System.out.println("-----------------------------------------------------------------------------"); bookstoreService.fetchAuthorByGenreAsDtoClassQueryBuilderMechanism(); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinDtoAllFields\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public Post findUsingJpql(Long id) { EntityManager entityManager = emf.createEntityManager(); EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); Post post = entityManager.createQuery("Select p from Post p where p.id=:id", Post.class) .setParameter("id", id) .setHint("jakarta.persistence.fetchgraph", entityGraph) .getSingleResult(); entityManager.close(); return post; } public Post findUsingCriteria(Long id) { EntityManager entityManager = emf.createEntityManager();
EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Post> criteriaQuery = criteriaBuilder.createQuery(Post.class); Root<Post> root = criteriaQuery.from(Post.class); criteriaQuery.where(criteriaBuilder.equal(root.<Long>get("id"), id)); TypedQuery<Post> typedQuery = entityManager.createQuery(criteriaQuery); typedQuery.setHint("jakarta.persistence.loadgraph", entityGraph); Post post = typedQuery.getSingleResult(); entityManager.close(); return post; } public void clean() { emf.close(); } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entitygraph\repo\PostRepository.java
1
请完成以下Java代码
protected Comment executeInternal(CommandContext commandContext, String processDefinitionId) { String userId = Authentication.getAuthenticatedUserId(); CommentEntity comment = commandContext.getCommentEntityManager().create(); comment.setUserId(userId); comment.setType((type == null) ? CommentEntity.TYPE_COMMENT : type); comment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime()); comment.setTaskId(taskId); comment.setProcessInstanceId(processInstanceId); comment.setAction(Event.ACTION_ADD_COMMENT); String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } comment.setMessage(eventMessage);
comment.setFullMessage(message); commandContext.getCommentEntityManager().insert(comment); return comment; } protected String getSuspendedTaskException() { return "Cannot add a comment to a suspended task"; } protected String getSuspendedExceptionMessage() { return "Cannot add a comment to a suspended execution"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddCommentCmd.java
1
请完成以下Java代码
public class MessageJobDeclaration extends JobDeclaration<AtomicOperationInvocation, MessageEntity> { public static final String ASYNC_BEFORE = "async-before"; public static final String ASYNC_AFTER = "async-after"; private static final long serialVersionUID = 1L; protected String[] operationIdentifier; public MessageJobDeclaration(String[] operationsIdentifier) { super(AsyncContinuationJobHandler.TYPE); this.operationIdentifier = operationsIdentifier; } @Override protected MessageEntity newJobInstance(AtomicOperationInvocation context) { MessageEntity message = new MessageEntity(); message.setExecution(context.getExecution()); return message; } public boolean isApplicableForOperation(AtomicOperation operation) { for (String identifier : operationIdentifier) { if (operation.getCanonicalName().equals(identifier)) { return true; } } return false; } protected ExecutionEntity resolveExecution(AtomicOperationInvocation context) { return context.getExecution(); } @Override
protected JobHandlerConfiguration resolveJobHandlerConfiguration(AtomicOperationInvocation context) { AsyncContinuationConfiguration configuration = new AsyncContinuationConfiguration(); configuration.setAtomicOperation(context.getOperation().getCanonicalName()); ExecutionEntity execution = context.getExecution(); PvmActivity activity = execution.getActivity(); if(activity != null && activity.isAsyncAfter()) { if(execution.getTransition() != null) { // store id of selected transition in case this is async after. // id is not serialized with the execution -> we need to remember it as // job handler configuration. configuration.setTransitionId(execution.getTransition().getId()); } } return configuration; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\MessageJobDeclaration.java
1
请完成以下Java代码
public class OrderedServerInterceptor implements ServerInterceptor, Ordered { private final ServerInterceptor serverInterceptor; private final int order; /** * Creates a new OrderedServerInterceptor with the given server interceptor and order. * * @param serverInterceptor The server interceptor to delegate to. * @param order The order of this interceptor. */ public OrderedServerInterceptor(final ServerInterceptor serverInterceptor, final int order) { this.serverInterceptor = requireNonNull(serverInterceptor, "serverInterceptor"); this.order = order; } @Override public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) { return this.serverInterceptor.interceptCall(call, headers, next); } @Override public int getOrder() { return this.order; } @Override public String toString() { return "OrderedServerInterceptor [interceptor=" + this.serverInterceptor + ", order=" + this.order + "]"; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\interceptor\OrderedServerInterceptor.java
1
请完成以下Java代码
public void onBeforeInvoiceLineCreated( @NonNull final I_C_InvoiceLine invoiceLine, @NonNull final IInvoiceLineRW fromInvoiceLine, @NonNull final List<I_C_Invoice_Candidate> fromCandidates) { for (final IInvoiceCandidateListener listener : listeners) { listener.onBeforeInvoiceLineCreated(invoiceLine, fromInvoiceLine, fromCandidates); } } @Override public void onBeforeInvoiceComplete( @NonNull final I_C_Invoice invoice, @NonNull final List<I_C_Invoice_Candidate> fromCandidates) {
for (final IInvoiceCandidateListener listener : listeners) { listener.onBeforeInvoiceComplete(invoice, fromCandidates); } } @Override public void onBeforeClosed(@NonNull final I_C_Invoice_Candidate candidate) { for (final IInvoiceCandidateListener listener : listeners) { listener.onBeforeClosed(candidate); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateListeners.java
1
请完成以下Java代码
public I_I_Postal retrieveImportRecord(final Properties ctx, final ResultSet rs) { return new X_I_Postal(ctx, rs, ITrx.TRXNAME_ThreadInherited); } @Override protected ImportRecordResult importRecord( @NonNull final IMutable<Object> state_NOTUSED, @NonNull final I_I_Postal importRecord, final boolean isInsertOnly_NOTUSED) { return importPostalCode(importRecord); } private ImportRecordResult importPostalCode(@NonNull final I_I_Postal importRecord) { // the current handling for duplicates (postal code + country) is nonexistent. // we blindly try to insert in db, and if there are unique constraints failing the records will automatically be marked as failed. //noinspection UnusedAssignment ImportRecordResult importResult = ImportRecordResult.Nothing; final I_C_Postal cPostal = createNewCPostalCode(importRecord); importResult = ImportRecordResult.Inserted; importRecord.setC_Postal_ID(cPostal.getC_Postal_ID()); InterfaceWrapperHelper.save(importRecord); return importResult; } private I_C_Postal createNewCPostalCode(final I_I_Postal importRecord) {
final I_C_Postal cPostal = InterfaceWrapperHelper.create(getCtx(), I_C_Postal.class, ITrx.TRXNAME_ThreadInherited); cPostal.setC_Country(Services.get(ICountryDAO.class).retrieveCountryByCountryCode(importRecord.getCountryCode())); cPostal.setCity(importRecord.getCity()); cPostal.setPostal(importRecord.getPostal()); cPostal.setRegionName(importRecord.getRegionName()); // these 2 are not yet used // importRecord.getValidFrom() // importRecord.getValidTo() InterfaceWrapperHelper.save(cPostal); return cPostal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impexp\PostalCodeImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public InsuranceContractQuantity pcn(String pcn) { this.pcn = pcn; return this; } /** * PZN für Maximalmenge * @return pcn **/ @Schema(example = "54658452", description = "PZN für Maximalmenge") public String getPcn() { return pcn; } public void setPcn(String pcn) { this.pcn = pcn; } public InsuranceContractQuantity quantity(BigDecimal quantity) { this.quantity = quantity; return this; } /** * Anzahl * @return quantity **/ @Schema(example = "3", description = "Anzahl") public BigDecimal getQuantity() { return quantity; } public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } public InsuranceContractQuantity unit(String unit) { this.unit = unit; return this; } /** * Mengeneinheit (mögliche Werte &#x27;Stk&#x27; oder &#x27;Ktn&#x27;) * @return unit **/ @Schema(example = "Stk", description = "Mengeneinheit (mögliche Werte 'Stk' oder 'Ktn')") public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public InsuranceContractQuantity archived(Boolean archived) { this.archived = archived; return this; } /** * Maximalmenge nicht mehr gültig - archiviert * @return archived **/ @Schema(example = "false", description = "Maximalmenge nicht mehr gültig - archiviert") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) {
return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractQuantity insuranceContractQuantity = (InsuranceContractQuantity) o; return Objects.equals(this.pcn, insuranceContractQuantity.pcn) && Objects.equals(this.quantity, insuranceContractQuantity.quantity) && Objects.equals(this.unit, insuranceContractQuantity.unit) && Objects.equals(this.archived, insuranceContractQuantity.archived); } @Override public int hashCode() { return Objects.hash(pcn, quantity, unit, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractQuantity {\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractQuantity.java
2
请完成以下Java代码
public void setWEBUI_Shortcut (java.lang.String WEBUI_Shortcut) { set_Value (COLUMNNAME_WEBUI_Shortcut, WEBUI_Shortcut); } /** Get Shortcut. @return Shortcut */ @Override public java.lang.String getWEBUI_Shortcut () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_Shortcut); } /** Set Is View Action. @param WEBUI_ViewAction Is View Action */ @Override public void setWEBUI_ViewAction (boolean WEBUI_ViewAction) { set_Value (COLUMNNAME_WEBUI_ViewAction, Boolean.valueOf(WEBUI_ViewAction)); } /** Get Is View Action. @return Is View Action */ @Override public boolean isWEBUI_ViewAction () { Object oo = get_Value(COLUMNNAME_WEBUI_ViewAction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quick action. @param WEBUI_ViewQuickAction Quick action */ @Override public void setWEBUI_ViewQuickAction (boolean WEBUI_ViewQuickAction) { set_Value (COLUMNNAME_WEBUI_ViewQuickAction, Boolean.valueOf(WEBUI_ViewQuickAction)); } /** Get Quick action. @return Quick action */ @Override public boolean isWEBUI_ViewQuickAction () { Object oo = get_Value(COLUMNNAME_WEBUI_ViewQuickAction); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Default quick action. @param WEBUI_ViewQuickAction_Default Default quick action */ @Override public void setWEBUI_ViewQuickAction_Default (boolean WEBUI_ViewQuickAction_Default) { set_Value (COLUMNNAME_WEBUI_ViewQuickAction_Default, Boolean.valueOf(WEBUI_ViewQuickAction_Default)); } /** Get Default quick action. @return Default quick action */ @Override public boolean isWEBUI_ViewQuickAction_Default () { Object oo = get_Value(COLUMNNAME_WEBUI_ViewQuickAction_Default); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Process.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ManagementService managementService = processEngineConfiguration.getManagementService(); List<Job> cleanupJobs = managementService.createTimerJobQuery().handlerType(BpmnHistoryCleanupJobHandler.TYPE).list(); if (cleanupJobs.isEmpty()) { scheduleTimerJob(processEngineConfiguration); } else if (cleanupJobs.size() == 1) { TimerJobEntity timerJob = (TimerJobEntity) cleanupJobs.get(0); if (!Objects.equals(processEngineConfiguration.getHistoryCleaningTimeCycleConfig(), timerJob.getRepeat())) { // If the cleaning time cycle config has changed we need to create a new timer job managementService.deleteTimerJob(timerJob.getId()); scheduleTimerJob(processEngineConfiguration); } } else { TimerJobEntity timerJob = (TimerJobEntity) cleanupJobs.get(0); if (!Objects.equals(processEngineConfiguration.getHistoryCleaningTimeCycleConfig(), timerJob.getRepeat())) { // If the cleaning time cycle config has changed we need to create a new timer job managementService.deleteTimerJob(timerJob.getId()); scheduleTimerJob(processEngineConfiguration); } for (int i = 1; i < cleanupJobs.size(); i++) { managementService.deleteTimerJob(cleanupJobs.get(i).getId()); }
} return null; } protected void scheduleTimerJob(ProcessEngineConfigurationImpl processEngineConfiguration) { TimerJobService timerJobService = processEngineConfiguration.getJobServiceConfiguration().getTimerJobService(); TimerJobEntity timerJob = timerJobService.createTimerJob(); timerJob.setJobType(JobEntity.JOB_TYPE_TIMER); timerJob.setRevision(1); timerJob.setJobHandlerType(BpmnHistoryCleanupJobHandler.TYPE); BusinessCalendar businessCalendar = processEngineConfiguration.getBusinessCalendarManager().getBusinessCalendar(CycleBusinessCalendar.NAME); timerJob.setDuedate(businessCalendar.resolveDuedate(processEngineConfiguration.getHistoryCleaningTimeCycleConfig())); timerJob.setRepeat(processEngineConfiguration.getHistoryCleaningTimeCycleConfig()); timerJobService.scheduleTimerJob(timerJob); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\HandleHistoryCleanupTimerJobCmd.java
1
请完成以下Java代码
public int getRetryWaitTimeInMillis() { return determineAsyncExecutor().getRetryWaitTimeInMillis(); } public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setRetryWaitTimeInMillis(retryWaitTimeInMillis); } } @Override public int getResetExpiredJobsInterval() { return determineAsyncExecutor().getResetExpiredJobsInterval(); } @Override public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setResetExpiredJobsInterval(resetExpiredJobsInterval);
} } @Override public int getResetExpiredJobsPageSize() { return determineAsyncExecutor().getResetExpiredJobsPageSize(); } @Override public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setResetExpiredJobsPageSize(resetExpiredJobsPageSize); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\multitenant\ExecutorPerTenantAsyncExecutor.java
1
请完成以下Spring Boot application配置
# # Copyright 2015-2022 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing perm
issions and # limitations under the License. # logging.level.root=WARN logging.level.sample.mybatis.velocity.legacy.mapper=TRACE mybatis.mapper-locations=classpath*:/mappers/*.xml mybatis.type-aliases-package=sample.mybatis.velocity.legacy.domain
repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-velocity-legacy\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public void consumeSSE() { ParameterizedTypeReference<ServerSentEvent<String>> type = new ParameterizedTypeReference<ServerSentEvent<String>>() { }; Flux<ServerSentEvent<String>> eventStream = client.get() .uri("/stream-sse") .retrieve() .bodyToFlux(type); eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), () -> logger.info("Completed!!!")); } @Async public void consumeFlux() { Flux<String> stringStream = client.get() .uri("/stream-flux") .accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(String.class);
stringStream.subscribe(content -> logger.info("Current time: {} - Received content: {} ", LocalTime.now(), content), error -> logger.error("Error retrieving content: {}", error), () -> logger.info("Completed!!!")); } @Async public void consumeSSEFromFluxEndpoint() { ParameterizedTypeReference<ServerSentEvent<String>> type = new ParameterizedTypeReference<ServerSentEvent<String>>() { }; Flux<ServerSentEvent<String>> eventStream = client.get() .uri("/stream-flux") .accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(type); eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), () -> logger.info("Completed!!!")); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-2\src\main\java\com\baeldung\reactive\serversentevents\consumer\controller\ClientController.java
2
请完成以下Java代码
public String getName() { return this.name; } @Override public long getId() { return this.id; } Instant getStartTime() { return this.startTime; } @Override public @Nullable Long getParentId() { return (this.parent != null) ? this.parent.getId() : null; } @Override public Tags getTags() { return Collections.unmodifiableList(this.tags)::iterator; } @Override public StartupStep tag(String key, Supplier<String> value) { return tag(key, value.get()); } @Override public StartupStep tag(String key, String value) { Assert.state(!this.ended.get(), "StartupStep has already ended."); this.tags.add(new DefaultTag(key, value)); return this; } @Override public void end() { this.ended.set(true);
this.recorder.accept(this); } boolean isEnded() { return this.ended.get(); } static class DefaultTag implements Tag { private final String key; private final String value; DefaultTag(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return this.key; } @Override public String getValue() { return this.value; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\BufferedStartupStep.java
1
请完成以下Java代码
public static @Nullable DockerComposeFile find(@Nullable File workingDirectory) { File base = (workingDirectory != null) ? workingDirectory : new File("."); if (!base.exists()) { return null; } Assert.state(base.isDirectory(), () -> "'%s' is not a directory".formatted(base)); Path basePath = base.toPath(); for (String candidate : SEARCH_ORDER) { Path resolved = basePath.resolve(candidate); if (Files.exists(resolved)) { return of(resolved.toAbsolutePath().toFile()); } } return null; } /** * Create a new {@link DockerComposeFile} for the given {@link File}. * @param file the source file * @return the Docker Compose file */ public static DockerComposeFile of(File file) { Assert.notNull(file, "'file' must not be null"); Assert.isTrue(file.exists(), () -> "'file' [%s] must exist".formatted(file)); Assert.isTrue(file.isFile(), () -> "'file' [%s] must be a normal file".formatted(file)); return new DockerComposeFile(Collections.singletonList(file)); }
/** * Creates a new {@link DockerComposeFile} for the given {@link File files}. * @param files the source files * @return the Docker Compose file * @since 3.4.0 */ public static DockerComposeFile of(Collection<? extends File> files) { Assert.notNull(files, "'files' must not be null"); for (File file : files) { Assert.notNull(file, "'files' must not contain null elements"); Assert.isTrue(file.exists(), () -> "'files' content [%s] must exist".formatted(file)); Assert.isTrue(file.isFile(), () -> "'files' content [%s] must be a normal file".formatted(file)); } return new DockerComposeFile(List.copyOf(files)); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DockerComposeFile.java
1
请完成以下Java代码
public java.lang.String getProductDescription() { return get_ValueAsString(COLUMNNAME_ProductDescription); } @Override public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM) { set_ValueNoCheck (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM); } @Override public BigDecimal getQtyEnteredInBPartnerUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoiced (final @Nullable BigDecimal QtyInvoiced) { set_Value (COLUMNNAME_QtyInvoiced, QtyInvoiced); } @Override public BigDecimal getQtyInvoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoicedInOrderedUOM (final @Nullable BigDecimal QtyInvoicedInOrderedUOM) { set_ValueNoCheck (COLUMNNAME_QtyInvoicedInOrderedUOM, QtyInvoicedInOrderedUOM); } @Override public BigDecimal getQtyInvoicedInOrderedUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInOrderedUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSupplier_GTIN_CU (final @Nullable java.lang.String Supplier_GTIN_CU) { set_ValueNoCheck (COLUMNNAME_Supplier_GTIN_CU, Supplier_GTIN_CU); } @Override public java.lang.String getSupplier_GTIN_CU() { return get_ValueAsString(COLUMNNAME_Supplier_GTIN_CU);
} @Override public void setTaxAmtInfo (final @Nullable BigDecimal TaxAmtInfo) { set_Value (COLUMNNAME_TaxAmtInfo, TaxAmtInfo); } @Override public BigDecimal getTaxAmtInfo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtInfo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void settaxfree (final boolean taxfree) { set_Value (COLUMNNAME_taxfree, taxfree); } @Override public boolean istaxfree() { return get_ValueAsBoolean(COLUMNNAME_taxfree); } @Override public void setUPC_CU (final @Nullable java.lang.String UPC_CU) { set_ValueNoCheck (COLUMNNAME_UPC_CU, UPC_CU); } @Override public java.lang.String getUPC_CU() { return get_ValueAsString(COLUMNNAME_UPC_CU); } @Override public void setUPC_TU (final @Nullable java.lang.String UPC_TU) { set_ValueNoCheck (COLUMNNAME_UPC_TU, UPC_TU); } @Override public java.lang.String getUPC_TU() { return get_ValueAsString(COLUMNNAME_UPC_TU); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_500_v.java
1
请完成以下Java代码
public class MaterialTrackingPPOrderBL implements IMaterialTrackingPPOrderBL { // public only for testing public static final String C_DocType_DOCSUBTYPE_QualityInspection = IMaterialTrackingBL.C_DocType_PPORDER_DOCSUBTYPE_QualityInspection; /** * Quality Inspection Filter * * NOTE: keep in sync with {@link #isQualityInspection(I_PP_Order)} */ private final IQueryFilter<I_PP_Order> qualityInspectionFilter = new EqualsQueryFilter<I_PP_Order>(I_PP_Order.COLUMN_OrderType, C_DocType_DOCSUBTYPE_QualityInspection); @Override public boolean isQualityInspection(final int ppOrderId) { final I_PP_Order ppOrderRecord = loadOutOfTrx(ppOrderId, I_PP_Order.class); return isQualityInspection(ppOrderRecord); } @Override public boolean isQualityInspection(@NonNull final I_PP_Order ppOrder) { // NOTE: keep in sync with #qualityInspectionFilter final String orderType = ppOrder.getOrderType(); return C_DocType_DOCSUBTYPE_QualityInspection.equals(orderType); } @Override public void assertQualityInspectionOrder(@NonNull final I_PP_Order ppOrder) { Check.assume(isQualityInspection(ppOrder), "Order shall be Quality Inspection Order: {}", ppOrder); } @Override public IQueryFilter<I_PP_Order> getQualityInspectionFilter() { return qualityInspectionFilter; } @Override public Timestamp getDateOfProduction(final I_PP_Order ppOrder) { final Timestamp dateOfProduction; if (ppOrder.getDateDelivered() != null)
{ dateOfProduction = ppOrder.getDateDelivered(); } else { dateOfProduction = ppOrder.getDateFinishSchedule(); } Check.assumeNotNull(dateOfProduction, "dateOfProduction not null for PP_Order {}", ppOrder); return dateOfProduction; } @Override public List<I_M_InOutLine> retrieveIssuedInOutLines(final I_PP_Order ppOrder) { // services final IPPOrderMInOutLineRetrievalService ppOrderMInOutLineRetrievalService = Services.get(IPPOrderMInOutLineRetrievalService.class); final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class); final List<I_M_InOutLine> allIssuedInOutLines = new ArrayList<>(); final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); for (final I_PP_Cost_Collector cc : ppCostCollectorDAO.getByOrderId(ppOrderId)) { if (!ppCostCollectorBL.isAnyComponentIssueOrCoProduct(cc)) { continue; } final List<I_M_InOutLine> issuedInOutLinesForCC = ppOrderMInOutLineRetrievalService.provideIssuedInOutLines(cc); allIssuedInOutLines.addAll(issuedInOutLinesForCC); } return allIssuedInOutLines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingPPOrderBL.java
1
请完成以下Java代码
public int getIMP_ProcessorParameter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_ProcessorParameter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Parameter Value. @param ParameterValue Parameter Value */ public void setParameterValue (String ParameterValue) { set_Value (COLUMNNAME_ParameterValue, ParameterValue); }
/** Get Parameter Value. @return Parameter Value */ public String getParameterValue () { return (String)get_Value(COLUMNNAME_ParameterValue); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_ProcessorParameter.java
1
请完成以下Java代码
public class DateUtil { private DateUtil() { super(); } /*** * 查询当前小时 * * @return */ public static int getCurrentHour() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); return cal.get(Calendar.HOUR_OF_DAY); // 获取当前小时 } /*** * 查询当前分钟 * * @return */ public static int getCurrentMinute() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); return cal.get(Calendar.MINUTE); // 获取当前分钟 } /***
* 获取几天前的日期格式 * * @param dayNum * @return */ public static String getDateByDayNum(int dayNum) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DAY_OF_MONTH, -dayNum); String result = sdf.format(cal.getTime()); return result; } /** * 计算 day 天后的时间 * * @param date * @param day * @return */ public static Date addDay(Date date, int day) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\utils\DateUtil.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getItemRef() { return itemRef; } public void setItemRef(String itemRef) { this.itemRef = itemRef; } public Message clone() { Message clone = new Message(); clone.setValues(this); return clone; } public void setValues(Message otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setItemRef(otherElement.getItemRef()); } /** * Creates builder to build {@link Message}. * @return created builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build {@link Message} and initialize it with the given object. * @param message to initialize the builder with * @return created builder */ public static Builder builderFrom(Message message) { return new Builder(message); } /** * Builder to build {@link Message}. */ public static final class Builder { private String id; private int xmlRowNumber; private int xmlColumnNumber; private Map<String, List<ExtensionElement>> extensionElements = emptyMap(); private Map<String, List<ExtensionAttribute>> attributes = emptyMap(); private String name; private String itemRef; private Builder() {} private Builder(Message message) { this.id = message.id; this.xmlRowNumber = message.xmlRowNumber; this.xmlColumnNumber = message.xmlColumnNumber; this.extensionElements = message.extensionElements; this.attributes = message.attributes; this.name = message.name; this.itemRef = message.itemRef; } public Builder id(String id) { this.id = id; return this;
} public Builder xmlRowNumber(int xmlRowNumber) { this.xmlRowNumber = xmlRowNumber; return this; } public Builder xmlColumnNumber(int xmlColumnNumber) { this.xmlColumnNumber = xmlColumnNumber; return this; } public Builder extensionElements(Map<String, List<ExtensionElement>> extensionElements) { this.extensionElements = extensionElements; return this; } public Builder attributes(Map<String, List<ExtensionAttribute>> attributes) { this.attributes = attributes; return this; } public Builder name(String name) { this.name = name; return this; } public Builder itemRef(String itemRef) { this.itemRef = itemRef; return this; } public Message build() { return new Message(this); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Message.java
1
请完成以下Java代码
public ModelInstance getEmptyModel() { DomDocument document = null; synchronized(documentBuilderFactory) { document = DomUtil.getEmptyDocument(documentBuilderFactory); } return createModelInstance(document); } /** * Validate DOM document * * @param document the DOM document to validate */ public void validateModel(DomDocument document) { Schema schema = getSchema(document); if (schema == null) { return; } Validator validator = schema.newValidator(); try { synchronized(document) { validator.validate(document.getDomSource()); } } catch (IOException e) { throw new ModelValidationException("Error during DOM document validation", e); } catch (SAXException e) { throw new ModelValidationException("DOM document is not valid", e); } } protected Schema getSchema(DomDocument document) {
DomElement rootElement = document.getRootElement(); String namespaceURI = rootElement.getNamespaceURI(); return schemas.get(namespaceURI); } protected void addSchema(String namespaceURI, Schema schema) { schemas.put(namespaceURI, schema); } protected Schema createSchema(String location, ClassLoader classLoader) { URL cmmnSchema = ReflectUtil.getResource(location, classLoader); try { return schemaFactory.newSchema(cmmnSchema); } catch (SAXException e) { throw new ModelValidationException("Unable to parse schema:" + cmmnSchema); } } protected abstract ModelInstance createModelInstance(DomDocument document); }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\parser\AbstractModelParser.java
1
请在Spring Boot框架中完成以下Java代码
public class OrgMappingId implements RepoIdAware { @JsonCreator public static OrgMappingId ofRepoId(final int repoId) { return new OrgMappingId(repoId); } public static OrgMappingId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new OrgMappingId(repoId) : null; } public static int toRepoId(final OrgMappingId id) { return id != null ? id.getRepoId() : -1; } int repoId; private OrgMappingId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "AD_OrgMapping_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(final OrgMappingId o1, final OrgMappingId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\service\OrgMappingId.java
2
请在Spring Boot框架中完成以下Java代码
public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public String getResetKey() { return resetKey; } public void setResetKey(String resetKey) { this.resetKey = resetKey; } public Instant getResetDate() { return resetDate; } public void setResetDate(Instant resetDate) { this.resetDate = resetDate; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey;
} public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; } return id != null && id.equals(((User) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
2
请完成以下Java代码
public boolean hasField(String fieldName) { return getDelegate().hasField(fieldName); } /** * @inheritDoc */ @Override public void sendTo(DataOutput out) throws IOException { PdxInstance delegate = getDelegate(); if (delegate instanceof Sendable) { ((Sendable) delegate).sendTo(out); } } /** * Returns a {@link String} representation of this {@link PdxInstance}. * * @return a {@link String} representation of this {@link PdxInstance}. * @see java.lang.String */ @Override public String toString() { //return getDelegate().toString(); return toString(this); } private String toString(PdxInstance pdx) { return toString(pdx, ""); } private String toString(PdxInstance pdx, String indent) { if (Objects.nonNull(pdx)) { StringBuilder buffer = new StringBuilder(OBJECT_BEGIN).append(NEW_LINE); String fieldIndent = indent + INDENT_STRING; buffer.append(fieldIndent).append(formatFieldValue(CLASS_NAME_PROPERTY, pdx.getClassName())); for (String fieldName : nullSafeList(pdx.getFieldNames())) { Object fieldValue = pdx.getField(fieldName); String valueString = toStringObject(fieldValue, fieldIndent); buffer.append(COMMA_NEW_LINE); buffer.append(fieldIndent).append(formatFieldValue(fieldName, valueString)); } buffer.append(NEW_LINE).append(indent).append(OBJECT_END); return buffer.toString(); } else { return null; } } private String toStringArray(Object value, String indent) { Object[] array = (Object[]) value;
StringBuilder buffer = new StringBuilder(ARRAY_BEGIN); boolean addComma = false; for (Object element : array) { buffer.append(addComma ? COMMA_SPACE : EMPTY_STRING); buffer.append(toStringObject(element, indent)); addComma = true; } buffer.append(ARRAY_END); return buffer.toString(); } private String toStringObject(Object value, String indent) { return isPdxInstance(value) ? toString((PdxInstance) value, indent) : isArray(value) ? toStringArray(value, indent) : String.valueOf(value); } private String formatFieldValue(String fieldName, Object fieldValue) { return String.format(FIELD_TYPE_VALUE, fieldName, nullSafeType(fieldValue), fieldValue); } private boolean hasText(String value) { return value != null && !value.trim().isEmpty(); } private boolean isArray(Object value) { return Objects.nonNull(value) && value.getClass().isArray(); } private boolean isPdxInstance(Object value) { return value instanceof PdxInstance; } private <T> List<T> nullSafeList(List<T> list) { return list != null ? list : Collections.emptyList(); } private Class<?> nullSafeType(Object value) { return value != null ? value.getClass() : Object.class; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\pdx\PdxInstanceWrapper.java
1
请完成以下Java代码
public void startWithNotContain(String key) { Assert.doesNotContain(key, "123", "key must not contain 123"); // ... } public void repair(Collection<String> repairParts) { Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty"); // ... } public void repair(Map<String, String> repairParts) { Assert.notEmpty(repairParts, "map of repairParts mustn't be empty"); // ... } public void repair(String[] repairParts) { Assert.notEmpty(repairParts, "array of repairParts must not be empty"); // ... } public void repairWithNoNull(String[] repairParts) { Assert.noNullElements(repairParts, "array of repairParts must not contain null elements"); // ... } public static void main(String[] args) { Car car = new Car(); car.drive(50); car.stop(); car.fuel(); car.сhangeOil("oil"); CarBattery carBattery = new CarBattery(); car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine()); car.startWithHasLength(" "); car.startWithHasText("t"); car.startWithNotContain("132"); List<String> repairPartsCollection = new ArrayList<>(); repairPartsCollection.add("part"); car.repair(repairPartsCollection); Map<String, String> repairPartsMap = new HashMap<>(); repairPartsMap.put("1", "part"); car.repair(repairPartsMap); String[] repairPartsArray = { "part" }; car.repair(repairPartsArray); } }
repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java
1
请完成以下Java代码
private boolean checkLastLoadedDataLineIsNotBlank() { return Check.isNotBlank(loadedDataLines.get(loadedDataLines.size() - 1)); } /** * add current line to the previous one */ private void appendToPreviousLine(@NonNull final String line) { final StringBuilder previousLine = new StringBuilder(); final int index = loadedDataLines.size() - 1; previousLine.append(loadedDataLines.get(index)); // append the new line, because the char exists if (Check.isNotBlank(previousLine.toString())) { previousLine.append("\n"); } previousLine.append(line); // // now remove the line and add the new line loadedDataLines.remove(index); loadedDataLines.add(previousLine.toString()); } @Override public List<String> getResult() { return loadedDataLines; } } /** * Read file that has at least on filed with multiline text * <br> * Assumes the <code>TEXT_DELIMITER</code> is not encountered in the field * * @param file * @param charset * @return * @throws IOException */ public List<String> readMultiLines(@NonNull final File file, @NonNull final Charset charset) throws IOException { return Files.readLines(file, charset, new MultiLineProcessor());
} public List<String> readMultiLines(@NonNull final byte[] data, @NonNull final Charset charset) throws IOException { return ByteSource.wrap(data).asCharSource(charset).readLines(new MultiLineProcessor()); } /** * Read file that has not any multi-line text * * @param file * @param charset * @return * @throws IOException */ public List<String> readRegularLines(@NonNull final File file, @NonNull final Charset charset) throws IOException { return Files.readLines(file, charset, new SingleLineProcessor()); } public List<String> readRegularLines(@NonNull final byte[] data, @NonNull final Charset charset) throws IOException { return ByteSource.wrap(data).asCharSource(charset).readLines(new SingleLineProcessor()); } /** * Build the preview from the loaded lines * * @param lines * @return */ public String buildDataPreview(@NonNull final List<String> lines) { String dataPreview = lines.stream() .limit(MAX_LOADED_LINES) .collect(Collectors.joining("\n")); if (lines.size() > MAX_LOADED_LINES) { dataPreview = dataPreview + "\n......................................................\n"; } return dataPreview; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FileImportReader.java
1
请完成以下Java代码
public UniqueKey<AuthorRecord> getPrimaryKey() { return Keys.AUTHOR_PKEY; } @Override public List<UniqueKey<AuthorRecord>> getKeys() { return Arrays.<UniqueKey<AuthorRecord>>asList(Keys.AUTHOR_PKEY); } @Override public Author as(String alias) { return new Author(DSL.name(alias), this); } @Override public Author as(Name alias) { return new Author(alias, this); } /** * Rename this table */ @Override public Author rename(String name) { return new Author(DSL.name(name), null);
} /** * Rename this table */ @Override public Author rename(Name name) { return new Author(name, null); } // ------------------------------------------------------------------------- // Row4 type methods // ------------------------------------------------------------------------- @Override public Row4<Integer, String, String, Integer> fieldsRow() { return (Row4) super.fieldsRow(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Author.java
1
请完成以下Java代码
protected boolean beforeSave(boolean newRecord) { if (getDateTo() == null) setDateTo(getDateFrom()); if (getDateFrom().after(getDateTo())) { throw new AdempiereException("@DateTo@ > @DateFrom@"); } return true; } // beforeSave /** * Check if the resource is unavailable for date * @return true if valid */
public boolean isUnAvailable(final Instant dateTime) { final ZoneId zoneId = SystemTime.zoneId(); LocalDate date = dateTime.atZone(zoneId).toLocalDate(); LocalDate dateFrom = TimeUtil.asLocalDate(getDateFrom(), zoneId); LocalDate dateTo = TimeUtil.asLocalDate(getDateTo(), zoneId); if (dateFrom != null && date.isBefore(dateFrom)) return false; if (dateTo != null && date.isAfter(dateTo)) return false; return true; } } // MResourceUnAvailable
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MResourceUnAvailable.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isLogLeakedSessions() { return this.logLeakedSessions; } public void setLogLeakedSessions(boolean logLeakedSessions) { this.logLeakedSessions = logLeakedSessions; } public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } public void setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; } public @Nullable Duration getIdleTimeBeforeConnectionTest() { return this.idleTimeBeforeConnectionTest; } public void setIdleTimeBeforeConnectionTest(@Nullable Duration idleTimeBeforeConnectionTest) { this.idleTimeBeforeConnectionTest = idleTimeBeforeConnectionTest; } public Duration getMaxConnectionLifetime() { return this.maxConnectionLifetime; } public void setMaxConnectionLifetime(Duration maxConnectionLifetime) { this.maxConnectionLifetime = maxConnectionLifetime; } public Duration getConnectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) { this.connectionAcquisitionTimeout = connectionAcquisitionTimeout; } } public static class Security { /** * Whether the driver should use encrypted traffic. */ private boolean encrypted; /** * Trust strategy to use. */ private TrustStrategy trustStrategy = TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES; /** * Path to the file that holds the trusted certificates. */ private @Nullable File certFile; /** * Whether hostname verification is required. */ private boolean hostnameVerificationEnabled = true; public boolean isEncrypted() { return this.encrypted; } public void setEncrypted(boolean encrypted) { this.encrypted = encrypted; } public TrustStrategy getTrustStrategy() { return this.trustStrategy; }
public void setTrustStrategy(TrustStrategy trustStrategy) { this.trustStrategy = trustStrategy; } public @Nullable File getCertFile() { return this.certFile; } public void setCertFile(@Nullable File certFile) { this.certFile = certFile; } public boolean isHostnameVerificationEnabled() { return this.hostnameVerificationEnabled; } public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) { this.hostnameVerificationEnabled = hostnameVerificationEnabled; } public enum TrustStrategy { /** * Trust all certificates. */ TRUST_ALL_CERTIFICATES, /** * Trust certificates that are signed by a trusted certificate. */ TRUST_CUSTOM_CA_SIGNED_CERTIFICATES, /** * Trust certificates that can be verified through the local system store. */ TRUST_SYSTEM_CA_SIGNED_CERTIFICATES } } }
repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java
2
请在Spring Boot框架中完成以下Java代码
public ConcurrencyControlConfigurer expiredUrl(String expiredUrl) { SessionManagementConfigurer.this.expiredUrl = expiredUrl; return this; } /** * Determines the behaviour when an expired session is detected. * @param expiredSessionStrategy the {@link SessionInformationExpiredStrategy} to * use when an expired session is detected. * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer expiredSessionStrategy( SessionInformationExpiredStrategy expiredSessionStrategy) { SessionManagementConfigurer.this.expiredSessionStrategy = expiredSessionStrategy; return this; } /** * If true, prevents a user from authenticating when the * {@link #maximumSessions(int)} has been reached. Otherwise (default), the user * who authenticates is allowed access and an existing user's session is expired. * The user's who's session is forcibly expired is sent to * {@link #expiredUrl(String)}. The advantage of this approach is if a user * accidentally does not log out, there is no need for an administrator to * intervene or wait till their session expires. * @param maxSessionsPreventsLogin true to have an error at time of * authentication, else false (default) * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer maxSessionsPreventsLogin(boolean maxSessionsPreventsLogin) {
SessionManagementConfigurer.this.maxSessionsPreventsLogin = maxSessionsPreventsLogin; return this; } /** * Controls the {@link SessionRegistry} implementation used. The default is * {@link SessionRegistryImpl} which is an in memory implementation. * @param sessionRegistry the {@link SessionRegistry} to use * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer sessionRegistry(SessionRegistry sessionRegistry) { SessionManagementConfigurer.this.sessionRegistry = sessionRegistry; return this; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\SessionManagementConfigurer.java
2
请完成以下Java代码
public class EventSubProcessStartEventActivityBehavior extends NoneStartEventActivityBehavior { // default = true protected boolean isInterrupting = true; protected String activityId; public EventSubProcessStartEventActivityBehavior(String activityId) { this.activityId = activityId; } @Override public void execute(DelegateExecution execution) { ActivityExecution activityExecution = (ActivityExecution) execution; InterpretableExecution interpretableExecution = (InterpretableExecution) execution; ActivityImpl activity = interpretableExecution.getProcessDefinition().findActivity(activityId); ActivityExecution outgoingExecution = activityExecution; if (isInterrupting) { activityExecution.destroyScope("Event subprocess triggered using activity " + activityId); } else { outgoingExecution = activityExecution.createExecution();
outgoingExecution.setActive(true); outgoingExecution.setScope(false); outgoingExecution.setConcurrent(true); } // set the outgoing execution to this activity ((InterpretableExecution) outgoingExecution).setActivity(activity); // continue execution outgoingExecution.takeAll(activity.getOutgoingTransitions(), Collections.EMPTY_LIST); } public void setInterrupting(boolean b) { isInterrupting = b; } public boolean isInterrupting() { return isInterrupting; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\EventSubProcessStartEventActivityBehavior.java
1
请完成以下Java代码
private final boolean isDecimalOrGroupingSeparator(final char ch) { return ch == m_decimalSeparator || ch == m_groupingSeparator || ch == '.' || ch == ','; } /** * Get Full Text * * @return text or empty string; never returns null */ private final String getText() { final Content content = getContent(); if (content == null) { return ""; } final int length = content.length(); if (length <= 0) { return ""; } String str = "";
try { str = content.getString(0, length - 1); // cr at end } catch (BadLocationException e) { // ignore it, shall not happen log.debug("Error while getting the string content", e); } catch (Exception e) { log.debug("Error while getting the string content", e); } return str; } // getString private final void provideErrorFeedback() { UIManager.getLookAndFeel().provideErrorFeedback(m_tc); } } // MDocNumber
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocNumber.java
1
请完成以下Java代码
private void handleAuthorizationFailure(OAuth2AuthorizationException authorizationException, Authentication principal) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); Map<String, Object> attributes = new HashMap<>(); if (requestAttributes != null) { attributes.put(HttpServletRequest.class.getName(), requestAttributes.getRequest()); if (requestAttributes.getResponse() != null) { attributes.put(HttpServletResponse.class.getName(), requestAttributes.getResponse()); } } this.authorizationFailureHandler.onAuthorizationFailure(authorizationException, principal, attributes); } /** * A strategy for resolving a {@code clientRegistrationId} from an intercepted * request. */ @FunctionalInterface public interface ClientRegistrationIdResolver { /** * Resolve the {@code clientRegistrationId} from the current request, which is * used to obtain an {@link OAuth2AuthorizedClient}. * @param request the intercepted request, containing HTTP method, URI, headers, * and request attributes * @return the {@code clientRegistrationId} to be used for resolving an * {@link OAuth2AuthorizedClient}.
*/ @Nullable String resolve(HttpRequest request); } /** * A strategy for resolving a {@link Authentication principal} from an intercepted * request. */ @FunctionalInterface public interface PrincipalResolver { /** * Resolve the {@link Authentication principal} from the current request, which is * used to obtain an {@link OAuth2AuthorizedClient}. * @param request the intercepted request, containing HTTP method, URI, headers, * and request attributes * @return the {@link Authentication principal} to be used for resolving an * {@link OAuth2AuthorizedClient}. */ @Nullable Authentication resolve(HttpRequest request); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\client\OAuth2ClientHttpRequestInterceptor.java
1
请完成以下Java代码
public void put(final IView view) { defaultViewsRepositoryStorage.put(view); } @Nullable @Override public IView getByIdOrNull(final ViewId viewId) { return defaultViewsRepositoryStorage.getByIdOrNull(viewId); } @Override public void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) {
defaultViewsRepositoryStorage.closeById(viewId, closeAction); } @Override public Stream<IView> streamAllViews() { return defaultViewsRepositoryStorage.streamAllViews(); } @Override public void invalidateView(final ViewId viewId) { defaultViewsRepositoryStorage.invalidateView(viewId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitViewsIndexStorage.java
1
请完成以下Java代码
public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() { if (adjstmntAmtAndRsn == null) { adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>(); } return this.adjstmntAmtAndRsn; } /** * Gets the value of the rmtdAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() { return rmtdAmt;
} /** * Sets the value of the rmtdAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) { this.rmtdAmt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceAmount1.java
1
请在Spring Boot框架中完成以下Java代码
public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() throws IOException { return responseBody.contentLength(); } @Override public BufferedSource source() throws IOException { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; }
private Source source(Source source) { return new ForwardingSource(source) { long totalBytesRead = 0L; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); // read() returns the number of bytes read, or -1 if this source is exhausted. totalBytesRead += bytesRead != -1 ? bytesRead : 0; progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); return bytesRead; } }; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\ProgressResponseBody.java
2
请在Spring Boot框架中完成以下Java代码
public class UserProperties { /** * 用户 ID */ private Long id; /** * 年龄 */ private int age; /** * 用户名称 */ private String desc; /** * 用户 UUID */ private String uuid; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age;
} public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } @Override public String toString() { return "UserProperties{" + "id=" + id + ", age=" + age + ", desc='" + desc + '\'' + ", uuid='" + uuid + '\'' + '}'; } }
repos\springboot-learning-example-master\springboot-properties\src\main\java\org\spring\springboot\property\UserProperties.java
2
请完成以下Java代码
class DefaultLibraryCoordinates implements LibraryCoordinates { private final @Nullable String groupId; private final @Nullable String artifactId; private final @Nullable String version; /** * Create a new instance from discrete elements. * @param groupId the group ID * @param artifactId the artifact ID * @param version the version */ DefaultLibraryCoordinates(@Nullable String groupId, @Nullable String artifactId, @Nullable String version) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; } /** * Return the group ID of the coordinates. * @return the group ID */ @Override public @Nullable String getGroupId() { return this.groupId; } /** * Return the artifact ID of the coordinates.
* @return the artifact ID */ @Override public @Nullable String getArtifactId() { return this.artifactId; } /** * Return the version of the coordinates. * @return the version */ @Override public @Nullable String getVersion() { return this.version; } /** * Return the coordinates in the form {@code groupId:artifactId:version}. */ @Override public String toString() { return LibraryCoordinates.toStandardNotationString(this); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\DefaultLibraryCoordinates.java
1
请完成以下Java代码
public class TbEntityActorId implements TbActorId { @Getter private final EntityId entityId; public TbEntityActorId(EntityId entityId) { this.entityId = entityId; } @Override public String toString() { return entityId.getEntityType() + "|" + entityId.getId(); } @Override public boolean equals(Object o) { if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; TbEntityActorId that = (TbEntityActorId) o; return entityId.equals(that.entityId); } @Override public int hashCode() { return Objects.hash(entityId); } @Override public EntityType getEntityType() { return entityId.getEntityType(); } }
repos\thingsboard-master\common\actor\src\main\java\org\thingsboard\server\actors\TbEntityActorId.java
1
请在Spring Boot框架中完成以下Java代码
public class ReconciliationFileParserBiz implements BeanFactoryAware { // 加载beanfactory private BeanFactory beanFactory; public Object getService(String payInterface) { return beanFactory.getBean(payInterface); } public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } private static final Log LOG = LogFactory.getLog(ReconciliationFileParserBiz.class); /** * 解析file文件 * * @param batch * 对账批次实体 * @param file * 下载的对账文件 * @param billDate * 下载对账单的日期 * * @param interfaceCode * 具体的支付方式 * * @return 转换之后的vo对象 * @throws IOException */ public List<ReconciliationEntityVo> parser(RpAccountCheckBatch batch, File file, Date billDate, String interfaceCode) throws IOException {
// 解析成 ReconciliationEntityVo 对象 List<ReconciliationEntityVo> rcVoList = null; // 根据支付方式得到解析器的名字 String parserClassName = interfaceCode + "Parser"; LOG.info("根据支付方式得到解析器的名字[" + parserClassName + "]"); ParserInterface service = null; try { // 根据名字获取相应的解析器 service = (ParserInterface) this.getService(parserClassName); } catch (NoSuchBeanDefinitionException e) { LOG.error("根据解析器的名字[" + parserClassName + "],没有找到相应的解析器"); return null; } // 使用相应的解析器解析文件 rcVoList = service.parser(file, billDate, batch); return rcVoList; } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\biz\ReconciliationFileParserBiz.java
2
请在Spring Boot框架中完成以下Java代码
public static void handleInsertVariableInstanceEntityCount(VariableInstanceEntity variableInstance, TaskServiceConfiguration taskServiceConfiguration) { if (variableInstance.getTaskId() != null && isTaskRelatedEntityCountEnabledGlobally(taskServiceConfiguration)) { CountingTaskEntity countingTaskEntity = (CountingTaskEntity) taskServiceConfiguration.getTaskEntityManager().findById(variableInstance.getTaskId()); if (isTaskRelatedEntityCountEnabled(countingTaskEntity, taskServiceConfiguration)) { countingTaskEntity.setVariableCount(countingTaskEntity.getVariableCount() + 1); } } } /** * Check if the Task Relationship Count performance improvement is enabled. */ public static boolean isTaskRelatedEntityCountEnabledGlobally(TaskServiceConfiguration taskServiceConfiguration) { if (taskServiceConfiguration == null) { return false; } return taskServiceConfiguration.isEnableTaskRelationshipCounts();
} public static boolean isTaskRelatedEntityCountEnabled(TaskEntity taskEntity, TaskServiceConfiguration taskServiceConfiguration) { if (taskEntity instanceof CountingTaskEntity) { return isTaskRelatedEntityCountEnabled((CountingTaskEntity) taskEntity, taskServiceConfiguration); } return false; } /** * Similar functionality with <b>ExecutionRelatedEntityCount</b>, but on the TaskEntity level. */ public static boolean isTaskRelatedEntityCountEnabled(CountingTaskEntity taskEntity, TaskServiceConfiguration taskServiceConfiguration) { return isTaskRelatedEntityCountEnabledGlobally(taskServiceConfiguration) && taskEntity.isCountEnabled(); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\util\CountingTaskUtil.java
2
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column private String name; @CreatedDate private Date createdDate = new Date(); public Date getCreatedDate() { return createdDate; } public Integer getId() {
return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-boot-mysql\src\main\java\com\baeldung\boot\User.java
2
请完成以下Java代码
public CarMaker getMaker() { return maker; } /** * @param maker the maker to set */ public void setMaker(CarMaker maker) { this.maker = maker; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((maker == null) ? 0 : maker.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((sku == null) ? 0 : sku.hashCode()); result = prime * result + ((year == null) ? 0 : year.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true;
if (obj == null) return false; if (getClass() != obj.getClass()) return false; CarModel other = (CarModel) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (maker == null) { if (other.maker != null) return false; } else if (!maker.equals(other.maker)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (sku == null) { if (other.sku != null) return false; } else if (!sku.equals(other.sku)) return false; if (year == null) { if (other.year != null) return false; } else if (!year.equals(other.year)) return false; return true; } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarModel.java
1
请完成以下Java代码
public class CallActivityBehavior extends CallableElementActivityBehavior implements MigrationObserverBehavior { public CallActivityBehavior() { } public CallActivityBehavior(String className) { super(className); } public CallActivityBehavior(Expression expression) { super(expression); } @Override protected void startInstance(ActivityExecution execution, VariableMap variables, String businessKey) { ExecutionEntity executionEntity = (ExecutionEntity) execution; ProcessDefinitionImpl definition = getProcessDefinitionToCall( executionEntity, executionEntity.getProcessDefinitionTenantId(), getCallableElement()); PvmProcessInstance processInstance = execution.createSubProcessInstance(definition, businessKey); processInstance.start(variables); } @Override public void migrateScope(ActivityExecution scopeExecution) {
} @Override public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) { ActivityImpl callActivity = (ActivityImpl) migratingInstance.getSourceScope(); // A call activity is typically scope and since we guarantee stability of scope executions during migration, // the superExecution link does not have to be maintained during migration. // There are some exceptions, though: A multi-instance call activity is not scope and therefore // does not have a dedicated scope execution. In this case, the link to the super execution // must be maintained throughout migration if (!callActivity.isScope()) { ExecutionEntity callActivityExecution = migratingInstance.resolveRepresentativeExecution(); ExecutionEntity calledProcessInstance = callActivityExecution.getSubProcessInstance(); migratingInstance.addMigratingDependentInstance(new MigratingCalledProcessInstance(calledProcessInstance)); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallActivityBehavior.java
1
请完成以下Java代码
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return values.getViewEditorRenderModeByFieldName(); } public boolean isPriceEditable() { return isFieldEditable(FIELD_Price); } @SuppressWarnings("SameParameterValue") private boolean isFieldEditable(final String fieldName) { final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName); return renderMode != null && renderMode.isEditable(); } @Override public DocumentId getId() { return id; } @Override public boolean isProcessed() { return false; } @Nullable @Override public DocumentPath getDocumentPath() { return null; } public ProductId getProductId() { return getProduct().getIdAs(ProductId::ofRepoId); } public String getProductName() { return getProduct().getDisplayName(); } public boolean isQtySet() { final BigDecimal qty = getQty(); return qty != null && qty.signum() != 0; } public ProductsProposalRow withLastShipmentDays(final Integer lastShipmentDays)
{ if (Objects.equals(this.lastShipmentDays, lastShipmentDays)) { return this; } else { return toBuilder().lastShipmentDays(lastShipmentDays).build(); } } public boolean isChanged() { return getProductPriceId() == null || !getPrice().isPriceListPriceUsed(); } public boolean isMatching(@NonNull final ProductsProposalViewFilter filter) { return Check.isEmpty(filter.getProductName()) || getProductName().toLowerCase().contains(filter.getProductName().toLowerCase()); } public ProductsProposalRow withExistingOrderLine(@Nullable final OrderLine existingOrderLine) { if(existingOrderLine == null) { return this; } final Amount existingPrice = Amount.of(existingOrderLine.getPriceEntered(), existingOrderLine.getCurrency().getCurrencyCode()); return toBuilder() .qty(existingOrderLine.isPackingMaterialWithInfiniteCapacity() ? existingOrderLine.getQtyEnteredCU() : BigDecimal.valueOf(existingOrderLine.getQtyEnteredTU())) .price(ProductProposalPrice.builder() .priceListPrice(existingPrice) .build()) .existingOrderLineId(existingOrderLine.getOrderLineId()) .description(existingOrderLine.getDescription()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRow.java
1
请完成以下Java代码
public bdo addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public bdo addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public bdo addElement(Element element) { addElementToRegistry(element); return(this);
} /** Adds an Element to the element. @param element Adds an Element to the element. */ public bdo addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public bdo removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\bdo.java
1
请完成以下Java代码
public class SpinValueMapperFactory { protected static final ScalaFeelLogger LOGGER = ScalaFeelLogger.LOGGER; public static final String SPIN_VALUE_MAPPER_CLASS_NAME = "org.camunda.spin.plugin.impl.feel.integration.SpinValueMapper"; public CustomValueMapper createInstance() { Class<?> valueMapperClass = lookupClass(); CustomValueMapper valueMapper = null; if (valueMapperClass != null) { valueMapper = newInstance(valueMapperClass); if (valueMapper != null) { LOGGER.logSpinValueMapperDetected(); } } // else: engine plugin is not on classpath return valueMapper; } protected CustomValueMapper newInstance(Class<?> valueMapperClass) { try { return (CustomValueMapper) valueMapperClass.newInstance(); } catch (InstantiationException e) { throw LOGGER.spinValueMapperInstantiationException(e);
} catch (IllegalAccessException e) { throw LOGGER.spinValueMapperAccessException(e); } catch (ClassCastException e) { throw LOGGER.spinValueMapperCastException(e, CustomValueMapper.class.getName()); } catch (Throwable e) { throw LOGGER.spinValueMapperException(e); } } protected Class<?> lookupClass() { try { return Class.forName(SPIN_VALUE_MAPPER_CLASS_NAME); } catch (ClassNotFoundException ignored) { // engine plugin is not on class path => ignore } catch (Throwable e) { throw LOGGER.spinValueMapperException(e); } return null; } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\spin\SpinValueMapperFactory.java
1
请完成以下Java代码
public class AttributeNotFoundException extends AdempiereException { /** * */ private static final long serialVersionUID = -7800379395702483714L; private final I_M_Attribute attribute; private final IAttributeSet attributeSet; public AttributeNotFoundException(final I_M_Attribute attribute, final Object attributeSetObj) { super(buildMsg(attribute, attributeSetObj)); this.attribute = attribute; if (attributeSetObj instanceof IAttributeSet) { attributeSet = (IAttributeSet)attributeSetObj; } else { attributeSet = null; } } public AttributeNotFoundException(final String attributeValueKey, final Object attributeSetObj) { super(buildMsg(attributeValueKey, attributeSetObj)); attribute = null; if (attributeSetObj instanceof IAttributeSet) { attributeSet = (IAttributeSet)attributeSetObj; } else { attributeSet = null; } } public AttributeNotFoundException(final AttributeId attributeId, final Object attributeSetObj) { this(attributeId.toString(), attributeSetObj); } private static final String toString(final I_M_Attribute attribute) { if (attribute == null) { return "<NULL>"; } else { return attribute.getName(); } } private static final ITranslatableString buildMsg(final I_M_Attribute attribute, final Object attributeSetObj) { final String attributeStr = toString(attribute); return buildMsg(attributeStr, attributeSetObj);
} private static final ITranslatableString buildMsg(final String attributeStr, final Object attributeSetObj) { final TranslatableStringBuilder builder = TranslatableStrings.builder(); builder.append("Attribute "); if (attributeStr == null) { builder.append("<NULL>"); } else { builder.append("'").append(attributeStr).append("'"); } builder.append(" was not found"); if (attributeSetObj != null) { builder.append(" for ").append(attributeSetObj.toString()); } return builder.build(); } public I_M_Attribute getM_Attribute() { return attribute; } public IAttributeSet getAttributeSet() { return attributeSet; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\exceptions\AttributeNotFoundException.java
1