instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class DecisionServiceExecutionAuditContainer extends DecisionExecutionAuditContainer { protected Map<String, List<Map<String, Object>>> decisionServiceResult = new HashMap<>(); protected Map<String, DecisionExecutionAuditContainer> childDecisionExecutions = new LinkedHashMap<>(); public DecisionServiceExecutionAuditContainer() { } public DecisionServiceExecutionAuditContainer(String id, String name, int decisionVersion, boolean strictMode, Map<String, Object> variables, Date startTime) { super(id, name, decisionVersion, strictMode, variables, startTime); } public Map<String, List<Map<String, Object>>> getDecisionServiceResult() { return decisionServiceResult; } public void setDecisionServiceResult(Map<String, List<Map<String, Object>>> decisionServiceResult) { this.decisionServiceResult = decisionServiceResult; } public void addDecisionServiceResult(String decisionKey, List<Map<String, Object>> decisionResult) { decisionServiceResult.put(decisionKey, decisionResult); }
public List<Map<String, Object>> getDecisionServiceResultForDecision(String decisionKey) { return decisionServiceResult.get(decisionKey); } public DecisionExecutionAuditContainer getChildDecisionExecution(String decisionKey) { return childDecisionExecutions.get(decisionKey); } public void addChildDecisionExecution(String decisionKey, DecisionExecutionAuditContainer decisionResult) { childDecisionExecutions.put(decisionKey, decisionResult); } public Map<String, DecisionExecutionAuditContainer> getChildDecisionExecutions() { return childDecisionExecutions; } public void setChildDecisionExecutions(Map<String, DecisionExecutionAuditContainer> childDecisionExecutions) { this.childDecisionExecutions = childDecisionExecutions; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DecisionServiceExecutionAuditContainer.java
1
请完成以下Java代码
public Builder tokenType(OAuth2AccessToken.TokenType tokenType) { this.tokenType = tokenType; return this; } /** * Sets the lifetime (in seconds) of the access token. * @param expiresIn the lifetime of the access token, in seconds. * @return the {@link Builder} */ public Builder expiresIn(long expiresIn) { this.expiresIn = expiresIn; this.expiresAt = null; return this; } /** * Sets the scope(s) associated to the access token. * @param scopes the scope(s) associated to the access token. * @return the {@link Builder} */ public Builder scopes(Set<String> scopes) { this.scopes = scopes; return this; } /** * Sets the refresh token associated to the access token. * @param refreshToken the refresh token associated to the access token. * @return the {@link Builder} */ public Builder refreshToken(String refreshToken) { this.refreshToken = refreshToken; return this; } /** * Sets the additional parameters returned in the response. * @param additionalParameters the additional parameters returned in the response * @return the {@link Builder} */ public Builder additionalParameters(Map<String, Object> additionalParameters) { this.additionalParameters = additionalParameters; return this; } /**
* Builds a new {@link OAuth2AccessTokenResponse}. * @return a {@link OAuth2AccessTokenResponse} */ public OAuth2AccessTokenResponse build() { Instant issuedAt = getIssuedAt(); Instant expiresAt = getExpiresAt(); OAuth2AccessTokenResponse accessTokenResponse = new OAuth2AccessTokenResponse(); accessTokenResponse.accessToken = new OAuth2AccessToken(this.tokenType, this.tokenValue, issuedAt, expiresAt, this.scopes); if (StringUtils.hasText(this.refreshToken)) { accessTokenResponse.refreshToken = new OAuth2RefreshToken(this.refreshToken, issuedAt); } accessTokenResponse.additionalParameters = Collections .unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap() : this.additionalParameters); return accessTokenResponse; } private Instant getIssuedAt() { if (this.issuedAt == null) { this.issuedAt = Instant.now(); } return this.issuedAt; } /** * expires_in is RECOMMENDED, as per spec * https://tools.ietf.org/html/rfc6749#section-5.1 Therefore, expires_in may not * be returned in the Access Token response which would result in the default * value of 0. For these instances, default the expiresAt to +1 second from * issuedAt time. * @return */ private Instant getExpiresAt() { if (this.expiresAt == null) { Instant issuedAt = getIssuedAt(); this.expiresAt = (this.expiresIn > 0) ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1); } return this.expiresAt; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AccessTokenResponse.java
1
请在Spring Boot框架中完成以下Java代码
public QName getServicedCondition() { return OneTimeUse.DEFAULT_ELEMENT_NAME; } @NonNull @Override public ValidationResult validate(Condition condition, Assertion assertion, ValidationContext context) { // applications should validate their own OneTimeUse conditions return ValidationResult.VALID; } }); conditions.add(new ProxyRestrictionConditionValidator()); subjects.add(new BearerSubjectConfirmationValidator() { @NonNull protected ValidationResult validateAddress(@NonNull SubjectConfirmation confirmation, @NonNull Assertion assertion, @NonNull ValidationContext context, boolean required) throws AssertionValidationException { return ValidationResult.VALID; } @NonNull protected ValidationResult validateAddress(@NonNull SubjectConfirmationData confirmationData, @NonNull Assertion assertion, @NonNull ValidationContext context, boolean required) throws AssertionValidationException { // applications should validate their own addresses - gh-7514 return ValidationResult.VALID; } }); } static final SAML20AssertionValidator attributeValidator = new SAML20AssertionValidator(conditions, subjects, statements, null, null, null) { @NonNull @Override protected ValidationResult validateSignature(Assertion token, ValidationContext context) { return ValidationResult.VALID; } }; } /** * A tuple containing an OpenSAML {@link Response} and its associated authentication * token. * * @since 5.4 */ static class ResponseToken { private final Saml2AuthenticationToken token; private final Response response; ResponseToken(Response response, Saml2AuthenticationToken token) { this.token = token; this.response = response; } Response getResponse() { return this.response; } Saml2AuthenticationToken getToken() { return this.token;
} } /** * A tuple containing an OpenSAML {@link Assertion} and its associated authentication * token. * * @since 5.4 */ static class AssertionToken { private final Saml2AuthenticationToken token; private final Assertion assertion; AssertionToken(Assertion assertion, Saml2AuthenticationToken token) { this.token = token; this.assertion = assertion; } Assertion getAssertion() { return this.assertion; } Saml2AuthenticationToken getToken() { return this.token; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\BaseOpenSamlAuthenticationProvider.java
2
请完成以下Java代码
private void processTable (MTable table, ClientId clientId) { StringBuffer sql = new StringBuffer(); MColumn[] columns = table.getColumns(false); for (MColumn column : columns) { if (column.getAD_Reference_ID() == DisplayType.String || column.getAD_Reference_ID() == DisplayType.Text) { String columnName = column.getColumnName(); if (sql.length() != 0) { sql.append(","); } sql.append(columnName); } }
String baseTable = table.getTableName(); baseTable = baseTable.substring(0, baseTable.length()-4); log.info(baseTable + ": " + sql); String columnNames = sql.toString(); sql = new StringBuffer(); sql.append("UPDATE ").append(table.getTableName()).append(" t SET (") .append(columnNames).append(") = (SELECT ").append(columnNames) .append(" FROM ").append(baseTable).append(" b WHERE t.") .append(baseTable).append("_ID=b.").append(baseTable).append("_ID) WHERE AD_Client_ID=") .append(clientId.getRepoId()); int no = DB.executeUpdateAndSaveErrorOnFail(DB.convertSqlToNative(sql.toString()), get_TrxName()); addLog(0, null, new BigDecimal(no), baseTable); } // processTable } // TranslationDocSync
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\TranslationDocSync.java
1
请在Spring Boot框架中完成以下Java代码
private void checkRequest(HttpServletRequest request) { // 获取当前 request 的方法 String currentMethod = request.getMethod(); Multimap<String, String> urlMapping = allUrlMapping(); for (String uri : urlMapping.keySet()) { // 通过 AntPathRequestMatcher 匹配 url // 可以通过 2 种方式创建 AntPathRequestMatcher // 1:new AntPathRequestMatcher(uri,method) 这种方式可以直接判断方法是否匹配,因为这里我们把 方法不匹配 自定义抛出,所以,我们使用第2种方式创建 // 2:new AntPathRequestMatcher(uri) 这种方式不校验请求方法,只校验请求路径 AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(uri); if (antPathMatcher.matches(request)) { if (!urlMapping.get(uri).contains(currentMethod)) { throw new SecurityException(Status.HTTP_BAD_METHOD); } else { return; } } } throw new SecurityException(Status.REQUEST_NOT_FOUND); } /** * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]} * * @return {@link ArrayListMultimap} 格式的 URL Mapping
*/ private Multimap<String, String> allUrlMapping() { Multimap<String, String> urlMapping = ArrayListMultimap.create(); // 获取url与类和方法的对应信息 Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods(); handlerMethods.forEach((k, v) -> { // 获取当前 key 下的获取所有URL Set<String> url = k.getPatternsCondition().getPatterns(); RequestMethodsRequestCondition method = k.getMethodsCondition(); // 为每个URL添加所有的请求方法 url.forEach(s -> urlMapping.putAll(s, method.getMethods().stream().map(Enum::toString).collect(Collectors.toList()))); }); return urlMapping; } }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\config\RbacAuthorityService.java
2
请完成以下Java代码
public Class<? extends DmnDeploymentEntity> getManagedEntityClass() { return DmnDeploymentEntityImpl.class; } @Override public DmnDeploymentEntity create() { return new DmnDeploymentEntityImpl(); } @Override public long findDeploymentCountByQueryCriteria(DmnDeploymentQueryImpl deploymentQuery) { return (Long) getDbSqlSession().selectOne("selectDmnDeploymentCountByQueryCriteria", deploymentQuery); } @Override @SuppressWarnings("unchecked") public List<DmnDeployment> findDeploymentsByQueryCriteria(DmnDeploymentQueryImpl deploymentQuery) { return getDbSqlSession().selectList("selectDmnDeploymentsByQueryCriteria", deploymentQuery);
} @Override public List<String> getDeploymentResourceNames(String deploymentId) { return getDbSqlSession().getSqlSession().selectList("selectDmnResourceNamesByDeploymentId", deploymentId); } @Override @SuppressWarnings("unchecked") public List<DmnDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectDmnDeploymentByNativeQuery", parameterMap); } @Override public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectDmnDeploymentCountByNativeQuery", parameterMap); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\data\impl\MybatisDmnDeploymentDataManager.java
1
请完成以下Java代码
public class PvmAtomicOperationActivityLeave implements PvmAtomicOperation { private final static PvmLogger LOG = PvmLogger.PVM_LOGGER; public boolean isAsync(PvmExecutionImpl execution) { return false; } public void execute(PvmExecutionImpl execution) { execution.activityInstanceDone(); ActivityBehavior activityBehavior = getActivityBehavior(execution); if (activityBehavior instanceof FlowNodeActivityBehavior) { FlowNodeActivityBehavior behavior = (FlowNodeActivityBehavior) activityBehavior; ActivityImpl activity = execution.getActivity(); String activityInstanceId = execution.getActivityInstanceId(); if(activityInstanceId != null) { LOG.debugLeavesActivityInstance(execution, activityInstanceId); }
try { behavior.doLeave(execution); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new PvmException("couldn't leave activity <"+activity.getProperty("type")+" id=\""+activity.getId()+"\" ...>: "+e.getMessage(), e); } } else { throw new PvmException("Behavior of current activity is not an instance of " + FlowNodeActivityBehavior.class.getSimpleName() + ". Execution " + execution); } } public String getCanonicalName() { return "activity-leave"; } public boolean isAsyncCapable() { return false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityLeave.java
1
请在Spring Boot框架中完成以下Java代码
public void setPoolPreparedStatements(Boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public Integer getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters;
} public Boolean getRemoveAbandoned() { return removeAbandoned; } public void setRemoveAbandoned(Boolean removeAbandoned) { this.removeAbandoned = removeAbandoned; } public Integer getRemoveAbandonedTimeout() { return removeAbandonedTimeout; } public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) { this.removeAbandonedTimeout = removeAbandonedTimeout; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\config\properties\DruidProperties.java
2
请完成以下Java代码
public void setAnalytics(boolean analytics) { this.analytics = analytics; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VariableDefinitionImpl that = (VariableDefinitionImpl) o; return ( required == that.required && Objects.equals(display, that.display) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(type, that.type) && Objects.equals(displayName, that.displayName) && Objects.equals(analytics, that.analytics) ); } @Override public int hashCode() { return Objects.hash(id, name, description, type, required, display, displayName, analytics); } @Override public String toString() { return ( "VariableDefinitionImpl{" + "id='" + id +
'\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type='" + type + '\'' + ", required=" + required + ", display=" + display + ", displayName='" + displayName + '\'' + ", analytics='" + analytics + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\VariableDefinitionImpl.java
1
请完成以下Java代码
public class RuleEngineComponentLifecycleEventNotificationInfo implements RuleOriginatedNotificationInfo { private RuleChainId ruleChainId; private String ruleChainName; private EntityId componentId; private String componentName; private String action; private ComponentLifecycleEvent eventType; private String error; @Override public Map<String, String> getTemplateData() { return mapOf( "ruleChainId", ruleChainId.toString(), "ruleChainName", ruleChainName,
"componentId", componentId.toString(), "componentType", componentId.getEntityType().getNormalName(), "componentName", componentName, "action", action, "eventType", eventType.name().toLowerCase(), "error", error ); } @Override public EntityId getStateEntityId() { return ruleChainId; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\info\RuleEngineComponentLifecycleEventNotificationInfo.java
1
请在Spring Boot框架中完成以下Java代码
public String getAnnotationFontName() { return annotationFontName; } public void setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; } public boolean isFormFieldValidationEnabled() { return formFieldValidationEnabled; } public void setFormFieldValidationEnabled(boolean formFieldValidationEnabled) { this.formFieldValidationEnabled = formFieldValidationEnabled; } public Duration getLockPollRate() { return lockPollRate; } public void setLockPollRate(Duration lockPollRate) { this.lockPollRate = lockPollRate; } public Duration getSchemaLockWaitTime() { return schemaLockWaitTime; } public void setSchemaLockWaitTime(Duration schemaLockWaitTime) { this.schemaLockWaitTime = schemaLockWaitTime; } public boolean isEnableHistoryCleaning() { return enableHistoryCleaning; } public void setEnableHistoryCleaning(boolean enableHistoryCleaning) { this.enableHistoryCleaning = enableHistoryCleaning; } public String getHistoryCleaningCycle() {
return historyCleaningCycle; } public void setHistoryCleaningCycle(String historyCleaningCycle) { this.historyCleaningCycle = historyCleaningCycle; } @Deprecated @DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration") public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) { this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays); } public Duration getHistoryCleaningAfter() { return historyCleaningAfter; } public void setHistoryCleaningAfter(Duration historyCleaningAfter) { this.historyCleaningAfter = historyCleaningAfter; } public int getHistoryCleaningBatchSize() { return historyCleaningBatchSize; } public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) { this.historyCleaningBatchSize = historyCleaningBatchSize; } public String getVariableJsonMapper() { return variableJsonMapper; } public void setVariableJsonMapper(String variableJsonMapper) { this.variableJsonMapper = variableJsonMapper; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java
2
请完成以下Java代码
public static boolean isRegular(@Nullable final HUPIItemProductId id) { return id != null && id.isRegular(); } public static final HUPIItemProductId TEMPLATE_HU = new HUPIItemProductId(100); public static final HUPIItemProductId VIRTUAL_HU = new HUPIItemProductId(101); int repoId; private HUPIItemProductId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Item_Product_ID"); } @JsonValue @Override public int getRepoId() { return repoId; } public static boolean equals(@Nullable final HUPIItemProductId id1, @Nullable final HUPIItemProductId id2) { return Objects.equals(id1, id2); } public static HUPIItemProductId nullToVirtual(final HUPIItemProductId id) { return id != null ? id : VIRTUAL_HU;
} public boolean isVirtualHU() { return isVirtualHU(repoId); } public static boolean isVirtualHU(final int repoId) { return repoId == VIRTUAL_HU.repoId; } public boolean isRegular() { return repoId != VIRTUAL_HU.repoId && repoId != TEMPLATE_HU.repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HUPIItemProductId.java
1
请完成以下Java代码
protected void setValue(Object value) { if (m_multiSelection) { boolean sel = false; if (value == null) ; else if (value instanceof IDColumn) sel = ((IDColumn)value).isSelected(); else if (value instanceof Boolean) sel = ((Boolean)value).booleanValue(); else sel = value.toString().equals("Y"); // m_check.setSelected(sel); } } // setValue /**
* Return rendering component * @param table * @param value * @param isSelected * @param hasFocus * @param row * @param column * @return Component (CheckBox or Button) */ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setValue(value); if (m_multiSelection) return m_check; else return m_button; } // setTableCellRenderereComponent } // IDColumnRenderer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\IDColumnRenderer.java
1
请在Spring Boot框架中完成以下Java代码
public static Payment createPayment(PaymentRequest paymentRequest) { UUID uuid = UUID.randomUUID(); String uuidAsString = uuid.toString(); Payment payment = new Payment(); payment.setPaymentId(uuidAsString); payment.setOrderId(paymentRequest.getOrderId()); payment.setAmount(paymentRequest.getAmount()); payment.setPaymentMethod(paymentRequest.getMethod()); payment.setStatus(Payment.Status.PENDING); // Check if returned error is non-empty, i.e failure if (!paymentsDAO.insertPayment(payment).isEmpty()) { log.error("Failed to process payment for order {}", paymentRequest.getOrderId()); payment.setErrorMsg("Payment creation failure"); payment.setStatus(Payment.Status.FAILED); } else { if(makePayment(payment)) { payment.setStatus(Payment.Status.SUCCESSFUL); } else { payment.setStatus(Payment.Status.FAILED); } } // Record final status paymentsDAO.updatePaymentStatus(payment); return payment; } public static void cancelPayment(String orderId) { // Cancel Payment in DB Payment payment = new Payment(); paymentsDAO.readPayment(orderId, payment); payment.setStatus(Payment.Status.CANCELED); paymentsDAO.updatePaymentStatus(payment); } private static boolean makePayment(Payment payment) { if (Objects.equals(payment.getPaymentMethod().getType(), "Credit Card")) { PaymentDetails details = payment.getPaymentMethod().getDetails(); DateFormat dateFormat= new SimpleDateFormat("MM/yyyy"); Date expiry = new Date();
try { expiry = dateFormat.parse(details.getExpiry()); } catch (ParseException e) { payment.setErrorMsg("Invalid expiry date:" + details.getExpiry()); return false; } Date today = new Date(); if (today.getTime() > expiry.getTime()) { payment.setErrorMsg("Expired payment method:" + details.getExpiry()); return false; } } // Ideally an async call would be made with a callback // But, we're skipping that and assuming payment went through return true; } }
repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\service\PaymentService.java
2
请完成以下Java代码
public boolean isBlocking() { return isBlockingAttribute.getValue(this); } public void setIsBlocking(boolean isBlocking) { isBlockingAttribute.setValue(this, isBlocking); } public Collection<InputsCaseParameter> getInputs() { return inputsCollection.get(this); } public Collection<OutputsCaseParameter> getOutputs() { return outputsCollection.get(this); } public Collection<InputCaseParameter> getInputParameters() { return inputParameterCollection.get(this); } public Collection<OutputCaseParameter> getOutputParameters() { return outputParameterCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Task.class, CMMN_ELEMENT_TASK) .namespaceUri(CMMN11_NS) .extendsType(PlanItemDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<Task>() { public Task newInstance(ModelTypeInstanceContext instanceContext) { return new TaskImpl(instanceContext); } }); isBlockingAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_IS_BLOCKING)
.defaultValue(true) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputsCollection = sequenceBuilder.elementCollection(InputsCaseParameter.class) .build(); outputsCollection = sequenceBuilder.elementCollection(OutputsCaseParameter.class) .build(); inputParameterCollection = sequenceBuilder.elementCollection(InputCaseParameter.class) .build(); outputParameterCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TaskImpl.java
1
请完成以下Java代码
protected Collection<Object> merge(Supplier<Collection<Object>> existing, Collection<Object> additional) { Collection<Object> existingCollection = getExistingIfPossible(existing); if (existingCollection == null) { return additional; } try { existingCollection.clear(); existingCollection.addAll(additional); return copyIfPossible(existingCollection); } catch (UnsupportedOperationException ex) { return createNewCollection(additional); } } private @Nullable Collection<Object> getExistingIfPossible(Supplier<Collection<Object>> existing) { try { return existing.get(); } catch (Exception ex) { return null; } }
private Collection<Object> copyIfPossible(Collection<Object> collection) { try { return createNewCollection(collection); } catch (Exception ex) { return collection; } } private Collection<Object> createNewCollection(Collection<Object> collection) { Collection<Object> result = CollectionFactory.createCollection(collection.getClass(), collection.size()); result.addAll(collection); return result; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\CollectionBinder.java
1
请完成以下Java代码
public List<Type> getContent() { return this.content; } /** * Return the {@link Type} with the specified id or {@code null} if no such type * exists. * @param id the ID to find * @return the Type or {@code null} */ public Type get(String id) { return this.content.stream().filter((it) -> id.equals(it.getId())).findFirst().orElse(null); } /** * Return the default {@link Type}.
*/ @Override public Type getDefault() { return this.content.stream().filter(DefaultMetadataElement::isDefault).findFirst().orElse(null); } @Override public void merge(List<Type> otherContent) { otherContent.forEach((it) -> { if (get(it.getId()) == null) { this.content.add(it); } }); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\TypeCapability.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isWithoutProcessInstanceId() { return withoutProcessInstanceId; } public String getActivityId() { return activityId; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isWithoutProcessDefinitionId() { return withoutProcessDefinitionId; } public String getSubScopeId() { return subScopeId; } public String getScopeId() { return scopeId; } public boolean isWithoutScopeId() { return withoutScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public boolean isWithoutScopeDefinitionId() { return withoutScopeDefinitionId; } public String getScopeDefinitionKey() { return scopeDefinitionKey; } public String getScopeType() { return scopeType; } public Date getCreatedBefore() { return createdBefore; } public Date getCreatedAfter() { return createdAfter; } public String getTenantId() { return tenantId; } public Collection<String> getTenantIds() { return tenantIds;
} public boolean isWithoutTenantId() { return withoutTenantId; } public String getConfiguration() { return configuration; } public Collection<String> getConfigurations() { return configurations; } public boolean isWithoutConfiguration() { return withoutConfiguration; } public List<EventSubscriptionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public EventSubscriptionQueryImpl getCurrentOrQueryObject() { return currentOrQueryObject; } public boolean isInOrStatement() { return inOrStatement; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public static <T> BaseResult<T> success() { return new BaseResult<>(); } public static <T> BaseResult<T> successWithData(T data) { return new BaseResult<>(data); } public static <T> BaseResult<T> failWithCodeAndMsg(int code, String msg) { return new BaseResult<>(code, msg, null); } public static <T> BaseResult<T> buildWithParam(ResponseParam param) { return new BaseResult<>(param.getCode(), param.getMsg(), null); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } public static class ResponseParam { private int code; private String msg;
private ResponseParam(int code, String msg) { this.code = code; this.msg = msg; } public static ResponseParam buildParam(int code, String msg) { return new ResponseParam(code, msg); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\config\BaseResult.java
2
请在Spring Boot框架中完成以下Java代码
public void init(PartitionedQueueConsumerManager<TbProtoQueueMsg<ToCalculatedFieldMsg>> eventConsumer) { super.stateService = new DefaultQueueStateService<>(eventConsumer); } @Override protected void doPersist(CalculatedFieldEntityCtxId stateId, CalculatedFieldStateProto stateMsgProto, TbCallback callback) { cfRocksDb.put(stateId.toKey(), stateMsgProto.toByteArray()); callback.onSuccess(); } @Override protected void doRemove(CalculatedFieldEntityCtxId stateId, TbCallback callback) { cfRocksDb.delete(stateId.toKey()); callback.onSuccess(); } @Override public void restore(QueueKey queueKey, Set<TopicPartitionInfo> partitions) { if (stateService.getPartitions().isEmpty()) { cfRocksDb.forEach((key, value) -> { CalculatedFieldStateProto stateMsg; try {
stateMsg = CalculatedFieldStateProto.parseFrom(value); } catch (Exception e) { log.error("Failed to parse CalculatedFieldStateProto for key {}", key, e); return; } processRestoredState(stateMsg, null, new TbCallback() { @Override public void onSuccess() {} @Override public void onFailure(Throwable t) { log.error("Failed to process CF state message: {}", stateMsg, t); } }); }); } super.restore(queueKey, partitions); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\ctx\state\RocksDBCalculatedFieldStateService.java
2
请完成以下Java代码
public void preventMovingSourceHu(@NonNull final I_M_HU hu) { final ISourceHuDAO sourceHuDAO = Services.get(ISourceHuDAO.class); final boolean sourceHU = sourceHuDAO.isSourceHu(HuId.ofRepoId(hu.getM_HU_ID())); if (sourceHU) { throw new SourceHuMayNotBeRemovedException(hu); } } @SuppressWarnings("serial") public static final class SourceHuMayNotBeRemovedException extends AdempiereException { private static final AdMessageKey MSG_CANNOT_MOVE_SOURCE_HU_1P = AdMessageKey.of("CANNOT_MOVE_SOURCE_HU"); private SourceHuMayNotBeRemovedException(final I_M_HU hu) { super(MSG_CANNOT_MOVE_SOURCE_HU_1P, new Object[] { hu.getValue() }); } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_M_HU.COLUMNNAME_HUStatus) public void validateHUStatus(@NonNull final I_M_HU hu) { final String huStatus = hu.getHUStatus();
final boolean isHUConsumed = X_M_HU.HUSTATUS_Picked.equals(huStatus) || X_M_HU.HUSTATUS_Shipped.equals(huStatus) || X_M_HU.HUSTATUS_Issued.equals(huStatus); if (!isHUConsumed) { return; } if (!handlingUnitsBL.isHUHierarchyCleared(hu)) { throw new AdempiereException("M_HUs that are not cleared can not be picked, shipped or issued!") .appendParametersToMessage() .setParameter("M_HU_ID", hu.getM_HU_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\interceptor\M_HU.java
1
请完成以下Java代码
public DocumentId toDocumentId() { DocumentId documentId = this._documentId; if (documentId == null) { final String sb = type.getCode() + PARTS_SEPARATOR + parentRowId + PARTS_SEPARATOR + recordId; documentId = this._documentId = DocumentId.ofString(sb); } return documentId; } public static PPOrderLineRowId fromDocumentId(final DocumentId documentId) { final List<String> parts = PARTS_SPLITTER.splitToList(documentId.toJson()); return fromStringPartsList(parts); } private static PPOrderLineRowId fromStringPartsList(final List<String> parts) { final int partsCount = parts.size(); if (partsCount < 1) { throw new IllegalArgumentException("Invalid id: " + parts); } final PPOrderLineRowType type = PPOrderLineRowType.forCode(parts.get(0)); final DocumentId parentRowId = !Check.isEmpty(parts.get(1), true) ? DocumentId.of(parts.get(1)) : null; final int recordId = Integer.parseInt(parts.get(2)); return new PPOrderLineRowId(type, parentRowId, recordId); } public static PPOrderLineRowId ofPPOrderBomLineId(int ppOrderBomLineId) { Preconditions.checkArgument(ppOrderBomLineId > 0, "ppOrderBomLineId > 0"); return new PPOrderLineRowId(PPOrderLineRowType.PP_OrderBomLine, null, ppOrderBomLineId);
} public static PPOrderLineRowId ofPPOrderId(int ppOrderId) { Preconditions.checkArgument(ppOrderId > 0, "ppOrderId > 0"); return new PPOrderLineRowId(PPOrderLineRowType.PP_Order, null, ppOrderId); } public static PPOrderLineRowId ofIssuedOrReceivedHU(@Nullable DocumentId parentRowId, @NonNull final HuId huId) { return new PPOrderLineRowId(PPOrderLineRowType.IssuedOrReceivedHU, parentRowId, huId.getRepoId()); } public static PPOrderLineRowId ofSourceHU(@NonNull DocumentId parentRowId, @NonNull final HuId sourceHuId) { return new PPOrderLineRowId(PPOrderLineRowType.Source_HU, parentRowId, sourceHuId.getRepoId()); } public Optional<PPOrderBOMLineId> getPPOrderBOMLineIdIfApplies() { return type.isPP_OrderBomLine() ? PPOrderBOMLineId.optionalOfRepoId(recordId) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRowId.java
1
请完成以下Java代码
public VariableInstanceQuery variableValueLike(String variableName, String variableValue) { wrappedVariableInstanceQuery.variableValueLike(variableName, variableValue); return this; } @Override public VariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) { wrappedVariableInstanceQuery.variableValueLikeIgnoreCase(variableName, variableValue); return this; } @Override public VariableInstanceQuery orderByVariableName() { wrappedVariableInstanceQuery.orderByVariableName(); return this; } @Override public VariableInstanceQuery asc() { wrappedVariableInstanceQuery.asc(); return this; } @Override public VariableInstanceQuery desc() { wrappedVariableInstanceQuery.desc(); return this; } @Override public VariableInstanceQuery orderBy(QueryProperty property) { wrappedVariableInstanceQuery.orderBy(property); return this; } @Override public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return wrappedVariableInstanceQuery.count(); } @Override public VariableInstance singleResult() { return wrappedVariableInstanceQuery.singleResult(); } @Override public List<VariableInstance> list() { return wrappedVariableInstanceQuery.list(); } @Override public List<VariableInstance> listPage(int firstResult, int maxResults) { return wrappedVariableInstanceQuery.listPage(firstResult, maxResults); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java
1
请完成以下Java代码
public class Jackson2JsonMessageConverter extends AbstractJackson2MessageConverter { /** * Construct with an internal {@link ObjectMapper} instance * and trusted packed to all ({@code *}). * @since 1.6.11 * @see JacksonUtils#enhancedObjectMapper() */ public Jackson2JsonMessageConverter() { this("*"); } /** * Construct with an internal {@link ObjectMapper} instance. * The {@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} is set to false on * the {@link ObjectMapper}. * @param trustedPackages the trusted Java packages for deserialization * @since 1.6.11 * @see DefaultJackson2JavaTypeMapper#setTrustedPackages(String...) * @see JacksonUtils#enhancedObjectMapper() */ public Jackson2JsonMessageConverter(String... trustedPackages) { this(JacksonUtils.enhancedObjectMapper(), trustedPackages);
} /** * Construct with the provided {@link ObjectMapper} instance * and trusted packed to all ({@code *}). * @param jsonObjectMapper the {@link ObjectMapper} to use. * @since 1.6.12 */ public Jackson2JsonMessageConverter(ObjectMapper jsonObjectMapper) { this(jsonObjectMapper, "*"); } /** * Construct with the provided {@link ObjectMapper} instance. * @param jsonObjectMapper the {@link ObjectMapper} to use. * @param trustedPackages the trusted Java packages for deserialization * @since 1.6.11 * @see DefaultJackson2JavaTypeMapper#setTrustedPackages(String...) */ public Jackson2JsonMessageConverter(ObjectMapper jsonObjectMapper, String... trustedPackages) { super(jsonObjectMapper, MimeTypeUtils.parseMimeType(MessageProperties.CONTENT_TYPE_JSON), trustedPackages); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\Jackson2JsonMessageConverter.java
1
请完成以下Java代码
public boolean supports(Class<?> authentication) { return OAuth2RefreshTokenAuthenticationToken.class.isAssignableFrom(authentication); } private static void verifyDPoPProofPublicKey(Jwt dPoPProof, ClaimAccessor accessTokenClaims) { JWK jwk = null; @SuppressWarnings("unchecked") Map<String, Object> jwkJson = (Map<String, Object>) dPoPProof.getHeaders().get("jwk"); try { jwk = JWK.parse(jwkJson); } catch (Exception ignored) { } if (jwk == null) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, "jwk header is missing or invalid.", null); throw new OAuth2AuthenticationException(error); } String jwkThumbprint; try { jwkThumbprint = jwk.computeThumbprint().toString(); } catch (Exception ex) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, "Failed to compute SHA-256 Thumbprint for jwk.", null); throw new OAuth2AuthenticationException(error);
} String jwkThumbprintClaim = null; Map<String, Object> confirmationMethodClaim = accessTokenClaims.getClaimAsMap("cnf"); if (!CollectionUtils.isEmpty(confirmationMethodClaim) && confirmationMethodClaim.containsKey("jkt")) { jwkThumbprintClaim = (String) confirmationMethodClaim.get("jkt"); } if (jwkThumbprintClaim == null) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, "jkt claim is missing.", null); throw new OAuth2AuthenticationException(error); } if (!jwkThumbprint.equals(jwkThumbprintClaim)) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, "jwk header is invalid.", null); throw new OAuth2AuthenticationException(error); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2RefreshTokenAuthenticationProvider.java
1
请完成以下Java代码
public class CompositeGridTabRowBuilder implements IGridTabRowBuilder { private static final transient Logger logger = LogManager.getLogger(CompositeGridTabRowBuilder.class); private final List<IGridTabRowBuilder> builders = new ArrayList<IGridTabRowBuilder>(); public void addGridTabRowBuilder(final IGridTabRowBuilder builder) { if (builder == null) { return; } if (builders.contains(builder)) { return; } builders.add(builder); } @Override public void apply(final Object model) { for (final IGridTabRowBuilder builder : builders) { if (!builder.isValid()) { logger.debug("Skip builder because it's not valid: {}", builder); continue; } builder.apply(model); logger.debug("Applied {} to {}", new Object[] { builder, model }); } } @Override public boolean isCreateNewRecord() { boolean createNewRecord = true; for (final IGridTabRowBuilder builder : builders) { if (!builder.isValid()) { createNewRecord = false; continue; } if (!builder.isCreateNewRecord()) { createNewRecord = false; } }
return createNewRecord; } /** * @return true if at least one builder is valid */ @Override public boolean isValid() { for (final IGridTabRowBuilder builder : builders) { if (builder.isValid()) { return true; } } return false; } @Override public void setSource(Object model) { for (final IGridTabRowBuilder builder : builders) { builder.setSource(model); } } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\impl\CompositeGridTabRowBuilder.java
1
请完成以下Java代码
public class Generic_OIHandler implements FAOpenItemsHandler { private final ElementValueService elementValueService; public Generic_OIHandler(final ElementValueService elementValueService) { this.elementValueService = elementValueService; } @Override public @NonNull Set<FAOpenItemsHandlerMatchingKey> getMatchers() { // shall not be called return ImmutableSet.of(); } @Override public Optional<FAOpenItemTrxInfo> computeTrxInfo(final FAOpenItemTrxInfoComputeRequest request) { final ElementValue elementValue = elementValueService.getById(request.getElementValueId()); if (elementValue.isOpenItem()) { final FAOpenItemKey key = FAOpenItemKey.ofTableRecordLineAndSubLineId( request.getAccountConceptualName(), request.getTableName(), request.getRecordId(), request.getLineId(), request.getSubLineId()); final FAOpenItemTrxInfo trxInfo = isClearing(request.getTableName()) ? FAOpenItemTrxInfo.clearing(key) : FAOpenItemTrxInfo.opening(key);
return Optional.of(trxInfo); } else { return Optional.empty(); } } private static boolean isClearing(final String tableName) { return I_C_AllocationHdr.Table_Name.equals(tableName) || I_M_MatchInv.Table_Name.equals(tableName); } @Override public void onGLJournalLineCompleted(final SAPGLJournalLine line) { } @Override public void onGLJournalLineReactivated(final SAPGLJournalLine line) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\handlers\Generic_OIHandler.java
1
请完成以下Java代码
public T orElseGet(Supplier<? extends T> other) { return (this.value != null) ? this.value : other.get(); } /** * Return the object that was bound, or throw an exception to be created by the * provided supplier if no value has been bound. * @param <X> the type of the exception to be thrown * @param exceptionSupplier the supplier which will return the exception to be thrown * @return the present value * @throws X if there is no value present */ public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (this.value == null) { throw exceptionSupplier.get(); } return this.value; } @Override public boolean equals(Object obj) { if (this == obj) {
return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return ObjectUtils.nullSafeEquals(this.value, ((BindResult<?>) obj).value); } @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(this.value); } @SuppressWarnings("unchecked") static <T> BindResult<T> of(@Nullable T value) { if (value == null) { return (BindResult<T>) UNBOUND; } return new BindResult<>(value); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\BindResult.java
1
请完成以下Java代码
public class HibernateScalarExample { private Session session; public HibernateScalarExample(Session session) { this.session = session; } public List<Object[]> fetchColumnWithNativeQuery() { return session.createNativeQuery("SELECT * FROM Student student") .list(); } public List<Object[]> fetchColumnWithScalar() { return session.createNativeQuery("SELECT * FROM Student student") .addScalar("studentId", StandardBasicTypes.LONG) .addScalar("name", StandardBasicTypes.STRING) .addScalar("age", StandardBasicTypes.INTEGER) .list(); }
public List<String> fetchLimitedColumnWithScalar() { return session.createNativeQuery("SELECT * FROM Student student") .addScalar("name", StandardBasicTypes.STRING) .list(); } public List<Object[]> fetchColumnWithOverloadedScalar() { return session.createNativeQuery("SELECT * FROM Student student") .addScalar("name", StandardBasicTypes.STRING) .addScalar("age") .list(); } public Double fetchAvgAgeWithScalar() { return (Double) session.createNativeQuery("SELECT AVG(age) as avgAge FROM Student student") .addScalar("avgAge") .uniqueResult(); } }
repos\tutorials-master\persistence-modules\hibernate-queries-2\src\main\java\com\baeldung\hibernate\scalarmethod\HibernateScalarExample.java
1
请完成以下Java代码
public List<ValidationResultType> getValidationResult() { if (validationResult == null) { validationResult = new ArrayList<ValidationResultType>(); } return this.validationResult; } /** * Gets the value of the originator property. * * @return * possible object is * {@link String } * */ public String getOriginator() { return originator; } /** * Sets the value of the originator property. * * @param value * allowed object is * {@link String } * */ public void setOriginator(String value) { this.originator = value; } /** * Gets the value of the remark property. * * @return * possible object is * {@link String }
* */ public String getRemark() { return remark; } /** * Sets the value of the remark property. * * @param value * allowed object is * {@link String } * */ public void setRemark(String value) { this.remark = value; } /** * Gets the value of the status property. * */ public int getStatus() { return status; } /** * Sets the value of the status property. * */ public void setStatus(int value) { this.status = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ValidationType.java
1
请完成以下Java代码
public static EntityType resolveEntityType(EntityFilter entityFilter) { switch (entityFilter.getType()) { case SINGLE_ENTITY: return ((SingleEntityFilter) entityFilter).getSingleEntity().getEntityType(); case ENTITY_LIST: return ((EntityListFilter) entityFilter).getEntityType(); case ENTITY_NAME: return ((EntityNameFilter) entityFilter).getEntityType(); case ENTITY_TYPE: return ((EntityTypeFilter) entityFilter).getEntityType(); case ASSET_TYPE: case ASSET_SEARCH_QUERY: return EntityType.ASSET; case DEVICE_TYPE: case DEVICE_SEARCH_QUERY: return EntityType.DEVICE;
case ENTITY_VIEW_TYPE: case ENTITY_VIEW_SEARCH_QUERY: return EntityType.ENTITY_VIEW; case EDGE_TYPE: case EDGE_SEARCH_QUERY: return EntityType.EDGE; case RELATIONS_QUERY: RelationsQueryFilter rgf = (RelationsQueryFilter) entityFilter; return rgf.isMultiRoot() ? rgf.getMultiRootEntitiesType() : rgf.getRootEntity().getEntityType(); case API_USAGE_STATE: return EntityType.API_USAGE_STATE; default: throw new RuntimeException("Not implemented!"); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\DefaultEntityQueryRepository.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientBillingAddress patientBillingAddress = (PatientBillingAddress) o; return Objects.equals(this.gender, patientBillingAddress.gender) && Objects.equals(this.title, patientBillingAddress.title) && Objects.equals(this.name, patientBillingAddress.name) && Objects.equals(this.address, patientBillingAddress.address) && Objects.equals(this.postalCode, patientBillingAddress.postalCode) && Objects.equals(this.city, patientBillingAddress.city); } @Override public int hashCode() { return Objects.hash(gender, title, name, address, postalCode, city); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientBillingAddress {\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientBillingAddress.java
2
请在Spring Boot框架中完成以下Java代码
public class PmsRolePermissionDaoImpl extends PermissionBaseDaoImpl<PmsRolePermission> implements PmsRolePermissionDao { /** * 根据角色ID找到角色关联的权限点. * * @param roleId * . * @return rolePermissionList . */ public List<PmsRolePermission> listByRoleId(final long roleId) { return super.getSessionTemplate().selectList(getStatement("listByRoleId"), roleId); } /** * 根据角色ID字符串获取相应角色-权限关联信息. * * @param roleIds
* @return */ public List<PmsRolePermission> listByRoleIds(String roleIdsStr) { List<String> roldIds = Arrays.asList(roleIdsStr.split(",")); return super.getSessionTemplate().selectList(getStatement("listByRoleIds"), roldIds); } public void deleteByRoleIdAndPermissionId(Long roleId, Long permissionId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("roleId", roleId); paramMap.put("permissionId", permissionId); super.getSessionTemplate().delete(getStatement("deleteByRoleIdAndPermissionId"), paramMap); } public void deleteByRoleId(Long roleId){ super.getSessionTemplate().delete(getStatement("deleteByRoleId"), roleId); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsRolePermissionDaoImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteLogicDeleted(List<String> ids) { this.baseMapper.deleteLogicDeleted(ids); resreshRouter(ids.get(0)); } /** * 路由复制 * @param id * @return */ @Override @Transactional(rollbackFor = Exception.class) public SysGatewayRoute copyRoute(String id) { log.info("--gateway 路由复制--"); SysGatewayRoute targetRoute = new SysGatewayRoute(); try { SysGatewayRoute sourceRoute = this.baseMapper.selectById(id); //1.复制路由 BeanUtils.copyProperties(sourceRoute,targetRoute); //1.1 获取当前日期 String formattedDate = dateFormat.format(new Date()); String copyRouteName = sourceRoute.getName() + "_copy_"; //1.2 判断数据库是否存在 Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<SysGatewayRoute>().eq(SysGatewayRoute::getName, copyRouteName + formattedDate)); //1.3 新的路由名称 copyRouteName += count > 0?RandomUtil.randomNumbers(4):formattedDate; targetRoute.setId(null); targetRoute.setName(copyRouteName); targetRoute.setCreateTime(new Date()); targetRoute.setStatus(0); targetRoute.setDelFlag(CommonConstant.DEL_FLAG_0); this.baseMapper.insert(targetRoute); //2.刷新路由 resreshRouter(null);
} catch (Exception e) { log.error("路由配置解析失败", e); resreshRouter(null); e.printStackTrace(); } return targetRoute; } /** * 查询删除列表 * @return */ @Override public List<SysGatewayRoute> getDeletelist() { return baseMapper.queryDeleteList(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysGatewayRouteServiceImpl.java
2
请完成以下Java代码
public CaseDefinitionCacheEntry getCaseDefinitionCacheEntry(String caseDefinitionId) { return caseDefinitionCache.get(caseDefinitionId); } // getters and setters //////////////////////////////////////////////////////// @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null; } @Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "CmmnDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityImpl.java
1
请完成以下Java代码
private final Optional<BPartnerLocationId> getShipReceiptBPLocationId() { Optional<BPartnerLocationId> shipReceiptBPLocationId = this._shipReceiptBPLocationId; if (shipReceiptBPLocationId == null) { shipReceiptBPLocationId = this._shipReceiptBPLocationId = computeShipReceiptBPLocationId(); } return shipReceiptBPLocationId; } private final Optional<BPartnerLocationId> computeShipReceiptBPLocationId() { final I_M_InOutLine inoutLine = getInOutLine().orElse(null); if (inoutLine != null) { final I_M_InOut inout = inoutLine.getM_InOut(); return Optional.of(BPartnerLocationId.ofRepoId(inout.getC_BPartner_ID(), inout.getC_BPartner_Location_ID())); } final I_C_Order order = invoiceCandidate.getC_Order(); if (order != null) { return Optional.of(BPartnerLocationId.ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID())); } return Optional.empty();
} public ArrayKey getInvoiceLineAttributesKey() { ArrayKey invoiceLineAttributesKey = _invoiceLineAttributesKey; if (invoiceLineAttributesKey == null) { invoiceLineAttributesKey = _invoiceLineAttributesKey = computeInvoiceLineAttributesKey(); } return invoiceLineAttributesKey; } private ArrayKey computeInvoiceLineAttributesKey() { final ArrayKeyBuilder keyBuilder = ArrayKey.builder(); for (final IInvoiceLineAttribute invoiceLineAttribute : invoiceLineAttributes) { keyBuilder.append(invoiceLineAttribute.toAggregationKey()); } return keyBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationKeyEvaluationContext.java
1
请完成以下Java代码
public boolean containsRawMaterialsIssueStep(final PPOrderIssueScheduleId issueScheduleId) { return rawMaterialsIssue != null && rawMaterialsIssue.containsRawMaterialsIssueStep(issueScheduleId); } public ManufacturingJobActivity withChangedRawMaterialsIssueStep( @NonNull final PPOrderIssueScheduleId issueScheduleId, @NonNull UnaryOperator<RawMaterialsIssueStep> mapper) { if (rawMaterialsIssue != null) { return withRawMaterialsIssue(rawMaterialsIssue.withChangedRawMaterialsIssueStep(issueScheduleId, mapper)); } else { return this; } } public ManufacturingJobActivity withRawMaterialsIssue(@Nullable RawMaterialsIssue rawMaterialsIssue) { return Objects.equals(this.rawMaterialsIssue, rawMaterialsIssue) ? this : toBuilder().rawMaterialsIssue(rawMaterialsIssue).build(); } public ManufacturingJobActivity withChangedReceiveLine( @NonNull final FinishedGoodsReceiveLineId id, @NonNull UnaryOperator<FinishedGoodsReceiveLine> mapper) { if (finishedGoodsReceive != null) { return withFinishedGoodsReceive(finishedGoodsReceive.withChangedReceiveLine(id, mapper));
} else { return this; } } public ManufacturingJobActivity withFinishedGoodsReceive(@Nullable FinishedGoodsReceive finishedGoodsReceive) { return Objects.equals(this.finishedGoodsReceive, finishedGoodsReceive) ? this : toBuilder().finishedGoodsReceive(finishedGoodsReceive).build(); } @NonNull public ManufacturingJobActivity withChangedRawMaterialsIssue(@NonNull final UnaryOperator<RawMaterialsIssue> mapper) { if (rawMaterialsIssue != null) { return withRawMaterialsIssue(mapper.apply(rawMaterialsIssue)); } else { return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobActivity.java
1
请在Spring Boot框架中完成以下Java代码
public UmsMenu getItem(Long id) { return menuMapper.selectByPrimaryKey(id); } @Override public int delete(Long id) { return menuMapper.deleteByPrimaryKey(id); } @Override public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); UmsMenuExample example = new UmsMenuExample(); example.setOrderByClause("sort desc"); example.createCriteria().andParentIdEqualTo(parentId); return menuMapper.selectByExample(example); } @Override public List<UmsMenuNode> treeList() { List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample()); List<UmsMenuNode> result = menuList.stream() .filter(menu -> menu.getParentId().equals(0L)) .map(menu -> covertMenuNode(menu, menuList)) .collect(Collectors.toList()); return result; }
@Override public int updateHidden(Long id, Integer hidden) { UmsMenu umsMenu = new UmsMenu(); umsMenu.setId(id); umsMenu.setHidden(hidden); return menuMapper.updateByPrimaryKeySelective(umsMenu); } /** * 将UmsMenu转化为UmsMenuNode并设置children属性 */ private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) { UmsMenuNode node = new UmsMenuNode(); BeanUtils.copyProperties(menu, node); List<UmsMenuNode> children = menuList.stream() .filter(subMenu -> subMenu.getParentId().equals(menu.getId())) .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList()); node.setChildren(children); return node; } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsMenuServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class CasUser { @Id private Long id; @Column(nullable = false, unique = true) private String email; private String password; public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\tutorials-master\security-modules\cas\cas-secured-app\src\main\java\com\baeldung\cassecuredapp\user\CasUser.java
2
请完成以下Java代码
protected Mono<Void> release(ServerWebExchange exchange, CachedBodyOutputMessage outputMessage, Throwable throwable) { if (outputMessage.isCached()) { return outputMessage.getBody().map(DataBufferUtils::release).then(Mono.error(throwable)); } return Mono.error(throwable); } ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers, CachedBodyOutputMessage outputMessage) { return new ServerHttpRequestDecorator(exchange.getRequest()) { @Override public HttpHeaders getHeaders() { long contentLength = headers.getContentLength(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.putAll(headers); if (contentLength > 0) { httpHeaders.setContentLength(contentLength); } else { // TODO: this causes a 'HTTP/1.1 411 Length Required' // on // httpbin.org httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked"); } return httpHeaders; } @Override public Flux<DataBuffer> getBody() { return outputMessage.getBody(); } }; } public static class Config { private @Nullable ParameterizedTypeReference inClass; private @Nullable ParameterizedTypeReference outClass; private @Nullable String contentType; private @Nullable RewriteFunction rewriteFunction; public @Nullable ParameterizedTypeReference getInClass() { return inClass; } public Config setInClass(Class inClass) { return setInClass(ParameterizedTypeReference.forType(inClass)); } public Config setInClass(ParameterizedTypeReference inTypeReference) { this.inClass = inTypeReference; return this; }
public @Nullable ParameterizedTypeReference getOutClass() { return outClass; } public Config setOutClass(Class outClass) { return setOutClass(ParameterizedTypeReference.forType(outClass)); } public Config setOutClass(ParameterizedTypeReference outClass) { this.outClass = outClass; return this; } public @Nullable RewriteFunction getRewriteFunction() { return rewriteFunction; } public Config setRewriteFunction(RewriteFunction rewriteFunction) { this.rewriteFunction = rewriteFunction; return this; } public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass, RewriteFunction<T, R> rewriteFunction) { setInClass(inClass); setOutClass(outClass); setRewriteFunction(rewriteFunction); return this; } public <T, R> Config setRewriteFunction(ParameterizedTypeReference<T> inClass, ParameterizedTypeReference<R> outClass, RewriteFunction<T, R> rewriteFunction) { setInClass(inClass); setOutClass(outClass); setRewriteFunction(rewriteFunction); return this; } public @Nullable String getContentType() { return contentType; } public Config setContentType(@Nullable String contentType) { this.contentType = contentType; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\ModifyRequestBodyGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) { ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig(); managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled()); managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl()); managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval()); return managementCenterConfig; } private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig(); /* Number of backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. */ mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount()); /* Valid values are: NONE (no eviction), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default. */ mapConfig.setEvictionPolicy(EvictionPolicy.LRU); /*
Maximum size of the map. When max size is reached, map is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. */ mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE)); return mapConfig; } private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig(); mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds()); return mapConfig; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\CacheConfiguration.java
2
请完成以下Java代码
public <ID extends RepoIdAware> ImmutableSet<ID> getRecordIdsToRefresh( @NonNull final DocumentIdsSelection rowIds, @NonNull final Function<DocumentId, ID> idMapper) { return getRowsIndex().getRecordIdsToRefresh(rowIds, idMapper); } public Stream<T> stream() {return getRowsIndex().stream();} public Stream<T> stream(Predicate<T> predicate) {return getRowsIndex().stream(predicate);} public long count(Predicate<T> predicate) {return getRowsIndex().count(predicate);} public boolean anyMatch(final Predicate<T> predicate) {return getRowsIndex().anyMatch(predicate);} public List<T> list() {return getRowsIndex().list();} public void compute(@NonNull final UnaryOperator<ImmutableRowsIndex<T>> remappingFunction) { holder.compute(remappingFunction); } public void addRow(@NonNull final T row) { compute(rows -> rows.addingRow(row)); } @SuppressWarnings("unused") public void removeRowsById(@NonNull final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return; } compute(rows -> rows.removingRowIds(rowIds)); } @SuppressWarnings("unused") public void removingIf(@NonNull final Predicate<T> predicate) { compute(rows -> rows.removingIf(predicate)); } public void changeRowById(@NonNull DocumentId rowId, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRow(rowId, rowMapper)); } public void changeRowsByIds(@NonNull DocumentIdsSelection rowIds, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRows(rowIds, rowMapper)); }
public void setRows(@NonNull final List<T> rows) { holder.setValue(ImmutableRowsIndex.of(rows)); } @NonNull private ImmutableRowsIndex<T> getRowsIndex() { final ImmutableRowsIndex<T> rowsIndex = holder.getValue(); // shall not happen if (rowsIndex == null) { throw new AdempiereException("rowsIndex shall be set"); } return rowsIndex; } public Predicate<DocumentId> isRelevantForRefreshingByDocumentId() { final ImmutableRowsIndex<T> rows = getRowsIndex(); return rows::isRelevantForRefreshing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\SynchronizedRowsIndexHolder.java
1
请完成以下Java代码
public class StageResponse { protected String id; protected String name; protected boolean ended; protected Date endTime; protected boolean current; public StageResponse(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public boolean isEnded() { return ended; } public void setEnded(boolean ended) { this.ended = ended; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public boolean isCurrent() { return current; } public void setCurrent(boolean current) { this.current = current; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\StageResponse.java
1
请完成以下Java代码
public abstract class ExecutableArchiveLauncher extends Launcher { private static final String START_CLASS_ATTRIBUTE = "Start-Class"; private final Archive archive; public ExecutableArchiveLauncher() throws Exception { this(Archive.create(Launcher.class)); } protected ExecutableArchiveLauncher(Archive archive) throws Exception { this.archive = archive; this.classPathIndex = getClassPathIndex(this.archive); } @Override protected ClassLoader createClassLoader(Collection<URL> urls) throws Exception { if (this.classPathIndex != null) { urls = new ArrayList<>(urls); urls.addAll(this.classPathIndex.getUrls()); } return super.createClassLoader(urls); } @Override protected final Archive getArchive() { return this.archive; }
@Override protected String getMainClass() throws Exception { Manifest manifest = this.archive.getManifest(); String mainClass = (manifest != null) ? manifest.getMainAttributes().getValue(START_CLASS_ATTRIBUTE) : null; if (mainClass == null) { throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this); } return mainClass; } @Override protected Set<URL> getClassPathUrls() throws Exception { return this.archive.getClassPathUrls(this::isIncludedOnClassPathAndNotIndexed, this::isSearchedDirectory); } /** * Determine if the specified directory entry is a candidate for further searching. * @param entry the entry to check * @return {@code true} if the entry is a candidate for further searching */ protected boolean isSearchedDirectory(Archive.Entry entry) { return ((getEntryPathPrefix() == null) || entry.name().startsWith(getEntryPathPrefix())) && !isIncludedOnClassPath(entry); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\ExecutableArchiveLauncher.java
1
请完成以下Java代码
public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Package_HU_ID (final int M_Package_HU_ID) { if (M_Package_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, M_Package_HU_ID); } @Override public int getM_Package_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_Package_HU_ID); } @Override public org.compiere.model.I_M_Package getM_Package() { return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class); } @Override public void setM_Package(final org.compiere.model.I_M_Package M_Package) { set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package); }
@Override public void setM_Package_ID (final int M_Package_ID) { if (M_Package_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Package_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Package_ID, M_Package_ID); } @Override public int getM_Package_ID() { return get_ValueAsInt(COLUMNNAME_M_Package_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_Value (COLUMNNAME_M_PickingSlot_ID, null); else set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Package_HU.java
1
请完成以下Java代码
protected void init() { throw new IllegalArgumentException( "Normal 'init' on process engine only used for extended MyBatis mappings is not allowed, please use 'initFromProcessEngineConfiguration'. You cannot construct a process engine with this configuration."); } /** * initialize the {@link ProcessEngineConfiguration} from an existing one, * just using the database settings and initialize the database / MyBatis * stuff. */ public void initFromProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration, List<String> mappings) { this.wrappedConfiguration = processEngineConfiguration; this.mappingFiles = mappings; setDatabaseType(processEngineConfiguration.getDatabaseType()); setDataSource(processEngineConfiguration.getDataSource()); setDatabaseTablePrefix(processEngineConfiguration.getDatabaseTablePrefix()); setSkipIsolationLevelCheck(processEngineConfiguration.getSkipIsolationLevelCheck()); setHistoryLevel(processEngineConfiguration.getHistoryLevel()); setHistory(processEngineConfiguration.getHistory()); initDataSource(); initSerialization(); initCommandContextFactory(); initTransactionFactory(); initTransactionContextFactory(); initCommandExecutors(); initIdentityProviderSessionFactory(); initSqlSessionFactory(); initSessionFactories(); initValueTypeResolver(); } @Override public boolean isAuthorizationEnabled() { return wrappedConfiguration.isAuthorizationEnabled(); } @Override public String getAuthorizationCheckRevokes() { return wrappedConfiguration.getAuthorizationCheckRevokes(); } @Override protected InputStream getMyBatisXmlConfigurationSteam() { String str = buildMappings(mappingFiles); return new ByteArrayInputStream(str.getBytes()); } protected String buildMappings(List<String> mappingFiles) { List<String> mappings = new ArrayList<String>(mappingFiles); mappings.addAll(Arrays.asList(DEFAULT_MAPPING_FILES));
StringBuilder builder = new StringBuilder(); for (String mappingFile: mappings) { builder.append(String.format("<mapper resource=\"%s\" />\n", mappingFile)); } String mappingsFileTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "\n" + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n" + "\n" + "<configuration>\n" + " <settings>\n" + " <setting name=\"lazyLoadingEnabled\" value=\"false\" />\n" + " </settings>\n" + " <mappers>\n" + "%s\n" + " </mappers>\n" + "</configuration>"; return String.format(mappingsFileTemplate, builder.toString()); } public ProcessEngineConfigurationImpl getWrappedConfiguration() { return wrappedConfiguration; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\db\QuerySessionFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String readJsonAsObject() { try { String json = "{\"userName\":\"mrbird\"}"; User user = mapper.readValue(json, User.class); String name = user.getUserName(); return name; } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping("formatobjecttojsonstring") @ResponseBody public String formatObjectToJsonString() { try { User user = new User(); user.setUserName("mrbird"); user.setAge(26); user.setPassword("123456"); user.setBirthday(new Date()); String jsonStr = mapper.writeValueAsString(user); return jsonStr; } catch (Exception e) { e.printStackTrace();
} return null; } @RequestMapping("updateuser") @ResponseBody public int updateUser(@RequestBody List<User> list) { return list.size(); } @RequestMapping("customize") @ResponseBody public String customize() throws JsonParseException, JsonMappingException, IOException { String jsonStr = "[{\"userName\":\"mrbird\",\"age\":26},{\"userName\":\"scott\",\"age\":27}]"; JavaType type = mapper.getTypeFactory().constructParametricType(List.class, User.class); List<User> list = mapper.readValue(jsonStr, type); String msg = ""; for (User user : list) { msg += user.getUserName(); } return msg; } }
repos\SpringAll-master\18.Spring-Boot-Jackson\src\main\java\com\example\controller\TestJsonController.java
2
请完成以下Java代码
public void addRuleResult(int ruleNumber, String outputName, Object outputValue) { Map<String, Object> ruleResult; if (ruleResults.containsKey(ruleNumber)) { ruleResult = ruleResults.get(ruleNumber); } else { ruleResult = new HashMap<>(); ruleResults.put(ruleNumber, ruleResult); } ruleResult.put(outputName, outputValue); } public void setStackVariables(Map<String, Object> variables) { this.stackVariables = variables; } public Map<String, Object> getStackVariables() { return stackVariables; } public Map<String, Object> getRuleResult(int ruleNumber) { return ruleResults.get(ruleNumber); } public Map<Integer, Map<String, Object>> getRuleResults() { return ruleResults; } public DecisionExecutionAuditContainer getAuditContainer() { return auditContainer; } public void setAuditContainer(DecisionExecutionAuditContainer auditContainer) { this.auditContainer = auditContainer; } public Map<String, List<Object>> getOutputValues() { return outputValues; } public void addOutputValues(String outputName, List<Object> outputValues) { this.outputValues.put(outputName, outputValues); } public BuiltinAggregator getAggregator() { return aggregator; } public void setAggregator(BuiltinAggregator aggregator) { this.aggregator = aggregator; }
public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java
1
请完成以下Java代码
public Integer getSearchType() { return searchType; } public void setSearchType(Integer searchType) { this.searchType = searchType; } public Integer getRelatedStatus() { return relatedStatus; } public void setRelatedStatus(Integer relatedStatus) { this.relatedStatus = relatedStatus; } public Integer getHandAddStatus() { return handAddStatus; } public void setHandAddStatus(Integer handAddStatus) { this.handAddStatus = handAddStatus; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", selectType=").append(selectType); sb.append(", inputType=").append(inputType); sb.append(", inputList=").append(inputList); sb.append(", sort=").append(sort); sb.append(", filterType=").append(filterType); sb.append(", searchType=").append(searchType); sb.append(", relatedStatus=").append(relatedStatus); sb.append(", handAddStatus=").append(handAddStatus); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttribute.java
1
请完成以下Java代码
public class X_AD_Print_Clients extends org.compiere.model.PO implements I_AD_Print_Clients, org.compiere.model.I_Persistent { private static final long serialVersionUID = -978034459L; /** Standard Constructor */ public X_AD_Print_Clients (Properties ctx, int AD_Print_Clients_ID, String trxName) { super (ctx, AD_Print_Clients_ID, trxName); } /** Load Constructor */ public X_AD_Print_Clients (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Print_Clients_ID (int AD_Print_Clients_ID) { if (AD_Print_Clients_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Print_Clients_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Print_Clients_ID, Integer.valueOf(AD_Print_Clients_ID)); } @Override public int getAD_Print_Clients_ID() { return get_ValueAsInt(COLUMNNAME_AD_Print_Clients_ID); } @Override public org.compiere.model.I_AD_Session getAD_Session() { return get_ValueAsPO(COLUMNNAME_AD_Session_ID, org.compiere.model.I_AD_Session.class); }
@Override public void setAD_Session(org.compiere.model.I_AD_Session AD_Session) { set_ValueFromPO(COLUMNNAME_AD_Session_ID, org.compiere.model.I_AD_Session.class, AD_Session); } @Override public void setAD_Session_ID (int AD_Session_ID) { if (AD_Session_ID < 1) set_Value (COLUMNNAME_AD_Session_ID, null); else set_Value (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID)); } @Override public int getAD_Session_ID() { return get_ValueAsInt(COLUMNNAME_AD_Session_ID); } @Override public void setDateLastPoll (java.sql.Timestamp DateLastPoll) { set_Value (COLUMNNAME_DateLastPoll, DateLastPoll); } @Override public java.sql.Timestamp getDateLastPoll() { return get_ValueAsTimestamp(COLUMNNAME_DateLastPoll); } @Override public void setHostKey (java.lang.String HostKey) { set_Value (COLUMNNAME_HostKey, HostKey); } @Override public java.lang.String getHostKey() { return (java.lang.String)get_Value(COLUMNNAME_HostKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Print_Clients.java
1
请完成以下Java代码
public boolean isAutoComplete() { return autoComplete; } public void setAutoComplete(boolean autoComplete) { this.autoComplete = autoComplete; } public String getAutoCompleteCondition() { return autoCompleteCondition; } public void setAutoCompleteCondition(String autoCompleteCondition) { this.autoCompleteCondition = autoCompleteCondition; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public boolean isSameDeployment() { return sameDeployment; } public void setSameDeployment(boolean sameDeployment) { this.sameDeployment = sameDeployment; } public String getValidateFormFields() { return validateFormFields; } public void setValidateFormFields(String validateFormFields) { this.validateFormFields = validateFormFields; } @Override public void addExitCriterion(Criterion exitCriterion) { exitCriteria.add(exitCriterion); } public Integer getDisplayOrder() { return displayOrder;
} public void setDisplayOrder(Integer displayOrder) { this.displayOrder = displayOrder; } public String getIncludeInStageOverview() { return includeInStageOverview; } public void setIncludeInStageOverview(String includeInStageOverview) { this.includeInStageOverview = includeInStageOverview; } @Override public List<Criterion> getExitCriteria() { return exitCriteria; } @Override public void setExitCriteria(List<Criterion> exitCriteria) { this.exitCriteria = exitCriteria; } public String getBusinessStatus() { return businessStatus; } public void setBusinessStatus(String businessStatus) { this.businessStatus = businessStatus; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Stage.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceLineQuickInputCallout { private final PackingItemProductFieldHelper packingItemProductFieldHelper; public InvoiceLineQuickInputCallout(final PackingItemProductFieldHelper packingItemProductFieldHelper) { this.packingItemProductFieldHelper = packingItemProductFieldHelper; } public void onProductChange(@NonNull final ICalloutField calloutField) { final QuickInput quickInput = QuickInput.getQuickInputOrNull(calloutField); if (quickInput == null) { return; } if (!quickInput.hasField(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID)) { return;
} final IInvoiceLineQuickInput invoiceLineQuickInput = quickInput.getQuickInputDocumentAs(IInvoiceLineQuickInput.class); final ProductId productId = ProductId.ofRepoIdOrNull( invoiceLineQuickInput.getM_Product_ID() ); if ( productId == null) { return; } final I_C_Invoice invoice = quickInput.getRootDocumentAs(I_C_Invoice.class); final Optional<DefaultPackingItemCriteria> defaultPackingItemCriteria = DefaultPackingItemCriteria.of(invoice, productId); final I_M_HU_PI_Item_Product huPIItemProduct = defaultPackingItemCriteria.flatMap(packingItemProductFieldHelper::getDefaultPackingMaterial).orElse(null); invoiceLineQuickInput.setM_HU_PI_Item_Product(huPIItemProduct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\invoiceline\InvoiceLineQuickInputCallout.java
2
请完成以下Java代码
public static File unzipEntry( final File destinationDir, final ZipEntry zipEntry, final ZipInputStream zipInputStream) throws IOException { final File destFile = new File(destinationDir, zipEntry.getName()); if (zipEntry.isDirectory()) { destFile.mkdirs(); } else { final String destDirPath = destinationDir.getCanonicalPath(); final String destFilePath = destFile.getCanonicalPath(); if (!destFilePath.startsWith(destDirPath + File.separator)) { throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
} try (final FileOutputStream fos = new FileOutputStream(destFile)) { final byte[] buffer = new byte[4096]; int len; while ((len = zipInputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } } } return destFile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\util\FileUtils.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Warehouse_Group_ID (final int M_Warehouse_Group_ID) { if (M_Warehouse_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_Group_ID, M_Warehouse_Group_ID); }
@Override public int getM_Warehouse_Group_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_Group_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Group.java
1
请完成以下Java代码
public IntermediateCatchEventActivityBehavior createIntermediateCatchEventActivityBehavior(IntermediateCatchEvent intermediateCatchEvent) { return new IntermediateCatchEventActivityBehavior(); } @Override public IntermediateThrowNoneEventActivityBehavior createIntermediateThrowNoneEventActivityBehavior(ThrowEvent throwEvent) { return new IntermediateThrowNoneEventActivityBehavior(); } @Override public IntermediateThrowSignalEventActivityBehavior createIntermediateThrowSignalEventActivityBehavior(ThrowEvent throwEvent, Signal signal, EventSubscriptionDeclaration eventSubscriptionDeclaration) { return new IntermediateThrowSignalEventActivityBehavior(throwEvent, signal, eventSubscriptionDeclaration); } @Override public IntermediateThrowCompensationEventActivityBehavior createIntermediateThrowCompensationEventActivityBehavior(ThrowEvent throwEvent, CompensateEventDefinition compensateEventDefinition) { return new IntermediateThrowCompensationEventActivityBehavior(compensateEventDefinition); } // End events @Override public NoneEndEventActivityBehavior createNoneEndEventActivityBehavior(EndEvent endEvent) { return new NoneEndEventActivityBehavior(); } @Override public ErrorEndEventActivityBehavior createErrorEndEventActivityBehavior(EndEvent endEvent, ErrorEventDefinition errorEventDefinition) { return new ErrorEndEventActivityBehavior(errorEventDefinition.getErrorCode()); } @Override public CancelEndEventActivityBehavior createCancelEndEventActivityBehavior(EndEvent endEvent) { return new CancelEndEventActivityBehavior(); }
@Override public TerminateEndEventActivityBehavior createTerminateEndEventActivityBehavior(EndEvent endEvent) { return new TerminateEndEventActivityBehavior(endEvent); } // Boundary Events @Override public BoundaryEventActivityBehavior createBoundaryEventActivityBehavior(BoundaryEvent boundaryEvent, boolean interrupting, ActivityImpl activity) { return new BoundaryEventActivityBehavior(interrupting, activity.getId()); } @Override public CancelBoundaryEventActivityBehavior createCancelBoundaryEventActivityBehavior(CancelEventDefinition cancelEventDefinition) { return new CancelBoundaryEventActivityBehavior(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
1
请在Spring Boot框架中完成以下Java代码
public GroupResponse updateGroup(@ApiParam(name = "groupId") @PathVariable String groupId, @RequestBody GroupRequest groupRequest) { Group group = getGroupFromRequest(groupId); if (groupRequest.getId() == null || groupRequest.getId().equals(group.getId())) { if (groupRequest.isNameChanged()) { group.setName(groupRequest.getName()); } if (groupRequest.isTypeChanged()) { group.setType(groupRequest.getType()); } identityService.saveGroup(group); } else { throw new FlowableIllegalArgumentException("Key provided in request body doesn't match the key in the resource URL."); } return restResponseFactory.createGroupResponse(group); } @ApiOperation(value = "Delete a group", tags = { "Groups" }, code = 204) @ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the group was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested group does not exist.") }) @DeleteMapping("/groups/{groupId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteGroup(@ApiParam(name = "groupId") @PathVariable String groupId) { Group group = getGroupFromRequest(groupId); if (restApiInterceptor != null) { restApiInterceptor.deleteGroup(group); } identityService.deleteGroup(group.getId()); } }
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\group\GroupResource.java
2
请完成以下Java代码
public class TemplateParam extends BaseModel { /** * 值 */ private String value; /** * 颜色 */ private String color; public TemplateParam() { super(); } public TemplateParam(String value) { super(); this.value = value; }
public TemplateParam(String value, String color) { super(); this.value = value; this.color = color; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\model\TemplateParam.java
1
请完成以下Java代码
public class MqttTransportContext extends TransportContext { @Getter @Autowired(required = false) private MqttSslHandlerProvider sslHandlerProvider; @Getter @Autowired private JsonMqttAdaptor jsonMqttAdaptor; @Getter @Autowired private ProtoMqttAdaptor protoMqttAdaptor; @Getter @Autowired private TransportTenantProfileCache tenantProfileCache; @Getter @Autowired private GatewayMetricsService gatewayMetricsService; @Getter @Value("${transport.mqtt.netty.max_payload_size}") private Integer maxPayloadSize; @Getter @Value("${transport.mqtt.ssl.skip_validity_check_for_client_cert:false}") private boolean skipValidityCheckForClientCert; @Getter @Setter private SslHandler sslHandler; @Getter @Value("${transport.mqtt.msg_queue_size_per_device_limit:100}") private int messageQueueSizePerDeviceLimit; @Getter @Value("${transport.mqtt.timeout:10000}") private long timeout;
@Getter @Value("${transport.mqtt.disconnect_timeout:1000}") private long disconnectTimeout; @Getter @Value("${transport.mqtt.proxy_enabled:false}") private boolean proxyEnabled; private final AtomicInteger connectionsCounter = new AtomicInteger(); @PostConstruct public void init() { super.init(); transportService.createGaugeStats("openConnections", connectionsCounter); } public void channelRegistered() { connectionsCounter.incrementAndGet(); } public void channelUnregistered() { connectionsCounter.decrementAndGet(); } public boolean checkAddress(InetSocketAddress address) { return rateLimitService.checkAddress(address); } public void onAuthSuccess(InetSocketAddress address) { rateLimitService.onAuthSuccess(address); } public void onAuthFailure(InetSocketAddress address) { rateLimitService.onAuthFailure(address); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\MqttTransportContext.java
1
请完成以下Java代码
public boolean hasWeightGross() { final AttributeCode attr_WeightGross = getWeightGrossAttribute(); return hasWeightAttribute(attr_WeightGross); } /** * @return true if has WeightNet attribute */ @Override public boolean hasWeightNet() { final AttributeCode attr_WeightNet = getWeightNetAttribute(); return hasWeightAttribute(attr_WeightNet); } /** * @return true if has WeightTare attribute */ @Override public boolean hasWeightTare() { final AttributeCode attr_WeightTare = getWeightTareAttribute(); return hasWeightAttribute(attr_WeightTare); } /**
* @return true if has WeightTare(adjust) attribute */ @Override public boolean hasWeightTareAdjust() { final AttributeCode attr_WeightTareAdjust = getWeightTareAdjustAttribute(); return hasWeightAttribute(attr_WeightTareAdjust); } /** * @return true if given attribute exists */ private boolean hasWeightAttribute(final AttributeCode weightAttribute) { if (weightAttribute == null) { return false; } final IAttributeStorage attributeStorage = getAttributeStorage(); return attributeStorage.hasAttribute(weightAttribute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\AttributeStorageWeightableWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public List<MediaType> getStreamingMediaTypes() { return List.of(); } @Override public boolean canEncode(ResolvableType elementType, MimeType mimeType) { return getEncodableMimeTypes().contains(mimeType); } @NonNull @Override public Flux<DataBuffer> encode(Publisher<? extends OAuth2Error> error, DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) { return Mono.from(error).flatMap((data) -> { ByteArrayHttpOutputMessage bytes = new ByteArrayHttpOutputMessage(); try { this.messageConverter.write(data, MediaType.APPLICATION_JSON, bytes); return Mono.just(bytes.getBody().toByteArray()); } catch (IOException ex) { return Mono.error(ex); } }).map(bufferFactory::wrap).flux(); } @NonNull @Override public List<MimeType> getEncodableMimeTypes() { return List.of(MediaType.APPLICATION_JSON); }
private static class ByteArrayHttpOutputMessage implements HttpOutputMessage { private final ByteArrayOutputStream body = new ByteArrayOutputStream(); @NonNull @Override public ByteArrayOutputStream getBody() { return this.body; } @NonNull @Override public HttpHeaders getHeaders() { return new HttpHeaders(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\web\server\OAuth2ErrorEncoder.java
2
请完成以下Java代码
public List<FeelCustomFunctionProvider> getDmnFeelCustomFunctionProviders() { return dmnFeelCustomFunctionProviders; } public ProcessEngineConfigurationImpl setDmnFeelCustomFunctionProviders(List<FeelCustomFunctionProvider> dmnFeelCustomFunctionProviders) { this.dmnFeelCustomFunctionProviders = dmnFeelCustomFunctionProviders; return this; } public boolean isDmnFeelEnableLegacyBehavior() { return dmnFeelEnableLegacyBehavior; } public ProcessEngineConfigurationImpl setDmnFeelEnableLegacyBehavior(boolean dmnFeelEnableLegacyBehavior) { this.dmnFeelEnableLegacyBehavior = dmnFeelEnableLegacyBehavior; return this; } public boolean isDmnReturnBlankTableOutputAsNull() { return dmnReturnBlankTableOutputAsNull; } public ProcessEngineConfigurationImpl setDmnReturnBlankTableOutputAsNull(boolean dmnReturnBlankTableOutputAsNull) { this.dmnReturnBlankTableOutputAsNull = dmnReturnBlankTableOutputAsNull; return this; } public DiagnosticsCollector getDiagnosticsCollector() { return diagnosticsCollector; } public void setDiagnosticsCollector(DiagnosticsCollector diagnosticsCollector) { this.diagnosticsCollector = diagnosticsCollector; } public TelemetryDataImpl getTelemetryData() { return telemetryData; } public ProcessEngineConfigurationImpl setTelemetryData(TelemetryDataImpl telemetryData) { this.telemetryData = telemetryData; return this; } public boolean isReevaluateTimeCycleWhenDue() { return reevaluateTimeCycleWhenDue; }
public ProcessEngineConfigurationImpl setReevaluateTimeCycleWhenDue(boolean reevaluateTimeCycleWhenDue) { this.reevaluateTimeCycleWhenDue = reevaluateTimeCycleWhenDue; return this; } public int getRemovalTimeUpdateChunkSize() { return removalTimeUpdateChunkSize; } public ProcessEngineConfigurationImpl setRemovalTimeUpdateChunkSize(int removalTimeUpdateChunkSize) { this.removalTimeUpdateChunkSize = removalTimeUpdateChunkSize; return this; } /** * @return a exception code interceptor. The interceptor is not registered in case * {@code disableExceptionCode} is configured to {@code true}. */ protected ExceptionCodeInterceptor getExceptionCodeInterceptor() { return new ExceptionCodeInterceptor(builtinExceptionCodeProvider, customExceptionCodeProvider); } public DiagnosticsRegistry getDiagnosticsRegistry() { return diagnosticsRegistry; } public ProcessEngineConfiguration setDiagnosticsRegistry(DiagnosticsRegistry diagnosticsRegistry) { this.diagnosticsRegistry = diagnosticsRegistry; return this; } public boolean isLegacyJobRetryBehaviorEnabled() { return legacyJobRetryBehaviorEnabled; } public ProcessEngineConfiguration setLegacyJobRetryBehaviorEnabled(boolean legacyJobRetryBehaviorEnabled) { this.legacyJobRetryBehaviorEnabled = legacyJobRetryBehaviorEnabled; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请完成以下Java代码
public Object getProperty(String name) { ConfigurationProperty configurationProperty = findConfigurationProperty(name); return (configurationProperty != null) ? configurationProperty.getValue() : null; } /** {@inheritDoc} */ @Override public Origin getOrigin(String name) { return Origin.from(findConfigurationProperty(name)); } private ConfigurationProperty findConfigurationProperty(String name) { try { return findConfigurationProperty(ConfigurationPropertyName.of(name)); } catch (InvalidConfigurationPropertyNameException ex) { // simulate non-exposed version of ConfigurationPropertyName.of(name, nullIfInvalid) if(ex.getInvalidCharacters().size() == 1 && ex.getInvalidCharacters().get(0).equals('.')) { return null; } throw ex; } }
private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) { if (name == null) { return null; } for (ConfigurationPropertySource configurationPropertySource : getSource()) { if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) { ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name); if (configurationProperty != null) { return configurationProperty; } } } return null; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableConfigurationPropertySourcesPropertySource.java
1
请完成以下Java代码
private static Dataset<String> convertToDataSetFromStrings(List<String> names) { return SPARK_SESSION.createDataset(names, Encoders.STRING()); } private static Dataset<Customer> convertToDataSetFromPOJO() { return SPARK_SESSION.createDataset(CUSTOMERS, Encoders.bean(Customer.class)); } private static final List<Customer> CUSTOMERS = Arrays.asList( aCustomerWith("01", "jo", "Female", 2000), aCustomerWith("02", "jack", "Female", 1200), aCustomerWith("03", "ash", "male", 2000), aCustomerWith("04", "emma", "Female", 2000) );
private static List<String> getNames() { return CUSTOMERS.stream() .map(Customer::getName) .collect(Collectors.toList()); } private static void print(Dataset<Row> df) { df.show(); df.printSchema(); } private static Customer aCustomerWith(String id, String name, String gender, int amount) { return new Customer(id, name, gender, amount); } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\dataframes\DataSetToDataFrameConverterApp.java
1
请在Spring Boot框架中完成以下Java代码
protected ConnectionProvider buildConnectionProvider(HttpClientProperties properties) { HttpClientProperties.Pool pool = properties.getPool(); ConnectionProvider connectionProvider; if (pool.getType() == DISABLED) { connectionProvider = ConnectionProvider.newConnection(); } else { // create either Fixed or Elastic pool ConnectionProvider.Builder builder = ConnectionProvider.builder(pool.getName()); if (pool.getType() == FIXED) { builder.maxConnections(pool.getMaxConnections()) .pendingAcquireMaxCount(-1) .pendingAcquireTimeout(Duration.ofMillis(pool.getAcquireTimeout())); } else { // Elastic builder.maxConnections(Integer.MAX_VALUE) .pendingAcquireTimeout(Duration.ofMillis(0)) .pendingAcquireMaxCount(-1); } if (pool.getMaxIdleTime() != null) { builder.maxIdleTime(pool.getMaxIdleTime()); }
if (pool.getMaxLifeTime() != null) { builder.maxLifeTime(pool.getMaxLifeTime()); } builder.evictInBackground(pool.getEvictionInterval()); builder.metrics(pool.isMetrics()); // Define the pool leasing strategy if (pool.getLeasingStrategy() == FIFO) { builder.fifo(); } else { // LIFO builder.lifo(); } connectionProvider = builder.build(); } return connectionProvider; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientFactory.java
2
请在Spring Boot框架中完成以下Java代码
default Iterator<SpanExporter> iterator() { return list().iterator(); } @Override default Spliterator<SpanExporter> spliterator() { return list().spliterator(); } /** * Constructs a {@link SpanExporters} instance with the given {@link SpanExporter span * exporters}. * @param spanExporters the span exporters * @return the constructed {@link SpanExporters} instance */ static SpanExporters of(SpanExporter... spanExporters) {
return of(Arrays.asList(spanExporters)); } /** * Constructs a {@link SpanExporters} instance with the given list of * {@link SpanExporter span exporters}. * @param spanExporters the list of span exporters * @return the constructed {@link SpanExporters} instance */ static SpanExporters of(Collection<? extends SpanExporter> spanExporters) { Assert.notNull(spanExporters, "'spanExporters' must not be null"); List<SpanExporter> copy = List.copyOf(spanExporters); return () -> copy; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\SpanExporters.java
2
请完成以下Java代码
public class MainApplication { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); for (int i = 1; i <= 1_000_000; i++) { list.add(i); } long startTimeV1 = System.nanoTime(); Lists.toChunkV1(list, 5);//.forEach(System.out::println); displayExecutionTime(System.nanoTime() - startTimeV1); long startTimeV2 = System.nanoTime(); Lists.toChunkV2(list, 5);//.forEach(System.out::println); displayExecutionTime(System.nanoTime() - startTimeV2); long startTimeV3 = System.nanoTime(); Lists.toChunkV3(list, 5);//.forEach(System.out::println); displayExecutionTime(System.nanoTime() - startTimeV3);
long startTimeV4 = System.nanoTime(); Lists.toChunkV4(list, 5);//.forEach(System.out::println); displayExecutionTime(System.nanoTime() - startTimeV4); long startTimeV5 = System.nanoTime(); Lists.toChunkV5(list, 5);//.forEach(System.out::println); displayExecutionTime(System.nanoTime() - startTimeV5); long startTimeV6 = System.nanoTime(); Lists.toChunkV6(list, 5);//.forEach(System.out::println); displayExecutionTime(System.nanoTime() - startTimeV6); } private static void displayExecutionTime(long time) { System.out.println("Execution time: " + time + " ns" + " (" + TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)"); } }
repos\Hibernate-SpringBoot-master\ChunkList\src\main\java\com\app\chunklist\MainApplication.java
1
请完成以下Java代码
public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Binärwert. @param BinaryData Binary Data */ @Override public void setBinaryData (byte[] BinaryData) { set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData); } /** Get Binärwert. @return Binary Data */ @Override public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** Set Migriert am. @param MigrationDate Migriert am */ @Override public void setMigrationDate (java.sql.Timestamp MigrationDate) { set_Value (COLUMNNAME_MigrationDate, MigrationDate); } /** Get Migriert am. @return Migriert am */ @Override public java.sql.Timestamp getMigrationDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Mitteilung. @param TextMsg
Text Message */ @Override public void setTextMsg (java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Mitteilung. @return Text Message */ @Override public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java
1
请完成以下Java代码
final class SecureRandomBytesKeyGenerator implements BytesKeyGenerator { private static final int DEFAULT_KEY_LENGTH = 8; private final SecureRandom random; private final int keyLength; /** * Creates a secure random key generator using the defaults. */ SecureRandomBytesKeyGenerator() { this(DEFAULT_KEY_LENGTH); } /** * Creates a secure random key generator with a custom key length. */ SecureRandomBytesKeyGenerator(int keyLength) {
this.random = new SecureRandom(); this.keyLength = keyLength; } @Override public int getKeyLength() { return this.keyLength; } @Override public byte[] generateKey() { byte[] bytes = new byte[this.keyLength]; this.random.nextBytes(bytes); return bytes; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\keygen\SecureRandomBytesKeyGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEventRegistryStartProcessInstanceAsync() { return eventRegistryStartProcessInstanceAsync; } public void setEventRegistryStartProcessInstanceAsync(boolean eventRegistryStartProcessInstanceAsync) { this.eventRegistryStartProcessInstanceAsync = eventRegistryStartProcessInstanceAsync; } public boolean isEventRegistryUniqueProcessInstanceCheckWithLock() { return eventRegistryUniqueProcessInstanceCheckWithLock; } public void setEventRegistryUniqueProcessInstanceCheckWithLock(boolean eventRegistryUniqueProcessInstanceCheckWithLock) { this.eventRegistryUniqueProcessInstanceCheckWithLock = eventRegistryUniqueProcessInstanceCheckWithLock; } public Duration getEventRegistryUniqueProcessInstanceStartLockTime() { return eventRegistryUniqueProcessInstanceStartLockTime; } public void setEventRegistryUniqueProcessInstanceStartLockTime(Duration eventRegistryUniqueProcessInstanceStartLockTime) { this.eventRegistryUniqueProcessInstanceStartLockTime = eventRegistryUniqueProcessInstanceStartLockTime; }
public static class AsyncHistory { private boolean enabled; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\process\FlowableProcessProperties.java
2
请在Spring Boot框架中完成以下Java代码
public PeerCacheConfigurer peerCacheGemFirePropertiesConfigurer(ConfigurableEnvironment environment) { return (beanName, bean) -> configureGemFireProperties(environment, bean); } protected void configureGemFireProperties(@NonNull ConfigurableEnvironment environment, @NonNull CacheFactoryBean cache) { Assert.notNull(environment, "Environment must not be null"); Assert.notNull(cache, "CacheFactoryBean must not be null"); MutablePropertySources propertySources = environment.getPropertySources(); if (propertySources != null) { Set<String> gemfirePropertyNames = propertySources.stream() .filter(EnumerablePropertySource.class::isInstance) .map(EnumerablePropertySource.class::cast) .map(EnumerablePropertySource::getPropertyNames) .map(propertyNamesArray -> ArrayUtils.nullSafeArray(propertyNamesArray, String.class)) .flatMap(Arrays::stream) .filter(this::isGemFireDotPrefixedProperty) .filter(this::isValidGemFireProperty) .collect(Collectors.toSet()); Properties gemfireProperties = cache.getProperties(); gemfirePropertyNames.stream() .filter(gemfirePropertyName -> isNotSet(gemfireProperties, gemfirePropertyName)) .filter(this::isValidGemFireProperty) .forEach(gemfirePropertyName -> { String propertyName = normalizeGemFirePropertyName(gemfirePropertyName); String propertyValue = environment.getProperty(gemfirePropertyName); if (StringUtils.hasText(propertyValue)) { gemfireProperties.setProperty(propertyName, propertyValue); } else { getLogger().warn("Apache Geode Property [{}] was not set", propertyName); } }); cache.setProperties(gemfireProperties); } } protected Logger getLogger() { return this.logger; } private boolean isGemFireDotPrefixedProperty(@NonNull String propertyName) { return StringUtils.hasText(propertyName) && propertyName.startsWith(GEMFIRE_PROPERTY_PREFIX); }
private boolean isNotSet(Properties gemfireProperties, String propertyName) { return !gemfireProperties.containsKey(normalizeGemFirePropertyName(propertyName)); } private boolean isValidGemFireProperty(String propertyName) { try { GemFireProperties.from(normalizeGemFirePropertyName(propertyName)); return true; } catch (IllegalArgumentException cause) { getLogger().warn(String.format("[%s] is not a valid Apache Geode property", propertyName)); // TODO: uncomment line below and replace line above when SBDG is rebased on SDG 2.3.0.RC2 or later. //getLogger().warn(cause.getMessage()); return false; } } private String normalizeGemFirePropertyName(@NonNull String propertyName) { int index = propertyName.lastIndexOf("."); return index > -1 ? propertyName.substring(index + 1) : propertyName; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\EnvironmentSourcedGemFirePropertiesAutoConfiguration.java
2
请完成以下Java代码
protected final void fireTableColumnChanged(final String columnName) { final int rowCount = getRowCount(); if (rowCount <= 0) { // no rows => no point to fire the event return; } final int columnIndex = getColumnIndexByColumnName(columnName); final int firstRow = 0; final int lastRow = rowCount - 1; final TableModelEvent event = new TableModelEvent(this, firstRow, lastRow, columnIndex, TableModelEvent.UPDATE); fireTableChanged(event); } public final void fireTableRowsUpdated(final Collection<ModelType> rows) { if (rows == null || rows.isEmpty()) { return; } // NOTE: because we are working with small amounts of rows, // it's pointless to figure out which are the row indexes of those rows // so it's better to fire a full data change event. // In future we can optimize this. fireTableDataChanged(); } /** * @return foreground color to be used when rendering the given cell or <code>null</code> if no suggestion */ protected Color getCellForegroundColor(final int modelRowIndex, final int modelColumnIndex) { return null; } public List<ModelType> getSelectedRows(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel) { final int rowMinView = selectionModel.getMinSelectionIndex(); final int rowMaxView = selectionModel.getMaxSelectionIndex(); if (rowMinView < 0 || rowMaxView < 0) { return ImmutableList.of(); } final ImmutableList.Builder<ModelType> selection = ImmutableList.builder(); for (int rowView = rowMinView; rowView <= rowMaxView; rowView++) {
if (selectionModel.isSelectedIndex(rowView)) { final int rowModel = convertRowIndexToModel.apply(rowView); selection.add(getRow(rowModel)); } } return selection.build(); } public ModelType getSelectedRow(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel) { final int rowIndexView = selectionModel.getMinSelectionIndex(); if (rowIndexView < 0) { return null; } final int rowIndexModel = convertRowIndexToModel.apply(rowIndexView); return getRow(rowIndexModel); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\AnnotatedTableModel.java
1
请完成以下Java代码
public void setCamundaDatePattern(String camundaDatePattern) { camundaDatePatternAttribute.setValue(this, camundaDatePattern); } public String getCamundaDefaultValue() { return camundaDefaultValueAttribute.getValue(this); } public void setCamundaDefaultValue(String camundaDefaultValue) { camundaDefaultValueAttribute.setValue(this, camundaDefaultValue); } public CamundaProperties getCamundaProperties() { return camundaPropertiesChild.getChild(this); }
public void setCamundaProperties(CamundaProperties camundaProperties) { camundaPropertiesChild.setChild(this, camundaProperties); } public CamundaValidation getCamundaValidation() { return camundaValidationChild.getChild(this); } public void setCamundaValidation(CamundaValidation camundaValidation) { camundaValidationChild.setChild(this, camundaValidation); } public Collection<CamundaValue> getCamundaValues() { return camundaValueCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFormFieldImpl.java
1
请完成以下Java代码
public static void main(String[] args) { final int threadCount = 4; final ExecutorService service = Executors.newFixedThreadPool(threadCount); StampedLockDemo object = new StampedLockDemo(); Runnable writeTask = () -> { try { object.put("key1", "value1"); } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable readTask = () -> { try { object.get("key1"); } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable readOptimisticTask = () -> {
try { object.readWithOptimisticLock("key1"); } catch (InterruptedException e) { e.printStackTrace(); } }; service.submit(writeTask); service.submit(writeTask); service.submit(readTask); service.submit(readOptimisticTask); service.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\StampedLockDemo.java
1
请完成以下Java代码
public long getHistoricStatisticsCountGroupedByActivity(HistoricActivityStatisticsQueryImpl query) { if (ensureHistoryReadOnProcessDefinition(query)) { return (Long) getDbEntityManager().selectOne("selectHistoricActivityStatisticsCount", query); } else { return 0; } } @SuppressWarnings("unchecked") public List<HistoricCaseActivityStatistics> getHistoricStatisticsGroupedByCaseActivity(HistoricCaseActivityStatisticsQueryImpl query, Page page) { return getDbEntityManager().selectList("selectHistoricCaseActivityStatistics", query, page); } public long getHistoricStatisticsCountGroupedByCaseActivity(HistoricCaseActivityStatisticsQueryImpl query) { return (Long) getDbEntityManager().selectOne("selectHistoricCaseActivityStatisticsCount", query); } protected boolean ensureHistoryReadOnProcessDefinition(HistoricActivityStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext();
if(isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String processDefinitionId = query.getProcessDefinitionId(); ProcessDefinitionEntity definition = getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); if (definition == null) { return false; } return getAuthorizationManager().isAuthorized(READ_HISTORY, PROCESS_DEFINITION, definition.getKey()); } return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricStatisticsManager.java
1
请完成以下Java代码
public static class Artikel extends ArtikelMenge { @XmlAttribute(name = "Bedarf", required = true) protected String bedarf; /** * Gets the value of the bedarf property. * * @return * possible object is * {@link String } * */ public String getBedarf() { return bedarf; }
/** * Sets the value of the bedarf property. * * @param value * allowed object is * {@link String } * */ public void setBedarf(String value) { this.bedarf = value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VerfuegbarkeitsanfrageEinzelne.java
1
请完成以下Java代码
public String getApp() { return app; } public void setApp(String app) { this.app = app; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; this.resourceCode = resource.hashCode(); } public Long getPassQps() { return passQps; } public void setPassQps(Long passQps) { this.passQps = passQps; } public Long getBlockQps() { return blockQps; } public void setBlockQps(Long blockQps) { this.blockQps = blockQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public double getRt() {
return rt; } public void setRt(double rt) { this.rt = rt; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getResourceCode() { return resourceCode; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } @Override public String toString() { return "MetricEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", timestamp=" + timestamp + ", resource='" + resource + '\'' + ", passQps=" + passQps + ", blockQps=" + blockQps + ", successQps=" + successQps + ", exceptionQps=" + exceptionQps + ", rt=" + rt + ", count=" + count + ", resourceCode=" + resourceCode + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java
1
请完成以下Java代码
public String getTaskOwner() { return taskOwner; } public Integer getTaskPriority() { return taskPriority; } public String getTaskParentTaskId() { return taskParentTaskId; } public String[] getTenantIds() { return tenantIds; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore;
} public boolean isTenantIdSet() { return isTenantIdSet; } public List<HistoricTaskInstanceQueryImpl> getQueries() { return queries; } public boolean isOrQueryActive() { return isOrQueryActive; } public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) { orQuery.isOrQueryActive = true; this.queries.add(orQuery); } public void setOrQueryActive() { isOrQueryActive = true; } @Override public HistoricTaskInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public HistoricTaskInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请完成以下Java代码
public class Dict implements Serializable { @Serial private static final long serialVersionUID = 1L; /** * 主键 */ @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 父主键 */ @Schema(description = "父主键") @JsonSerialize(using = ToStringSerializer.class) private Long parentId; /** * 字典码 */ @Schema(description = "字典码") private String code; /** * 字典值 */
@Schema(description = "字典值") private Integer dictKey; /** * 字典名称 */ @Schema(description = "字典名称") private String dictValue; /** * 排序 */ @Schema(description = "排序") private Integer sort; /** * 字典备注 */ @Schema(description = "字典备注") private String remark; /** * 是否已删除 */ @TableLogic @Schema(description = "是否已删除") private Integer isDeleted; }
repos\SpringBlade-master\blade-service-api\blade-dict-api\src\main\java\org\springblade\system\entity\Dict.java
1
请完成以下Java代码
protected PackageableRowsData getRowsData() { return PackageableRowsData.cast(super.getRowsData()); } /** * @return {@link I_M_Packageable_V#Table_Name}. */ @Override public String getTableNameOrNull(@Nullable final DocumentId ignored) { return I_M_Packageable_V.Table_Name; } @Override public void close(final ViewCloseAction action) { if (action.isDone()) { closePickingCandidatesFromRackSystemPickingSlots(); } } private void closePickingCandidatesFromRackSystemPickingSlots() { final Set<ShipmentScheduleId> shipmentScheduleIds = getRows() .stream() .map(PackageableRow::getShipmentScheduleId) .collect(ImmutableSet.toImmutableSet()); // Close all picking candidates which are on a rack system picking slot (gh2740) pickingCandidateService.closeForShipmentSchedules(CloseForShipmentSchedulesRequest.builder() .shipmentScheduleIds(shipmentScheduleIds) .pickingSlotIsRackSystem(true) .failOnError(false) // close as much candidates as it's possible .build()); } public void setPickingSlotView(@NonNull final DocumentId rowId, @NonNull final PickingSlotView pickingSlotView) { pickingSlotsViewByRowId.put(rowId, pickingSlotView); }
public void removePickingSlotView(@NonNull final DocumentId rowId, @NonNull final ViewCloseAction viewCloseAction) { final PickingSlotView view = pickingSlotsViewByRowId.remove(rowId); if (view != null) { view.close(viewCloseAction); } } public PickingSlotView getPickingSlotViewOrNull(@NonNull final DocumentId rowId) { return pickingSlotsViewByRowId.get(rowId); } public PickingSlotView computePickingSlotViewIfAbsent(@NonNull final DocumentId rowId, @NonNull final Supplier<PickingSlotView> pickingSlotViewFactory) { return pickingSlotsViewByRowId.computeIfAbsent(rowId, id -> pickingSlotViewFactory.get()); } public void invalidatePickingSlotViews() { pickingSlotsViewByRowId.values().forEach(PickingSlotView::invalidateAll); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableView.java
1
请完成以下Java代码
static Builder builder() { return new Builder(); } static class Builder { private Promise<Void> future; private String topic; private MqttUnsubscribeMessage unsubscribeMessage; private String ownerId; private PendingOperation pendingOperation; private MqttClientConfig.RetransmissionConfig retransmissionConfig; Builder future(Promise<Void> future) { this.future = future; return this; } Builder topic(String topic) { this.topic = topic; return this; } Builder unsubscribeMessage(MqttUnsubscribeMessage unsubscribeMessage) { this.unsubscribeMessage = unsubscribeMessage; return this; } Builder ownerId(String ownerId) { this.ownerId = ownerId; return this; } Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) {
this.retransmissionConfig = retransmissionConfig; return this; } Builder pendingOperation(PendingOperation pendingOperation) { this.pendingOperation = pendingOperation; return this; } MqttPendingUnsubscription build() { return new MqttPendingUnsubscription(future, topic, unsubscribeMessage, ownerId, retransmissionConfig, pendingOperation); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingUnsubscription.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-task-instances/6") public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @ApiModelProperty(example = "variableUpdate") public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } @ApiModelProperty(example = "2") public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } public RestVariable getVariable() { return variable; }
public void setVariable(RestVariable variable) { this.variable = variable; } @ApiModelProperty(example = "null") public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } @ApiModelProperty(example = "null") public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java
2
请完成以下Java代码
public class SEPADocumentBL implements ISEPADocumentBL { private final BankAccountService bankAccountService = SpringContextHolder.instance.getBean(BankAccountService.class); @Override public I_SEPA_Export createSEPAExportFromPaySelection(final I_C_PaySelection from, final boolean isGroupTransactions) { return new CreateSEPAExportFromPaySelectionCommand(from, isGroupTransactions) .run(); } @Override public Date getDueDate(final I_SEPA_Export_Line line) { // NOTE: for now, return SystemTime + 1 // return TimeUtil.addDays(line.getSEPA_Export().getPaymentDate(), 1); // ts: unrelated: don'T add another day, because it turn our that it makes the creditors get their money one day after they expected it final Timestamp paymentDate = line.getSEPA_Export().getPaymentDate(); if (paymentDate == null) { return SystemTime.asTimestamp(); } return paymentDate; } @Override public SEPACreditTransferXML exportCreditTransferXML(@NonNull final I_SEPA_Export sepaExport, @NonNull final SEPAExportContext exportContext) { final SEPAProtocol protocol = SEPAProtocol.ofCode(sepaExport.getSEPA_Protocol()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final SEPAMarshaler marshaler = newSEPAMarshaler(protocol, exportContext); try
{ marshaler.marshal(sepaExport, out); } catch (final RuntimeException e) { throw AdempiereException.wrapIfNeeded(e); } return SEPACreditTransferXML.builder() .filename(FileUtil.stripIllegalCharacters(sepaExport.getDocumentNo()) + ".xml") .contentType(MimeType.TYPE_XML) .content(out.toByteArray()) .build(); } private SEPAMarshaler newSEPAMarshaler(@NonNull final SEPAProtocol protocol, @NonNull final SEPAExportContext exportContext) { if (SEPAProtocol.CREDIT_TRANSFER_PAIN_001_001_03_CH_02.equals(protocol)) { final BankRepository bankRepository = SpringContextHolder.instance.getBean(BankRepository.class); return new SEPAVendorCreditTransferMarshaler_Pain_001_001_03_CH_02(bankRepository, exportContext, bankAccountService); } else if (SEPAProtocol.DIRECT_DEBIT_PAIN_008_003_02.equals(protocol)) { return new SEPACustomerDirectDebitMarshaler_Pain_008_003_02(bankAccountService); } else { throw new AdempiereException("Unknown SEPA protocol: " + protocol); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\SEPADocumentBL.java
1
请在Spring Boot框架中完成以下Java代码
public DataResponse<DecisionResponse> getDecisionTables(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { DmnDecisionQuery definitionQuery = dmnRepositoryService.createDecisionQuery(); // Populate filter-parameters if (allRequestParams.containsKey("category")) { definitionQuery.decisionCategory(allRequestParams.get("category")); } if (allRequestParams.containsKey("categoryLike")) { definitionQuery.decisionCategoryLike(allRequestParams.get("categoryLike")); } if (allRequestParams.containsKey("categoryNotEquals")) { definitionQuery.decisionCategoryNotEquals(allRequestParams.get("categoryNotEquals")); } if (allRequestParams.containsKey("key")) { definitionQuery.decisionKey(allRequestParams.get("key")); } if (allRequestParams.containsKey("keyLike")) { definitionQuery.decisionKeyLike(allRequestParams.get("keyLike")); } if (allRequestParams.containsKey("name")) { definitionQuery.decisionName(allRequestParams.get("name")); } if (allRequestParams.containsKey("nameLike")) { definitionQuery.decisionNameLike(allRequestParams.get("nameLike")); } if (allRequestParams.containsKey("resourceName")) { definitionQuery.decisionResourceName(allRequestParams.get("resourceName")); }
if (allRequestParams.containsKey("resourceNameLike")) { definitionQuery.decisionResourceNameLike(allRequestParams.get("resourceNameLike")); } if (allRequestParams.containsKey("version")) { definitionQuery.decisionVersion(Integer.valueOf(allRequestParams.get("version"))); } if (allRequestParams.containsKey("latest")) { if (Boolean.parseBoolean(allRequestParams.get("latest"))) { definitionQuery.latestVersion(); } } if (allRequestParams.containsKey("deploymentId")) { definitionQuery.deploymentId(allRequestParams.get("deploymentId")); } if (allRequestParams.containsKey("tenantId")) { definitionQuery.decisionTenantId(allRequestParams.get("tenantId")); } if (allRequestParams.containsKey("tenantIdLike")) { definitionQuery.decisionTenantIdLike(allRequestParams.get("tenantIdLike")); } if (restApiInterceptor != null) { restApiInterceptor.accessDecisionTableInfoWithQuery(definitionQuery); } return paginateList(allRequestParams, definitionQuery, "name", properties, dmnRestResponseFactory::createDecisionTableResponseList); } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DecisionTableCollectionResource.java
2
请完成以下Java代码
public class OnlineAuthDTO implements Serializable { private static final long serialVersionUID = 1771827545416418203L; /** * 用户名 */ private String username; /** * 可能的请求地址 */ private List<String> possibleUrl; /** * online开发的菜单地址 */ private String onlineFormUrl;
/** * online工单的地址 */ private String onlineWorkOrderUrl; public OnlineAuthDTO(){ } public OnlineAuthDTO(String username, List<String> possibleUrl, String onlineFormUrl){ this.username = username; this.possibleUrl = possibleUrl; this.onlineFormUrl = onlineFormUrl; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\dto\OnlineAuthDTO.java
1
请完成以下Java代码
private void applySslBundle(AbstractHttp11Protocol<?> protocol, SSLHostConfig sslHostConfig, SslBundle sslBundle) { SslBundleKey key = sslBundle.getKey(); SslStoreBundle stores = sslBundle.getStores(); SslOptions options = sslBundle.getOptions(); sslHostConfig.setSslProtocol(sslBundle.getProtocol()); SSLHostConfigCertificate certificate = new SSLHostConfigCertificate(sslHostConfig, Type.UNDEFINED); String keystorePassword = (stores.getKeyStorePassword() != null) ? stores.getKeyStorePassword() : ""; certificate.setCertificateKeystorePassword(keystorePassword); if (key.getPassword() != null) { certificate.setCertificateKeyPassword(key.getPassword()); } if (key.getAlias() != null) { certificate.setCertificateKeyAlias(key.getAlias()); } sslHostConfig.addCertificate(certificate); if (options.getCiphers() != null) { String ciphers = StringUtils.arrayToCommaDelimitedString(options.getCiphers()); sslHostConfig.setCiphers(ciphers); } configureSslStores(sslHostConfig, certificate, stores); configureEnabledProtocols(sslHostConfig, options); } private void configureEnabledProtocols(SSLHostConfig sslHostConfig, SslOptions options) { if (options.getEnabledProtocols() != null) { String enabledProtocols = StringUtils.arrayToDelimitedString(options.getEnabledProtocols(), "+"); sslHostConfig.setProtocols(enabledProtocols); } }
private void configureSslClientAuth(SSLHostConfig config) { config.setCertificateVerification(ClientAuth.map(this.clientAuth, "none", "optional", "required")); } private void configureSslStores(SSLHostConfig sslHostConfig, SSLHostConfigCertificate certificate, SslStoreBundle stores) { try { if (stores.getKeyStore() != null) { certificate.setCertificateKeystore(stores.getKeyStore()); } if (stores.getTrustStore() != null) { sslHostConfig.setTrustStore(stores.getTrustStore()); } } catch (Exception ex) { throw new IllegalStateException("Could not load store: " + ex.getMessage(), ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\SslConnectorCustomizer.java
1
请在Spring Boot框架中完成以下Java代码
private void assertLineTableNamesUnique() { final List<LineBuilder> nonUniqueLines = lineBuilders.stream() .collect(Collectors.groupingBy(r -> r.getTableName())) // group them by tableName; this returns a map .entrySet().stream() // now stream the map's entries .filter(e -> e.getValue().size() > 1) // now remove from the stream those that are OK .flatMap(e -> e.getValue().stream()) // now get a stream with those that are not OK .collect(Collectors.toList()); Check.errorUnless(nonUniqueLines.isEmpty(), "Found LineBuilders with duplicate tableNames: {}", nonUniqueLines); } public PartitionConfig build() { assertLineTableNamesUnique(); final PartitionConfig partitionerConfig = new PartitionConfig(name, changed); partitionerConfig.setDLM_Partition_Config_ID(DLM_Partition_Config_ID);
// first build the lines for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders) { final PartitionerConfigLine line = lineBuilder.buildLine(partitionerConfig); partitionerConfig.lines.add(line); } for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders) { lineBuilder.buildRefs(); } return partitionerConfig; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionConfig.java
2
请完成以下Java代码
void createEmptyKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { if(keyStoreType ==null || keyStoreType.isEmpty()){ keyStoreType = KeyStore.getDefaultType(); } keyStore = KeyStore.getInstance(keyStoreType); //load char[] pwdArray = keyStorePassword.toCharArray(); keyStore.load(null, pwdArray); // Save the keyStore FileOutputStream fos = new FileOutputStream(keyStoreName); keyStore.store(fos, pwdArray); fos.close(); } void loadKeyStore() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { char[] pwdArray = keyStorePassword.toCharArray(); FileInputStream fis = new FileInputStream(keyStoreName); keyStore.load(fis, pwdArray); fis.close(); } void setEntry(String alias, KeyStore.SecretKeyEntry secretKeyEntry, KeyStore.ProtectionParameter protectionParameter) throws KeyStoreException { keyStore.setEntry(alias, secretKeyEntry, protectionParameter); } KeyStore.Entry getEntry(String alias) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException { KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keyStorePassword.toCharArray()); return keyStore.getEntry(alias, protParam); } void setKeyEntry(String alias, PrivateKey privateKey, String keyPassword, Certificate[] certificateChain) throws KeyStoreException { keyStore.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), certificateChain); } void setCertificateEntry(String alias, Certificate certificate) throws KeyStoreException { keyStore.setCertificateEntry(alias, certificate);
} Certificate getCertificate(String alias) throws KeyStoreException { return keyStore.getCertificate(alias); } void deleteEntry(String alias) throws KeyStoreException { keyStore.deleteEntry(alias); } void deleteKeyStore() throws KeyStoreException, IOException { Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); keyStore.deleteEntry(alias); } keyStore = null; Path keyStoreFile = Paths.get(keyStoreName); Files.delete(keyStoreFile); } KeyStore getKeyStore() { return this.keyStore; } }
repos\tutorials-master\core-java-modules\core-java-security\src\main\java\com\baeldung\keystore\JavaKeyStore.java
1
请完成以下Java代码
public Facet<ModelType> build() { return new Facet<>(this); } public Builder<ModelType> setId(final String id) { this.id = id; return this; } public Builder<ModelType> setDisplayName(final String displayName) { this.displayName = displayName; return this;
} public Builder<ModelType> setFilter(final IQueryFilter<ModelType> filter) { this.filter = filter; return this; } public Builder<ModelType> setFacetCategory(final IFacetCategory facetCategory) { this.facetCategory = facetCategory; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\Facet.java
1
请完成以下Java代码
public static LocalTime fromJsonToLocalTime(final String valueStr) { final JSONDateConfig config = JSONDateConfig.DEFAULT; return LocalTime.parse(valueStr, config.getLocalTimeFormatter()); } @NonNull public static ZonedDateTime fromJsonToZonedDateTime(final String valueStr) { final JSONDateConfig config = JSONDateConfig.DEFAULT; return ZonedDateTime.parse(valueStr, config.getZonedDateTimeFormatter()); } @NonNull public static Instant fromJsonToInstant(final String valueStr) { final JSONDateConfig config = JSONDateConfig.DEFAULT; return ZonedDateTime.parse(valueStr, config.getTimestampFormatter()) .toInstant(); } @Nullable private static LocalDate fromObjectToLocalDate(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, LocalDate.class, DateTimeConverters::fromJsonToLocalDate, (object) -> TimeUtil.asLocalDate(object, zoneId)); } @Nullable private static LocalTime fromObjectToLocalTime(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, LocalTime.class, DateTimeConverters::fromJsonToLocalTime, (object) -> TimeUtil.asLocalTime(object, zoneId)); } @Nullable private static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, ZonedDateTime.class, DateTimeConverters::fromJsonToZonedDateTime,
(object) -> TimeUtil.asZonedDateTime(object, zoneId)); } @Nullable private static Instant fromObjectToInstant(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, Instant.class, DateTimeConverters::fromJsonToInstant, (object) -> TimeUtil.asInstant(object, zoneId)); } @Nullable private static <T> T fromObjectTo( @NonNull final Object valueObj, @NonNull final Class<T> type, @NonNull final Function<String, T> fromJsonConverter, @NonNull final Function<Object, T> fromObjectConverter) { if (type.isInstance(valueObj)) { return type.cast(valueObj); } else if (valueObj instanceof CharSequence) { final String json = valueObj.toString().trim(); if (json.isEmpty()) { return null; } if (json.length() == 21 && json.charAt(10) == ' ') // json string - possible in JDBC format (`2016-06-11 00:00:00.0`) { final Timestamp timestamp = Timestamp.valueOf(json); return fromObjectConverter.apply(timestamp); } else { return fromJsonConverter.apply(json); } } else { return fromObjectConverter.apply(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\DateTimeConverters.java
1
请完成以下Java代码
public void setM_TU_HU_PI_ID (final int M_TU_HU_PI_ID) { if (M_TU_HU_PI_ID < 1) set_Value (COLUMNNAME_M_TU_HU_PI_ID, null); else set_Value (COLUMNNAME_M_TU_HU_PI_ID, M_TU_HU_PI_ID); } @Override public int getM_TU_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_TU_HU_PI_ID); } @Override public void setQtyCUsPerTU (final BigDecimal QtyCUsPerTU) { set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU); } @Override public BigDecimal getQtyCUsPerTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyLU (final BigDecimal QtyLU) { set_Value (COLUMNNAME_QtyLU, QtyLU);
} @Override public BigDecimal getQtyLU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final BigDecimal QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public BigDecimal getQtyTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_LUTU_Configuration.java
1
请完成以下Java代码
private void runGarbageCollector() { // Clear cache first, because there we can also have some instances. CacheMgt.get().reset(); // Create a weak reference to a newly created object gcTestObject = new Object(); final WeakReference<Object> ref = new WeakReference<Object>(gcTestObject); gcTestObject = null; // Run system garbage collector until our newly created object is garbage collected. // In this way we make sure garbage collector was executed. while (ref.get() != null) { System.gc(); } } private Object gcTestObject = null; private final Object mkRecordKeyIfTrackable(Object record) { final String tableName = InterfaceWrapperHelper.getModelTableName(record); final int recordId = InterfaceWrapperHelper.getId(record); final String trxName = InterfaceWrapperHelper.getTrxName(record); // don't track out of transaction objects if (Services.get(ITrxManager.class).isNull(trxName)) { return null; } return Util.mkKey(tableName, recordId, trxName); } private final void assertUniqueIds(final List<?> records) { if (records == null || records.isEmpty()) { return; } if (records.size() == 1) { // ofc it's unique ID return; } final Set<Integer> ids = new HashSet<Integer>(); for (final Object record : records) { final POJOWrapper wrapper = POJOWrapper.getWrapper(record); final int recordId = wrapper.getId(); if (!ids.add(recordId)) { throw new RuntimeException("Duplicate ID found when retrieving from database" +"\n ID="+recordId +"\n Records: "+records); }
} } private final String toString(final List<Object> records) { final StringBuilder sb = new StringBuilder(); for (final Object record : records) { if (sb.length() > 0) { sb.append("\n\n"); } sb.append("Record: ").append(record); final Throwable trackingStackTrace = InterfaceWrapperHelper.getDynAttribute(record, DYNATTR_TrackingStackTrace); if (trackingStackTrace != null) { sb.append("\nTrack stacktrace: ").append(Util.dumpStackTraceToString(trackingStackTrace)); } } return sb.toString(); } private static final class RecordInfo { private final WeakList<Object> records = new WeakList<>(); public void add(final Object recordToAdd) { for (final Object record : records.hardList()) { if (record == recordToAdd) { return; } } records.add(recordToAdd); } public List<Object> getRecords() { return records.hardList(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOLookupMapInstancesTracker.java
1
请在Spring Boot框架中完成以下Java代码
public static BPartnerLocationCandidate fromDeliveryAddress(@NonNull final OrderDeliveryAddress orderDeliveryAddress) { final String addressName = Joiner.on(", ").skipNulls() .join(orderDeliveryAddress.getAddress(), orderDeliveryAddress.getAdditionalAddress(), orderDeliveryAddress.getAdditionalAddress2()); return BPartnerLocationCandidate.builder() .bpartnerName(orderDeliveryAddress.getName()) .name(addressName) .address1(orderDeliveryAddress.getAddress()) .address2(orderDeliveryAddress.getAdditionalAddress()) .address3(orderDeliveryAddress.getAdditionalAddress2()) .postal(orderDeliveryAddress.getPostalCode()) .city(orderDeliveryAddress.getCity()) .countryCode(GetPatientsRouteConstants.COUNTRY_CODE_DE) .billTo(false) .shipTo(true) .ephemeral(true) .build(); }
@NonNull public JsonRequestLocation toJsonRequestLocation() { final JsonRequestLocation requestLocation = new JsonRequestLocation(); requestLocation.setBpartnerName(getBpartnerName()); requestLocation.setName(getName()); requestLocation.setAddress1(getAddress1()); requestLocation.setAddress2(getAddress2()); requestLocation.setAddress3(getAddress3()); requestLocation.setPostal(getPostal()); requestLocation.setCity(getCity()); requestLocation.setCountryCode(getCountryCode()); requestLocation.setShipTo(getShipTo()); requestLocation.setBillTo(getBillTo()); requestLocation.setEphemeral(getEphemeral()); return requestLocation; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\common\util\BPartnerLocationCandidate.java
2
请完成以下Java代码
public void run() { if (PlanItemInstanceState.ACTIVE.equals(planItemInstanceEntity.getState()) || (planItemInstanceEntity.getPlanItem() != null && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof EventListener && PlanItemInstanceState.AVAILABLE.equals(planItemInstanceEntity.getState()))){ executeTrigger(); } else { if (planItemInstanceEntity.getPlanItem() != null && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof EventListener){ throw new FlowableIllegalStateException("Can only trigger an event listener plan item that is in the AVAILABLE state"); } else { throw new FlowableIllegalStateException("Can only trigger a plan item that is in the ACTIVE state"); } } } protected void executeTrigger() { Object behaviorObject = planItemInstanceEntity.getPlanItem().getBehavior(); if (!(behaviorObject instanceof CmmnTriggerableActivityBehavior)) { throw new FlowableException("Cannot trigger a plan item which activity behavior does not implement the " + CmmnTriggerableActivityBehavior.class + " interface in " + planItemInstanceEntity);
} CmmnTriggerableActivityBehavior behavior = (CmmnTriggerableActivityBehavior) planItemInstanceEntity.getPlanItem().getBehavior(); if (behavior instanceof CoreCmmnTriggerableActivityBehavior) { ((CoreCmmnTriggerableActivityBehavior) behavior).trigger(commandContext, planItemInstanceEntity); } else { behavior.trigger(planItemInstanceEntity); } } @Override public String toString() { PlanItem planItem = planItemInstanceEntity.getPlanItem(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[Trigger PlanItem] "); stringBuilder.append(planItem); return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TriggerPlanItemInstanceOperation.java
1
请完成以下Java代码
public Builder setRowId(final String rowIdStr) { final DocumentId rowId = DocumentId.ofStringOrEmpty(rowIdStr); setRowId(rowId); return this; } public Builder setRowId(@Nullable final DocumentId rowId) { rowIds.clear(); if (rowId != null) { rowIds.add(rowId); } return this; } public Builder setRowIdsList(final String rowIdsListStr) { return setRowIds(DocumentIdsSelection.ofCommaSeparatedString(rowIdsListStr)); }
public Builder setRowIds(final DocumentIdsSelection rowIds) { this.rowIds.clear(); this.rowIds.addAll(rowIds.toSet()); return this; } public Builder allowNullRowId() { rowId_allowNull = true; return this; } public Builder allowNewRowId() { rowId_allowNew = true; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentPath.java
1
请完成以下Java代码
public DatePeriodDetails getDt() { return dt; } /** * Sets the value of the dt property. * * @param value * allowed object is * {@link DatePeriodDetails } * */ public void setDt(DatePeriodDetails value) { this.dt = value; } /** * Gets the value of the dtTm property. * * @return * possible object is * {@link DateTimePeriodDetails } * */ public DateTimePeriodDetails getDtTm() {
return dtTm; } /** * Sets the value of the dtTm property. * * @param value * allowed object is * {@link DateTimePeriodDetails } * */ public void setDtTm(DateTimePeriodDetails value) { this.dtTm = 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\DateOrDateTimePeriodChoice.java
1
请完成以下Java代码
public class GetTaskVariableCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected String variableName; protected boolean isLocal; public GetTaskVariableCmd(String taskId, String variableName, boolean isLocal) { this.taskId = taskId; this.variableName = variableName; this.isLocal = isLocal; } public Object execute(CommandContext commandContext) { if (taskId == null) { throw new ActivitiIllegalArgumentException("taskId is null"); } if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
if (task == null) { throw new ActivitiObjectNotFoundException("task " + taskId + " doesn't exist", Task.class); } Object value; if (isLocal) { value = task.getVariableLocal(variableName, false); } else { value = task.getVariable(variableName, false); } return value; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetTaskVariableCmd.java
1
请完成以下Java代码
public void setLinkedProcessInstanceId(String linkedProcessInstanceId) { this.linkedProcessInstanceId = linkedProcessInstanceId; } @Override public String getLinkedProcessInstanceId() { return linkedProcessInstanceId; } public void setLinkedProcessInstanceType(String linkedProcessInstanceType) { this.linkedProcessInstanceType = linkedProcessInstanceType; } @Override public String getLinkedProcessInstanceType() { return linkedProcessInstanceType; } @Override public ProcessEvents getEventType() { return ProcessEvents.PROCESS_STARTED; } @Override
public String toString() { return ( "ProcessStartedEventImpl{" + super.toString() + "nestedProcessDefinitionId='" + nestedProcessDefinitionId + '\'' + ", nestedProcessInstanceId='" + nestedProcessInstanceId + '\'' + ", linkedProcessInstanceId='" + linkedProcessInstanceId + '\'' + ", linkedProcessInstanceType='" + linkedProcessInstanceType + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\impl\ProcessStartedEventImpl.java
1
请完成以下Java代码
public class BoundaryEventParseHandler extends AbstractFlowNodeBpmnParseHandler<BoundaryEvent> { private static final Logger logger = LoggerFactory.getLogger(BoundaryEventParseHandler.class); public Class<? extends BaseElement> getHandledType() { return BoundaryEvent.class; } protected void executeParse(BpmnParse bpmnParse, BoundaryEvent boundaryEvent) { if (boundaryEvent.getAttachedToRef() == null) { logger.warn( "Invalid reference in boundary event. Make sure that the referenced activity " + "is defined in the same scope as the boundary event " + boundaryEvent.getId() ); return; } EventDefinition eventDefinition = null;
if (boundaryEvent.getEventDefinitions().size() > 0) { eventDefinition = boundaryEvent.getEventDefinitions().get(0); } if ( eventDefinition instanceof TimerEventDefinition || eventDefinition instanceof ErrorEventDefinition || eventDefinition instanceof SignalEventDefinition || eventDefinition instanceof CancelEventDefinition || eventDefinition instanceof MessageEventDefinition || eventDefinition instanceof CompensateEventDefinition ) { bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition); } else { // Should already be picked up by process validator on deploy, so this is just to be sure logger.warn("Unsupported boundary event type for boundary event " + boundaryEvent.getId()); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\BoundaryEventParseHandler.java
1
请完成以下Java代码
private void dbUpdateActivities(@NonNull final ImportRecordsSelection selection) { final String sql = "UPDATE " + targetTableName + " i " + " SET C_Activity_ID =(SELECT C_Activity_ID FROM C_Activity p" + " WHERE i.ActivityValue = p.Value AND i.AD_Org_ID=p.AD_Org_ID) " + "WHERE C_Activity_ID IS NULL AND ActivityValue IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + " <> 'Y'" + selection.toSqlWhereClause("i"); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); logger.info("Activities Existing Value={}", no); /// set error message if needed final String errorSql = "UPDATE " + targetTableName + " i " + " SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid Activity,' " + "WHERE C_Activity_ID IS NULL AND ActivityValue IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'" + selection.toSqlWhereClause("i"); DB.executeUpdateAndThrowExceptionOnFail(errorSql, ITrx.TRXNAME_ThreadInherited); } private void dbUpdateCampaigns(@NonNull final ImportRecordsSelection selection) {
final String sql = "UPDATE " + targetTableName + " i " + " SET C_Campaign_ID =(SELECT C_Campaign_ID FROM C_Campaign p" + " WHERE i.CampaignValue = p.Value AND i.AD_Org_ID=p.AD_Org_ID) " + "WHERE C_Campaign_ID IS NULL AND CampaignValue IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + " <> 'Y'" + selection.toSqlWhereClause("i"); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); logger.info("Campaigns Existing Value={}", no); /// set error message if needed final String errorSql = "UPDATE " + targetTableName + " i " + " SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid Campaign,' " + "WHERE C_Campaign_ID IS NULL AND CampaignValue IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'" + selection.toSqlWhereClause("i"); DB.executeUpdateAndThrowExceptionOnFail(errorSql, ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impexp\MForecastImportTableSqlUpdater.java
1
请在Spring Boot框架中完成以下Java代码
public class DocOutboundAttachmentStoredListener implements AttachmentStoredListener { private final AttachmentEntryService attachmentEntryService; public DocOutboundAttachmentStoredListener(@NonNull final AttachmentEntryService attachmentEntryService) { this.attachmentEntryService = attachmentEntryService; } @Override public void attachmentWasStored( @NonNull final AttachmentEntry attachmentEntry, @NonNull final URI storageIdentifier) { final ImmutableList<I_C_Doc_Outbound_Log> docOutboundLogRecords = attachmentEntry .getLinkedRecords() .stream() .filter(this::isDocOutBoundLogReference) .map(ref -> ref.getModel(I_C_Doc_Outbound_Log.class)) .collect(ImmutableList.toImmutableList()); final ImmutableList.Builder<I_C_Doc_Outbound_Log_Line> createdLogLineRecords = ImmutableList.builder(); for (final I_C_Doc_Outbound_Log docOutboundLogRecord : docOutboundLogRecords) { final I_C_Doc_Outbound_Log_Line docOutboundLogLineRecord = DocOutboundUtils.createOutboundLogLineRecord(docOutboundLogRecord); docOutboundLogLineRecord.setAction(ArchiveAction.ATTACHMENT_STORED.getCode()); docOutboundLogLineRecord.setStoreURI(storageIdentifier.toString()); saveRecord(docOutboundLogLineRecord); createdLogLineRecords.add(docOutboundLogLineRecord);
docOutboundLogRecord.setDateLastStore(SystemTime.asTimestamp()); saveRecord(docOutboundLogRecord); } attachmentEntryService.createAttachmentLinks( ImmutableList.of(attachmentEntry), createdLogLineRecords.build()); } private boolean isDocOutBoundLogReference(ITableRecordReference ref) { return I_C_Doc_Outbound_Log.Table_Name.equals(ref.getTableName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\storage\attachments\DocOutboundAttachmentStoredListener.java
2