instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public RefBuilder newRef() { return endRef().ref(); } /** * Supposed to be called only by the parent builder. * * @param parent * @return */ /* package */ PartitionerConfigReference build(final PartitionerConfigLine parent) { final PartitionerConfigReference partitionerConfigReference = new PartitionerConfigReference(parent, referencingColumnName, referencedTableName, partitionBoundary); partitionerConfigReference.setDLM_Partition_Config_Reference_ID(DLM_Partition_Config_Reference_ID); return partitionerConfigReference; } @Override public int hashCode() { return new HashcodeBuilder() .append(referencedTableName) .append(referencingColumnName) .append(parentbuilder) .toHashcode(); }; /** * Note: it's important not to include {@link #getDLM_Partition_Config_Reference_ID()} in the result. * Check the implementation of {@link PartitionerConfigLine.LineBuilder#endRef()} for details. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final RefBuilder other = EqualsBuilder.getOther(this, obj);
if (other == null) { return false; } return new EqualsBuilder() .append(referencedTableName, other.referencedTableName) .append(referencingColumnName, other.referencingColumnName) .append(parentbuilder, other.parentbuilder) .isEqual(); } @Override public String toString() { return "RefBuilder [referencingColumnName=" + referencingColumnName + ", referencedTableName=" + referencedTableName + ", partitionBoundary=" + partitionBoundary + ", DLM_Partition_Config_Reference_ID=" + DLM_Partition_Config_Reference_ID + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionerConfigReference.java
2
请完成以下Java代码
public java.math.BigDecimal getPricingSystemSurchargeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricingSystemSurchargeAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set QualityIssuePercentage. @param QualityIssuePercentage QualityIssuePercentage */ @Override public void setQualityIssuePercentage (java.math.BigDecimal QualityIssuePercentage) { set_Value (COLUMNNAME_QualityIssuePercentage, QualityIssuePercentage); } /** Get QualityIssuePercentage. @return QualityIssuePercentage */ @Override public java.math.BigDecimal getQualityIssuePercentage () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QualityIssuePercentage); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Reihenfolge.
@param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak.java
1
请在Spring Boot框架中完成以下Java代码
public class StockAvailabilityResponseItem { PZN pzn; Quantity qty; /** * If specified, ALL parts of the substitution article will be accepted (except for reason of substitution "suggestion"). * The solution excludes for complexity reasons that substitution for normal delivery may yield one share with and one share without substitution! */ StockAvailabilitySubstitution substitution; /** a maximum of 5 parts of the feedback whereby each type of type may only be used once. */ ImmutableList<StockAvailabilityResponseItemPart> parts; @Builder private StockAvailabilityResponseItem(
@NonNull final PZN pzn, @NonNull final Quantity qty, @Nullable final StockAvailabilitySubstitution substitution, @NonNull @Singular final ImmutableList<StockAvailabilityResponseItemPart> parts) { this.pzn = pzn; this.qty = qty; this.substitution = substitution; this.parts = parts; // TODO: validate parts: // * max 5 are allowed (per protocol) // * Only one StockAvailabilityResponseItemPartType shall exist! // * sum of part's qtys shall be this.qty } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\stockAvailability\StockAvailabilityResponseItem.java
2
请完成以下Java代码
public final class CrossOriginOpenerPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter { public static final String OPENER_POLICY = "Cross-Origin-Opener-Policy"; private @Nullable ServerHttpHeadersWriter delegate; /** * Sets the {@link CrossOriginOpenerPolicy} value to be used in the * {@code Cross-Origin-Opener-Policy} header * @param openerPolicy the {@link CrossOriginOpenerPolicy} to use */ public void setPolicy(CrossOriginOpenerPolicy openerPolicy) { Assert.notNull(openerPolicy, "openerPolicy cannot be null"); this.delegate = createDelegate(openerPolicy); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return (this.delegate != null) ? this.delegate.writeHttpHeaders(exchange) : Mono.empty(); } private static ServerHttpHeadersWriter createDelegate(CrossOriginOpenerPolicy openerPolicy) { StaticServerHttpHeadersWriter.Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(OPENER_POLICY, openerPolicy.getPolicy()); return builder.build(); } public enum CrossOriginOpenerPolicy { UNSAFE_NONE("unsafe-none"),
SAME_ORIGIN_ALLOW_POPUPS("same-origin-allow-popups"), SAME_ORIGIN("same-origin"); private final String policy; CrossOriginOpenerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\CrossOriginOpenerPolicyServerHttpHeadersWriter.java
1
请在Spring Boot框架中完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "kermit") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @ApiModelProperty(example = "sales") public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @ApiModelProperty(example = "null") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getTaskUrl() { return taskUrl; }
public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "5") public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/5") public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricIdentityLinkResponse.java
2
请在Spring Boot框架中完成以下Java代码
public SessionDAO sessionDAO() { return new MemorySessionDAO(); } /** * 自定义cookie名称 * @return */ @Bean public SimpleCookie sessionIdCookie() { SimpleCookie cookie = new SimpleCookie("sid"); cookie.setMaxAge(-1); cookie.setPath("/"); cookie.setHttpOnly(false); return cookie;
} @Bean public DefaultWebSessionManager sessionManager(SimpleCookie sessionIdCookie, SessionDAO sessionDAO) { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionIdCookie(sessionIdCookie); sessionManager.setSessionIdCookieEnabled(true); //30分钟 sessionManager.setGlobalSessionTimeout(180000); sessionManager.setSessionDAO(sessionDAO); sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(true); return sessionManager; } }
repos\spring-boot-quick-master\quick-shiro-cas\src\main\java\com\shiro\config\ShiroConfig.java
2
请完成以下Java代码
public UserOperationLogQuery categoryIn(String... categories) { ensureNotNull("categories", (Object[]) categories); this.categories = categories; return this; } public UserOperationLogQuery afterTimestamp(Date after) { this.timestampAfter = after; return this; } public UserOperationLogQuery beforeTimestamp(Date before) { this.timestampBefore = before; return this; } public UserOperationLogQuery orderByTimestamp() { return orderBy(OperationLogQueryProperty.TIMESTAMP); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntryCountByQueryCriteria(this); } public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntriesByQueryCriteria(this, page); } public boolean isTenantIdSet() { return isTenantIdSet; }
public UserOperationLogQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; this.isTenantIdSet = true; return this; } public UserOperationLogQuery withoutTenantId() { this.tenantIds = null; this.isTenantIdSet = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
1
请完成以下Java代码
private boolean retrieveEnabledNoFail(final UserId loggedUserId) { try { return retrieveEnabled(loggedUserId); } catch (Exception ex) { logger.error(ex.getLocalizedMessage(), ex); return false; } } private boolean retrieveEnabled(final UserId loggedUserId) { final AdWindowId windowId = AdWindowId.ofRepoIdOrNull(MTable.get(Env.getCtx(), I_AD_Field.Table_Name).getAD_Window_ID()); if (windowId == null) { return false; } final ClientId clientId = Env.getClientId(); final LocalDate date = Env.getLocalDate(); // // Makes sure the logged in user has at least one role assigned which has read-write access to our window return Services.get(IUserRolePermissionsDAO.class) .matchUserRolesPermissionsForUser( clientId, loggedUserId, date, rolePermissions -> rolePermissions.checkWindowPermission(windowId).hasWriteAccess()); } public void save(final GridTab gridTab) { Services.get(ITrxManager.class).runInNewTrx(() -> save0(gridTab)); }
private void save0(final GridTab gridTab) { Check.assumeNotNull(gridTab, "gridTab not null"); for (final GridField gridField : gridTab.getFields()) { save(gridField); } } private void save(final GridField gridField) { final GridFieldVO gridFieldVO = gridField.getVO(); final AdFieldId adFieldId = gridFieldVO.getAD_Field_ID(); if (adFieldId == null) { return; } final I_AD_Field adField = InterfaceWrapperHelper.load(adFieldId, I_AD_Field.class); if (adField == null) { return; } adField.setIsDisplayedGrid(gridFieldVO.isDisplayedGrid()); adField.setSeqNoGrid(gridFieldVO.getSeqNoGrid()); adField.setColumnDisplayLength(gridFieldVO.getLayoutConstraints().getColumnDisplayLength()); InterfaceWrapperHelper.save(adField); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveStateModel.java
1
请完成以下Java代码
public void beforeCompletion() { transactionListener.execute(commandContext); } }); } else if (transactionState == TransactionState.ROLLED_BACK) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { if (TransactionSynchronization.STATUS_ROLLED_BACK == status) { transactionListener.execute(commandContext); } } }); } } protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered { @Override public void suspend() { } @Override public void resume() { } @Override public void flush() { }
@Override public void beforeCommit(boolean readOnly) { } @Override public void beforeCompletion() { } @Override public void afterCommit() { } @Override public void afterCompletion(int status) { } @Override public int getOrder() { return transactionSynchronizationAdapterOrder; } } }
repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\SpringTransactionContext.java
1
请在Spring Boot框架中完成以下Java代码
public static class Opaquetoken { /** * Client id used to authenticate with the token introspection endpoint. */ private @Nullable String clientId; /** * Client secret used to authenticate with the token introspection endpoint. */ private @Nullable String clientSecret; /** * OAuth 2.0 endpoint through which token introspection is accomplished. */ private @Nullable String introspectionUri; public @Nullable String getClientId() { return this.clientId; } public void setClientId(@Nullable String clientId) { this.clientId = clientId; }
public @Nullable String getClientSecret() { return this.clientSecret; } public void setClientSecret(@Nullable String clientSecret) { this.clientSecret = clientSecret; } public @Nullable String getIntrospectionUri() { return this.introspectionUri; } public void setIntrospectionUri(@Nullable String introspectionUri) { this.introspectionUri = introspectionUri; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\OAuth2ResourceServerProperties.java
2
请完成以下Java代码
private void setIsSOTrx(final boolean isSOTrx) { this._isSOTrx = isSOTrx; } public boolean isSOTrx() { return _isSOTrx; } public int getAD_Color_ID() { return AD_Color_ID; } public int getAD_Image_ID() { return AD_Image_ID; } public int getWinWidth() { return WinWidth; } public int getWinHeight() {
return WinHeight; } public String getWindowType() { return WindowType; } private int getBaseTable_ID() { return _BaseTable_ID; } boolean isLoadAllLanguages() { return loadAllLanguages; } boolean isApplyRolePermissions() { return applyRolePermissions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindowVO.java
1
请完成以下Java代码
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) { String clientRegistrationId = this.resolveClientRegistrationId(parameter); if (!StringUtils.hasLength(clientRegistrationId)) { throw new IllegalArgumentException("Unable to resolve the Client Registration Identifier. " + "It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or " + "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\")."); } Authentication principal = this.securityContextHolderStrategy.getContext().getAuthentication(); if (principal == null) { principal = ANONYMOUS_AUTHENTICATION; } HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class); // @formatter:off OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(clientRegistrationId) .principal(principal) .attribute(HttpServletRequest.class.getName(), servletRequest) .attribute(HttpServletResponse.class.getName(), servletResponse) .build(); // @formatter:on return this.authorizedClientManager.authorize(authorizeRequest); } private String resolveClientRegistrationId(MethodParameter parameter) { RegisteredOAuth2AuthorizedClient authorizedClientAnnotation = AnnotatedElementUtils .findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class); Authentication principal = this.securityContextHolderStrategy.getContext().getAuthentication(); if (StringUtils.hasLength(authorizedClientAnnotation.registrationId())) { return authorizedClientAnnotation.registrationId(); } if (StringUtils.hasLength(authorizedClientAnnotation.value())) { return authorizedClientAnnotation.value();
} if (principal != null && OAuth2AuthenticationToken.class.isAssignableFrom(principal.getClass())) { return ((OAuth2AuthenticationToken) principal).getAuthorizedClientRegistrationId(); } return null; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\method\annotation\OAuth2AuthorizedClientArgumentResolver.java
1
请在Spring Boot框架中完成以下Java代码
public static class PickFrom { @Nullable String qrCode; @Nullable BigDecimal qtyPicked; @NonNull @JsonIgnore public Optional<Quantity> getQtyPicked(@NonNull final I_C_UOM uom) { return qtyPicked != null ? Optional.of(Quantity.of(qtyPicked, uom)) : Optional.empty(); } } @Nullable PickFrom pickFrom; @Value @Builder @Jacksonized public static class Unpick { @Nullable String unpickToTargetQRCode; } @Nullable Unpick unpick; @Value @Builder @Jacksonized public static class DropTo { @Nullable ScannedCode qrCode; } @Nullable DropTo dropTo; @Builder @Jacksonized private JsonDistributionEvent( @NonNull final String wfProcessId, @NonNull final String wfActivityId, @Nullable final DistributionJobLineId lineId, @Nullable final DistributionJobStepId distributionStepId, // @Nullable final PickFrom pickFrom,
@Nullable final Unpick unpick, @Nullable final DropTo dropTo) { if (CoalesceUtil.countNotNulls(pickFrom, dropTo, unpick) != 1) { throw new AdempiereException("One and only one action like pickFrom, dropTo etc shall be specified in an event."); } this.wfProcessId = wfProcessId; this.wfActivityId = wfActivityId; this.lineId = lineId; this.distributionStepId = distributionStepId; // this.pickFrom = pickFrom; this.dropTo = dropTo; this.unpick = unpick; } @NonNull @JsonIgnore public DropTo getDropToNonNull() { return Check.assumeNotNull(dropTo, "dropTo shall not be null: {}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\rest_api\json\JsonDistributionEvent.java
2
请在Spring Boot框架中完成以下Java代码
public ServiceProperties serviceProperties() { logger.info("service properties"); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setService("http://localhost:8900/login/cas"); serviceProperties.setSendRenew(false); return serviceProperties; } @Bean public TicketValidator ticketValidator() { return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); } @Bean public CasUserDetailsService getUser(){ return new CasUserDetailsService(); } @Bean public CasAuthenticationProvider casAuthenticationProvider( TicketValidator ticketValidator, ServiceProperties serviceProperties) { CasAuthenticationProvider provider = new CasAuthenticationProvider(); provider.setServiceProperties(serviceProperties); provider.setTicketValidator(ticketValidator); provider.setUserDetailsService( s -> new User("casuser", "Mellon", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); //For Authentication with a Database-backed UserDetailsService //provider.setUserDetailsService(getUser()); provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); return provider; }
@Bean public SecurityContextLogoutHandler securityContextLogoutHandler() { return new SecurityContextLogoutHandler(); } @Bean public LogoutFilter logoutFilter() { LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/cas/logout", securityContextLogoutHandler()); logoutFilter.setFilterProcessesUrl("/logout/cas"); return logoutFilter; } @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } }
repos\tutorials-master\security-modules\cas\cas-secured-app\src\main\java\com\baeldung\cassecuredapp\CasSecuredApplication.java
2
请完成以下Java代码
public int read() throws IOException { return m_reader.read(); } // read /** * Method read * @param cbuf char[] * @param off int * @param len int * @return int * @throws IOException */ public int read(char[] cbuf, int off, int len) throws IOException { return m_reader.read(cbuf, off, len); } // read /** * Encodes strings for XML * @param text text * @return string */ public final static String xmlEncodeTextAsPCDATA(String text) { if (text == null) return null; char c; StringBuffer n = new StringBuffer (text.length () * 2); for (int i = 0; i < text.length (); i++) { c = text.charAt (i); switch (c) { case '&': n.append ("&amp;"); break; case '<':
n.append ("&lt;"); break; case '>': n.append ("&gt;"); break; case '"': n.append ("&quot;"); break; case '\'': n.append ("&apos;"); break; default: { n.append (c); break; } } } return n.toString (); } // xmlEncodeTextAsPCDATA } //Ofx1To2Convertor
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\impexp\OFX1ToXML.java
1
请完成以下Java代码
public final class UIDisplayedEntityTypes extends Constraint { /** * @param showAllEntityTypes true if we shall display all UI elements, even if a entity type was configured to not show them * @return new constraint instance */ public static UIDisplayedEntityTypes of(final boolean showAllEntityTypes) { return new UIDisplayedEntityTypes(showAllEntityTypes); } /** * Convenient method to check if role allows a given entity type to be displayed in UI. * * @param entityType entity type or <code>null</code> * @return * <ul> * <li>true/false if current role has {@link UIDisplayedEntityTypes} constraint and the constraint allows or disallow it (see {@link #isDisplayedInUI(String)}) * <li>true if current role does not have the {@link UIDisplayedEntityTypes} constraint. * </ul> */ public static boolean isEntityTypeDisplayedInUIOrTrueIfNull( @NonNull final Properties ctx, @NonNull final String entityType) { // Get the constraint of current logged in role. final IUserRolePermissions role = Env.getUserRolePermissionsOrNull(ctx); if(role == null) { // cannot extract the role from given context => consider the entity as displayed return true; } return isEntityTypeDisplayedInUIOrTrueIfNull(role, entityType); } public static boolean isEntityTypeDisplayedInUIOrTrueIfNull( @NonNull final IUserRolePermissions role, @NonNull final String entityType) { final UIDisplayedEntityTypes constraint = role .getConstraint(UIDisplayedEntityTypes.class) .orElse(null); // If no constraint => return default (true) if (constraint == null) {
return true; } // Ask the constraint return constraint.isDisplayedInUI(entityType); } private final boolean showAllEntityTypes; private UIDisplayedEntityTypes(final boolean showAllEntityTypes) { super(); this.showAllEntityTypes = showAllEntityTypes; } @Override public boolean isInheritable() { return false; } /** * @return true if UI elements for given entity type shall be displayed */ public boolean isDisplayedInUI(final String entityType) { if (showAllEntityTypes) { return EntityTypesCache.instance.isActive(entityType); } else { return EntityTypesCache.instance.isDisplayedInUI(entityType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\UIDisplayedEntityTypes.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SuspensionStateImpl other = (SuspensionStateImpl) obj; return stateCode == other.stateCode; } @Override public String toString() { return name; } } /////////////////////////////////////////// helper class public static class SuspensionStateUtil { public static void setSuspensionState(ProcessDefinitionEntity processDefinitionEntity, SuspensionState state) { if (processDefinitionEntity.getSuspensionState() == state.getStateCode()) { throw new ActivitiException("Cannot set suspension state '" + state + "' for " + processDefinitionEntity + "': already in state '" + state + "'."); } processDefinitionEntity.setSuspensionState(state.getStateCode()); dispatchStateChangeEvent(processDefinitionEntity, state); } public static void setSuspensionState(ExecutionEntity executionEntity, SuspensionState state) { if (executionEntity.getSuspensionState() == state.getStateCode()) { throw new ActivitiException("Cannot set suspension state '" + state + "' for " + executionEntity + "': already in state '" + state + "'."); } executionEntity.setSuspensionState(state.getStateCode()); dispatchStateChangeEvent(executionEntity, state); } public static void setSuspensionState(TaskEntity taskEntity, SuspensionState state) { if (taskEntity.getSuspensionState() == state.getStateCode()) {
throw new ActivitiException("Cannot set suspension state '" + state + "' for " + taskEntity + "': already in state '" + state + "'."); } taskEntity.setSuspensionState(state.getStateCode()); dispatchStateChangeEvent(taskEntity, state); } protected static void dispatchStateChangeEvent(Object entity, SuspensionState state) { if (Context.getCommandContext() != null && Context.getCommandContext().getEventDispatcher().isEnabled()) { FlowableEngineEventType eventType = null; if (state == SuspensionState.ACTIVE) { eventType = FlowableEngineEventType.ENTITY_ACTIVATED; } else { eventType = FlowableEngineEventType.ENTITY_SUSPENDED; } Context.getCommandContext().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(eventType, entity), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\SuspensionState.java
1
请完成以下Java代码
public java.lang.String getSenderGLN() { return get_ValueAsString(COLUMNNAME_SenderGLN); } @Override public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } @Override public void setSurchargeAmt (final @Nullable BigDecimal SurchargeAmt) { set_Value (COLUMNNAME_SurchargeAmt, SurchargeAmt); } @Override public BigDecimal getSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalLines (final @Nullable BigDecimal TotalLines) { set_Value (COLUMNNAME_TotalLines, TotalLines); } @Override public BigDecimal getTotalLines() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLines); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalLinesWithSurchargeAmt (final @Nullable BigDecimal TotalLinesWithSurchargeAmt) { set_Value (COLUMNNAME_TotalLinesWithSurchargeAmt, TotalLinesWithSurchargeAmt); } @Override public BigDecimal getTotalLinesWithSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLinesWithSurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalTaxBaseAmt (final @Nullable BigDecimal TotalTaxBaseAmt) { set_Value (COLUMNNAME_TotalTaxBaseAmt, TotalTaxBaseAmt); }
@Override public BigDecimal getTotalTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalTaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalVat (final @Nullable BigDecimal TotalVat) { set_Value (COLUMNNAME_TotalVat, TotalVat); } @Override public BigDecimal getTotalVat() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVat); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalVatWithSurchargeAmt (final BigDecimal TotalVatWithSurchargeAmt) { set_ValueNoCheck (COLUMNNAME_TotalVatWithSurchargeAmt, TotalVatWithSurchargeAmt); } @Override public BigDecimal getTotalVatWithSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVatWithSurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_v.java
1
请完成以下Spring Boot application配置
info: scm-url: "@scm.url@" build-url: "https://travis-ci.org/codecentric/spring-boot-admin" logging: file: name: "target/boot-admin-sample-reactive.log" management: endpoints: web: exposure: include: "*" endpoint: health: show-details: ALWAYS spring: application: name: spr
ing-boot-admin-sample-reactive boot: admin: client: url: http://localhost:8080 profiles: active: - insecure
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-reactive\src\main\resources\application.yml
2
请完成以下Java代码
public class TelemetryCmdsWrapper { private List<AttributesSubscriptionCmd> attrSubCmds; private List<TimeseriesSubscriptionCmd> tsSubCmds; private List<GetHistoryCmd> historyCmds; private List<EntityDataCmd> entityDataCmds; private List<EntityDataUnsubscribeCmd> entityDataUnsubscribeCmds; private List<AlarmDataCmd> alarmDataCmds; private List<AlarmDataUnsubscribeCmd> alarmDataUnsubscribeCmds; private List<EntityCountCmd> entityCountCmds; private List<EntityCountUnsubscribeCmd> entityCountUnsubscribeCmds; private List<AlarmCountCmd> alarmCountCmds;
private List<AlarmCountUnsubscribeCmd> alarmCountUnsubscribeCmds; @JsonIgnore public WsCommandsWrapper toCommonCmdsWrapper() { return new WsCommandsWrapper(null, Stream.of( attrSubCmds, tsSubCmds, historyCmds, entityDataCmds, entityDataUnsubscribeCmds, alarmDataCmds, alarmDataUnsubscribeCmds, entityCountCmds, entityCountUnsubscribeCmds, alarmCountCmds, alarmCountUnsubscribeCmds ) .filter(Objects::nonNull) .flatMap(Collection::stream) .collect(Collectors.toList())); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\telemetry\cmd\TelemetryCmdsWrapper.java
1
请完成以下Java代码
void collect(@NonNull final IAttributeSet from) { final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>() { @Nullable @Override public Object string() { return from.getValueAsString(attributeCode); } @Override public Object number() { return from.getValueAsBigDecimal(attributeCode); } @Nullable @Override public Object date() { return from.getValueAsDate(attributeCode); } @Nullable @Override public Object list() { return from.getValueAsString(attributeCode);
} }); values.add(value); } void updateAggregatedValueTo(@NonNull final IAttributeSet to) { if (values.size() == 1 && to.hasAttribute(attributeCode)) { to.setValue(attributeCode, values.iterator().next()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } final CityVO other = EqualsBuilder.getOther(this, obj); if (other == null) return false; return new EqualsBuilder() .append(C_City_ID, other.C_City_ID) .append(C_Region_ID, other.C_Region_ID) .append(CityName, other.CityName) .append(RegionName, other.RegionName) .isEqual(); } @Override public String getText() { return CityName; } @Override public String toString() { // needed for ListCellRenderer final StringBuilder sb = new StringBuilder(); if (this.CityName != null)
{ sb.append(this.CityName); } if (this.RegionName != null) { sb.append(" (").append(this.RegionName).append(")"); } return sb.toString(); } public int getC_City_ID() { return C_City_ID; } public String getCityName() { return CityName; } public int getC_Region_ID() { return C_Region_ID; } public String getRegionName() { return RegionName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CityVO.java
1
请完成以下Java代码
public Optional<Warehouse> getOptionalById(@NonNull final WarehouseId id) { return Optional.ofNullable(getById(id)) .map(WarehouseDAO::ofRecord); } public void save(@NonNull final Warehouse warehouse) { final I_M_Warehouse record = toRecord(warehouse); saveRecord(record); } @NonNull public Warehouse createWarehouse(@NonNull final CreateWarehouseRequest request) { final I_M_Warehouse warehouseRecord = newInstance(I_M_Warehouse.class); warehouseRecord.setName(request.getName()); warehouseRecord.setValue(request.getValue()); warehouseRecord.setAD_Org_ID(request.getOrgId().getRepoId()); warehouseRecord.setC_BPartner_ID(request.getPartnerLocationId().getBpartnerId().getRepoId()); warehouseRecord.setC_BPartner_Location_ID(request.getPartnerLocationId().getRepoId()); warehouseRecord.setIsActive(request.isActive()); saveRecord(warehouseRecord); createDefaultLocator(WarehouseId.ofRepoId(warehouseRecord.getM_Warehouse_ID())); return ofRecord(warehouseRecord); } @NonNull private I_M_Warehouse toRecord(@NonNull final Warehouse warehouse) { final I_M_Warehouse record = Optional.ofNullable(getById(warehouse.getId())) .orElseThrow(() -> new AdempiereException("No warehouse found for ID!") .appendParametersToMessage() .setParameter("WarehouseId", warehouse.getId())); record.setAD_Org_ID(warehouse.getOrgId().getRepoId()); record.setValue(warehouse.getValue()); record.setName(warehouse.getName()); record.setC_BPartner_ID(warehouse.getPartnerLocationId().getBpartnerId().getRepoId());
record.setC_BPartner_Location_ID(warehouse.getPartnerLocationId().getRepoId()); record.setIsActive(warehouse.isActive()); return record; } @NonNull private static Warehouse ofRecord(@NonNull final I_M_Warehouse warehouseRecord) { return Warehouse.builder() .id(WarehouseId.ofRepoId(warehouseRecord.getM_Warehouse_ID())) .orgId(OrgId.ofRepoId(warehouseRecord.getAD_Org_ID())) .name(warehouseRecord.getName()) .value(warehouseRecord.getValue()) .partnerLocationId(BPartnerLocationId.ofRepoId(warehouseRecord.getC_BPartner_ID(), warehouseRecord.getC_BPartner_Location_ID())) .active(warehouseRecord.isActive()) .build(); } @Override public ClientAndOrgId getClientAndOrgIdByLocatorId(@NonNull LocatorId locatorId) { return getClientAndOrgIdByLocatorId(locatorId.getWarehouseId()); } public ClientAndOrgId getClientAndOrgIdByLocatorId(@NonNull WarehouseId warehouseId) { final I_M_Warehouse warehouse = getById(warehouseId); return ClientAndOrgId.ofClientAndOrg(warehouse.getAD_Client_ID(), warehouse.getAD_Org_ID()); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds) { return getLocatorsByRepoIds(ImmutableSet.copyOf(locatorIds)) .stream() .map(LocatorId::ofRecord) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseDAO.java
1
请完成以下Spring Boot application配置
spring: flyway: enabled: true # 迁移前校验 SQL 文件是否存在问题 validate-on-migrate: true # 生产环境一定要关闭 clean-disabled: true # 校验路径下是否存在 SQL 文件 check-location: false # 最开始已经存在表结构,且不存在 flyway_schema_history 表时,需要设置为 true baseline-on-migrate: true # 基础版本 0 baseline-version: 0 datasource:
url: jdbc:mysql://127.0.0.1:3306/flyway-test?useSSL=false username: root password: root type: com.zaxxer.hikari.HikariDataSource
repos\spring-boot-demo-master\demo-flyway\src\main\resources\application.yml
2
请完成以下Java代码
public int getSpanY () { Integer ii = (Integer)get_Value(COLUMNNAME_SpanY); if (ii == null) return 0; return ii.intValue(); } public I_C_POSKeyLayout getSubKeyLayout() throws RuntimeException { return (I_C_POSKeyLayout)MTable.get(getCtx(), I_C_POSKeyLayout.Table_Name) .getPO(getSubKeyLayout_ID(), get_TrxName()); } /** Set Key Layout. @param SubKeyLayout_ID Key Layout to be displayed when this key is pressed */ public void setSubKeyLayout_ID (int SubKeyLayout_ID) { if (SubKeyLayout_ID < 1) set_Value (COLUMNNAME_SubKeyLayout_ID, null); else set_Value (COLUMNNAME_SubKeyLayout_ID, Integer.valueOf(SubKeyLayout_ID)); } /** Get Key Layout. @return Key Layout to be displayed when this key is pressed */ public int getSubKeyLayout_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SubKeyLayout_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); }
/** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } @Override public I_AD_Reference getAD_Reference() throws RuntimeException { return (I_AD_Reference)MTable.get(getCtx(), I_AD_Reference.Table_Name) .getPO(getAD_Reference_ID(), get_TrxName()); } @Override public int getAD_Reference_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Reference_ID); if (ii == null) return 0; return ii.intValue(); } @Override public void setAD_Reference_ID(int AD_Reference_ID) { if (AD_Reference_ID < 1) set_Value (COLUMNNAME_AD_Reference_ID, null); else set_Value (COLUMNNAME_AD_Reference_ID, Integer.valueOf(AD_Reference_ID)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POSKey.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Employee. @param IsEmployee Indicates if this Business Partner is an employee */ public void setIsEmployee (boolean IsEmployee) { set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee)); } /** Get Employee. @return Indicates if this Business Partner is an employee */ public boolean isEmployee () { Object oo = get_Value(COLUMNNAME_IsEmployee); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Job.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * Attribute AD_Reference_ID=541332 * Reference name: AD_User_Attribute */ public static final int ATTRIBUTE_AD_Reference_ID=541332; /** Delegate = D */ public static final String ATTRIBUTE_Delegate = "D"; /** Politician = P */ public static final String ATTRIBUTE_Politician = "P"; @Override public void setAttribute (final java.lang.String Attribute) { set_Value (COLUMNNAME_Attribute, Attribute); } @Override public java.lang.String getAttribute() { return get_ValueAsString(COLUMNNAME_Attribute); } @Override public void setC_BPartner_Contact_QuickInput_Attributes_ID (final int C_BPartner_Contact_QuickInput_Attributes_ID) { if (C_BPartner_Contact_QuickInput_Attributes_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID, C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public int getC_BPartner_Contact_QuickInput_Attributes_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public org.compiere.model.I_C_BPartner_Contact_QuickInput getC_BPartner_Contact_QuickInput() { return get_ValueAsPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class);
} @Override public void setC_BPartner_Contact_QuickInput(final org.compiere.model.I_C_BPartner_Contact_QuickInput C_BPartner_Contact_QuickInput) { set_ValueFromPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class, C_BPartner_Contact_QuickInput); } @Override public void setC_BPartner_Contact_QuickInput_ID (final int C_BPartner_Contact_QuickInput_ID) { if (C_BPartner_Contact_QuickInput_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, C_BPartner_Contact_QuickInput_ID); } @Override public int getC_BPartner_Contact_QuickInput_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput_Attributes.java
1
请完成以下Java代码
static void register(LazyDelegateFilter<? extends Filter> lazyDelegateFilter) { REGISTRATION.add(lazyDelegateFilter); } @SuppressWarnings("unchecked") protected static <T extends Filter> InitHook<T> getInitHook() { if (APPLICATION_CONTEXT != null && APPLICATION_CONTEXT.containsBean(RESOURCE_LOADER_DEPENDING_INIT_HOOK)) { return APPLICATION_CONTEXT.getBean(RESOURCE_LOADER_DEPENDING_INIT_HOOK, InitHook.class); } return null; } static boolean isRegistered(LazyDelegateFilter<? extends Filter> lazyDelegateFilter) { return REGISTRATION.contains(lazyDelegateFilter); } static <T extends Filter> boolean lazyInit(LazyDelegateFilter<T> lazyDelegateFilter) { if (APPLICATION_CONTEXT != null) { if (isRegistered(lazyDelegateFilter)) { lazyDelegateFilter.setInitHook(LazyInitRegistration.<T> getInitHook()); lazyDelegateFilter.lazyInit(); REGISTRATION.remove(lazyDelegateFilter); LOGGER.info("lazy initialized {}", lazyDelegateFilter); return true; } else {
LOGGER.debug("skipping lazy init for {} because of no init hook registration", lazyDelegateFilter); } } else { LOGGER.debug("skipping lazy init for {} because application context not initialized yet", lazyDelegateFilter); } return false; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { APPLICATION_CONTEXT = applicationContext; for (LazyDelegateFilter<? extends Filter> lazyDelegateFilter : getRegistrations()) { lazyInit(lazyDelegateFilter); } } @EventListener protected void onContextClosed(ContextClosedEvent ev) { APPLICATION_CONTEXT = null; } static Set<LazyDelegateFilter<? extends Filter>> getRegistrations() { return Collections.unmodifiableSet(new HashSet<LazyDelegateFilter<? extends Filter>>(REGISTRATION)); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\LazyInitRegistration.java
1
请完成以下Java代码
public String getName() { return "Invoking @PreUndeploy"; } public void performOperationStep(DeploymentOperation operationContext) { final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION); final String paName = processApplication.getName(); Class<? extends AbstractProcessApplication> paClass = processApplication.getClass(); Method preUndeployMethod = InjectionUtil.detectAnnotatedMethod(paClass, PreUndeploy.class); if(preUndeployMethod == null) { LOG.debugPaLifecycleMethodNotFound(CALLBACK_NAME, paName); return; } LOG.debugFoundPaLifecycleCallbackMethod(CALLBACK_NAME, paName); // resolve injections Object[] injections = InjectionUtil.resolveInjections(operationContext, preUndeployMethod); try { // perform the actual invocation preUndeployMethod.invoke(processApplication, injections); } catch (IllegalArgumentException e) { throw LOG.exceptionWhileInvokingPaLifecycleCallback(CALLBACK_NAME, paName, e);
} catch (IllegalAccessException e) { throw LOG.exceptionWhileInvokingPaLifecycleCallback(CALLBACK_NAME, paName, e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if(cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw LOG.exceptionWhileInvokingPaLifecycleCallback(CALLBACK_NAME, paName, e); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\PreUndeployInvocationStep.java
1
请完成以下Java代码
public static void fillTypes( Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { fillJsonTypes(convertersToBpmnMap); fillBpmnTypes(convertersToJsonMap); } public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_TASK_RECEIVE, ReceiveTaskJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { convertersToJsonMap.put(ReceiveTask.class, ReceiveTaskJsonConverter.class);
} protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_RECEIVE; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {} protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { ReceiveTask task = new ReceiveTask(); return task; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\ReceiveTaskJsonConverter.java
1
请完成以下Java代码
public class HousekeeperTask implements Serializable { private TenantId tenantId; private EntityId entityId; private HousekeeperTaskType taskType; private long ts; protected HousekeeperTask(@NonNull TenantId tenantId, @NonNull EntityId entityId, @NonNull HousekeeperTaskType taskType) { this.tenantId = tenantId; this.entityId = entityId; this.taskType = taskType; this.ts = System.currentTimeMillis(); } public static HousekeeperTask deleteAttributes(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_ATTRIBUTES); } public static HousekeeperTask deleteTelemetry(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_TELEMETRY); } public static HousekeeperTask deleteEvents(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_EVENTS); }
public static HousekeeperTask unassignAlarms(User user) { return new AlarmsUnassignHousekeeperTask(user); } public static HousekeeperTask deleteAlarms(TenantId tenantId, EntityId entityId) { return new AlarmsDeletionHousekeeperTask(tenantId, entityId); } public static HousekeeperTask deleteTenantEntities(TenantId tenantId, EntityType entityType) { return new TenantEntitiesDeletionHousekeeperTask(tenantId, entityType); } public static HousekeeperTask deleteCalculatedFields(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_CALCULATED_FIELDS); } public static HousekeeperTask deleteJobs(TenantId tenantId, EntityId entityId) { return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_JOBS); } @JsonIgnore public String getDescription() { return taskType.getDescription() + " for " + entityId.getEntityType().getNormalName().toLowerCase() + " " + entityId.getId(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\housekeeper\HousekeeperTask.java
1
请完成以下Java代码
public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Attribute Set Instance. @return Product Attribute Set Instance */ public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_InOutLine getM_InOutLine() throws RuntimeException { return (I_M_InOutLine)MTable.get(getCtx(), I_M_InOutLine.Table_Name) .getPO(getM_InOutLine_ID(), get_TrxName()); } /** Set Shipment/Receipt Line. @param M_InOutLine_ID Line on Shipment or Receipt document */ public void setM_InOutLine_ID (int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID)); } /** Get Shipment/Receipt Line. @return Line on Shipment or Receipt document */ public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_InOutLine_ID())); } /** Set Movement Quantity. @param MovementQty Quantity of a product moved. */ public void setMovementQty (BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Movement Quantity. @return Quantity of a product moved. */ public BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLineMA.java
1
请完成以下Java代码
public class MPreference extends X_AD_Preference { /** * */ private static final long serialVersionUID = -5098559160325123593L; /** Null Indicator */ public static String NULL = "null"; /** * Standatrd Constructor * @param ctx ctx * @param AD_Preference_ID id * @param trxName transaction */ public MPreference(Properties ctx, int AD_Preference_ID, String trxName) { super(ctx, AD_Preference_ID, trxName); if (AD_Preference_ID == 0) { // setAD_Preference_ID (0); // setAttribute (null); // setValue (null); } } // MPreference /** * Load Contsructor * @param ctx context * @param rs result set * @param trxName transaction */ public MPreference(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MPreference /** * Full Constructor * @param ctx context * @param Attribute attribute * @param Value value * @param trxName trx */ public MPreference (Properties ctx, String Attribute, String Value, String trxName) { this (ctx, 0, trxName);
setAttribute (Attribute); setValue (Value); } // MPreference /** * Before Save * @param newRecord * @return true if can be saved */ protected boolean beforeSave (boolean newRecord) { String value = getValue(); if (value == null) value = ""; if (value.equals("-1")) setValue(""); return true; } // beforeSave /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MPreference["); sb.append (get_ID()).append("-") .append(getAttribute()).append("-").append(getValue()) .append ("]"); return sb.toString (); } // toString } // MPreference
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPreference.java
1
请完成以下Java代码
public void setCRM_Occupation_Parent(final org.compiere.model.I_CRM_Occupation CRM_Occupation_Parent) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_Parent_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation_Parent); } @Override public void setCRM_Occupation_Parent_ID (final int CRM_Occupation_Parent_ID) { if (CRM_Occupation_Parent_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_Parent_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_Parent_ID, CRM_Occupation_Parent_ID); } @Override public int getCRM_Occupation_Parent_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_Parent_ID); } /** * JobType AD_Reference_ID=541383 * Reference name: JobType */ public static final int JOBTYPE_AD_Reference_ID=541383; /** Job = B */ public static final String JOBTYPE_Job = "B"; /** Specialization = F */ public static final String JOBTYPE_Specialization = "F"; /** AdditionalSpecialization = Z */ public static final String JOBTYPE_AdditionalSpecialization = "Z"; @Override public void setJobType (final @Nullable java.lang.String JobType)
{ set_Value (COLUMNNAME_JobType, JobType); } @Override public java.lang.String getJobType() { return get_ValueAsString(COLUMNNAME_JobType); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CRM_Occupation.java
1
请完成以下Spring Boot application配置
spring: task: # Spring 执行器配置,对应 TaskExecutionProperties 配置类。对于 Spring 异步任务,会使用该执行器。 execution: thread-name-prefix: task- # 线程池的线程名的前缀。默认为 task- ,建议根据自己应用来设置 pool: # 线程池相关 core-size: 8 # 核心线程数,线程池创建时候初始化的线程数。默认为 8 。 max-size: 20 # 最大线程数,线程池最大的线程数,只有在缓冲队列满了之后,才会申请超过核心线程数的线程。默认为 Integer.MAX_VALUE keep-alive: 60s # 允许线程的空闲时间,当超过了核心线程之外的线程,在空闲时间到达之后会被销毁。默认为 60 秒 queue-capacity: 200 # 缓冲队列大小,用来缓冲执行任务的队列的大小。默认为 Integer.MAX_VALUE 。 allow-core-threa
d-timeout: true # 是否允许核心线程超时,即开启线程池的动态增长和缩小。默认为 true 。 shutdown: await-termination: true # 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true await-termination-period: 60 # 等待任务完成的最大时长,单位为秒。默认为 0 ,根据自己应用来设置
repos\SpringBoot-Labs-master\lab-29\lab-29-async-demo\src\main\resources\application.yaml
2
请完成以下Java代码
public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType changeType) throws Exception { if (InterfaceWrapperHelper.isInstanceOf(model, I_M_Product.class)) { final I_M_Product product = InterfaceWrapperHelper.create(model, I_M_Product.class); productChange(product, changeType); } } private void productChange(@NonNull final I_M_Product productPO, @NonNull final ModelChangeType type) { if (type.isChange() /* not on new, because a new product can't have any shipment schedules yet */ && type.isAfter()) { final boolean isDiverseChanged = InterfaceWrapperHelper.isValueChanged(productPO, de.metas.adempiere.model.I_M_Product.COLUMNNAME_IsDiverse); final boolean isProductTypeChanged = InterfaceWrapperHelper.isValueChanged(productPO, I_M_Product.COLUMNNAME_ProductType);
if (isDiverseChanged || isProductTypeChanged) { final ProductId productId = ProductId.ofRepoId(productPO.getM_Product_ID()); final boolean display = ProductType.ofCode(productPO.getProductType()).isItem(); final IShipmentSchedulePA shipmentSchedulePA = Services.get(IShipmentSchedulePA.class); shipmentSchedulePA.setIsDiplayedForProduct(productId, display); final IShipmentScheduleInvalidateBL shipmentScheduleInvalidator = Services.get(IShipmentScheduleInvalidateBL.class); shipmentScheduleInvalidator.flagForRecompute(productId); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\InOutCandidateValidator.java
1
请完成以下Java代码
public I_M_HU_LUTU_Configuration createNewLUTUConfiguration(final List<T> documentLines) { Check.assumeNotEmpty(documentLines, "documentLines not empty"); final T documentLine = documentLines.get(0); return handler.createNewLUTUConfiguration(documentLine); } @Override public void updateLUTUConfigurationFromDocumentLine(final I_M_HU_LUTU_Configuration lutuConfiguration, final List<T> documentLines) { Check.assumeNotEmpty(documentLines, "documentLines not empty"); final T documentLine = documentLines.get(0); handler.updateLUTUConfigurationFromDocumentLine(lutuConfiguration, documentLine); } @Override public void setCurrentLUTUConfiguration(@NonNull final List<T> documentLines, final I_M_HU_LUTU_Configuration lutuConfiguration) { for (final T documentLine : documentLines) { handler.setCurrentLUTUConfiguration(documentLine, lutuConfiguration); } } @Override public I_M_HU_LUTU_Configuration getCurrentLUTUConfigurationOrNull(final List<T> documentLines) { Check.assumeNotEmpty(documentLines, "documentLines not empty"); final T documentLine = documentLines.get(0); return handler.getCurrentLUTUConfigurationOrNull(documentLine); } @Override public List<I_M_HU_LUTU_Configuration> getCurrentLUTUConfigurationAlternatives(final List<T> documentLines) { Check.assumeNotEmpty(documentLines, "documentLines not empty"); final Set<Integer> seenConfigurationIds = new HashSet<>(); final List<I_M_HU_LUTU_Configuration> altConfigurations = new ArrayList<>(documentLines.size()); // // Main configuration final T mainDocumentLine = documentLines.get(0); final I_M_HU_LUTU_Configuration mainConfiguration = handler.getCurrentLUTUConfigurationOrNull(mainDocumentLine); // Skip the main configuration from returning it if (mainConfiguration != null) { seenConfigurationIds.add(mainConfiguration.getM_HU_LUTU_Configuration_ID());
} for (int i = 1; i < documentLines.size(); i++) { final T documentLine = documentLines.get(i); final I_M_HU_LUTU_Configuration configuration = handler.getCurrentLUTUConfigurationOrNull(documentLine); if (configuration == null) { continue; } final int configurationId = configuration.getM_HU_LUTU_Configuration_ID(); if (configurationId <= 0) { continue; } if (!seenConfigurationIds.add(configurationId)) { continue; } altConfigurations.add(configuration); } return altConfigurations; } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product(final List<T> documentLines) { Check.assumeNotEmpty(documentLines, "documentLines not empty"); final T documentLine = documentLines.get(0); return handler.getM_HU_PI_Item_Product(documentLine); } @Override public void save(@NonNull final List<T> documentLines) { for (final T documentLine : documentLines) { handler.save(documentLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\CompositeDocumentLUTUConfigurationHandler.java
1
请完成以下Java代码
protected String doIt() { if (p_C_Print_Job_ID <= 0) { throw new FillMandatoryException(I_C_Print_Job.COLUMNNAME_C_Print_Job_ID); } if (p_SeqNo_From <= 0) { p_SeqNo_From = IPrintingDAO.SEQNO_First; } if (p_SeqNo_To <= 0) { p_SeqNo_To = IPrintingDAO.SEQNO_Last; } final UserId adUserToPrintId = UserId.ofRepoIdOrNull(getAD_User_ID()); // create those instructions just for us and don't let some other printing client running with the same user-id snatch it from us. final boolean createWithSpecificHostKey = true; final I_C_Print_Job printJob = InterfaceWrapperHelper.create(getCtx(), p_C_Print_Job_ID, I_C_Print_Job.class, get_TrxName()); final I_C_Print_Job_Line firstLine = printingDAO.retrievePrintJobLine(printJob, p_SeqNo_From);
final I_C_Print_Job_Line lastLine = printingDAO.retrievePrintJobLine(printJob, p_SeqNo_To); this.jobInstructions = printJobBL .createPrintJobInstructions(adUserToPrintId, createWithSpecificHostKey, firstLine, lastLine, p_copies); return MSG_OK; } public I_C_Print_Job_Instructions getC_Print_Job_Instructions() { return jobInstructions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Print_Job_Instructions_Create.java
1
请完成以下Java代码
public void close() { } public void flush() { } // authorizations /////////////////////////////////////// protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected AuthorizationManager getAuthorizationManager() { return getSession(AuthorizationManager.class); } protected void configureQuery(AbstractQuery<?,?> query, Resource resource) { getAuthorizationManager().configureQuery(query, resource); } protected void checkAuthorization(Permission permission, Resource resource, String resourceId) { getAuthorizationManager().checkAuthorization(permission, resource, resourceId); } public boolean isAuthorizationEnabled() { return Context.getProcessEngineConfiguration().isAuthorizationEnabled(); } protected Authentication getCurrentAuthentication() { return Context.getCommandContext().getAuthentication(); } protected ResourceAuthorizationProvider getResourceAuthorizationProvider() { return Context.getProcessEngineConfiguration() .getResourceAuthorizationProvider(); } protected void deleteAuthorizations(Resource resource, String resourceId) { getAuthorizationManager().deleteAuthorizationsByResourceId(resource, resourceId); } protected void deleteAuthorizationsForUser(Resource resource, String resourceId, String userId) { getAuthorizationManager().deleteAuthorizationsByResourceIdAndUserId(resource, resourceId, userId); } protected void deleteAuthorizationsForGroup(Resource resource, String resourceId, String groupId) { getAuthorizationManager().deleteAuthorizationsByResourceIdAndGroupId(resource, resourceId, groupId); } public void saveDefaultAuthorizations(final AuthorizationEntity[] authorizations) { if(authorizations != null && authorizations.length > 0) { Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() { AuthorizationManager authorizationManager = getAuthorizationManager(); for (AuthorizationEntity authorization : authorizations) { if(authorization.getId() == null) { authorizationManager.insert(authorization); } else { authorizationManager.update(authorization); } } return null; } }); } } public void deleteDefaultAuthorizations(final AuthorizationEntity[] authorizations) { if(authorizations != null && authorizations.length > 0) { Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() { public Void call() { AuthorizationManager authorizationManager = getAuthorizationManager(); for (AuthorizationEntity authorization : authorizations) { authorizationManager.delete(authorization); } return null; } }); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractManager.java
1
请完成以下Java代码
private void retrieveOrCreateMediaSizeRecord( @NonNull final I_AD_PrinterHW printerRecord, @NonNull final PrinterHWMediaSize mediaSizePojo) { I_AD_PrinterHW_MediaSize mediaSizeRecord = Services.get(IQueryBL.class).createQueryBuilder(I_AD_PrinterHW_MediaSize.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_PrinterHW_MediaSize.COLUMN_Name, mediaSizePojo.getName()) .addEqualsFilter(I_AD_PrinterHW_MediaSize.COLUMN_AD_PrinterHW_ID, printerRecord.getAD_PrinterHW_ID()) .create() .firstOnly(I_AD_PrinterHW_MediaSize.class); if (mediaSizeRecord == null) { mediaSizeRecord = newInstance(I_AD_PrinterHW_MediaSize.class); mediaSizeRecord.setName(mediaSizePojo.getName()); mediaSizeRecord.setAD_PrinterHW(printerRecord); save(mediaSizeRecord); } } private void retrieveOrCreateMediaTrayRecord( @NonNull final I_AD_PrinterHW printerRecord, @NonNull final PrinterHWMediaTray printerTrayPojo) { final Integer trayNumber = Integer.valueOf(printerTrayPojo.getTrayNumber()); I_AD_PrinterHW_MediaTray printerTrayRecord = Services.get(IQueryBL.class).createQueryBuilder(I_AD_PrinterHW_MediaTray.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_PrinterHW_MediaTray.COLUMN_TrayNumber, trayNumber) .addEqualsFilter(I_AD_PrinterHW_MediaTray.COLUMN_AD_PrinterHW_ID, printerRecord.getAD_PrinterHW_ID()) .create() .firstOnly(I_AD_PrinterHW_MediaTray.class); if (printerTrayRecord == null) { printerTrayRecord = newInstance(I_AD_PrinterHW_MediaTray.class); printerTrayRecord.setTrayNumber(trayNumber); printerTrayRecord.setAD_PrinterHW(printerRecord); printerTrayRecord.setName(printerTrayPojo.getName());
save(printerTrayRecord); Services.get(IPrinterBL.class).createDefaultTrayMatching(printerTrayRecord); } printerTrayRecord.setName(printerTrayPojo.getName()); save(printerTrayRecord); } private I_AD_PrinterHW retrieveOrCreatePrinterRecord( @NonNull final String hostKey, @NonNull final PrinterHW hwPrinter) { I_AD_PrinterHW printerRecord = Services.get(IQueryBL.class).createQueryBuilder(I_AD_PrinterHW.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_PrinterHW.COLUMNNAME_HostKey, hostKey) .addEqualsFilter(I_AD_PrinterHW.COLUMN_Name, hwPrinter.getName()) .create() .firstOnly(I_AD_PrinterHW.class); if (printerRecord == null) { printerRecord = newInstance(I_AD_PrinterHW.class); printerRecord.setName(hwPrinter.getName()); printerRecord.setHostKey(hostKey); printerRecord.setOutputType(OutputType.Queue.getCode()); save(printerRecord); Services.get(IPrinterBL.class).createConfigAndDefaultPrinterMatching(printerRecord); } return printerRecord; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.rest-api-impl\src\main\java\de\metas\printing\rest\PrinterHWRepo.java
1
请完成以下Java代码
public PlanItemInstanceEntityBuilder addToParent(boolean addToParent) { this.addToParent = addToParent; return this; } @Override public PlanItemInstanceEntityBuilder silentNameExpressionEvaluation(boolean silentNameExpressionEvaluation) { this.silentNameExpressionEvaluation = silentNameExpressionEvaluation; return this; } @Override public PlanItemInstanceEntity create() { validateData(); return planItemInstanceEntityManager.createChildPlanItemInstance(this); } public PlanItem getPlanItem() { return planItem; } public String getName() { return name; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getDerivedCaseDefinitionId() { return derivedCaseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public PlanItemInstance getStagePlanItemInstance() { return stagePlanItemInstance; } public String getTenantId() { return tenantId; } public Map<String, Object> getLocalVariables() { return localVariables; }
public boolean hasLocalVariables() { return localVariables != null && localVariables.size() > 0; } public boolean isAddToParent() { return addToParent; } public boolean isSilentNameExpressionEvaluation() { return silentNameExpressionEvaluation; } protected void validateData() { if (planItem == null) { throw new FlowableIllegalArgumentException("The plan item must be provided when creating a new plan item instance"); } if (caseDefinitionId == null) { throw new FlowableIllegalArgumentException("The case definition id must be provided when creating a new plan item instance"); } if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("The case instance id must be provided when creating a new plan item instance"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\PlanItemInstanceEntityBuilderImpl.java
1
请完成以下Java代码
public DocumentNoBuilder setSequenceNo(@NonNull final String sequenceNo) { _sequenceNo = Check.assumeNotEmpty(sequenceNo, DocumentNoBuilderException.class, "sequenceNo"); return this; } private boolean stringCanBeParsedAsInt(@NonNull final String string) { return string.matches("\\d+"); } @Override public DocumentNoBuilder setFailOnError(final boolean failOnError) { _failOnError = failOnError; return this; } private boolean isFailOnError() { return _failOnError; } @Override public DocumentNoBuilder setUsePreliminaryDocumentNo(final boolean usePreliminaryDocumentNo) { this._usePreliminaryDocumentNo = usePreliminaryDocumentNo; return this; } private boolean isUsePreliminaryDocumentNo() {
return _usePreliminaryDocumentNo; } @NonNull private DocumentNoBuilder.CalendarYearMonthAndDay getCalendarYearMonthAndDay(@NonNull final DocumentSequenceInfo docSeqInfo) { final CalendarYearMonthAndDay.CalendarYearMonthAndDayBuilder calendarYearMonthAndDayBuilder = CalendarYearMonthAndDay.builder() .calendarYear(getCalendarYear(docSeqInfo.getDateColumn())) .calendarMonth(DEFAULT_CALENDAR_MONTH_TO_USE) .calendarDay(DEFAULT_CALENDAR_DAY_TO_USE); if (docSeqInfo.isStartNewDay()) { calendarYearMonthAndDayBuilder.calendarMonth(getCalendarMonth(docSeqInfo.getDateColumn())); calendarYearMonthAndDayBuilder.calendarDay(getCalendarDay(docSeqInfo.getDateColumn())); } else if (docSeqInfo.isStartNewMonth()) { calendarYearMonthAndDayBuilder.calendarMonth(getCalendarMonth(docSeqInfo.getDateColumn())); } return calendarYearMonthAndDayBuilder.build(); } @Builder @Value private static class CalendarYearMonthAndDay { String calendarYear; String calendarMonth; String calendarDay; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilder.java
1
请在Spring Boot框架中完成以下Java代码
private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig) { LwM2MServerSecurityConfigDefault bsServ = new LwM2MServerSecurityConfigDefault(); bsServ.setShortServerId(bsServerConfig.getId()); bsServ.setHost(bsServerConfig.getHost()); bsServ.setPort(bsServerConfig.getPort()); bsServ.setSecurityHost(bsServerConfig.getSecureHost()); bsServ.setSecurityPort(bsServerConfig.getSecurePort()); byte[] publicKeyBase64 = getPublicKey(bsServerConfig); if (publicKeyBase64 == null) { bsServ.setServerPublicKey(""); } else { bsServ.setServerPublicKey(Base64.encodeBase64String(publicKeyBase64)); } byte[] certificateBase64 = getCertificate(bsServerConfig); if (certificateBase64 == null) { bsServ.setServerCertificate(""); } else { bsServ.setServerCertificate(Base64.encodeBase64String(certificateBase64)); } return bsServ; } private byte[] getPublicKey(LwM2MSecureServerConfig config) { try {
SslCredentials sslCredentials = config.getSslCredentials(); if (sslCredentials != null) { return sslCredentials.getPublicKey().getEncoded(); } } catch (Exception e) { log.trace("Failed to fetch public key from key store!", e); } return null; } private byte[] getCertificate(LwM2MSecureServerConfig config) { try { SslCredentials sslCredentials = config.getSslCredentials(); if (sslCredentials != null) { return sslCredentials.getCertificateChain()[0].getEncoded(); } } catch (Exception e) { log.trace("Failed to fetch certificate from key store!", e); } return null; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\lwm2m\LwM2MServiceImpl.java
2
请完成以下Java代码
public Builder setMultiCurrency(final boolean multiCurrency) { this.multiCurrency = multiCurrency; return this; } public Builder setDate(final Date date) { this.date = date; return this; } /** * @param allowedWriteOffTypes allowed write-off types, in the same order they were enabled */ public Builder setAllowedWriteOffTypes(final Set<InvoiceWriteOffAmountType> allowedWriteOffTypes) { this.allowedWriteOffTypes.clear(); if (allowedWriteOffTypes != null) { this.allowedWriteOffTypes.addAll(allowedWriteOffTypes); } return this; } public Builder addAllowedWriteOffType(final InvoiceWriteOffAmountType allowedWriteOffType) { Check.assumeNotNull(allowedWriteOffType, "allowedWriteOffType not null"); allowedWriteOffTypes.add(allowedWriteOffType); return this; } public Builder setWarningsConsumer(final IProcessor<Exception> warningsConsumer) { this.warningsConsumer = warningsConsumer; return this; }
public Builder setDocumentIdsToIncludeWhenQuering(final Multimap<AllocableDocType, Integer> documentIds) { this.documentIds = documentIds; return this; } public Builder setFilter_Payment_ID(int filter_Payment_ID) { this.filterPaymentId = filter_Payment_ID; return this; } public Builder setFilter_POReference(String filterPOReference) { this.filterPOReference = filterPOReference; return this; } public Builder allowPurchaseSalesInvoiceCompensation(final boolean allowPurchaseSalesInvoiceCompensation) { this.allowPurchaseSalesInvoiceCompensation = allowPurchaseSalesInvoiceCompensation; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationContext.java
1
请完成以下Java代码
public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "DPoP proof jwt cannot be null"); String jwkThumbprintClaim = null; Map<String, Object> confirmationMethodClaim = this.accessToken.getClaimAsMap("cnf"); if (!CollectionUtils.isEmpty(confirmationMethodClaim) && confirmationMethodClaim.containsKey("jkt")) { jwkThumbprintClaim = (String) confirmationMethodClaim.get("jkt"); } if (jwkThumbprintClaim == null) { OAuth2Error error = createOAuth2Error("jkt claim is required."); return OAuth2TokenValidatorResult.failure(error); } JWK jwk = null; @SuppressWarnings("unchecked") Map<String, Object> jwkJson = (Map<String, Object>) jwt.getHeaders().get("jwk"); try { jwk = JWK.parse(jwkJson); } catch (Exception ignored) { } if (jwk == null) { OAuth2Error error = createOAuth2Error("jwk header is missing or invalid."); return OAuth2TokenValidatorResult.failure(error); } String jwkThumbprint; try { jwkThumbprint = jwk.computeThumbprint().toString(); } catch (Exception ex) { OAuth2Error error = createOAuth2Error("Failed to compute SHA-256 Thumbprint for jwk."); return OAuth2TokenValidatorResult.failure(error); } if (!jwkThumbprintClaim.equals(jwkThumbprint)) { OAuth2Error error = createOAuth2Error("jkt claim is invalid."); return OAuth2TokenValidatorResult.failure(error); } return OAuth2TokenValidatorResult.success(); } private static OAuth2Error createOAuth2Error(String reason) { return new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, reason, null); }
} private static final class OAuth2AccessTokenClaims implements OAuth2Token, ClaimAccessor { private final OAuth2Token accessToken; private final Map<String, Object> claims; private OAuth2AccessTokenClaims(OAuth2Token accessToken, Map<String, Object> claims) { this.accessToken = accessToken; this.claims = claims; } @Override public String getTokenValue() { return this.accessToken.getTokenValue(); } @Override public Instant getIssuedAt() { return this.accessToken.getIssuedAt(); } @Override public Instant getExpiresAt() { return this.accessToken.getExpiresAt(); } @Override public Map<String, Object> getClaims() { return this.claims; } } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\DPoPAuthenticationProvider.java
1
请完成以下Java代码
private SortedMap<Integer, ConstantWorkpackagePrio> retrieveParametersSortedMap() { final int AD_Client_ID = Env.getAD_Client_ID(ctx); final int AD_Org_ID = Env.getAD_Org_ID(ctx); final String chachingKey = "" + AD_Client_ID + "_" + AD_Org_ID + "_" + sysConfigPrefix; final SortedMap<Integer, ConstantWorkpackagePrio> sortedMap = cache.get( chachingKey, new Supplier<SortedMap<Integer, ConstantWorkpackagePrio>>() { @Override public SortedMap<Integer, ConstantWorkpackagePrio> get() { final Map<String, String> valuesForPrefix = Services.get(ISysConfigBL.class).getValuesForPrefix(sysConfigPrefix, ClientAndOrgId.ofClientAndOrg(AD_Client_ID, AD_Org_ID)); // initialize reverse-sorted map (biggest number first) final TreeMap<Integer, ConstantWorkpackagePrio> sortedMap = new TreeMap<Integer, ConstantWorkpackagePrio>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); // add our values to the map for (final Entry<String, String> entry : valuesForPrefix.entrySet()) { final int sizeInt = parseInt(entry.getKey(), sysConfigPrefix); if (sizeInt < 0) { // ignore it; note that we already logged a warning. continue; } final ConstantWorkpackagePrio constrantPrio = ConstantWorkpackagePrio.fromString(entry.getValue()); if (constrantPrio == null) { logger.warn("Unable to parse the the priority string {}.\nPlease fix the value of the AD_SysConfig record with name={}", entry.getValue(), entry.getKey());
continue; } sortedMap.put(sizeInt, constrantPrio); } return sortedMap; } }); return sortedMap; } private int parseInt(final String completeString, final String prefix) { final String sizeStr = completeString.substring(prefix.length()); int size = -1; try { size = Integer.parseInt(sizeStr); } catch (NumberFormatException e) { logger.warn("Unable to parse the prio int value from AD_SysConfig.Name={}. Ignoring its value.", completeString); } return size; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\impl\SysconfigBackedSizeBasedWorkpackagePrioConfig.java
1
请完成以下Java代码
protected void checkPermission(OpenApi openApi, OpenApiAuth openApiAuth) { List<OpenApiPermission> permissionList = openApiPermissionService.findByAuthId(openApiAuth.getId()); boolean hasPermission = false; for (OpenApiPermission permission : permissionList) { if (permission.getApiId().equals(openApi.getId())) { hasPermission = true; break; } } if (!hasPermission) { throw new JeecgBootException("该appKey未授权当前接口"); } } /** * @return String 返回类型 * @Title: MD5 * @Description: 【MD5加密】 */ protected static String md5(String sourceStr) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sourceStr.getBytes("utf-8")); byte[] hash = md.digest(); int i; StringBuffer buf = new StringBuffer(32);
for (int offset = 0; offset < hash.length; offset++) { i = hash[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (Exception e) { log.error("sign签名错误", e); } return result; } protected OpenApi findOpenApi(HttpServletRequest request) { String uri = request.getRequestURI(); String path = uri.substring(uri.lastIndexOf("/") + 1); return openApiService.findByPath(path); } public static void main(String[] args) { long timestamp = System.currentTimeMillis(); System.out.println("timestamp:" + timestamp); System.out.println("signature:" + md5("ak-eAU25mrMxhtaZsyS" + "rjxMqB6YyUXpSHAz4DCIz8vZ5aozQQiV" + timestamp)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\filter\ApiAuthFilter.java
1
请完成以下Java代码
public static Color getColor(final String colorKey, final String colorKeyDefault, final Color defaultColor) { Color color = getColor(colorKey); if (color != null) { return color; } color = getColor(colorKeyDefault); if (color != null) { return color; } return defaultColor; } /** * Creates an active value which actual value will always be resolved as the value of the given proxy key. * * If there is no value for proxy key, the given default value will be returned. * * @param proxyKey * @param defaultValue * @return active value which forward to the value of given given proxy key. */ public static UIDefaults.ActiveValue createActiveValueProxy(final String proxyKey, final Object defaultValue) { return new UIDefaults.ActiveValue() { @Override public Object createValue(final UIDefaults table) { final Object value = table.get(proxyKey); return value != null ? value : defaultValue; } }; } /** * Gets integer value of given key. If no value was found or the value is not {@link Integer} the default value will be returned. * * @return integer value or default value */ public static int getInt(final String key, final int defaultValue)
{ final Object value = UIManager.getDefaults().get(key); if (value instanceof Integer) { return ((Integer)value).intValue(); } return defaultValue; } public static boolean getBoolean(final String key, final boolean defaultValue) { final Object value = UIManager.getDefaults().get(key); if (value instanceof Boolean) { return ((Boolean)value).booleanValue(); } return defaultValue; } public static String getString(final String key, final String defaultValue) { final Object value = UIManager.getDefaults().get(key); if(value == null) { return defaultValue; } return value.toString(); } public static void setDefaultBackground(final JComponent comp) { comp.putClientProperty(AdempiereLookAndFeel.BACKGROUND, MFColor.ofFlatColor(AdempierePLAF.getFormBackground())); } } // AdempierePLAF
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempierePLAF.java
1
请在Spring Boot框架中完成以下Java代码
public class ArrayOfOrders extends ArrayList<Order> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArrayOfOrders {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\ArrayOfOrders.java
2
请完成以下Java代码
private final void updateOrderLine_CableProduct(final I_C_OrderLine newOrderLine, final ICablesOrderLineQuickInput fromQuickInputModel) { final ProductId productId = getBOMProductId(fromQuickInputModel); final BigDecimal cableLength = fromQuickInputModel.getCableLength(); if (cableLength.signum() <= 0) { throw new FillMandatoryException(ICablesOrderLineQuickInput.COLUMNNAME_CableLength); } final BigDecimal qty = fromQuickInputModel.getQty(); if (qty.signum() <= 0) { throw new FillMandatoryException(ICablesOrderLineQuickInput.COLUMNNAME_Qty); } final I_M_AttributeSetInstance asi = asiBL.createASIWithASFromProductAndInsertAttributeSet(productId, ImmutableAttributeSet.builder() .attributeValue(CablesConstants.ATTRIBUTE_CableLength, cableLength) .build()); newOrderLine.setM_Product_ID(productId.getRepoId()); newOrderLine.setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); newOrderLine.setQtyEntered(qty); } private final void updateOrderLine_RegularProduct(final I_C_OrderLine newOrderLine, final ICablesOrderLineQuickInput fromQuickInputModel) { if (fromQuickInputModel.getPlug1_Product_ID() <= 0) { throw new FillMandatoryException(ICablesOrderLineQuickInput.COLUMNNAME_Plug1_Product_ID); } final ProductId productId = ProductId.ofRepoId(fromQuickInputModel.getPlug1_Product_ID()); final BigDecimal qty = fromQuickInputModel.getQty(); if (qty.signum() <= 0) { throw new FillMandatoryException(ICablesOrderLineQuickInput.COLUMNNAME_Qty); } newOrderLine.setM_Product_ID(productId.getRepoId()); newOrderLine.setQtyEntered(qty); } private ProductId getBOMProductId(ICablesOrderLineQuickInput quickInputModel) { final ProductId plugProduct1Id = ProductId.ofRepoId(quickInputModel.getPlug1_Product_ID()); final ProductId plugProduct2Id = ProductId.ofRepoId(quickInputModel.getPlug2_Product_ID()); final ProductId cableProductId = ProductId.ofRepoId(quickInputModel.getCable_Product_ID()); final IProductBOMDAO productBOMsRepo = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOM> boms = productBOMsRepo.retrieveBOMsContainingExactProducts(plugProduct1Id.getRepoId(), cableProductId.getRepoId(), plugProduct2Id.getRepoId()); if (boms.isEmpty()) { throw new AdempiereException("@NotFound@ @PP_Product_BOM_ID@"); } else if (boms.size() > 1) { final String bomValues = boms.stream().map(I_PP_Product_BOM::getValue).collect(Collectors.joining(", ")); throw new AdempiereException("More than one BOMs found: " + bomValues); } else { final I_PP_Product_BOM bom = boms.get(0); return ProductId.ofRepoId(bom.getM_Product_ID()); } } private boolean isCableProduct(final ICablesOrderLineQuickInput quickInputModel) { return quickInputModel.getPlug1_Product_ID() > 0 && quickInputModel.getCable_Product_ID() > 0 && quickInputModel.getPlug2_Product_ID() > 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\vertical\cables\webui\quickinput\CableSalesOrderLineQuickInputProcessor.java
1
请完成以下Java代码
public IWorkPackageQueue getQueueForEnqueuing(final Properties ctx, final Class<? extends IWorkpackageProcessor> packageProcessorClass) { final I_C_Queue_PackageProcessor packageProcessor = queueDAO.retrievePackageProcessorDefByClass(ctx, packageProcessorClass); return getQueueForEnqueuing(ctx, packageProcessor); } @Override public IWorkPackageQueue getQueueForEnqueuing(final Properties ctx, final String packageProcessorClassname) { final I_C_Queue_PackageProcessor packageProcessor = queueDAO.retrievePackageProcessorDefByClassname(ctx, packageProcessorClassname); return getQueueForEnqueuing(ctx, packageProcessor); } private IWorkPackageQueue getQueueForEnqueuing(final Properties ctx, final I_C_Queue_PackageProcessor packageProcessor) { final String internalNameToUse; if (Check.isEmpty(packageProcessor.getInternalName())) { internalNameToUse = packageProcessor.getClassname(); } else
{ internalNameToUse = packageProcessor.getInternalName(); } final QueuePackageProcessorId packageProcessorId = QueuePackageProcessorId.ofRepoId(packageProcessor.getC_Queue_PackageProcessor_ID()); final QueueProcessorId queueProcessorId = queueProcessorDescriptorIndex.getQueueProcessorForPackageProcessor(packageProcessorId); return WorkPackageQueue.createForEnqueuing( ctx, packageProcessorId, queueProcessorId, internalNameToUse); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkPackageQueueFactory.java
1
请完成以下Java代码
public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; }
public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } public String getApplicationId() { return applicationId; } public void setApplicationId(String applicationId) { this.applicationId = applicationId; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\PosParam.java
1
请完成以下Java代码
public static<T> Result<T> ok() { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); return r; } public static<T> Result<T> ok(String msg) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); //Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D r.setResult((T) msg); r.setMessage(msg); return r; } public static<T> Result<T> ok(T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setResult(data); return r; } public static<T> Result<T> OK() { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); return r; } /** * 此方法是为了兼容升级所创建 * * @param msg * @param <T> * @return */ public static<T> Result<T> OK(String msg) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setMessage(msg); //Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D r.setResult((T) msg); return r; } public static<T> Result<T> OK(T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setResult(data); return r; } public static<T> Result<T> OK(String msg, T data) { Result<T> r = new Result<T>(); r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200); r.setMessage(msg); r.setResult(data); return r; } public static<T> Result<T> error(String msg, T data) { Result<T> r = new Result<T>(); r.setSuccess(false); r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500); r.setMessage(msg); r.setResult(data); return r; } public static<T> Result<T> error(String msg) { return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg); } public static<T> Result<T> error(int code, String msg) { Result<T> r = new Result<T>(); r.setCode(code); r.setMessage(msg); r.setSuccess(false); return r; } public Result<T> error500(String message) { this.message = message; this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500; this.success = false; return this; } /** * 无权限访问返回结果 */ public static<T> Result<T> noauth(String msg) { return error(CommonConstant.SC_JEECG_NO_AUTHZ, msg); } @JsonIgnore private String onlTable; }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\vo\Result.java
1
请完成以下Java代码
public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getEngineVersion() { return engineVersion; } @Override public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } @Override public String getDerivedFrom() { return derivedFrom; } @Override public void setDerivedFrom(String derivedFrom) { this.derivedFrom = derivedFrom; } @Override
public String getDerivedFromRoot() { return derivedFromRoot; } @Override public void setDerivedFromRoot(String derivedFromRoot) { this.derivedFromRoot = derivedFromRoot; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "DeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityImpl.java
1
请完成以下Java代码
public class LongRestVariableConverter implements RestVariableConverter { @Override public String getRestTypeName() { return "long"; } @Override public Class<?> getVariableType() { return Long.class; } @Override public Object getVariableValue(EngineRestVariable result) { if (result.getValue() != null) { if (!(result.getValue() instanceof Number)) { throw new FlowableIllegalArgumentException("Converter can only convert longs"); } return ((Number) result.getValue()).longValue();
} return null; } @Override public void convertVariableValue(Object variableValue, EngineRestVariable result) { if (variableValue != null) { if (!(variableValue instanceof Long)) { throw new FlowableIllegalArgumentException("Converter can only convert integers"); } result.setValue(variableValue); } else { result.setValue(null); } } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\LongRestVariableConverter.java
1
请完成以下Java代码
public Optional<Long> getLongValue() { return kv.getLongValue(); } @Override public Optional<Boolean> getBooleanValue() { return kv.getBooleanValue(); } @Override public Optional<Double> getDoubleValue() { return kv.getDoubleValue(); } @Override public Optional<String> getJsonValue() { return kv.getJsonValue(); } @Override public Object getValue() { return kv.getValue(); }
@Override public String getValueAsString() { return kv.getValueAsString(); } @Override public int getDataPoints() { int length; switch (getDataType()) { case STRING: length = getStrValue().get().length(); break; case JSON: length = getJsonValue().get().length(); break; default: return 1; } return Math.max(1, (length + MAX_CHARS_PER_DATA_POINT - 1) / MAX_CHARS_PER_DATA_POINT); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicTsKvEntry.java
1
请完成以下Java代码
public static String createStringFromDOMNode(final Node node) { final Writer writer = new StringWriter(); writeDocument(writer, node); return writer.toString(); } // t.schoneberg@metas.de, 03132: code extraced from class 'TopicRplExportProcessor' public static void writeDocument(final Writer writer, final Node node) { // Construct Transformer Factory and Transformer final TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer; try { aTransformer = tranFactory.newTransformer(); } catch (final TransformerConfigurationException e) {
throw new AdempiereException(e); } aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); final Source src = new DOMSource(node); // =================================== Write to String // Writer writer = new StringWriter(); final Result dest2 = new StreamResult(writer); try { aTransformer.transform(src, dest2); } catch (final TransformerException e) { throw new AdempiereException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\XMLHelper.java
1
请完成以下Java代码
public static Expression createExpressionForField(FieldExtension fieldExtension) { if (StringUtils.isNotEmpty(fieldExtension.getExpression())) { ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager(); return expressionManager.createExpression(fieldExtension.getExpression()); } else { return new FixedValue(fieldExtension.getStringValue()); } } /** * Returns the {@link Expression} for the field defined for the current * activity of the provided {@link DelegateExecution}. * <p> * Returns null if no such field was found in the process definition xml. * <p> * If the execution is currently being used for executing an * {@link ExecutionListener}, it will return the field expression for the * listener. Use * {@link #getFlowElementFieldExpression(DelegateExecution, String)} or * {@link #getListenerFieldExpression(DelegateExecution, String)} for * specifically getting the flow element or listener field expression. */ public static Expression getFieldExpression(DelegateExecution execution, String fieldName) { if (isExecutingExecutionListener(execution)) { return getListenerFieldExpression(execution, fieldName); } else { return getFlowElementFieldExpression(execution, fieldName); } } /** * Similar to {@link #getFieldExpression(DelegateExecution, String)}, but for use within a {@link TaskListener}. */ public static Expression getFieldExpression(DelegateTask task, String fieldName) { if (task.getCurrentActivitiListener() != null) { List<FieldExtension> fieldExtensions = task.getCurrentActivitiListener().getFieldExtensions(); if (fieldExtensions != null && fieldExtensions.size() > 0) { for (FieldExtension fieldExtension : fieldExtensions) {
if (fieldName.equals(fieldExtension.getFieldName())) { return createExpressionForField(fieldExtension); } } } } return null; } public static Expression getFlowElementFieldExpression(DelegateExecution execution, String fieldName) { FieldExtension fieldExtension = getFlowElementField(execution, fieldName); if (fieldExtension != null) { return createExpressionForField(fieldExtension); } return null; } public static Expression getListenerFieldExpression(DelegateExecution execution, String fieldName) { FieldExtension fieldExtension = getListenerField(execution, fieldName); if (fieldExtension != null) { return createExpressionForField(fieldExtension); } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\DelegateHelper.java
1
请完成以下Java代码
public void initialize(ConfigurableApplicationContext applicationContext) { ContextId contextId = getContextId(applicationContext); applicationContext.setId(contextId.getId()); applicationContext.getBeanFactory().registerSingleton(ContextId.class.getName(), contextId); } private ContextId getContextId(ConfigurableApplicationContext applicationContext) { ApplicationContext parent = applicationContext.getParent(); if (parent != null && parent.containsBean(ContextId.class.getName())) { return parent.getBean(ContextId.class).createChildId(); } return new ContextId(getApplicationId(applicationContext.getEnvironment())); } private String getApplicationId(ConfigurableEnvironment environment) { String name = environment.getProperty("spring.application.name"); return StringUtils.hasText(name) ? name : "application"; } /** * The ID of a context. */
static class ContextId { private final AtomicLong children = new AtomicLong(); private final String id; ContextId(String id) { this.id = id; } ContextId createChildId() { return new ContextId(this.id + "-" + this.children.incrementAndGet()); } String getId() { return this.id; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\ContextIdApplicationContextInitializer.java
1
请完成以下Java代码
public JsonPOSOrder changeStatusToClosed(@RequestBody JsonChangeOrderStatusRequest request) { return changeStatusTo(request, POSOrderStatus.Closed); } private JsonPOSOrder changeStatusTo(@NonNull JsonChangeOrderStatusRequest request, @NonNull final POSOrderStatus nextStatus) { final POSTerminalId posTerminalId = request.getPosTerminalId(); final POSOrderExternalId externalId = request.getOrder_uuid(); final UserId loggedUserId = getLoggedUserId(); final POSOrder order = posService.changeStatusTo(posTerminalId, externalId, nextStatus, loggedUserId); return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol); } @PostMapping("/orders") public JsonPOSOrder updateOrder(@RequestBody @NonNull final JsonPOSOrder remoteOrder) { final POSOrder order = posService.updateOrderFromRemote(remoteOrder.toRemotePOSOrder(), getLoggedUserId()); return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol); } @PostMapping("/orders/checkoutPayment") public JsonPOSOrder checkoutPayment(@RequestBody JsonPOSPaymentCheckoutRequest request) { final POSOrder order = posService.checkoutPayment(POSPaymentCheckoutRequest.builder() .posTerminalId(request.getPosTerminalId()) .posOrderExternalId(request.getOrder_uuid()) .posPaymentExternalId(request.getPayment_uuid()) .userId(getLoggedUserId()) .cardPayAmount(request.getCardPayAmount()) .cashTenderedAmount(request.getCashTenderedAmount()) .build()); return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol);
} @PostMapping("/orders/refundPayment") public JsonPOSOrder refundPayment(@RequestBody JsonPOSPaymentRefundRequest request) { final POSOrder order = posService.refundPayment(request.getPosTerminalId(), request.getOrder_uuid(), request.getPayment_uuid(), getLoggedUserId()); return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol); } @GetMapping("/orders/receipt/{filename:.*}") @PostMapping("/orders/receipt/{filename:.*}") public ResponseEntity<Resource> getReceiptPdf( @PathVariable("filename") final String filename, @RequestParam(value = "id") final String idStr) { final POSOrderExternalId posOrderExternalId = POSOrderExternalId.ofString(idStr); return posService.getReceiptPdf(posOrderExternalId) .map(resource -> createPDFResponseEntry(resource, filename)) .orElseGet(() -> ResponseEntity.notFound().build()); } private static ResponseEntity<Resource> createPDFResponseEntry(@NonNull final Resource resource, @NonNull final String filename) { final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MimeType.getMediaType(filename)); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); return new ResponseEntity<>(resource, headers, HttpStatus.OK); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\POSRestController.java
1
请完成以下Java代码
public <T> T getProperty(final String name, final Supplier<T> valueInitializer) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.get()); return value; } @Override public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.apply(this)); return value; } @Override public <T> T setAndGetProperty(@NonNull final String name, @NonNull final Function<T, T> valueRemappingFunction) { final BiFunction<? super String, ? super Object, ?> remappingFunction = (propertyName, oldValue) -> {
@SuppressWarnings("unchecked") final T oldValueCasted = (T)oldValue; return valueRemappingFunction.apply(oldValueCasted); }; @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().compute(name, remappingFunction); return value; } protected final void setDebugConnectionBackendId(final String debugConnectionBackendId) { this.debugConnectionBackendId = debugConnectionBackendId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrx.java
1
请完成以下Java代码
public int compare(ErrorEventDefinition o1, ErrorEventDefinition o2) { return o2.getPrecedence().compareTo(o1.getPrecedence()); } }; private static final long serialVersionUID = 1L; protected final String handlerActivityId; protected String errorCode; protected Integer precedence = 0; public ErrorEventDefinition(String handlerActivityId) { this.handlerActivityId = handlerActivityId; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode;
} public String getHandlerActivityId() { return handlerActivityId; } public Integer getPrecedence() { // handlers with error code take precedence over catchall-handlers return precedence + (errorCode != null ? 1 : 0); } public void setPrecedence(Integer precedence) { this.precedence = precedence; } public boolean catches(String errorCode) { return errorCode == null || this.errorCode == null || this.errorCode.equals(errorCode); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\ErrorEventDefinition.java
1
请完成以下Java代码
public void run() { planItemInstanceEntity.setState(PlanItemInstanceState.AVAILABLE); CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper().executeLifecycleListeners( commandContext, planItemInstanceEntity, null, PlanItemInstanceState.AVAILABLE); RepetitionRule repetitionRule = ExpressionUtil.getRepetitionRule(planItemInstanceEntity); if (repetitionRule != null) { //Increase repetition counter, value is kept from the previous instance of the repetition //@see CmmOperation.copyAndInsertPlanItemInstance used by @see EvaluateCriteriaOperation and @see AbstractDeletePlanItemInstanceOperation //Or if its the first instance of the repetition, this call sets the counter to 1 int repetitionCounter = PlanItemInstanceUtil.getRepetitionCounter(planItemInstanceEntity); if (repetitionCounter == 0 && repetitionRule.getAggregations() != null) { // This is the first repetition counter so we need to create the aggregated overview values // If there are aggregations we need to create an overview variable for every aggregation Map<String, VariableAggregationDefinition> aggregationsByTarget = groupAggregationsByTarget(planItemInstanceEntity, repetitionRule.getAggregations().getOverviewAggregations(), CommandContextUtil.getCmmnEngineConfiguration(commandContext)); for (String variableName : aggregationsByTarget.keySet()) {
CmmnAggregation bpmnAggregation = new CmmnAggregation(planItemInstanceEntity.getId()); planItemInstanceEntity.getParentVariableScope().setVariable(variableName, bpmnAggregation); } } if (repetitionRule.getAggregations() != null || !PlanItemInstanceUtil.hasIgnoreCounterVariable(planItemInstanceEntity)) { setRepetitionCounter(planItemInstanceEntity, repetitionCounter + 1); } } CmmnHistoryManager cmmnHistoryManager = CommandContextUtil.getCmmnHistoryManager(commandContext); cmmnHistoryManager.recordPlanItemInstanceCreated(planItemInstanceEntity); planItemInstanceEntity.setLastAvailableTime(getCurrentTime(commandContext)); cmmnHistoryManager.recordPlanItemInstanceAvailable(planItemInstanceEntity); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\CreatePlanItemInstanceWithoutEvaluationOperation.java
1
请完成以下Java代码
public class ReturnResponse<T> implements Serializable { private static final long serialVersionUID = 313975329998789878L; public static final int SUCCESS_CODE = 0; public static final int FAILURE_CODE = 1; public static final String SUCCESS_MSG = "SUCCESS"; public static final String FAILURE_MSG = "FAILURE"; /** * 返回状态 * 0. 成功 * 1. 失败 */ private int code; /** * 返回状态描述 * XXX成功 * XXX失败 */ private String msg; private T content; public ReturnResponse(int code, String msg, T content) { this.code = code; this.msg = msg; this.content = content; } public static ReturnResponse<Object> failure(String errMsg) { return new ReturnResponse<>(FAILURE_CODE, errMsg, null); } public static ReturnResponse<Object> failure() { return failure(FAILURE_MSG); } public static ReturnResponse<Object> success(){ return success(null); } public static ReturnResponse<Object> success(Object content) { return new ReturnResponse<>(SUCCESS_CODE, SUCCESS_MSG, content); } public boolean isSuccess(){ return SUCCESS_CODE == code; } public boolean isFailure(){ return !isSuccess(); }
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 getContent() { return content; } public void setContent(T content) { this.content = content; } }
repos\kkFileView-master\server\src\main\java\cn\keking\model\ReturnResponse.java
1
请完成以下Java代码
public KPIDataSet.KPIDataSetBuilder dataSet(final String name) { if (builtDatasets != null) { throw new AdempiereException("datasets were already built"); } if (datasets == null) { datasets = new LinkedHashMap<>(); } return datasets.computeIfAbsent(name, KPIDataSet::builder); } private void datasetsComputedTime(@Nullable final Instant datasetsComputedTime) { this.datasetsComputedTime = datasetsComputedTime; } private void builtDatasets(final ImmutableList<KPIDataSet> builtDatasets) { if (datasets != null && !datasets.isEmpty()) { throw new AdempiereException("Setting builtDatasets not allowed when some datasets builder were previously set"); } this.builtDatasets = builtDatasets; } public Builder range(@Nullable final TimeRange range) { this.range = range; return this; } @Nullable public TimeRange getRange() { return range; } public Builder datasetsComputeDuration(@Nullable final Duration datasetsComputeDuration) { this.datasetsComputeDuration = datasetsComputeDuration; return this; }
public void putValue( @NonNull final String dataSetName, @NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSet(dataSetName).putValue(dataSetValueKey, fieldName, value); } public void putValueIfAbsent( @NonNull final String dataSetName, @NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSet(dataSetName).putValueIfAbsent(dataSetValueKey, fieldName, value); } public Builder error(@NonNull final Exception exception) { final ITranslatableString errorMessage = AdempiereException.isUserValidationError(exception) ? AdempiereException.extractMessageTrl(exception) : TranslatableStrings.adMessage(MSG_FailedLoadingKPI); this.error = WebuiError.of(exception, errorMessage); return this; } public Builder error(@NonNull final ITranslatableString errorMessage) { this.error = WebuiError.of(errorMessage); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataResult.java
1
请完成以下Java代码
public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKeys(String[] processDefinitionKeys) { this.processDefinitionKeys = processDefinitionKeys; } public String[] getProcessDefinitionKeys() { return processDefinitionKeys; } public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) { this.processDefinitionVersionTag = processDefinitionVersionTag; } public String getProcessDefinitionVersionTag() { return processDefinitionVersionTag; } public boolean isTenantIdSet() { return isTenantIdSet; } public void setTenantIdSet(boolean isTenantIdSet) { this.isTenantIdSet = isTenantIdSet; } public String[] getTenantIds() { return tenantIds; } public void setTenantIds(String[] tenantIds) { isTenantIdSet = true; this.tenantIds = tenantIds; } public List<QueryVariableValue> getFilterVariables() { return filterVariables; } public void setFilterVariables(Map<String, Object> filterVariables) { QueryVariableValue variableValue; for (Map.Entry<String, Object> filter : filterVariables.entrySet()) { variableValue = new QueryVariableValue(filter.getKey(), filter.getValue(), null, false); this.filterVariables.add(variableValue); } } public void addFilterVariable(String name, Object value) { QueryVariableValue variableValue = new QueryVariableValue(name, value, QueryOperator.EQUALS, true); this.filterVariables.add(variableValue);
} public Long getLockDuration() { return lockDuration; } public String getTopicName() { return topicName; } public boolean isDeserializeVariables() { return deserializeVariables; } public void setDeserializeVariables(boolean deserializeVariables) { this.deserializeVariables = deserializeVariables; } public void ensureVariablesInitialized() { if (!filterVariables.isEmpty()) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers(); String dbType = processEngineConfiguration.getDatabaseType(); for(QueryVariableValue queryVariableValue : filterVariables) { queryVariableValue.initialize(variableSerializers, dbType); } } } public boolean isLocalVariables() { return localVariables; } public void setLocalVariables(boolean localVariables) { this.localVariables = localVariables; } public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\TopicFetchInstruction.java
1
请在Spring Boot框架中完成以下Java代码
private static Map.Entry<PickingJobOptionsId, PickingJobOptions> fromRecord(final I_MobileUI_UserProfile_Picking_Job record) { final PickingJobOptionsId pickingJobOptionsId = PickingJobOptionsId.ofRepoId(record.getMobileUI_UserProfile_Picking_Job_ID()); final PickingJobOptions pickingJobOptions = PickingJobOptions.builder() .aggregationType(PickingJobAggregationType.ofNullableCode(record.getPickingJobAggregationType())) .isAlwaysSplitHUsEnabled(record.isAlwaysSplitHUsEnabled()) .isAllowPickingAnyHU(record.isAllowPickingAnyHU()) .allowedPickToStructures(extractAllowedPickToStructures(record)) .pickAttributes(PickAttributesConfig.UNKNOWN) .isShipOnCloseLU(record.isShipOnCloseLU()) .considerSalesOrderCapacity(record.isConsiderSalesOrderCapacity()) .isCatchWeightTUPickingEnabled(record.isCatchWeightTUPickingEnabled()) .isAllowSkippingRejectedReason(record.isAllowSkippingRejectedReason()) .isShowConfirmationPromptWhenOverPick(record.isShowConfirmationPromptWhenOverPick()) .isShowLastPickedBestBeforeDateForLines(record.isShowLastPickedBestBeforeDateForLines()) .createShipmentPolicy(CreateShipmentPolicy.ofCode(record.getCreateShipmentPolicy())) .isAllowCompletingPartialPickingJob(record.isAllowCompletingPartialPickingJob()) .isAnonymousPickHUsOnTheFly(record.isAnonymousHuPickedOnTheFly()) .displayPickingSlotSuggestions(OptionalBoolean.ofNullableString(record.getIsDisplayPickingSlotSuggestions()))
.pickingLineGroupBy(PickingLineGroupBy.ofNullableCode(record.getPickingLineGroupBy())) .pickingLineSortBy(PickingLineSortBy.ofNullableCode(record.getPickingLineSortBy())) .build(); return GuavaCollectors.entry(pickingJobOptionsId, pickingJobOptions); } private static AllowedPickToStructures extractAllowedPickToStructures(final I_MobileUI_UserProfile_Picking_Job record) { final HashMap<PickToStructure, Boolean> map = new HashMap<>(); OptionalBoolean.ofNullableString(record.getAllowPickToStructure_LU_TU()).ifPresent(allowed -> map.put(PickToStructure.LU_TU, allowed)); OptionalBoolean.ofNullableString(record.getAllowPickToStructure_TU()).ifPresent(allowed -> map.put(PickToStructure.TU, allowed)); OptionalBoolean.ofNullableString(record.getAllowPickToStructure_LU_CU()).ifPresent(allowed -> map.put(PickToStructure.LU_CU, allowed)); OptionalBoolean.ofNullableString(record.getAllowPickToStructure_CU()).ifPresent(allowed -> map.put(PickToStructure.CU, allowed)); return AllowedPickToStructures.ofMap(map); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\MobileUIPickingUserProfileRepository.java
2
请完成以下Java代码
public class FileUtils { private final Logger logger = LoggerFactory.getLogger(FileUtils.class); private String fileName; private CSVReader CSVReader; private CSVWriter CSVWriter; private FileReader fileReader; private FileWriter fileWriter; private File file; public FileUtils(String fileName) { this.fileName = fileName; } public Line readLine() { try { if (CSVReader == null) initReader(); String[] line = CSVReader.readNext(); if (line == null) return null; return new Line(line[0], LocalDate.parse(line[1], DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } catch (Exception e) { logger.error("Error while reading line in file: " + this.fileName); return null; } } public void writeLine(Line line) { try { if (CSVWriter == null) initWriter(); String[] lineStr = new String[2]; lineStr[0] = line.getName(); lineStr[1] = line .getAge() .toString(); CSVWriter.writeNext(lineStr); } catch (Exception e) { logger.error("Error while writing line in file: " + this.fileName); } } private void initReader() throws Exception { ClassLoader classLoader = this .getClass() .getClassLoader(); if (file == null) file = new File(classLoader .getResource(fileName) .getFile()); if (fileReader == null) fileReader = new FileReader(file); if (CSVReader == null) CSVReader = new CSVReader(fileReader); }
private void initWriter() throws Exception { if (file == null) { file = new File(fileName); file.createNewFile(); } if (fileWriter == null) fileWriter = new FileWriter(file, true); if (CSVWriter == null) CSVWriter = new CSVWriter(fileWriter); } public void closeWriter() { try { CSVWriter.close(); fileWriter.close(); } catch (IOException e) { logger.error("Error while closing writer."); } } public void closeReader() { try { CSVReader.close(); fileReader.close(); } catch (IOException e) { logger.error("Error while closing reader."); } } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\utils\FileUtils.java
1
请在Spring Boot框架中完成以下Java代码
private Mono<ServerResponse> unsupportedMediaType(ServerRequest request) { return ServerResponse.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).headers(this::acceptJson).build(); } private void acceptJson(HttpHeaders headers) { headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); } private Mono<ServerResponse> onlyAllowPost(ServerRequest request) { return ServerResponse.status(HttpStatus.METHOD_NOT_ALLOWED).headers(this::onlyAllowPost).build(); } private void onlyAllowPost(HttpHeaders headers) { headers.setAllow(Collections.singleton(HttpMethod.POST)); } @Configuration(proxyBeanMethods = false) static class GraphQlEndpointCorsConfiguration implements WebFluxConfigurer { final GraphQlProperties graphQlProperties; final GraphQlCorsProperties corsProperties; GraphQlEndpointCorsConfiguration(GraphQlProperties graphQlProps, GraphQlCorsProperties corsProps) { this.graphQlProperties = graphQlProps; this.corsProperties = corsProps; } @Override public void addCorsMappings(CorsRegistry registry) { CorsConfiguration configuration = this.corsProperties.toCorsConfiguration(); if (configuration != null) { registry.addMapping(this.graphQlProperties.getHttp().getPath()).combine(configuration); } } }
@Configuration(proxyBeanMethods = false) @ConditionalOnProperty("spring.graphql.websocket.path") static class WebSocketConfiguration { @Bean @ConditionalOnMissingBean GraphQlWebSocketHandler graphQlWebSocketHandler(WebGraphQlHandler webGraphQlHandler, GraphQlProperties properties, ServerCodecConfigurer configurer) { return new GraphQlWebSocketHandler(webGraphQlHandler, configurer, properties.getWebsocket().getConnectionInitTimeout(), properties.getWebsocket().getKeepAlive()); } @Bean HandlerMapping graphQlWebSocketEndpoint(GraphQlWebSocketHandler graphQlWebSocketHandler, GraphQlProperties properties) { String path = properties.getWebsocket().getPath(); Assert.state(path != null, "'path' must not be null"); logger.info(LogMessage.format("GraphQL endpoint WebSocket %s", path)); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setHandlerPredicate(new WebSocketUpgradeHandlerPredicate()); mapping.setUrlMap(Collections.singletonMap(path, graphQlWebSocketHandler)); mapping.setOrder(-2); // Ahead of HTTP endpoint ("routerFunctionMapping" bean) return mapping; } } static class GraphiQlResourceHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("graphiql/index.html"); } } }
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\reactive\GraphQlWebFluxAutoConfiguration.java
2
请完成以下Java代码
public org.compiere.model.I_M_ProductPrice getM_ProductPrice() { return get_ValueAsPO(COLUMNNAME_M_ProductPrice_ID, org.compiere.model.I_M_ProductPrice.class); } @Override public void setM_ProductPrice(org.compiere.model.I_M_ProductPrice M_ProductPrice) { set_ValueFromPO(COLUMNNAME_M_ProductPrice_ID, org.compiere.model.I_M_ProductPrice.class, M_ProductPrice); } /** Set Produkt-Preis. @param M_ProductPrice_ID Produkt-Preis */ @Override public void setM_ProductPrice_ID (int M_ProductPrice_ID) { if (M_ProductPrice_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, Integer.valueOf(M_ProductPrice_ID)); } /** Get Produkt-Preis. @return Produkt-Preis */ @Override public int getM_ProductPrice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Mindestpreis. @param PriceLimit Unterster Preis für Kostendeckung */ @Override public void setPriceLimit (java.math.BigDecimal PriceLimit) { set_Value (COLUMNNAME_PriceLimit, PriceLimit); } /** Get Mindestpreis. @return Unterster Preis für Kostendeckung */ @Override public java.math.BigDecimal getPriceLimit () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Auszeichnungspreis. @param PriceList Auszeichnungspreis */ @Override public void setPriceList (java.math.BigDecimal PriceList) { set_Value (COLUMNNAME_PriceList, PriceList); } /** Get Auszeichnungspreis. @return Auszeichnungspreis */ @Override public java.math.BigDecimal getPriceList () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Standardpreis. @param PriceStd Standardpreis */ @Override
public void setPriceStd (java.math.BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } /** Get Standardpreis. @return Standardpreis */ @Override public java.math.BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute.java
1
请完成以下Java代码
public void setLookupTableName(final TableName lookupTableName) { assertNotBuilt(); this.lookupTableName = lookupTableName; } public void setCtxTableName(final String ctxTableName) { assertNotBuilt(); this.ctxTableName = ctxTableName; } public void setCtxColumnName(final String ctxColumnName) { assertNotBuilt(); this.ctxColumnName = ctxColumnName; } public void setDisplayType(final int displayType) { assertNotBuilt(); this.displayType = displayType; } public void addFilter(@NonNull final Collection<IValidationRule> validationRules, @Nullable LookupDescriptorProvider.LookupScope scope) { for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRules)) { addFilter(SqlLookupFilter.of(valRule, scope)); }
} public void addFilter(@Nullable final IValidationRule validationRule, @Nullable LookupDescriptorProvider.LookupScope scope) { for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRule)) { addFilter(SqlLookupFilter.of(valRule, scope)); } } private void addFilter(@NonNull final SqlLookupFilter filter) { assertNotBuilt(); filters.add(filter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilterBuilder.java
1
请完成以下Java代码
public boolean isKeyColumnName(final String columnName) { return getPOInfo().isKey(columnName); } @Override public Object getValue(final String propertyName, final int idx, final Class<?> returnType) { return po.get_Value(idx); } @Override public Object getValue(final String propertyName, final Class<?> returnType) { return po.get_Value(propertyName); } @Override public boolean setValue(final String columnName, final Object value) { final Object valueToSet = POWrapper.checkZeroIdValue(columnName, value); final POInfo poInfo = po.getPOInfo(); if (!poInfo.isColumnUpdateable(columnName)) { // If the column is not updateable we need to use set_ValueNoCheck // because else is not consistent with how the generated classes were created // see org.adempiere.util.ModelClassGenerator.createColumnMethods return po.set_ValueNoCheck(columnName, valueToSet); } else { return po.set_ValueOfColumn(columnName, valueToSet); } } @Override public boolean setValueNoCheck(String propertyName, Object value) { return po.set_ValueOfColumn(propertyName, value); } @Override public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception {
final Class<?> returnType = interfaceMethod.getReturnType(); return po.get_ValueAsPO(propertyName, returnType); } @Override public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value) { po.set_ValueFromPO(idPropertyName, parameterType, value); } @Override public boolean invokeEquals(final Object[] methodArgs) { if (methodArgs == null || methodArgs.length != 1) { throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs); } return po.equals(methodArgs[0]); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { return method.invoke(po, methodArgs); } @Override public boolean isCalculated(final String columnName) { return getPOInfo().isCalculated(columnName); } @Override public boolean hasColumnName(final String columnName) { return getPOInfo().hasColumnName(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java
1
请完成以下Java代码
public IDocumentLUTUConfigurationManager getLUTUConfigurationManager() { if (_lutuConfigurationManager == null) { final List<I_M_ReceiptSchedule> receiptSchedules = getReceiptSchedules(); _lutuConfigurationManager = huReceiptScheduleBL.createLUTUConfigurationManager(receiptSchedules); markNotConfigurable(); } return _lutuConfigurationManager; } /** * Sets the LU/TU configuration to be used when generating HUs. */ public ReceiptScheduleHUGenerator setM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration lutuConfiguration) { assertConfigurable(); Check.assumeNotNull(lutuConfiguration, "Parameter lutuConfiguration is not null"); _lutuConfiguration = lutuConfiguration; return this; } /** * @return the LU/TU configuration to be used when generating HUs. */ public I_M_HU_LUTU_Configuration getM_HU_LUTU_Configuration() { if (_lutuConfiguration != null) { return _lutuConfiguration; } _lutuConfiguration = getLUTUConfigurationManager().getCurrentLUTUConfigurationOrNull(); Check.assumeNotNull(_lutuConfiguration, "_lutuConfiguration not null"); markNotConfigurable();
return _lutuConfiguration; } public ILUTUProducerAllocationDestination getLUTUProducerAllocationDestination() { if (_lutuProducer != null) { return _lutuProducer; } final I_M_HU_LUTU_Configuration lutuConfiguration = getM_HU_LUTU_Configuration(); _lutuProducer = lutuConfigurationFactory.createLUTUProducerAllocationDestination(lutuConfiguration); // // Ask the "lutuProducer" to consider currently created HUs that are linked to our receipt schedule // In case they are suitable, they will be used, else they will be destroyed. // NOTE: we do this only if we have only one M_ReceiptSchedule final I_M_ReceiptSchedule receiptSchedule = getSingleReceiptScheduleOrNull(); if (receiptSchedule != null) { final IHUAllocations huAllocations = getHUAllocations(receiptSchedule); _lutuProducer.setExistingHUs(huAllocations); } markNotConfigurable(); return _lutuProducer; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUGenerator.java
1
请完成以下Java代码
public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters) { return new ADMessageTranslatableString(adMessage, msgParameters); } @Override public void cacheReset() { Msg.cacheReset(); } @Override public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return TranslatableStrings.adMessage(adMessage, msgParameters).translate(Language.getBaseAD_Language()); } @Override public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey adMessage) { return Msg.toMap().getIdByAdMessage(adMessage); } @Override public boolean isMessageExists(AdMessageKey adMessage)
{ return Msg.toMap().isMessageExists(adMessage); } @Override public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId) { return Msg.toMap().getAdMessageKeyById(adMessageId); } @Override public String getErrorCode(final @NonNull AdMessageKey messageKey) { return Msg.getErrorCode(messageKey.toAD_Message()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\MsgBL.java
1
请完成以下Java代码
public String finishAddArticle(ArticleCreateDto articleDto, RedirectAttributes redirectAttrs) { //TODO:validate and return to GET:/add on errors Article article = articleService.createArticle(articleDto); redirectAttrs.addFlashAttribute("success", "Article with title " + article.getTitle() + " is received and being analyzed"); return "redirect:/"; } @GetMapping("/delete/{id}") @PreAuthorize("@permEvaluator.hasAccess(#id, 'Article' )") public String deleteArticle(@PathVariable Long id, RedirectAttributes redirectAttrs) { articleService.delete(id); redirectAttrs.addFlashAttribute("success", "Article with id " + id + " is deleted"); return "redirect:/article/"; } @GetMapping("/edit/{id}") @PreAuthorize("@permEvaluator.hasAccess(#id, 'Article' )") public String startEditArticle(Model model, @PathVariable Long id) { model.addAttribute("msg", "Add a new article"); model.addAttribute("article", articleService.read(id)); return "article/edit-article"; } @PostMapping("/edit") @PreAuthorize("@permEvaluator.hasAccess(#articleDto.id, 'Article' )") public String finishEditArticle(Model model, ArticleEditDto articleDto, RedirectAttributes redirectAttrs) { model.addAttribute("msg", "Add a new article"); //TODO:validate and return to GET:/edit/{id} on errors articleService.update(articleDto);
redirectAttrs.addFlashAttribute("success", "Article with title " + articleDto.getTitle() + " is updated"); return "redirect:/article/"; } @PostMapping("/addComment") public String addComment(NewCommentDto dto, RedirectAttributes redirectAttrs) { //TODO:validate and return to GET:/add on errors commentService.save(dto); redirectAttrs.addFlashAttribute("success", "Comment saved. Its currently under review."); return "redirect:/article/read/" + dto.getArticleId(); } @GetMapping("/read/{id}") public String read(@PathVariable Long id, Model model) { ArticleReadDto dto = articleService.read(id); //TODO: fix ordering -- ordering is not consistent model.addAttribute("article", dto); return "article/read-article"; } }
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\web\mvc\ArticleController.java
1
请完成以下Java代码
class MatchResult { private final boolean match; private final Map<String, String> variables; MatchResult(boolean match, Map<String, String> variables) { this.match = match; this.variables = variables; } /** * Return whether the comparison against the {@code Message} produced a successful * match */ public boolean isMatch() { return this.match; } /** * Returns the extracted variable values where the key is the variable name and * the value is the variable value * @return a map containing key-value pairs representing extracted variable names * and variable values */ public Map<String, String> getVariables() { return this.variables; }
/** * Creates an instance of {@link MatchResult} that is a match with no variables */ public static MatchResult match() { return new MatchResult(true, Collections.emptyMap()); } /** * Creates an instance of {@link MatchResult} that is a match with the specified * variables */ public static MatchResult match(Map<String, String> variables) { return new MatchResult(true, variables); } /** * Creates an instance of {@link MatchResult} that is not a match. * @return a {@code MatchResult} with match set to false */ public static MatchResult notMatch() { return new MatchResult(false, Collections.emptyMap()); } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\util\matcher\MessageMatcher.java
1
请完成以下Java代码
public void setExportBy_ID (final int ExportBy_ID) { if (ExportBy_ID < 1) set_ValueNoCheck (COLUMNNAME_ExportBy_ID, null); else set_ValueNoCheck (COLUMNNAME_ExportBy_ID, ExportBy_ID); } @Override public int getExportBy_ID() { return get_ValueAsInt(COLUMNNAME_ExportBy_ID); } @Override public void setExportDate (final @Nullable java.sql.Timestamp ExportDate) { set_ValueNoCheck (COLUMNNAME_ExportDate, ExportDate); } @Override public java.sql.Timestamp getExportDate() { return get_ValueAsTimestamp(COLUMNNAME_ExportDate); } /** * ExportType AD_Reference_ID=541172 * Reference name: DatevExportType */ public static final int EXPORTTYPE_AD_Reference_ID=541172; /** Payment = Payment */ public static final String EXPORTTYPE_Payment = "Payment"; /** Commission Invoice = CommissionInvoice */
public static final String EXPORTTYPE_CommissionInvoice = "CommissionInvoice"; /** Sales Invoice = SalesInvoice */ public static final String EXPORTTYPE_SalesInvoice = "SalesInvoice"; /** Credit Memo = CreditMemo */ public static final String EXPORTTYPE_CreditMemo = "CreditMemo"; @Override public void setExportType (final java.lang.String ExportType) { set_Value (COLUMNNAME_ExportType, ExportType); } @Override public java.lang.String getExportType() { return get_ValueAsString(COLUMNNAME_ExportType); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExport.java
1
请完成以下Java代码
void stop() { this.shouldContinue = false; } int calculateFactorial(int n) { if (n <= 1) { return 1; // base case } return n * calculateFactorial(n - 1); } int calculateSum(int[] x) { int sum = 0; for (int i = 0; i < 10; i++) { if (x[i] < 0) { break; } sum += x[i]; } return sum; } <T> T stopExecutionUsingException(T object) { if (object instanceof Number) { throw new IllegalArgumentException("Parameter can not be number."); } T upperCase = (T) String.valueOf(object) .toUpperCase(Locale.ENGLISH); return upperCase; } int processLines(String[] lines) { int statusCode = 0;
parser: for (String line : lines) { System.out.println("Processing line: " + line); if (line.equals("stop")) { System.out.println("Stopping parsing..."); statusCode = -1; break parser; // Stop parsing and exit the loop } System.out.println("Line processed."); } return statusCode; } void download(String fileUrl, String destinationPath) throws MalformedURLException, URISyntaxException { if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) { return; } // execute downloading URL url = new URI(fileUrl).toURL(); try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\stopexecution\StopExecutionFurtherCode.java
1
请在Spring Boot框架中完成以下Java代码
private byte[] toByteArray(Object obj) throws IOException { byte[] bytes; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); bytes = bos.toByteArray(); oos.close(); bos.close(); return bytes; } private Object toObject(byte[] bytes) throws IOException, ClassNotFoundException { Object obj; ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); obj = ois.readObject(); ois.close(); bis.close(); return obj; } private void cleanPdfCache() throws IOException, RocksDBException {
Map<String, String> initPDFCache = new HashMap<>(); db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache)); } private void cleanImgCache() throws IOException, RocksDBException { Map<String, List<String>> initIMGCache = new HashMap<>(); db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache)); } private void cleanPdfImgCache() throws IOException, RocksDBException { Map<String, Integer> initPDFIMGCache = new HashMap<>(); db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache)); } private void cleanMediaConvertCache() throws IOException, RocksDBException { Map<String, String> initMediaConvertCache = new HashMap<>(); db.put(FILE_PREVIEW_MEDIA_CONVERT_KEY.getBytes(), toByteArray(initMediaConvertCache)); } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRocksDBImpl.java
2
请在Spring Boot框架中完成以下Java代码
public List<ComponentDescriptor> getComponents(ComponentType type, RuleChainType ruleChainType) { if (RuleChainType.CORE.equals(ruleChainType)) { if (coreComponentsMap.containsKey(type)) { return Collections.unmodifiableList(coreComponentsMap.get(type)); } else { return Collections.emptyList(); } } else if (RuleChainType.EDGE.equals(ruleChainType)) { if (edgeComponentsMap.containsKey(type)) { return Collections.unmodifiableList(edgeComponentsMap.get(type)); } else { return Collections.emptyList(); } } else { log.error("Unsupported rule chain type {}", ruleChainType); throw new RuntimeException("Unsupported rule chain type " + ruleChainType); } } @Override public List<ComponentDescriptor> getComponents(Set<ComponentType> types, RuleChainType ruleChainType) { if (RuleChainType.CORE.equals(ruleChainType)) { return getComponents(types, coreComponentsMap); } else if (RuleChainType.EDGE.equals(ruleChainType)) { return getComponents(types, edgeComponentsMap); } else { log.error("Unsupported rule chain type {}", ruleChainType); throw new RuntimeException("Unsupported rule chain type " + ruleChainType);
} } @Override public Optional<ComponentDescriptor> getComponent(String clazz) { return Optional.ofNullable(components.get(clazz)); } private List<ComponentDescriptor> getComponents(Set<ComponentType> types, Map<ComponentType, List<ComponentDescriptor>> componentsMap) { List<ComponentDescriptor> result = new ArrayList<>(); types.stream().filter(componentsMap::containsKey).forEach(type -> { result.addAll(componentsMap.get(type)); }); return Collections.unmodifiableList(result); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\component\AnnotationComponentDiscoveryService.java
2
请在Spring Boot框架中完成以下Java代码
protected byte[] newBody(List<byte[]> list) { return this.encoding.encode(list); } @Override protected void postSpans(URI endpoint, byte[] body) throws IOException { Map<String, String> headers = getDefaultHeaders(); if (needsCompression(body)) { body = compress(body); headers.put("Content-Encoding", "gzip"); } postSpans(endpoint, headers, body); } abstract void postSpans(URI endpoint, Map<String, String> headers, byte[] body) throws IOException; Map<String, String> getDefaultHeaders() { Map<String, String> headers = new LinkedHashMap<>(); headers.put("b3", "0"); headers.put("Content-Type", this.encoding.mediaType()); return headers;
} private boolean needsCompression(byte[] body) { return body.length > COMPRESSION_THRESHOLD.toBytes(); } private byte[] compress(byte[] input) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); try (GZIPOutputStream gzip = new GZIPOutputStream(result)) { gzip.write(input); } return result.toByteArray(); } }
repos\spring-boot-4.0.1\module\spring-boot-zipkin\src\main\java\org\springframework\boot\zipkin\autoconfigure\HttpSender.java
2
请完成以下Java代码
public LookupValue lookupPriceType(@NonNull final PriceSpecificationType priceType) { return priceTypeLookup.findById(priceType.getCode()); } public LookupValue lookupPricingSystem(@Nullable final PricingSystemId pricingSystemId) { if (pricingSystemId == null) { return null; } return pricingSystemLookup.findById(pricingSystemId.getRepoId()); } public LookupValue lookupPaymentTerm(@Nullable final PaymentTermId paymentTermId) { if (paymentTermId == null) { return null; } return paymentTermLookup.findById(paymentTermId.getRepoId()); } public LookupValue lookupCurrency(@Nullable final CurrencyId currencyId) { if (currencyId == null) { return null; } return currencyIdLookup.findById(currencyId.getRepoId()); } public LookupValuesPage getFieldTypeahead(@NonNull final String fieldName, final String query) { return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), query); } public LookupValuesList getFieldDropdown(@NonNull final String fieldName) { return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), 20).getValues(); } private LookupDataSource getLookupDataSource(@NonNull final String fieldName) {
if (PricingConditionsRow.FIELDNAME_PaymentTerm.equals(fieldName)) { return paymentTermLookup; } else if (PricingConditionsRow.FIELDNAME_BasePriceType.equals(fieldName)) { return priceTypeLookup; } else if (PricingConditionsRow.FIELDNAME_BasePricingSystem.equals(fieldName)) { return pricingSystemLookup; } else if (PricingConditionsRow.FIELDNAME_C_Currency_ID.equals(fieldName)) { return currencyIdLookup; } else { throw new AdempiereException("Field " + fieldName + " does not exist or it's not a lookup field"); } } public String getTemporaryPriceConditionsColor() { return temporaryPriceConditionsColorCache.getOrLoad(0, this::retrieveTemporaryPriceConditionsColor); } private String retrieveTemporaryPriceConditionsColor() { final ColorId temporaryPriceConditionsColorId = Services.get(IOrderLinePricingConditions.class).getTemporaryPriceConditionsColorId(); return toHexString(Services.get(IColorRepository.class).getColorById(temporaryPriceConditionsColorId)); } private static String toHexString(@Nullable final MFColor color) { if (color == null) { return null; } final Color awtColor = color.toFlatColor().getFlatColor(); return ColorValue.toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowLookups.java
1
请完成以下Java代码
public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Beta-Funktionalität. @param IsBetaFunctionality This functionality is considered Beta */ @Override public void setIsBetaFunctionality (boolean IsBetaFunctionality) { set_Value (COLUMNNAME_IsBetaFunctionality, Boolean.valueOf(IsBetaFunctionality)); } /** Get Beta-Funktionalität. @return This functionality is considered Beta */ @Override public boolean isBetaFunctionality () { Object oo = get_Value(COLUMNNAME_IsBetaFunctionality); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set jsp-URL. @param JSPURL Web URL of the jsp function */ @Override public void setJSPURL (java.lang.String JSPURL) { set_Value (COLUMNNAME_JSPURL, JSPURL); } /** Get jsp-URL. @return Web URL of the jsp function */ @Override public java.lang.String getJSPURL () { return (java.lang.String)get_Value(COLUMNNAME_JSPURL); } /** Set Is Modal. @param Modal Is Modal */ @Override public void setModal (boolean Modal)
{ set_Value (COLUMNNAME_Modal, Boolean.valueOf(Modal)); } /** Get Is Modal. @return Is Modal */ @Override public boolean isModal () { Object oo = get_Value(COLUMNNAME_Modal); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form.java
1
请完成以下Java代码
public static class NonBlockingRetryBackOff { protected String delay; protected String maxDelay; protected String multiplier; protected String random; public String getDelay() { return delay; } public void setDelay(String delay) { this.delay = delay; } public String getMaxDelay() { return maxDelay; } public void setMaxDelay(String maxDelay) { this.maxDelay = maxDelay; } public String getMultiplier() { return multiplier; } public void setMultiplier(String multiplier) { this.multiplier = multiplier; } public String getRandom() { return random; } public void setRandom(String random) {
this.random = random; } } public static class TopicPartition { protected String topic; protected Collection<String> partitions; public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public Collection<String> getPartitions() { return partitions; } public void setPartitions(Collection<String> partitions) { this.partitions = partitions; } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaInboundChannelModel.java
1
请完成以下Java代码
public int getM_CostType_ID() { return get_ValueAsInt(COLUMNNAME_M_CostType_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPostCalculationAmt (final BigDecimal PostCalculationAmt) { set_Value (COLUMNNAME_PostCalculationAmt, PostCalculationAmt); } @Override public BigDecimal getPostCalculationAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PostCalculationAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPP_Order_Cost_ID (final int PP_Order_Cost_ID) { if (PP_Order_Cost_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Cost_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Cost_ID, PP_Order_Cost_ID); } @Override public int getPP_Order_Cost_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Cost_ID); } /** * PP_Order_Cost_TrxType AD_Reference_ID=540941 * Reference name: PP_Order_Cost_TrxType
*/ public static final int PP_ORDER_COST_TRXTYPE_AD_Reference_ID=540941; /** MainProduct = MR */ public static final String PP_ORDER_COST_TRXTYPE_MainProduct = "MR"; /** MaterialIssue = MI */ public static final String PP_ORDER_COST_TRXTYPE_MaterialIssue = "MI"; /** ResourceUtilization = RU */ public static final String PP_ORDER_COST_TRXTYPE_ResourceUtilization = "RU"; /** ByProduct = BY */ public static final String PP_ORDER_COST_TRXTYPE_ByProduct = "BY"; /** CoProduct = CO */ public static final String PP_ORDER_COST_TRXTYPE_CoProduct = "CO"; @Override public void setPP_Order_Cost_TrxType (final java.lang.String PP_Order_Cost_TrxType) { set_Value (COLUMNNAME_PP_Order_Cost_TrxType, PP_Order_Cost_TrxType); } @Override public java.lang.String getPP_Order_Cost_TrxType() { return get_ValueAsString(COLUMNNAME_PP_Order_Cost_TrxType); } @Override public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Cost.java
1
请完成以下Java代码
public class DelegateExpressionTaskListener implements TaskListener { protected Expression expression; private final List<FieldDeclaration> fieldDeclarations; public DelegateExpressionTaskListener(Expression expression, List<FieldDeclaration> fieldDeclarations) { this.expression = expression; this.fieldDeclarations = fieldDeclarations; } public void notify(DelegateTask delegateTask) { // Note: we can't cache the result of the expression, because the // execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}' VariableScope variableScope = delegateTask.getExecution(); if (variableScope == null) { variableScope = delegateTask.getCaseExecution(); } Object delegate = expression.getValue(variableScope); applyFieldDeclaration(fieldDeclarations, delegate); if (delegate instanceof TaskListener) { try { Context.getProcessEngineConfiguration() .getDelegateInterceptor()
.handleInvocation(new TaskListenerInvocation((TaskListener)delegate, delegateTask)); }catch (Exception e) { throw new ProcessEngineException("Exception while invoking TaskListener: "+e.getMessage(), e); } } else { throw new ProcessEngineException("Delegate expression " + expression + " did not resolve to an implementation of " + TaskListener.class ); } } /** * returns the expression text for this task listener. Comes in handy if you want to * check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); } public List<FieldDeclaration> getFieldDeclarations() { return fieldDeclarations; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\listener\DelegateExpressionTaskListener.java
1
请完成以下Java代码
public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine) { set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine); } @Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProductNo (final @Nullable java.lang.String ProductNo) { set_Value (COLUMNNAME_ProductNo, ProductNo); }
@Override public java.lang.String getProductNo() { return get_ValueAsString(COLUMNNAME_ProductNo); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Product_v.java
1
请完成以下Java代码
public class TimeSeriesChartExample { public static void main(String[] args) { // Create a dataset TimeSeries series = new TimeSeries("Monthly Sales"); series.add(new Month(1, 2024), 200); series.add(new Month(2, 2024), 150); series.add(new Month(3, 2024), 180); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); // Create a chart using the dataset JFreeChart chart = ChartFactory.createTimeSeriesChart( "Monthly Sales", // Chart title "Date", // X-axis label "Sales", // Y-axis label
dataset, // data true, // legend false, // tooltips false); // no URLs // Display the chart ChartPanel chartPanel = new ChartPanel(chart); JFrame frame = new JFrame(); frame.setSize(800, 600); frame.setContentPane(chartPanel); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\jfreechart\TimeSeriesChartExample.java
1
请完成以下Java代码
public class JobExecutorContext { protected List<String> currentProcessorJobQueue = new LinkedList<String>(); /** the currently executed job */ protected JobEntity currentJob; /** reusable cache */ protected DbEntityCache entityCache; public List<String> getCurrentProcessorJobQueue() { return currentProcessorJobQueue; } public boolean isExecutingExclusiveJob() { return currentJob == null ? false : currentJob.isExclusive(); } public void setCurrentJob(JobEntity currentJob) {
this.currentJob = currentJob; } public JobEntity getCurrentJob() { return currentJob; } public DbEntityCache getEntityCache() { return entityCache; } public void setEntityCache(DbEntityCache entityCache) { this.entityCache = entityCache; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutorContext.java
1
请完成以下Java代码
public HistoricDetailQuery orderByTime() { orderBy(HistoricDetailQueryProperty.TIME); return this; } public HistoricDetailQuery orderByVariableName() { orderBy(HistoricDetailQueryProperty.VARIABLE_NAME); return this; } public HistoricDetailQuery orderByFormPropertyId() { orderBy(HistoricDetailQueryProperty.VARIABLE_NAME); return this; } public HistoricDetailQuery orderByVariableRevision() { orderBy(HistoricDetailQueryProperty.VARIABLE_REVISION); return this; } public HistoricDetailQuery orderByVariableType() { orderBy(HistoricDetailQueryProperty.VARIABLE_TYPE); return this; } public HistoricDetailQuery orderPartiallyByOccurrence() { orderBy(HistoricDetailQueryProperty.SEQUENCE_COUNTER); return this; } public HistoricDetailQuery orderByTenantId() { return orderBy(HistoricDetailQueryProperty.TENANT_ID); } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public String getExecutionId() { return executionId; } public String getCaseExecutionId() { return caseExecutionId; }
public String getTaskId() { return taskId; } public String getActivityId() { return activityId; } public String getType() { return type; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getDetailId() { return detailId; } public String[] getProcessInstanceIds() { return processInstanceIds; } public Date getOccurredBefore() { return occurredBefore; } public Date getOccurredAfter() { return occurredAfter; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isInitial() { return initial; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDetailQueryImpl.java
1
请完成以下Java代码
public String getLocalRootLocation() { return get_ValueAsString(COLUMNNAME_LocalRootLocation); } @Override public void setProcessedDirectory (final String ProcessedDirectory) { set_Value (COLUMNNAME_ProcessedDirectory, ProcessedDirectory); } @Override public String getProcessedDirectory() { return get_ValueAsString(COLUMNNAME_ProcessedDirectory); } @Override public void setProductFileNamePattern (final @Nullable String ProductFileNamePattern) { set_Value (COLUMNNAME_ProductFileNamePattern, ProductFileNamePattern); } @Override public String getProductFileNamePattern() {
return get_ValueAsString(COLUMNNAME_ProductFileNamePattern); } @Override public void setPurchaseOrderFileNamePattern (final @Nullable String PurchaseOrderFileNamePattern) { set_Value (COLUMNNAME_PurchaseOrderFileNamePattern, PurchaseOrderFileNamePattern); } @Override public String getPurchaseOrderFileNamePattern() { return get_ValueAsString(COLUMNNAME_PurchaseOrderFileNamePattern); } @Override public void setWarehouseFileNamePattern (final @Nullable String WarehouseFileNamePattern) { set_Value (COLUMNNAME_WarehouseFileNamePattern, WarehouseFileNamePattern); } @Override public String getWarehouseFileNamePattern() { return get_ValueAsString(COLUMNNAME_WarehouseFileNamePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement_LocalFile.java
1
请完成以下Java代码
public DateAndPlaceOfBirth getDtAndPlcOfBirth() { return dtAndPlcOfBirth; } /** * Sets the value of the dtAndPlcOfBirth property. * * @param value * allowed object is * {@link DateAndPlaceOfBirth } * */ public void setDtAndPlcOfBirth(DateAndPlaceOfBirth value) { this.dtAndPlcOfBirth = value; } /** * Gets the value of the othr property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the othr property. * * <p> * For example, to add a new item, do as follows:
* <pre> * getOthr().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link GenericPersonIdentification1 } * * */ public List<GenericPersonIdentification1> getOthr() { if (othr == null) { othr = new ArrayList<GenericPersonIdentification1>(); } return this.othr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PersonIdentification5.java
1
请在Spring Boot框架中完成以下Java代码
public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration configuration) { return super.springProcessEngineBean(configuration); } @Bean @ConditionalOnMissingBean @Override public RuntimeService runtimeServiceBean(ProcessEngine processEngine) { return super.runtimeServiceBean(processEngine); } @Bean @ConditionalOnMissingBean @Override public RepositoryService repositoryServiceBean(ProcessEngine processEngine) { return super.repositoryServiceBean(processEngine); } @Bean @ConditionalOnMissingBean @Override public TaskService taskServiceBean(ProcessEngine processEngine) { return super.taskServiceBean(processEngine); } @Bean @ConditionalOnMissingBean @Override public HistoryService historyServiceBean(ProcessEngine processEngine) { return super.historyServiceBean(processEngine); } @Bean @ConditionalOnMissingBean @Override public ManagementService managementServiceBeanBean(ProcessEngine processEngine) { return super.managementServiceBeanBean(processEngine); } @Bean @ConditionalOnMissingBean
public TaskExecutor taskExecutor() { return new SimpleAsyncTaskExecutor(); } @Bean @ConditionalOnMissingBean @Override public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) { return super.integrationContextManagerBean(processEngine); } @Bean @ConditionalOnMissingBean @Override public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) { return super.integrationContextServiceBean(processEngine); } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AbstractProcessEngineAutoConfiguration.java
2
请完成以下Java代码
public void pointcut() { } @Before("pointcut()") public Object before(JoinPoint point) { //get params Object[] args = point.getArgs(); //get param name Method method = ((MethodSignature) point.getSignature()).getMethod(); LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] paramNames = u.getParameterNames(method); CheckContainer checkContainer = method.getDeclaredAnnotation(CheckContainer.class); List<Check> value = new ArrayList<>(); if (checkContainer != null) { value.addAll(Arrays.asList(checkContainer.value())); } else { Check check = method.getDeclaredAnnotation(Check.class); value.add(check); } for (int i = 0; i < value.size(); i++) { Check check = value.get(i); String ex = check.ex(); //In the rule engine, null is represented by nil ex = ex.replaceAll("null", "nil");
String msg = check.msg(); if (StringUtils.isEmpty(msg)) { msg = "server exception..."; } Map<String, Object> map = new HashMap<>(16); for (int j = 0; j < paramNames.length; j++) { //Prevent index out of bounds if (j > args.length) { continue; } map.put(paramNames[j], args[j]); } Boolean result = (Boolean) AviatorEvaluator.execute(ex, map); if (!result) { throw new UserFriendlyException(msg); } } return null; } }
repos\springboot-demo-master\Aviator\src\main\java\com\et\annotation\AopConfig.java
1
请在Spring Boot框架中完成以下Java代码
public class WeiXinBaseUtils { private static String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /** * 生成16位随机的字符串 * * @return */ public static String createNoncestr() { return createNoncestr(16); } /** * 生成随机的字符串 * * @param length * @return */ private static String createNoncestr(int length) { StringBuilder sb = new StringBuilder(); Random rd = new Random(); int clength = chars.length(); for (int i = 0; i < length; i++) { sb.append(chars.charAt(rd.nextInt(clength - 1))); } return sb.toString(); } /** * 生成xml文件 * * @param arr * @return
*/ public static String arrayToXml(HashMap<String, String> arr) { String xml = "<xml>"; Iterator<Entry<String, String>> iter = arr.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> entry = iter.next(); String key = entry.getKey(); String val = entry.getValue(); if (isNumeric(val)) { xml += "<" + key + ">" + val + "</" + key + ">"; } else xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">"; } xml += "</xml>"; return xml; } private static boolean isNumeric(String str) { if (str.matches("\\d *")) { return true; } else { return false; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\WeiXinBaseUtils.java
2
请完成以下Java代码
public String getNbOfTxs() { return nbOfTxs; } /** * Sets the value of the nbOfTxs property. * * @param value * allowed object is * {@link String } * */ public void setNbOfTxs(String value) { this.nbOfTxs = value; } /** * Gets the value of the ttlAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getTtlAmt() { return ttlAmt; } /** * Sets the value of the ttlAmt property. * * @param value
* allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) { this.ttlAmt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BatchInformation2.java
1
请在Spring Boot框架中完成以下Java代码
public GetArticlesResult handle(GetArticles query) { var currentUserId = authenticationService.getCurrentUserId(); Long tagId; if (query.getTag() == null) { tagId = null; } else { tagId = tagRepository.findByName(query.getTag()) .map(Tag::id) .orElse(null); if (tagId == null) { return new GetArticlesResult(List.of(), 0L); } } Long authorId; if (query.getAuthor() == null) { authorId = null; } else { authorId = userRepository.findByUsername(query.getAuthor()) .map(User::id) .orElse(null); if (authorId == null) { return new GetArticlesResult(List.of(), 0L); } } Long favoritedById; if (query.getFavorited() == null) { favoritedById = null; } else {
favoritedById = userRepository.findByUsername(query.getFavorited()) .map(User::id) .orElse(null); if (favoritedById == null) { return new GetArticlesResult(List.of(), 0L); } } var articles = articleRepository.findAllAssemblyByFilters(currentUserId, tagId, authorId, favoritedById, query.getLimit(), query.getOffset()); var results = articles.stream() .map(a -> conversionService.convert(a, ArticleDto.class)) .toList(); var count = articleRepository.countByFilters(tagId, authorId, favoritedById); return new GetArticlesResult(results, count); } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\application\query\GetArticlesHandler.java
2
请完成以下Java代码
protected boolean afterDelete(boolean success) { if (!success) return success; BundleUtil.updateCCM_Bundle_Status(getR_Group_ID(), get_TrxName()); return true; } public void lockContact() { int AD_User_ID = Env.getAD_User_ID(getCtx()); Timestamp ts = new Timestamp(System.currentTimeMillis()); setLocked(true); setLockedBy(AD_User_ID); setLockedDate(ts); } public void unlockContact() { setLocked(false); set_Value(COLUMNNAME_LockedBy, null); setLockedDate(null); } public boolean isExpired() { if (!isLocked()) return true; Timestamp dateExpire = TimeUtil.addMinutes(getLockedDate(), LOCK_EXPIRE_MIN); Timestamp now = new Timestamp(System.currentTimeMillis()); return dateExpire.before(now); } public void expireLock() { if (isLocked() && isExpired())
unlockContact(); } @Override public String toString() { String bundleName = DB.getSQLValueString(get_TrxName(), "SELECT "+I_R_Group.COLUMNNAME_Name+" FROM "+I_R_Group.Table_Name +" WHERE "+I_R_Group.COLUMNNAME_R_Group_ID+"=?", getR_Group_ID()); String bpName = DB.getSQLValueString(get_TrxName(), "SELECT "+I_C_BPartner.COLUMNNAME_Value+"||'_'||"+I_C_BPartner.COLUMNNAME_Name +" FROM "+I_C_BPartner.Table_Name +" WHERE "+I_C_BPartner.COLUMNNAME_C_BPartner_ID+"=?", getC_BPartner_ID()); return bundleName+"/"+bpName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\model\MRGroupProspect.java
1
请完成以下Spring Boot application配置
spring: kafka: bootstrap-servers: localhost:9092 properties: sasl.mechanism: PLAIN sasl.jaas.config: > org.apache.kafka.common.security.plain.PlainLoginModule required username="user1" password="user1-secret"; security: protocol: SASL_PLAINTEXT consumer: group-id: test-group auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
repos\tutorials-master\spring-kafka-4\src\main\resources\application-sasl-plaintext.yml
2
请完成以下Java代码
public List<JobDefinition> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefnitionByQueryCriteria(this, page); } // getters ///////////////////////////////////////////// public String getId() { return id; } public String[] getActivityIds() { return activityIds; } public String getProcessDefinitionId() { return processDefinitionId; }
public String getProcessDefinitionKey() { return processDefinitionKey; } public String getJobType() { return jobType; } public String getJobConfiguration() { return jobConfiguration; } public SuspensionState getSuspensionState() { return suspensionState; } public Boolean getWithOverridingJobPriority() { return withOverridingJobPriority; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobDefinitionQueryImpl.java
1