instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class ArticleReadDto { private Long id; private String title; private ArticleStatus status; private String content; private UUID userId; private String username; private Instant createdDate; private List<FileInfo> files = new ArrayList<>(); private List<CommentDto> comments = new LinkedList<>(); @Data @NoArgsConstructor public static class FileInfo { UUID id; String name;
} @Data @NoArgsConstructor public static class CommentDto { Long id; String content; UUID userId; String username; Instant createdDate; Long articleId; Long parentCommentId; List<CommentDto> childComments = new LinkedList<>(); } }
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\modules\article\ArticleReadDto.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("category", this.category); return persistentState; } @Override public String getCategory() { return category; } @Override public void setName(String name) { this.name = name; } @Override public String getName() { return name; } @Override public String getKey() { return key; } @Override public String getDescription() { return description; } @Override public int getVersion() { return version; } @Override public String getResourceName() { return resourceName; } @Override public String getDeploymentId() { return deploymentId; } @Override public String getTenantId() { return tenantId; } @Override public void setDescription(String description) { this.description = description; }
@Override public void setCategory(String category) { this.category = category; } @Override public void setVersion(int version) { this.version = version; } @Override public void setKey(String key) { this.key = key; } @Override public void setResourceName(String resourceName) { this.resourceName = resourceName; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDefinitionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public TbSubscription<?> registerPendingSubscription(TbSubscription<?> subscription, TbEntitySubEvent event) { if (TbSubscriptionType.ATTRIBUTES.equals(subscription.getType())) { if (event != null) { log.trace("[{}][{}] Registering new pending attributes subscription event: {} for subscription: {}", tenantId, entityId, event.getSeqNumber(), subscription.getSubscriptionId()); pendingAttributesEvent = event.getSeqNumber(); pendingAttributesEventTs = System.currentTimeMillis(); pendingSubs.computeIfAbsent(pendingAttributesEvent, e -> new HashSet<>()).add(subscription); } else if (pendingAttributesEvent > 0) { log.trace("[{}][{}] Registering pending attributes subscription {} for event: {} ", tenantId, entityId, subscription.getSubscriptionId(), pendingAttributesEvent); pendingSubs.computeIfAbsent(pendingAttributesEvent, e -> new HashSet<>()).add(subscription); } else { return subscription; } } else if (subscription instanceof TbTimeSeriesSubscription) { if (event != null) { log.trace("[{}][{}] Registering new pending time-series subscription event: {} for subscription: {}", tenantId, entityId, event.getSeqNumber(), subscription.getSubscriptionId()); pendingTimeSeriesEvent = event.getSeqNumber(); pendingTimeSeriesEventTs = System.currentTimeMillis(); pendingSubs.computeIfAbsent(pendingTimeSeriesEvent, e -> new HashSet<>()).add(subscription); } else if (pendingTimeSeriesEvent > 0) {
log.trace("[{}][{}] Registering pending time-series subscription {} for event: {} ", tenantId, entityId, subscription.getSubscriptionId(), pendingTimeSeriesEvent); pendingSubs.computeIfAbsent(pendingTimeSeriesEvent, e -> new HashSet<>()).add(subscription); } else { return subscription; } } return null; } public Set<TbSubscription<?>> clearPendingSubscriptions(int seqNumber) { if (pendingTimeSeriesEvent == seqNumber) { pendingTimeSeriesEvent = 0; pendingTimeSeriesEventTs = 0L; } else if (pendingAttributesEvent == seqNumber) { pendingAttributesEvent = 0; pendingAttributesEventTs = 0L; } return pendingSubs.remove(seqNumber); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbEntityLocalSubsInfo.java
2
请在Spring Boot框架中完成以下Java代码
public class ActivityControlCreateRequest { @NonNull I_PP_Order order; @NonNull PPOrderRoutingActivity orderActivity; @NonNull ZonedDateTime movementDate; @NonNull Quantity qtyMoved; @NonNull Duration durationSetup; @NonNull Duration duration; @Builder private ActivityControlCreateRequest( @NonNull final I_PP_Order order, @NonNull final PPOrderRoutingActivity orderActivity, @Nullable final ZonedDateTime movementDate, @NonNull final Quantity qtyMoved,
@NonNull final Duration durationSetup, @NonNull final Duration duration) { Check.assume(!durationSetup.isNegative(), "durationSetup >= 0 but it was {}", durationSetup); Check.assume(!duration.isNegative(), "duration >= 0 but it was {}", duration); this.order = order; this.orderActivity = orderActivity; this.movementDate = movementDate != null ? movementDate : SystemTime.asZonedDateTime(); this.qtyMoved = qtyMoved; this.durationSetup = durationSetup; this.duration = duration; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\ActivityControlCreateRequest.java
2
请在Spring Boot框架中完成以下Java代码
private static RSAKey getRsaKey() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); return rsaKey; } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); }
return keyPair; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(JwtDecoder.class) static class JwtDecoderConfiguration { @Bean @ConditionalOnMissingBean JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-authorization-server\src\main\java\org\springframework\boot\security\oauth2\server\authorization\autoconfigure\servlet\OAuth2AuthorizationServerJwtAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public IQuery<I_C_Flatrate_Term> queryMembershipRunningSubscription( @NonNull final BPartnerId bPartnerId, @NonNull final Instant orgChangeDate, @NonNull final OrgId orgId) { final IQuery<I_M_Product> membershipProductQuery = queryMembershipProducts(orgId); return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId) .addInSubQueryFilter(I_C_Flatrate_Term.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, membershipProductQuery) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, CompareQueryFilter.Operator.GREATER, orgChangeDate) .create(); } public IQuery<I_M_Product> queryMembershipProducts(@NonNull final OrgId orgId) { return queryBL.createQueryBuilder(I_M_Product.class) .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Org_ID, orgId) .addNotEqualsFilter(I_M_Product.COLUMNNAME_C_CompensationGroup_Schema_ID, null) .addNotEqualsFilter(I_M_Product.COLUMNNAME_C_CompensationGroup_Schema_Category_ID, null) .create(); } public ImmutableSet<OrderId> retrieveMembershipOrderIds(
@NonNull final OrgId orgId, @NonNull final Instant orgChangeDate) { final IQuery<I_M_Product> membershipProductQuery = queryMembershipProducts(orgId); return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId) .addInSubQueryFilter(I_C_Flatrate_Term.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, membershipProductQuery) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, CompareQueryFilter.Operator.GREATER, orgChangeDate) .andCollect(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, I_C_Order.class) .addEqualsFilter(I_C_Order.COLUMNNAME_AD_Org_ID, orgId) .create() .idsAsSet(OrderId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\repository\MembershipContractRepository.java
2
请完成以下Java代码
public boolean isStoreResultVariableAsTransient() { return storeResultVariableAsTransient; } public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) { this.storeResultVariableAsTransient = storeResultVariableAsTransient; } @Override public ServiceTask clone() { ServiceTask clone = new ServiceTask(); clone.setValues(this); return clone; } public void setValues(ServiceTask otherElement) { super.setValues(otherElement); setImplementation(otherElement.getImplementation()); setImplementationType(otherElement.getImplementationType()); setResultVariableName(otherElement.getResultVariableName()); setType(otherElement.getType()); setOperationRef(otherElement.getOperationRef()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); setUseLocalScopeForResultVariable(otherElement.isUseLocalScopeForResultVariable()); setTriggerable(otherElement.isTriggerable()); setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient());
fieldExtensions = new ArrayList<>(); if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherElement.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } customProperties = new ArrayList<>(); if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) { for (CustomProperty property : otherElement.getCustomProperties()) { customProperties.add(property.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ServiceTask.java
1
请在Spring Boot框架中完成以下Java代码
public int getSocketBufferSize() { return this.socketBufferSize; } public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; } public int getSubscriptionCapacity() { return this.subscriptionCapacity; } public void setSubscriptionCapacity(int subscriptionCapacity) { this.subscriptionCapacity = subscriptionCapacity; } public String getSubscriptionDiskStoreName() { return this.subscriptionDiskStoreName; } public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) { this.subscriptionDiskStoreName = subscriptionDiskStoreName; }
public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() { return this.subscriptionEvictionPolicy; } public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) { this.subscriptionEvictionPolicy = subscriptionEvictionPolicy; } public boolean isTcpNoDelay() { return this.tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java
2
请完成以下Java代码
private MailSender getMailSender(@NonNull final MailboxType type) { final MailSender mailSender = mailSenders.get(type); if (mailSender == null) { throw new AdempiereException("Unsupported type: " + type); } return mailSender; } private boolean isDebugModeEnabled() { return sysConfigBL.getBooleanValue(SYSCONFIG_DEBUG, false); } /** * Gets the EMail TO address to be used when sending mails. * If present, this address will be used to send all emails to a particular address instead of actual email addresses. * * @return email address or null */ @Nullable private InternetAddress getDebugMailToAddressOrNull() { final Properties ctx = Env.getCtx(); final String emailStr = StringUtils.trimBlankToNull( sysConfigBL.getValue(SYSCONFIG_DebugMailTo, null, // defaultValue Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx)) ); if (Check.isEmpty(emailStr, true) || emailStr.equals("-")) { return null; } try
{ return new InternetAddress(emailStr, true); } catch (final Exception ex) { logger.warn("Invalid debug email address provided by sysconfig {}: {}. Returning null.", SYSCONFIG_DebugMailTo, emailStr, ex); return null; } } public void send(final EMail email) { final EMailSentStatus sentStatus = email.send(); sentStatus.throwIfNotOK(); } public MailTextBuilder newMailTextBuilder(@NonNull final MailTemplate mailTemplate) { return MailTextBuilder.newInstance(mailTemplate); } public MailTextBuilder newMailTextBuilder(final MailTemplateId mailTemplateId) { final MailTemplate mailTemplate = mailTemplatesRepo.getById(mailTemplateId); return newMailTextBuilder(mailTemplate); } public void test(@NonNull final TestMailRequest request) { TestMailCommand.builder() .mailService(this) .request(request) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\MailService.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-provider cloud: # Sentinel 配置项,对应 SentinelProperties 配置属性类 sentinel: enabled: true # 是否开启。默认为 true 开启 eager: true # 是否饥饿加载。默认为 false 关闭 transport: dashboard: 127.0.0.1:7070 # Sentinel 控制台地址 filter: url-patterns: /** # 拦截请求的地址。默认为 /* # Sentinel 规则的数据源,是一个 Map 类型。key 为数据源名,可自定义;value 为数据源的具体配置 datasource: ds1: # 对应 DataSourcePropertiesConfiguration 类 nacos: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 # data-id: demo-application-flow-rule #
data-id: demo-provider-flow-rule namespace: # Nacos 命名空间 group-id: DEFAULT_GROUP # Nacos 分组 data-id: ${spring.application.name}-flow-rule # Nacos 配置集编号 data-type: json # 数据格式 rule-type: FLOW # 规则类型
repos\SpringBoot-Labs-master\labx-04-spring-cloud-alibaba-sentinel\labx-04-sca-sentinel-nacos-provider\src\main\resources\application.yaml
2
请完成以下Java代码
public void setC_RfQ_TopicSubscriber_ID (int C_RfQ_TopicSubscriber_ID) { if (C_RfQ_TopicSubscriber_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, Integer.valueOf(C_RfQ_TopicSubscriber_ID)); } /** Get RfQ Subscriber. @return Request for Quotation Topic Subscriber */ @Override public int getC_RfQ_TopicSubscriber_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriber_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum der Abmeldung. @param OptOutDate Date the contact opted out */ @Override public void setOptOutDate (java.sql.Timestamp OptOutDate) { set_Value (COLUMNNAME_OptOutDate, OptOutDate); } /** Get Datum der Abmeldung. @return Date the contact opted out
*/ @Override public java.sql.Timestamp getOptOutDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate); } /** Set Anmeldung. @param SubscribeDate Date the contact actively subscribed */ @Override public void setSubscribeDate (java.sql.Timestamp SubscribeDate) { set_Value (COLUMNNAME_SubscribeDate, SubscribeDate); } /** Get Anmeldung. @return Date the contact actively subscribed */ @Override public java.sql.Timestamp getSubscribeDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java
1
请完成以下Java代码
public final String toString() { return ObjectUtils.toString(this); } @Override public final ILock getLock() { return lock; } @Override public final void close() { // If lock was already closed, there is nothing to do if (lock.isClosed())
{ return; } closeImpl(); } /** Actual lock closing logic */ protected abstract void closeImpl(); protected final void closeNow() { lock.close(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\AbstractLockAutoCloseable.java
1
请在Spring Boot框架中完成以下Java代码
private void handleSentEvent(@NonNull final CamelEvent.ExchangeSentEvent sentEvent) { final Endpoint endpoint = sentEvent.getEndpoint(); final Exception exception = sentEvent.getExchange().getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); if (!(exception instanceof HttpOperationFailedException)) { return; } final HttpOperationFailedException httpOperationFailedException = (HttpOperationFailedException)exception; if (httpOperationFailedException.getStatusCode() == 401) { if (endpoint.getEndpointUri() == null || !metasfreshAPIURL.contains(endpoint.getEndpointUri()))
{ logger.info("Received a 401 HttpStatusCode from: " + endpoint.getEndpointUri() +"; considered a non-MF-API URL based on: " + metasfreshAPIURL); return; } final String usedAuthToken = String.valueOf(sentEvent.getExchange().getIn().getHeader(CoreConstants.AUTHORIZATION)); logger.info("MF-API responded with 401, stopping all routes; " + " Request sent had the following auth token:" + StringUtils.maskString(usedAuthToken) + "; metasfreshAuthProvider has: " + StringUtils.maskString(metasfreshAuthProvider.getAuthToken())); this.customRouteController.stopAllRoutes(); producerTemplate.sendBody("direct:" + CUSTOM_TO_MF_ROUTE_ID, "Trigger external system authentication for metasfresh!"); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\authorization\MetasfreshAuthorizationTokenNotifier.java
2
请完成以下Java代码
public void setAD_User_Alberta_ID (final int AD_User_Alberta_ID) { if (AD_User_Alberta_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Alberta_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Alberta_ID, AD_User_Alberta_ID); } @Override public int getAD_User_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Alberta_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * Gender AD_Reference_ID=541317 * Reference name: Gender_List */ public static final int GENDER_AD_Reference_ID=541317; /** Unbekannt = 0 */ public static final String GENDER_Unbekannt = "0"; /** Weiblich = 1 */ public static final String GENDER_Weiblich = "1"; /** Männlich = 2 */ public static final String GENDER_Maennlich = "2"; /** Divers = 3 */ public static final String GENDER_Divers = "3"; @Override public void setGender (final @Nullable java.lang.String Gender) { set_Value (COLUMNNAME_Gender, Gender); } @Override public java.lang.String getGender() { return get_ValueAsString(COLUMNNAME_Gender); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp)
{ set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } /** * Title AD_Reference_ID=541318 * Reference name: Title_List */ public static final int TITLE_AD_Reference_ID=541318; /** Unbekannt = 0 */ public static final String TITLE_Unbekannt = "0"; /** Dr. = 1 */ public static final String TITLE_Dr = "1"; /** Prof. Dr. = 2 */ public static final String TITLE_ProfDr = "2"; /** Dipl. Ing. = 3 */ public static final String TITLE_DiplIng = "3"; /** Dipl. Med. = 4 */ public static final String TITLE_DiplMed = "4"; /** Dipl. Psych. = 5 */ public static final String TITLE_DiplPsych = "5"; /** Dr. Dr. = 6 */ public static final String TITLE_DrDr = "6"; /** Dr. med. = 7 */ public static final String TITLE_DrMed = "7"; /** Prof. Dr. Dr. = 8 */ public static final String TITLE_ProfDrDr = "8"; /** Prof. = 9 */ public static final String TITLE_Prof = "9"; /** Prof. Dr. med. = 10 */ public static final String TITLE_ProfDrMed = "10"; /** Rechtsanwalt = 11 */ public static final String TITLE_Rechtsanwalt = "11"; /** Rechtsanwältin = 12 */ public static final String TITLE_Rechtsanwaeltin = "12"; /** Schwester (Orden) = 13 */ public static final String TITLE_SchwesterOrden = "13"; @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_AD_User_Alberta.java
1
请完成以下Java代码
public class CorrelationSubscriptionImpl extends BaseElementImpl implements CorrelationSubscription { protected static AttributeReference<CorrelationKey> correlationKeyAttribute; protected static ChildElementCollection<CorrelationPropertyBinding> correlationPropertyBindingCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CorrelationSubscription.class, BPMN_ELEMENT_CORRELATION_SUBSCRIPTION) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<CorrelationSubscription>() { public CorrelationSubscription newInstance(ModelTypeInstanceContext instanceContext) { return new CorrelationSubscriptionImpl(instanceContext); } }); correlationKeyAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_CORRELATION_KEY_REF) .required() .qNameAttributeReference(CorrelationKey.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); correlationPropertyBindingCollection = sequenceBuilder.elementCollection(CorrelationPropertyBinding.class) .build();
typeBuilder.build(); } public CorrelationSubscriptionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public CorrelationKey getCorrelationKey() { return correlationKeyAttribute.getReferenceTargetElement(this); } public void setCorrelationKey(CorrelationKey correlationKey) { correlationKeyAttribute.setReferenceTargetElement(this, correlationKey); } public Collection<CorrelationPropertyBinding> getCorrelationPropertyBindings() { return correlationPropertyBindingCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CorrelationSubscriptionImpl.java
1
请完成以下Java代码
public final ProcessPreconditionsResolution checkPreconditionsApplicable() { final List<PickingSlotRow> pickingSlotRows = getSelectedPickingSlotRows(); if (pickingSlotRows.size() <= 1) { return ProcessPreconditionsResolution.rejectWithInternalReason("select more than one HU"); } final Set<PickingSlotRowId> rootRowIds = getRootRowIdsForSelectedPickingSlotRows(); if (rootRowIds.size() > 1) { return ProcessPreconditionsResolution.rejectWithInternalReason("all selected HU rows shall be from one picking slot"); } for (final PickingSlotRow pickingSlotRow : pickingSlotRows) { if (!pickingSlotRow.isPickedHURow()) { return ProcessPreconditionsResolution.rejectWithInternalReason("select an HU"); } if (!pickingSlotRow.isTopLevelHU()) { return ProcessPreconditionsResolution.rejectWithInternalReason("select an top level HU"); } } // return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final List<I_M_HU> fromHUs = getSelectedPickingSlotTopLevelHUs(); final IAllocationSource source = HUListAllocationSourceDestination.of(fromHUs) .setDestroyEmptyHUs(true); final IHUProducerAllocationDestination destination = createHUProducer(); HULoader.of(source, destination) .setAllowPartialUnloads(false) .setAllowPartialLoads(false) .unloadAllFromSource(); // If the source HU was destroyed, then "remove" it from picking slots final ImmutableSet<HuId> destroyedHUIds = fromHUs.stream() .filter(handlingUnitsBL::isDestroyedRefreshFirst) .map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (!destroyedHUIds.isEmpty()) { pickingCandidateService.inactivateForHUIds(destroyedHUIds); } return MSG_OK; } @Override protected void postProcess(final boolean success) { if (!success) { return; } // Invalidate views getPickingSlotsClearingView().invalidateAll(); getPackingHUsView().invalidateAll(); } private IHUProducerAllocationDestination createHUProducer() { final PickingSlotRow pickingRow = getRootRowForSelectedPickingSlotRows(); return createNewHUProducer(pickingRow, targetHUPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutMultiHUsAndAddToNewHU.java
1
请在Spring Boot框架中完成以下Java代码
public OtaPackage findOtaPackageByTenantIdAndTitleAndVersion(TenantId tenantId, String title, String version) { return DaoUtil.getData(otaPackageRepository.findByTenantIdAndTitleAndVersion(tenantId.getId(), title, version)); } @Transactional @Override public PageData<OtaPackage> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(otaPackageRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } @Transactional @Override public PageData<OtaPackage> findByTenantId(UUID tenantId, PageLink pageLink) { return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink); } @Override public PageData<OtaPackageId> findIdsByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.pageToPageData(otaPackageRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink)).map(OtaPackageId::new)); } @Transactional @Override public OtaPackage findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(otaPackageRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public OtaPackageId getExternalIdByInternal(OtaPackageId internalId) {
return DaoUtil.toEntityId(otaPackageRepository.getExternalIdById(internalId.getId()), OtaPackageId::new); } @Override protected Class<OtaPackageEntity> getEntityClass() { return OtaPackageEntity.class; } @Override protected JpaRepository<OtaPackageEntity, UUID> getRepository() { return otaPackageRepository; } @Override public EntityType getEntityType() { return EntityType.OTA_PACKAGE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\ota\JpaOtaPackageDao.java
2
请完成以下Java代码
public void setESR_Trx_Qty (final @Nullable BigDecimal ESR_Trx_Qty) { throw new IllegalArgumentException ("ESR_Trx_Qty is virtual column"); } @Override public BigDecimal getESR_Trx_Qty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Trx_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); } @Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsArchiveFile (final boolean IsArchiveFile) { set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile); } @Override public boolean isArchiveFile() { return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsReconciled (final boolean IsReconciled) {
set_Value (COLUMNNAME_IsReconciled, IsReconciled); } @Override public boolean isReconciled() { return get_ValueAsBoolean(COLUMNNAME_IsReconciled); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { throw new IllegalArgumentException ("Processing is virtual column"); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
1
请在Spring Boot框架中完成以下Java代码
public void preInit(SpringProcessEngineConfiguration configuration) { if (camundaBpmProperties.isAutoDeploymentEnabled()) { final Set<Resource> resources = getDeploymentResources(); configuration.setDeploymentResources(resources.toArray(new Resource[resources.size()])); LOG.autoDeployResources(resources); } } @Override public Set<Resource> getDeploymentResources() { final ResourceArrayPropertyEditor resolver = new ResourceArrayPropertyEditor(); try { final String[] resourcePattern = camundaBpmProperties.getDeploymentResourcePattern(); logger.debug("resolving deployment resources for pattern {}", (Object[]) resourcePattern); resolver.setValue(resourcePattern); return Arrays.stream((Resource[])resolver.getValue()) .peek(resource -> logger.debug("processing deployment resource {}", resource)) .filter(this::isFile) .peek(resource -> logger.debug("added deployment resource {}", resource)) .collect(Collectors.toSet()); } catch (final RuntimeException e) { logger.error("unable to resolve resources", e); } return EMPTY_SET; } private boolean isFile(Resource resource) { if (resource.isReadable()) { if (resource instanceof UrlResource || resource instanceof ClassPathResource) { try {
URL url = resource.getURL(); return !url.toString().endsWith("/"); } catch (IOException e) { logger.debug("unable to handle " + resource + " as URL", e); } } else { try { return !resource.getFile().isDirectory(); } catch (IOException e) { logger.debug("unable to handle " + resource + " as file", e); } } } logger.warn("unable to determine if resource {} is a deployable resource", resource); return false; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\DefaultDeploymentConfiguration.java
2
请完成以下Java代码
public class ManagedJobExecutor extends JobExecutor { private ManagedExecutorService managedExecutorService; /** * Constructs a new ManagedJobExecutor with the provided * {@link ManagedExecutorService} */ public ManagedJobExecutor(final ManagedExecutorService managedExecutorService) { this.managedExecutorService = managedExecutorService; } @Override public void executeJobs(List<String> jobIds, ProcessEngineImpl processEngine) { try { managedExecutorService.execute(getExecuteJobsRunnable(jobIds, processEngine)); } catch (RejectedExecutionException e) { logRejectedExecution(processEngine, jobIds.size()); rejectedJobsHandler.jobsRejected(jobIds, processEngine, this); }
} @Override protected void startExecutingJobs() { try { managedExecutorService.execute(acquireJobsRunnable); } catch (Exception e) { throw new ProcessEngineException("Could not schedule AcquireJobsRunnable for execution.", e); } } @Override protected void stopExecutingJobs() { // nothing to do } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\ManagedJobExecutor.java
1
请完成以下Java代码
public String toString() { return "Activity(" + id + ")"; } public ActivityImpl getParentActivity() { if (parent instanceof ActivityImpl) { return (ActivityImpl) parent; } return null; } // restricted setters /////////////////////////////////////////////////////// protected void setOutgoingTransitions(List<TransitionImpl> outgoingTransitions) { this.outgoingTransitions = outgoingTransitions; } protected void setParent(ScopeImpl parent) { this.parent = parent; } protected void setIncomingTransitions(List<TransitionImpl> incomingTransitions) { this.incomingTransitions = incomingTransitions; } // getters and setters ////////////////////////////////////////////////////// @Override @SuppressWarnings("unchecked") public List<PvmTransition> getOutgoingTransitions() { return (List) outgoingTransitions; } public ActivityBehavior getActivityBehavior() { return activityBehavior; } public void setActivityBehavior(ActivityBehavior activityBehavior) { this.activityBehavior = activityBehavior; } @Override public ScopeImpl getParent() { return parent; } @Override @SuppressWarnings("unchecked") public List<PvmTransition> getIncomingTransitions() { return (List) incomingTransitions; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public boolean isScope() { return isScope; } public void setScope(boolean isScope) { this.isScope = isScope; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x;
} @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width; } @Override public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height; } @Override public void setHeight(int height) { this.height = height; } @Override public boolean isAsync() { return isAsync; } public void setAsync(boolean isAsync) { this.isAsync = isAsync; } @Override public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { this.isExclusive = isExclusive; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
1
请完成以下Java代码
public static String sortByValueForVariableOrderProperty(VariableOrderProperty variableOrderProperty) { for (QueryEntityRelationCondition relationCondition : variableOrderProperty.getRelationConditions()) { if (relationCondition.isPropertyComparison()) { return sortByValueForQueryEntityRelationCondition(relationCondition); } } // if no property comparison was found throw an exception throw new RestException("Unknown variable order property for task query " + variableOrderProperty); } public static String sortByValueForQueryEntityRelationCondition(QueryEntityRelationCondition relationCondition) { QueryProperty property = relationCondition.getProperty(); QueryProperty comparisonProperty = relationCondition.getComparisonProperty(); if (VariableInstanceQueryProperty.EXECUTION_ID.equals(property) && TaskQueryProperty.PROCESS_INSTANCE_ID.equals(comparisonProperty)) { return SORT_BY_PROCESS_VARIABLE; } else if (VariableInstanceQueryProperty.EXECUTION_ID.equals(property) && TaskQueryProperty.EXECUTION_ID.equals(comparisonProperty)) { return SORT_BY_EXECUTION_VARIABLE; } else if (VariableInstanceQueryProperty.TASK_ID.equals(property) && TaskQueryProperty.TASK_ID.equals(comparisonProperty)) { return SORT_BY_TASK_VARIABLE; } else if (VariableInstanceQueryProperty.CASE_EXECUTION_ID.equals(property) && TaskQueryProperty.CASE_INSTANCE_ID.equals(comparisonProperty)) {
return SORT_BY_CASE_INSTANCE_VARIABLE; } else if (VariableInstanceQueryProperty.CASE_EXECUTION_ID.equals(property) && TaskQueryProperty.CASE_EXECUTION_ID.equals(comparisonProperty)) { return SORT_BY_CASE_EXECUTION_VARIABLE; } else { throw new RestException("Unknown relation condition for task query with query property " + property + " and comparison property " + comparisonProperty); } } public static Map<String,Object> sortParametersForVariableOrderProperty(VariableOrderProperty variableOrderProperty) { Map<String, Object> parameters = new HashMap<>(); for (QueryEntityRelationCondition relationCondition : variableOrderProperty.getRelationConditions()) { QueryProperty property = relationCondition.getProperty(); if (VariableInstanceQueryProperty.VARIABLE_NAME.equals(property)) { parameters.put(SORT_PARAMETERS_VARIABLE_NAME, relationCondition.getScalarValue()); } else if (VariableInstanceQueryProperty.VARIABLE_TYPE.equals(property)) { String type = VariableValueDto.toRestApiTypeName((String) relationCondition.getScalarValue()); parameters.put(SORT_PARAMETERS_VALUE_TYPE, type); } } return parameters; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class UserRoleRepository { static Map<String, CustomUser> DB_BASED_USER_MAPPING; static { DB_BASED_USER_MAPPING = new LinkedHashMap<>(); DB_BASED_USER_MAPPING.put("jane", new CustomUser("jane", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_VIEWER"), "jane")); DB_BASED_USER_MAPPING.put("john", new CustomUser("john", "1234", getGrantedAuthorities("ROLE_EDITOR", "ROLE_ADMIN"), "jane")); DB_BASED_USER_MAPPING.put("jack", new CustomUser("jack", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_REVIEWER"), "jane")); } private static List<GrantedAuthority> getGrantedAuthorities(String... roles) { ArrayList<GrantedAuthority> authorities = new ArrayList<>(); for (String role : roles) { authorities.add(new SimpleGrantedAuthority(role)); } return authorities; } public CustomUser loadUserByUserName(String username) { if (DB_BASED_USER_MAPPING.containsKey(username)) { return DB_BASED_USER_MAPPING.get(username); } throw new UsernameNotFoundException("User " + username + " cannot be found"); } public boolean isValidUsername(String username) { return DB_BASED_USER_MAPPING.containsKey(username);
} public boolean isValidRole(String roleName) { return roleName.startsWith("ROLE_"); } public List<String> getAllUsernames() { List<String> usernames = new ArrayList<>(); usernames.add("jane"); usernames.add("john"); usernames.add("jack"); return usernames; } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\repository\UserRoleRepository.java
2
请完成以下Java代码
protected List<String[]> convertToSequence(Sentence sentence) { List<String[]> collector = Utility.convertSentenceToNER(sentence, tagSet); for (String[] pair : collector) { pair[1] = pair[2]; } return collector; } @Override protected TagSet getTagSet() { return tagSet; } @Override public String[] recognize(String[] wordArray, String[] posArray) { int[] obsArray = new int[wordArray.length]; for (int i = 0; i < obsArray.length; i++)
{ obsArray[i] = vocabulary.idOf(wordArray[i]); } int[] tagArray = new int[obsArray.length]; model.predict(obsArray, tagArray); String[] tags = new String[obsArray.length]; for (int i = 0; i < tagArray.length; i++) { tags[i] = tagSet.stringOf(tagArray[i]); } return tags; } @Override public NERTagSet getNERTagSet() { return tagSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMNERecognizer.java
1
请完成以下Java代码
public class C_RfQ_PublishResults extends JavaProcess implements IProcessPrecondition { // services private final transient IRfQConfiguration rfqConfiguration = Services.get(IRfQConfiguration.class); private final transient IRfqBL rfqBL = Services.get(IRfqBL.class); private final transient IRfqDAO rfqDAO = Services.get(IRfqDAO.class); private final transient IPMM_RfQ_BL pmmRfqBL = Services.get(IPMM_RfQ_BL.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { final I_C_RfQ rfq = context.getSelectedModel(I_C_RfQ.class); return ProcessPreconditionsResolution.acceptIf(rfqBL.isClosed(rfq)); } @Override protected String doIt() { final I_C_RfQ rfq = getRecord(I_C_RfQ.class); final IRfQResponsePublisher rfQResponsePublisher = rfqConfiguration.getRfQResponsePublisher(); for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{ if (!rfqBL.isClosed(rfqResponse)) { addLog("@Error@ @NotClosed@: {}", rfqBL.getSummary(rfqResponse)); continue; } pmmRfqBL.checkCompleteContractsForWinners(rfqResponse); rfQResponsePublisher.publish(RfQResponsePublisherRequest.of(rfqResponse, PublishingType.Close)); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\process\C_RfQ_PublishResults.java
1
请在Spring Boot框架中完成以下Java代码
public static final class Builder extends AbstractSaml2AuthenticationRequest.Builder<Builder> { private String sigAlg; private String signature; private Builder(RelyingPartyRegistration registration) { super(registration); } /** * Sets the {@code SigAlg} parameter that will accompany this AuthNRequest * @param sigAlg the SigAlg parameter value. * @return this object */ public Builder sigAlg(String sigAlg) { this.sigAlg = sigAlg; return _this(); } /** * Sets the {@code Signature} parameter that will accompany this AuthNRequest * @param signature the Signature parameter value.
* @return this object */ public Builder signature(String signature) { this.signature = signature; return _this(); } /** * Constructs an immutable {@link Saml2RedirectAuthenticationRequest} object. * @return an immutable {@link Saml2RedirectAuthenticationRequest} object. */ public Saml2RedirectAuthenticationRequest build() { return new Saml2RedirectAuthenticationRequest(this.samlRequest, this.sigAlg, this.signature, this.relayState, this.authenticationRequestUri, this.relyingPartyRegistrationId, this.id); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2RedirectAuthenticationRequest.java
2
请完成以下Java代码
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // Let's Chat requires the token as basic username, the password can be an // arbitrary string. String auth = Base64.getEncoder() .encodeToString(String.format("%s:%s", token, username).getBytes(StandardCharsets.UTF_8)); headers.add(HttpHeaders.AUTHORIZATION, String.format("Basic %s", auth)); return Mono.fromRunnable(() -> restTemplate.exchange(createUrl(), HttpMethod.POST, new HttpEntity<>(createMessage(event, instance), headers), Void.class)); } private URI createUrl() { if (url == null) { throw new IllegalStateException("'url' must not be null."); } return URI.create(String.format("%s/rooms/%s/messages", url, room)); } protected Object createMessage(InstanceEvent event, Instance instance) { Map<String, String> messageJson = new HashMap<>(); messageJson.put("text", createContent(event, instance)); return messageJson; } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Nullable public URI getUrl() { return url; } public void setUrl(@Nullable URI url) { this.url = url; } public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; } @Nullable public String getRoom() { return room; } public void setRoom(@Nullable String room) { this.room = room; } @Nullable public String getToken() { return token; } public void setToken(@Nullable String token) { this.token = token; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\LetsChatNotifier.java
1
请完成以下Java代码
public final class APITransactionId { public static APITransactionId random() { return new APITransactionId(UUID.randomUUID().toString()); } @JsonCreator public static APITransactionId ofString(@NonNull final String value) { return new APITransactionId(value); } public static Optional<APITransactionId> optionalOfString(@Nullable final String value) { return Check.isNotBlank(value) ? Optional.of(ofString(value)) : Optional.empty(); } private final String value; private APITransactionId(@NonNull final String value) { Check.assumeNotEmpty(value, "value is not empty");
this.value = value; } @Override @Deprecated public String toString() { return toJson(); } @JsonValue public String toJson() { return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\exportaudit\APITransactionId.java
1
请完成以下Java代码
public void cleanTempFiles(Path dir) { List<Path> tempFiles = this.temporaryFiles.remove(dir); if (!tempFiles.isEmpty()) { tempFiles.forEach((path) -> { try { FileSystemUtils.deleteRecursively(path); } catch (IOException ex) { // Continue } }); } } private byte[] generateBuild(ProjectGenerationContext context) throws IOException { ProjectDescription description = context.getBean(ProjectDescription.class); StringWriter out = new StringWriter(); BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class).getIfAvailable(); if (buildWriter != null) { buildWriter.writeBuild(out); return out.toString().getBytes(); } else { throw new IllegalStateException("No BuildWriter implementation found for " + description.getLanguage()); } }
private void customizeProjectGenerationContext(AnnotationConfigApplicationContext context, InitializrMetadata metadata) { context.setParent(this.parentApplicationContext); context.registerBean(InitializrMetadata.class, () -> metadata); context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(metadata, context.getBean(ProjectDescription.class).getPlatformVersion())); context.registerBean(MetadataProjectDescriptionCustomizer.class, () -> new MetadataProjectDescriptionCustomizer(metadata)); } private void publishProjectGeneratedEvent(R request, ProjectGenerationContext context) { InitializrMetadata metadata = context.getBean(InitializrMetadata.class); ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, metadata); this.eventPublisher.publishEvent(event); } private void publishProjectFailedEvent(R request, InitializrMetadata metadata, Exception cause) { ProjectFailedEvent event = new ProjectFailedEvent(request, metadata, cause); this.eventPublisher.publishEvent(event); } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectGenerationInvoker.java
1
请完成以下Java代码
public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Boolean isBestSelling() {
return bestSelling; } public void setBestSelling(Boolean bestSelling) { this.bestSelling = bestSelling; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + ", bestSelling=" + bestSelling + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMapBooleanToYesNo\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public static String getHostWithPort(HttpServletRequest request) { String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); boolean isDefaultPort = ("http".equals(scheme) && serverPort == 80) || ("https".equals(scheme) && serverPort == 443); if (isDefaultPort) { return String.format("%s://%s", scheme, serverName); } else { return String.format("%s://%s:%d", scheme, serverName, serverPort); } } public static String getBaseUrl() { return ServletUriComponentsBuilder.fromCurrentRequestUri() .replacePath(null) .build() .toUriString();
} public static String getForwardedHost(HttpServletRequest request) { String forwardedHost = request.getHeader("X-Forwarded-Host"); String forwardedProto = request.getHeader("X-Forwarded-Proto"); String forwardedPort = request.getHeader("X-Forwarded-Port"); String scheme = forwardedProto != null ? forwardedProto : request.getScheme(); String host = forwardedHost != null ? forwardedHost : request.getServerName(); String port = forwardedPort != null ? forwardedPort : String.valueOf(request.getServerPort()); boolean isDefaultPort = ("http".equals(scheme) && "80".equals(port)) || ("https".equals(scheme) && "443".equals(port)); return isDefaultPort ? String.format("%s://%s", scheme, host) : String.format("%s://%s:%s", scheme, host, port); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-5\src\main\java\com\baeldung\hostport\GetHostPort.java
1
请完成以下Java代码
public class WEBUI_M_HU_Assign_QRCode extends JavaProcess implements IProcessPrecondition { private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); private final HUQRCodesService huQRCodesService = SpringContextHolder.instance.getBean(HUQRCodesService.class); private final QRCodeConfigurationService qrCodeConfigurationService = SpringContextHolder.instance.getBean(QRCodeConfigurationService.class); @Param(parameterName = "Barcode", mandatory = true, barcodeScannerType = ParamBarcodeScannerType.QRCode) private String p_Barcode; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final int huId = context.getSingleSelectedRecordId(); final I_M_HU hu = handlingUnitsDAO.getById(HuId.ofRepoId(huId)); final QtyTU qtyTU = handlingUnitsBL.getTUsCount(hu); if (handlingUnitsBL.isAggregateHU(hu) && qtyTU.toInt() > 1)
{ return ProcessPreconditionsResolution.rejectWithInternalReason("HU is aggregated and Qty is bigger then 1. Cannot assign QR code to it."); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final HUQRCode huQRCode = HUQRCode.fromGlobalQRCodeJsonString(p_Barcode); final HuId selectedHuId = HuId.ofRepoId(getRecord_ID()); final boolean ensureSingleAssignment = !qrCodeConfigurationService.isOneQrCodeForAggregatedHUsEnabledFor(handlingUnitsBL.getById(selectedHuId)); huQRCodesService.assign(huQRCode, selectedHuId, ensureSingleAssignment); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Assign_QRCode.java
1
请完成以下Java代码
protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } public String getOuterOrderBy() { String outerOrderBy = getOrderBy(); if (outerOrderBy == null || outerOrderBy.isEmpty()) { return "ID_ asc"; } else if (outerOrderBy.contains(".")) { return outerOrderBy.substring(outerOrderBy.lastIndexOf(".") + 1); } else { return outerOrderBy; } } private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) {
List<QueryVariableValue> values = new ArrayList<QueryVariableValue>(); if (variables == null) { return values; } for (VariableQueryParameterDto variable : variables) { QueryVariableValue value = new QueryVariableValue( variable.getName(), resolveVariableValue(variable.getValue()), ConditionQueryParameterDto.getQueryOperator(variable.getOperator()), false); value.initialize(variableTypes, dbType); values.add(value); } return values; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\AbstractProcessInstanceQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public void setServlet(Servlet servlet) { this.servlet = servlet; } /** * Determine the session timeout. If no timeout is configured, the * {@code fallbackTimeout} is used. * @param fallbackTimeout a fallback timeout value if the timeout isn't configured * @return the session timeout * @deprecated since 4.0.1 for removal in 4.2.0 in favor of {@link SessionTimeout} */ @Deprecated(since = "4.0.1", forRemoval = true) public Duration determineTimeout(Supplier<Duration> fallbackTimeout) { return (this.timeout != null) ? this.timeout : fallbackTimeout.get(); } /** * Servlet-related properties. */ public static class Servlet { /** * Session repository filter order. */ private int filterOrder = SessionRepositoryFilter.DEFAULT_ORDER; /** * Session repository filter dispatcher types. */ private Set<DispatcherType> filterDispatcherTypes = new HashSet<>(
Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); public int getFilterOrder() { return this.filterOrder; } public void setFilterOrder(int filterOrder) { this.filterOrder = filterOrder; } public Set<DispatcherType> getFilterDispatcherTypes() { return this.filterDispatcherTypes; } public void setFilterDispatcherTypes(Set<DispatcherType> filterDispatcherTypes) { this.filterDispatcherTypes = filterDispatcherTypes; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionProperties.java
2
请在Spring Boot框架中完成以下Java代码
private ItemMetadata findMatchingItemMetadata(ItemMetadata metadata) { List<ItemMetadata> candidates = this.items.get(metadata.getName()); if (candidates == null || candidates.isEmpty()) { return null; } candidates = new ArrayList<>(candidates); candidates.removeIf((itemMetadata) -> !itemMetadata.hasSameType(metadata)); if (candidates.size() > 1 && metadata.getType() != null) { candidates.removeIf((itemMetadata) -> !metadata.getType().equals(itemMetadata.getType())); } if (candidates.size() == 1) { return candidates.get(0); } for (ItemMetadata candidate : candidates) { if (nullSafeEquals(candidate.getSourceType(), metadata.getSourceType())) { return candidate; } } return null; } private boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } return o1 != null && o1.equals(o2); }
public static String nestedPrefix(String prefix, String name) { String nestedPrefix = (prefix != null) ? prefix : ""; String dashedName = ConventionUtils.toDashedCase(name); nestedPrefix += nestedPrefix.isEmpty() ? dashedName : "." + dashedName; return nestedPrefix; } private static <T extends Comparable<T>> List<T> flattenValues(Map<?, List<T>> map) { List<T> content = new ArrayList<>(); for (List<T> values : map.values()) { content.addAll(values); } Collections.sort(content); return content; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(String.format("items: %n")); this.items.values().forEach((itemMetadata) -> result.append("\t").append(String.format("%s%n", itemMetadata))); return result.toString(); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ConfigurationMetadata.java
2
请完成以下Java代码
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) { return VERSION_DEFAULT; } @Override public int retrieveLastLineNo(final DocumentQuery query) { throw new UnsupportedOperationException(); } private static final class ProcessInfoParameterDocumentValuesSupplier implements DocumentValuesSupplier { private final DocumentId adPInstanceId; private final Map<String, ProcessInfoParameter> processInfoParameters; public ProcessInfoParameterDocumentValuesSupplier(final DocumentId adPInstanceId, final Map<String, ProcessInfoParameter> processInfoParameters) { this.adPInstanceId = adPInstanceId; this.processInfoParameters = processInfoParameters;
} @Override public DocumentId getDocumentId() { return adPInstanceId; } @Override public String getVersion() { return VERSION_DEFAULT; } @Override public Object getValue(final DocumentFieldDescriptor parameterDescriptor) { return extractParameterValue(processInfoParameters, parameterDescriptor); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessParametersRepository.java
1
请完成以下Java代码
public String getUrlExpression() { return urlExpression; } public void setUrlExpression(String urlExpression) { this.urlExpression = urlExpression; } public boolean isLowerCaseServiceId() { return lowerCaseServiceId; } public void setLowerCaseServiceId(boolean lowerCaseServiceId) { this.lowerCaseServiceId = lowerCaseServiceId; } public List<PredicateDefinition> getPredicates() { return predicates; } public void setPredicates(List<PredicateDefinition> predicates) { this.predicates = predicates; } public List<FilterDefinition> getFilters() { return filters;
} public void setFilters(List<FilterDefinition> filters) { this.filters = filters; } @Override public String toString() { return new ToStringCreator(this).append("enabled", enabled) .append("routeIdPrefix", routeIdPrefix) .append("includeExpression", includeExpression) .append("urlExpression", urlExpression) .append("lowerCaseServiceId", lowerCaseServiceId) .append("predicates", predicates) .append("filters", filters) .toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryLocatorProperties.java
1
请完成以下Java代码
public boolean isIncl() { return incl; } /** * Sets the value of the incl property. * */ public void setIncl(boolean value) { this.incl = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */
public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = 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\CreditLine2.java
1
请完成以下Java代码
private static class Sync extends AbstractQueuedSynchronizer { public Sync(int count) { if (count <= 0) { throw new IllegalArgumentException("count must large than zero."); } setState(count); } @Override protected int tryAcquireShared(int arg) { int count = getState(); if (count > 0 && compareAndSetState(count, count - arg)) { setExclusiveOwnerThread(Thread.currentThread()); return count; } return -1; } @Override protected boolean tryReleaseShared(int arg) { for (; ; ) { // 通过循环和CAS来保证安全的释放锁 int count = getState(); if (compareAndSetState(count, count + arg)) { setExclusiveOwnerThread(null); return true; } } } @Override protected boolean isHeldExclusively() { return getState() <= 0; } public Condition newCondition() { return new ConditionObject(); } } private Sync sync; /** * @param count 能同时获取到锁的线程数 */ public SharedLock(int count) { this.sync = new Sync(count); } @Override public void lock() { sync.acquireShared(1); } @Override public void lockInterruptibly() throws InterruptedException { sync.acquireSharedInterruptibly(1); } @Override public boolean tryLock() { try { return sync.tryAcquireSharedNanos(1, 100L); } catch (InterruptedException e) { return false; } } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(time)); }
@Override public void unlock() { sync.releaseShared(1); } @Override public Condition newCondition() { return sync.newCondition(); } public static void main(String[] args) { final Lock lock = new SharedLock(5); // 启动10个线程 for (int i = 0; i < 100; i++) { new Thread(() -> { lock.lock(); try { System.out.println(Thread.currentThread().getName()); Thread.sleep(1000); } catch (Exception e) { } finally { lock.unlock(); } }).start(); } // 每隔1秒换行 for (int i = 0; i < 20; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\SharedLock.java
1
请完成以下Java代码
public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Included_Val_Rule_ID. @param Included_Val_Rule_ID Validation rule to be included. */ public void setIncluded_Val_Rule_ID (int Included_Val_Rule_ID) { if (Included_Val_Rule_ID < 1) set_ValueNoCheck (COLUMNNAME_Included_Val_Rule_ID, null); else set_ValueNoCheck (COLUMNNAME_Included_Val_Rule_ID, Integer.valueOf(Included_Val_Rule_ID)); } /** Get Included_Val_Rule_ID. @return Validation rule to be included. */ public int getIncluded_Val_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Included_Val_Rule_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ public void setSeqNo (String SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ public String getSeqNo () { return (String)get_Value(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule_Included.java
1
请在Spring Boot框架中完成以下Java代码
public class LoginController { private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Reference private UserService userService; /** * @return */ @RequestMapping(value = "/login", method = RequestMethod.POST) public ResponseEntity login() { //TODO:登录日志。 ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal(); user.setToken(SecurityUtils.getSubject().getSession().getId().toString()); return ResponseEntity.ok(user); } /** * 获取当前登录人的登录信息,包括拥有的角色、权限等。 * * @return */ @GetMapping("/logininfo") public ResponseEntity loginInfo() { ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal(); Map<String, Object> map = new HashMap<>(); Set<String> permissions = Sets.newHashSet();
//TODO 获取当前用户所有的权限和角色 User user = userService.getById(shiroUser.getUserId().intValue()); map.put("roleList", user.getRoles()); map.put("permissionList", permissions); map.put("userId", shiroUser.getUserId()); map.put("username", shiroUser.getLoginName()); return ResponseEntity.ok(map); } /** * 注销 * @return */ @PostMapping("/logout") public ResponseEntity logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return ResponseEntity.ok(); } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\controller\LoginController.java
2
请完成以下Java代码
public String getKey() { return this.key; } /** * Return the key as a lowercase value. * @return the key as a lowercase value * @since 3.5.0 */ public String getLowerCaseKey() { String result = this.lowerCaseKey; if (result == null) { result = this.key.toLowerCase(Locale.getDefault()); this.lowerCaseKey = result; } return result; } /** * Return the value of the data. * @return the data value */
public @Nullable Object getValue() { return this.value; } /** * Return a new {@link SanitizableData} instance with sanitized value. * @return a new sanitizable data instance. * @since 3.1.0 */ public SanitizableData withSanitizedValue() { return withValue(SANITIZED_VALUE); } /** * Return a new {@link SanitizableData} instance with a different value. * @param value the new value (often {@link #SANITIZED_VALUE} * @return a new sanitizable data instance */ public SanitizableData withValue(@Nullable Object value) { return new SanitizableData(this.propertySource, this.key, value); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\SanitizableData.java
1
请完成以下Java代码
public void onError(Throwable t) { responseObserver.onError(t); } @Override public void onCompleted() { if (InjectError()) { responseObserver.onError(Status.INTERNAL.asException()); } else { responseObserver.onCompleted(); } } }; } @Override public void serverStreamingRpc(ServerStreamingRequest request, StreamObserver<ServerStreamingResponse> responseObserver) { if (InjectError()) { responseObserver.onError(Status.INTERNAL.asException()); } else { responseObserver.onNext( ServerStreamingResponse.newBuilder().setMessage(request.getMessage()).build()); responseObserver.onCompleted(); } } @Override public StreamObserver<BidiStreamingRequest> bidiStreamingRpc( StreamObserver<BidiStreamingResponse> responseObserver) { return new StreamObserver<>() { @Override public void onNext(BidiStreamingRequest value) { responseObserver.onNext( BidiStreamingResponse.newBuilder().setMessage(value.getMessage()).build()); }
@Override public void onError(Throwable t) { responseObserver.onError(t); } @Override public void onCompleted() { if (InjectError()) { responseObserver.onError(Status.INTERNAL.asException()); } else { responseObserver.onCompleted(); } } }; } }
repos\grpc-spring-master\examples\grpc-observability\backend\src\main\java\net\devh\boot\grpc\examples\observability\backend\ExampleServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class SoftDeletePerson { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "Emails", joinColumns = @JoinColumn(name = "id")) @Column(name = "emailId") @SoftDelete(strategy = SoftDeleteType.ACTIVE, converter = YesNoConverter.class) private List<String> emailIds; public String getName() { return name; }
public void setName(String name) { this.name = name; } public List<String> getEmailIds() { return emailIds; } public void setEmailIds(List<String> emailIds) { this.emailIds = emailIds; } @Override public String toString() { return "SoftDeletePerson{" + "id=" + id + ", name='" + name + '\'' + ", emailIds=" + emailIds + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\softdelete\model\SoftDeletePerson.java
2
请完成以下Java代码
public abstract class AbstractLanguage implements Language { private final String id; private final String jvmVersion; private final String sourceFileExtension; /** * Creates a new instance. * @param id the id * @param jvmVersion the JVM version * @param sourceFileExtension the source file extension */ protected AbstractLanguage(String id, String jvmVersion, String sourceFileExtension) { this.id = id; this.jvmVersion = (jvmVersion != null) ? jvmVersion : DEFAULT_JVM_VERSION; this.sourceFileExtension = sourceFileExtension; } @Override
public String id() { return this.id; } @Override public String jvmVersion() { return this.jvmVersion; } @Override public String sourceFileExtension() { return this.sourceFileExtension; } @Override public String toString() { return id(); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\AbstractLanguage.java
1
请在Spring Boot框架中完成以下Java代码
public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3 == null ? null : field3.trim(); } public String getField4() { return field4; } public void setField4(String field4) { this.field4 = field4 == null ? null : field4.trim(); } public String getField5() { return field5; } public void setField5(String field5) { this.field5 = field5 == null ? null : field5.trim(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(super.getId()); sb.append(", version=").append(super.getVersion()); sb.append(", createTime=").append(super.getCreateTime()); sb.append(", editor=").append(super.getEditor()); sb.append(", creater=").append(super.getCreater()); sb.append(", editTime=").append(super.getEditTime()); sb.append(", status=").append(super.getStatus()); sb.append(", productName=").append(productName);
sb.append(", merchantOrderNo=").append(merchantOrderNo); sb.append(", orderAmount=").append(orderAmount); sb.append(", orderFrom=").append(orderFrom); sb.append(", merchantName=").append(merchantName); sb.append(", merchantNo=").append(merchantNo); sb.append(", orderTime=").append(orderTime); sb.append(", orderDate=").append(orderDate); sb.append(", orderIp=").append(orderIp); sb.append(", orderRefererUrl=").append(orderRefererUrl); sb.append(", returnUrl=").append(returnUrl); sb.append(", notifyUrl=").append(notifyUrl); sb.append(", cancelReason=").append(cancelReason); sb.append(", orderPeriod=").append(orderPeriod); sb.append(", expireTime=").append(expireTime); sb.append(", payWayCode=").append(payWayCode); sb.append(", payWayName=").append(payWayName); sb.append(", remark=").append(remark); sb.append(", trxType=").append(trxType); sb.append(", payTypeCode=").append(payTypeCode); sb.append(", payTypeName=").append(payTypeName); sb.append(", fundIntoType=").append(fundIntoType); sb.append(", isRefund=").append(isRefund); sb.append(", refundTimes=").append(refundTimes); sb.append(", successRefundAmount=").append(successRefundAmount); sb.append(", trxNo=").append(trxNo); sb.append(", field1=").append(field1); sb.append(", field2=").append(field2); sb.append(", field3=").append(field3); sb.append(", field4=").append(field4); sb.append(", field5=").append(field5); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpTradePaymentOrder.java
2
请完成以下Java代码
public class EventGatewayJsonConverter extends BaseBpmnJsonConverter { 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_GATEWAY_EVENT, EventGatewayJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { convertersToJsonMap.put(EventGateway.class, EventGatewayJsonConverter.class); }
protected String getStencilId(BaseElement baseElement) { return STENCIL_GATEWAY_EVENT; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {} protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { EventGateway gateway = new EventGateway(); return gateway; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\EventGatewayJsonConverter.java
1
请完成以下Java代码
public static int labeledBreak() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; compare: while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (name.equalsIgnoreCase(searchName)) { counter++; break compare; } } } return counter; } public static int unlabeledContinue() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (!name.equalsIgnoreCase(searchName)) { continue;
} counter++; } } return counter; } public static int labeledContinue() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; compare: while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (name.equalsIgnoreCase(searchName)) { counter++; continue compare; } } } return counter; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\breakcontinue\BreakContinue.java
1
请完成以下Java代码
public int size() { throw new UnsupportedOperationException(getClass().getName()+".size() is not supported."); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(getClass().getName()+".isEmpty() is not supported."); } @Override public boolean containsKey(Object key) { throw new UnsupportedOperationException(getClass().getName()+".containsKey() is not supported."); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(getClass().getName()+".containsValue() is not supported."); } @Override public Object remove(Object key) { throw new UnsupportedOperationException(getClass().getName()+".remove is unsupported. Use " + getClass().getName() + ".put(key, null)"); } @Override public void clear() { throw new UnsupportedOperationException(getClass().getName()+".clear() is not supported."); } @Override
public Set<String> keySet() { throw new UnsupportedOperationException(getClass().getName()+".keySet() is not supported."); } @Override public Collection<Object> values() { throw new UnsupportedOperationException(getClass().getName()+".values() is not supported."); } @Override public Set<java.util.Map.Entry<String, Object>> entrySet() { throw new UnsupportedOperationException(getClass().getName()+".entrySet() is not supported."); } public VariableContext asVariableContext() { throw new UnsupportedOperationException(getClass().getName()+".asVariableContext() is not supported."); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\AbstractVariableMap.java
1
请完成以下Java代码
public static String toRestApiTypeName(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } public static String fromRestApiTypeName(String name) { return name.substring(0, 1).toLowerCase() + name.substring(1); } public static VariableValueDto fromFormPart(String type, FormPart binaryDataFormPart) { VariableValueDto dto = new VariableValueDto(); dto.type = type; dto.value = binaryDataFormPart.getBinaryContent(); if (ValueType.FILE.getName().equals(fromRestApiTypeName(type))) { String contentType = binaryDataFormPart.getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } dto.valueInfo = new HashMap<>(); dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_NAME, binaryDataFormPart.getFileName()); MimeType mimeType = null; try { mimeType = new MimeType(contentType); } catch (MimeTypeParseException e) {
throw new RestException(Status.BAD_REQUEST, "Invalid mime type given"); } dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_MIME_TYPE, mimeType.getBaseType()); String encoding = mimeType.getParameter("encoding"); if (encoding != null) { dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_ENCODING, encoding); } String transientString = mimeType.getParameter("transient"); boolean isTransient = Boolean.parseBoolean(transientString); if (isTransient) { dto.valueInfo.put(AbstractValueTypeImpl.VALUE_INFO_TRANSIENT, isTransient); } } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\VariableValueDto.java
1
请完成以下Java代码
public UserDashboardItemDataResponse getItemData(@NonNull final UserDashboardItemDataRequest request) { final UserDashboard dashboard = getDashboard(); final UserDashboardItem dashboardItem = dashboard.getItemById(request.getWidgetType(), request.getItemId()); final KPIDataContext context = request.getContext(); return getItemData(dashboardItem, context); } private UserDashboardItemDataResponse getItemData( @NonNull final UserDashboardItem item, @NonNull final KPIDataContext context) { KPIDataRequest request = null; try { request = toKPIDataRequest(item, context); final KPIDataResult kpiData = kpiDataProvider.getKPIData(request); return UserDashboardItemDataResponse.ok(dashboardId, item.getId(), kpiData); } catch (@NonNull final Exception ex) { logger.warn("Failed computing KPI data for request={}, item={}, context={}.", request, item, context, ex); final ITranslatableString errorMessage = AdempiereException.isUserValidationError(ex) ? AdempiereException.extractMessageTrl(ex) : TranslatableStrings.adMessage(KPIDataProvider.MSG_FailedLoadingKPI); return UserDashboardItemDataResponse.error(dashboardId, item.getId(), WebuiError.of(ex, errorMessage)); } } private static KPIDataRequest toKPIDataRequest( final @NonNull UserDashboardItem item,
final @NonNull KPIDataContext context) { final KPIId kpiId = item.getKPIId(); final KPITimeRangeDefaults timeRangeDefaults = item.getTimeRangeDefaults(); return KPIDataRequest.builder() .kpiId(kpiId) .timeRangeDefaults(timeRangeDefaults) .context(context) .build(); } private UserDashboard getDashboard() { return userDashboardRepository.getUserDashboardById(dashboardId); } public Optional<KPIZoomIntoDetailsInfo> getZoomIntoDetailsInfo(@NonNull final UserDashboardItemDataRequest request) { final UserDashboard dashboard = getDashboard(); final UserDashboardItem dashboardItem = dashboard.getItemById(request.getWidgetType(), request.getItemId()); final KPIDataContext context = request.getContext(); return kpiDataProvider.getZoomIntoDetailsInfo(toKPIDataRequest(dashboardItem, context)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardDataProvider.java
1
请完成以下Java代码
public UserTask getUserTask() { return userTask; } public void setUserTask(UserTask userTask) { this.userTask = userTask; } public DelegateExecution getExecution() { return execution; } public void setExecution(DelegateExecution execution) { this.execution = execution; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDueDate() { return dueDate; } public void setDueDate(String dueDate) { this.dueDate = dueDate; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; }
public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\CreateUserTaskBeforeContext.java
1
请在Spring Boot框架中完成以下Java代码
public HistoryJobQuery locked() { this.onlyLocked = true; return this; } @Override public HistoryJobQuery unlocked() { this.onlyUnlocked = true; return this; } @Override public HistoryJobQuery withoutScopeType() { this.withoutScopeType = true; return this; } // sorting ////////////////////////////////////////// @Override public HistoryJobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } @Override public HistoryJobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } @Override public HistoryJobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobCountByQueryCriteria(this); } @Override public List<HistoryJob> executeList(CommandContext commandContext) { return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobsByQueryCriteria(this); } // getters ////////////////////////////////////////// public String getHandlerType() { return this.handlerType; } public Collection<String> getHandlerTypes() { return handlerTypes; } public Date getNow() { return jobServiceConfiguration.getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getScopeType() { return scopeType; } public String getTenantId() { return tenantId;
} public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getLockOwner() { return lockOwner; } public boolean isOnlyLocked() { return onlyLocked; } public boolean isOnlyUnlocked() { return onlyUnlocked; } public boolean isWithoutScopeType() { return withoutScopeType; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public ApplicationRunner init() { return args -> { System.out.println("\n\nFetch authors with books via query builder mechanism"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksQueryBuilderMechanism(); System.out.println("\n\nFetch authors with books via JPQL query"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksViaQuery(); System.out.println("\n\nFetch authors with books via JOIN FETCH"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksViaJoinFetch(); System.out.println("\n\nFetch authors with books via query and simple DTO"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksViaQuerySimpleDto();
System.out.println("\n\nFetch authors with books via array of objects:"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksViaArrayOfObjects(); System.out.println("\n\nFetch authors with books via array of objects and transform to DTO:"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksViaArrayOfObjectsAndTransformToDto(); System.out.println("\n\nFetch authors with books via JdbcTemplate as DTO:"); System.out.println("-----------------------------------------------------------------"); bookstoreService.fetchAuthorsWithBooksViaJdbcTemplateToDto(); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootProjectionAndCollections\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public Optional<I_AD_User> getCounterpartUser( @NonNull final UserId sourceUserId, @NonNull final OrgId targetOrgId) { final OrgMappingId orgMappingId = getOrgMappingId(sourceUserId).orElse(null); if (orgMappingId == null) { return Optional.empty(); } final UserId targetUserId = queryBL.createQueryBuilder(I_AD_User.class) .addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_Mapping_ID, orgMappingId) .addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_ID, targetOrgId) .orderByDescending(I_AD_User.COLUMNNAME_AD_User_ID) .create() .firstId(UserId::ofRepoIdOrNull); if (targetUserId == null) { return Optional.empty(); } return Optional.of(getById(targetUserId)); }
@Override public ImmutableSet<UserId> retrieveUsersByJobId(@NonNull final JobId jobId) { return queryBL.createQueryBuilder(I_AD_User.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User.COLUMNNAME_C_Job_ID, jobId) .create() .idsAsSet(UserId::ofRepoId); } private Optional<OrgMappingId> getOrgMappingId(@NonNull final UserId sourceUserId) { final I_AD_User sourceUserRecord = getById(sourceUserId); return OrgMappingId.optionalOfRepoId(sourceUserRecord.getAD_Org_Mapping_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserDAO.java
1
请完成以下Java代码
public class CustomAuthorizationManager<T> implements AuthorizationManager<MethodInvocation> { private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); @Override public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation methodInvocation) { if (hasAuthentication(authentication.get())) { Policy policyAnnotation = AnnotationUtils.findAnnotation(methodInvocation.getMethod(), Policy.class); SecurityUser user = (SecurityUser) authentication.get() .getPrincipal(); return new AuthorizationDecision(Optional.ofNullable(policyAnnotation) .map(Policy::value)
.filter(policy -> policy == PolicyEnum.OPEN || (policy == PolicyEnum.RESTRICTED && user.hasAccessToRestrictedPolicy())) .isPresent()); } return new AuthorizationDecision(false); } private boolean hasAuthentication(Authentication authentication) { return authentication != null && isNotAnonymous(authentication) && authentication.isAuthenticated(); } private boolean isNotAnonymous(Authentication authentication) { return !this.trustResolver.isAnonymous(authentication); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-4\src\main\java\com\baeldung\enablemethodsecurity\authorization\CustomAuthorizationManager.java
1
请完成以下Java代码
public List<Artifact> getGlobalArtifacts() { return globalArtifacts; } public void setGlobalArtifacts(List<Artifact> globalArtifacts) { this.globalArtifacts = globalArtifacts; } public void addNamespace(String prefix, String uri) { namespaceMap.put(prefix, uri); } public boolean containsNamespacePrefix(String prefix) { return namespaceMap.containsKey(prefix); } public String getNamespace(String prefix) { return namespaceMap.get(prefix); } public Map<String, String> getNamespaces() { return namespaceMap; } public String getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; } public String getSourceSystemId() { return sourceSystemId; } public void setSourceSystemId(String sourceSystemId) {
this.sourceSystemId = sourceSystemId; } public List<String> getUserTaskFormTypes() { return userTaskFormTypes; } public void setUserTaskFormTypes(List<String> userTaskFormTypes) { this.userTaskFormTypes = userTaskFormTypes; } public List<String> getStartEventFormTypes() { return startEventFormTypes; } public void setStartEventFormTypes(List<String> startEventFormTypes) { this.startEventFormTypes = startEventFormTypes; } @JsonIgnore public Object getEventSupport() { return eventSupport; } public void setEventSupport(Object eventSupport) { this.eventSupport = eventSupport; } public String getStartFormKey(String processId) { FlowElement initialFlowElement = getProcessById(processId).getInitialFlowElement(); if (initialFlowElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) initialFlowElement; return startEvent.getFormKey(); } return null; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BpmnModel.java
1
请完成以下Java代码
private <T> T getByType(CamelContext ctx, Class<T> kls) { Map<String, T> looked = ctx.getRegistry().findByTypeWithName(kls); if (looked.isEmpty()) { return null; } return looked.values().iterator().next(); } @Override protected Endpoint createEndpoint(String s, String s1, Map<String, Object> parameters) throws Exception { FlowableEndpoint ae = new FlowableEndpoint(s, getCamelContext()); ae.setComponent(this); ae.setIdentityService(identityService); ae.setRuntimeService(runtimeService); ae.setRepositoryService(repositoryService); ae.setManagementService(managementService); ae.setCopyVariablesToProperties(this.copyVariablesToProperties); ae.setCopyVariablesToBodyAsMap(this.copyVariablesToBodyAsMap); ae.setCopyCamelBodyToBody(this.copyCamelBodyToBody); Map<String, Object> returnVars = PropertiesHelper.extractProperties(parameters, "var.return."); if (returnVars != null && returnVars.size() > 0) { ae.getReturnVarMap().putAll(returnVars); } return ae; } public boolean isCopyVariablesToProperties() { return copyVariablesToProperties;
} public void setCopyVariablesToProperties(boolean copyVariablesToProperties) { this.copyVariablesToProperties = copyVariablesToProperties; } public boolean isCopyCamelBodyToBody() { return copyCamelBodyToBody; } public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) { this.copyCamelBodyToBody = copyCamelBodyToBody; } public boolean isCopyVariablesToBodyAsMap() { return copyVariablesToBodyAsMap; } public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) { this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap; } }
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableComponent.java
1
请完成以下Java代码
public int getC_ReferenceNo_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Manuell. @param IsManual Dies ist ein manueller Vorgang */ @Override public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return Dies ist ein manueller Vorgang */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenznummer. @param ReferenceNo
Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public void setReferenceNo (java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } /** Get Referenznummer. @return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public java.lang.String getReferenceNo () { return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo.java
1
请完成以下Java代码
protected String replacePlaceholder(String data, String appName, String engineName, String applicationPath, String contextPath, String cspNonce) { return data.replace(APP_ROOT_PLACEHOLDER, contextPath + applicationPath) .replace(BASE_PLACEHOLDER, String.format("%s%s/app/%s/%s/", contextPath, applicationPath, appName, engineName)) .replace(PLUGIN_PACKAGES_PLACEHOLDER, createPluginPackagesStr(appName, applicationPath, contextPath)) .replace(PLUGIN_DEPENDENCIES_PLACEHOLDER, createPluginDependenciesStr(appName)) .replace(CSP_NONCE_PLACEHOLDER, cspNonce == null ? "" : String.format("nonce=\"%s\"", cspNonce)); } protected <T extends AppPlugin> CharSequence createPluginPackagesStr(String appName, String applicationPath, String contextPath) { final List<T> plugins = getPlugins(appName); StringBuilder builder = new StringBuilder(); for (T plugin : plugins) { if (builder.length() > 0) { builder.append(", ").append("\n"); } String pluginId = plugin.getId(); String definition = String.format(pluginPackageFormat, appName, pluginId, contextPath, applicationPath, appName, pluginId); builder.append(definition); } return "[" + builder.toString() + "]"; } protected <T extends AppPlugin> CharSequence createPluginDependenciesStr(String appName) { final List<T> plugins = getPlugins(appName); StringBuilder builder = new StringBuilder(); for (T plugin : plugins) { if (builder.length() > 0) { builder.append(", ").append("\n"); } String pluginId = plugin.getId(); String definition = String.format(pluginDependencyFormat, appName, pluginId, appName, pluginId);
builder.append(definition); } return "[" + builder.toString() + "]"; } @SuppressWarnings("unchecked") protected <T extends AppPlugin> List<T> getPlugins(String appName) { if (COCKPIT_APP_NAME.equals(appName)) { return (List<T>) cockpitRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else if (ADMIN_APP_NAME.equals(appName)) { return (List<T>) adminRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else if (TASKLIST_APP_NAME.equals(appName)) { return (List<T>) tasklistRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else if (WELCOME_APP_NAME.equals(appName)) { return (List<T>) welcomeRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else { return Collections.emptyList(); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\engine\ProcessEnginesFilter.java
1
请在Spring Boot框架中完成以下Java代码
public void executeDeadLetterJobAction(@ApiParam(name = "jobId") @PathVariable String jobId, @RequestBody RestActionRequest actionRequest) { if (actionRequest == null || !(MOVE_ACTION.equals(actionRequest.getAction()) || MOVE_TO_HISTORY_JOB_ACTION.equals(actionRequest.getAction()))) { throw new FlowableIllegalArgumentException("Invalid action, only 'move' or 'moveToHistoryJob' is supported."); } Job deadLetterJob = getDeadLetterJobById(jobId); if (MOVE_ACTION.equals(actionRequest.getAction())) { if (restApiInterceptor != null) { restApiInterceptor.moveDeadLetterJob(deadLetterJob, MOVE_ACTION); } /* * Note that the jobType is checked to know which kind of move that needs to be done. * The MOVE_TO_HISTORY_JOB_ACTION allows to specifically force the move to a history job and trigger the else part below. */ try { if (HistoryJobEntity.HISTORY_JOB_TYPE.equals(deadLetterJob.getJobType())) { managementService.moveDeadLetterJobToHistoryJob(deadLetterJob.getId(), cmmnEngineConfiguration.getAsyncExecutorNumberOfRetries()); } else { managementService.moveDeadLetterJobToExecutableJob(deadLetterJob.getId(), cmmnEngineConfiguration.getAsyncExecutorNumberOfRetries()); } } catch (FlowableObjectNotFoundException e) { // Re-throw to have consistent error-messaging across REST-API throw new FlowableObjectNotFoundException("Could not find a dead letter job with id '" + jobId + "'.", Job.class); }
} else if (MOVE_TO_HISTORY_JOB_ACTION.equals(actionRequest.getAction())) { if (restApiInterceptor != null) { restApiInterceptor.moveDeadLetterJob(deadLetterJob, MOVE_TO_HISTORY_JOB_ACTION); } try { managementService.moveDeadLetterJobToHistoryJob(deadLetterJob.getId(), cmmnEngineConfiguration.getAsyncHistoryExecutorNumberOfRetries()); } catch (FlowableObjectNotFoundException e) { // Re-throw to have consistent error-messaging across REST-api throw new FlowableObjectNotFoundException("Could not find a dead letter job with id '" + jobId + "'.", Job.class); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobResource.java
2
请在Spring Boot框架中完成以下Java代码
public JwtTokenUtil jwtTokenUtil() { return new JwtTokenUtil(); } @Bean public RestfulAccessDeniedHandler restfulAccessDeniedHandler() { return new RestfulAccessDeniedHandler(); } @Bean public RestAuthenticationEntryPoint restAuthenticationEntryPoint() { return new RestAuthenticationEntryPoint(); } @Bean public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){ return new JwtAuthenticationTokenFilter(); } @ConditionalOnBean(name = "dynamicSecurityService") @Bean
public DynamicAccessDecisionManager dynamicAccessDecisionManager() { return new DynamicAccessDecisionManager(); } @ConditionalOnBean(name = "dynamicSecurityService") @Bean public DynamicSecurityMetadataSource dynamicSecurityMetadataSource() { return new DynamicSecurityMetadataSource(); } @ConditionalOnBean(name = "dynamicSecurityService") @Bean public DynamicSecurityFilter dynamicSecurityFilter(){ return new DynamicSecurityFilter(); } }
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\config\CommonSecurityConfig.java
2
请完成以下Java代码
public final void setClazz(final Class<T> clazzToSet) { this.clazz = clazzToSet; } public T findOne(final long id) { return entityManager.find(clazz, id); } @SuppressWarnings("unchecked") public List<T> findAll() { return entityManager.createQuery("from " + clazz.getName()).getResultList(); } public void create(final T entity) { entityManager.persist(entity); } public T update(final T entity) { return entityManager.merge(entity); } public void delete(final T entity) { entityManager.remove(entity); } public void deleteById(final long entityId) { final T entity = findOne(entityId); delete(entity); } public long countAllRowsUsingHibernateCriteria() { Session session = entityManager.unwrap(Session.class);
Criteria criteria = session.createCriteria(clazz); criteria.setProjection(Projections.rowCount()); Long count = (Long) criteria.uniqueResult(); return count != null ? count : 0L; } public long getFooCountByBarNameUsingHibernateCriteria(String barName) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } public long getFooCountByBarNameAndFooNameUsingHibernateCriteria(String barName, String fooName) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.add(Restrictions.eq("name", fooName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernate\cache\dao\AbstractJpaDAO.java
1
请完成以下Java代码
byte[] getBuffer() { return _buf; } /** * 取字节 * @param id 字节下标 * @return 字节 */ byte get(int id) { return _buf[id]; } /** * 设置值 * @param id 下标 * @param value 值 */ void set(int id, byte value) { _buf[id] = value; } /** * 是否为空 * @return true表示为空 */ boolean empty() { return (_size == 0); } /** * 缓冲区大小 * @return 大小 */ int size() { return _size; } /** * 清空缓存 */ void clear() { resize(0); _buf = null; _size = 0; _capacity = 0; } /** * 在末尾加一个值 * @param value 值 */ void add(byte value) { if (_size == _capacity) { resizeBuf(_size + 1); } _buf[_size++] = value; } /** * 将最后一个值去掉 */ void deleteLast() { --_size; } /** * 重设大小 * @param size 大小 */ void resize(int size) { if (size > _capacity) { resizeBuf(size); } _size = size; } /** * 重设大小,并且在末尾加一个值 * @param size 大小 * @param value 值 */ void resize(int size, byte value) { if (size > _capacity) { resizeBuf(size); } while (_size < size) { _buf[_size++] = value; } } /** * 增加容量
* @param size 容量 */ void reserve(int size) { if (size > _capacity) { resizeBuf(size); } } /** * 设置缓冲区大小 * @param size 大小 */ private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) { capacity = size; } else { capacity = 1; while (capacity < size) { capacity <<= 1; } } byte[] buf = new byte[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } /** * 缓冲区 */ private byte[] _buf; /** * 大小 */ private int _size; /** * 容量 */ private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoBytePool.java
1
请完成以下Java代码
public HUDistributeBuilder setVHUToDistribute(final I_M_HU vhuToDistribute) { _vhuToDistribute = vhuToDistribute; return this; } private I_M_HU getVHUToDistribute() { Check.assumeNotNull(_vhuToDistribute, "_vhuToDistribute not null"); return _vhuToDistribute; } public HUDistributeBuilder setTUsToDistributeOn(final Collection<I_M_HU> tusToDistributeOn) { _tusToDistributeOn = tusToDistributeOn; return this; } private Collection<I_M_HU> getTUsToDistributeOn() { Check.assumeNotEmpty(_tusToDistributeOn, "_tusToDistributeOn not empty"); return _tusToDistributeOn;
} public HUDistributeBuilder setQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { _qtyCUsPerTU = qtyCUsPerTU; return this; } private BigDecimal getQtyCUsPerTU() { Check.assumeNotNull(_qtyCUsPerTU, "_qtyCUsPerTU not null"); Check.assume(_qtyCUsPerTU.signum() > 0, "Qty CUs/TU > 0"); return _qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUDistributeBuilder.java
1
请在Spring Boot框架中完成以下Java代码
private static ScannableCodeFormat fromRecord( @NotNull final I_C_ScannableCode_Format formatRecord, @NotNull final List<I_C_ScannableCode_Format_Part> partRecords) { try { return ScannableCodeFormat.builder() .id(extactScannableCodeFormatId(formatRecord)) .name(formatRecord.getName()) .description(formatRecord.getDescription()) .parts(partRecords.stream() .map(ScannableCodeFormatLoaderAndSaver::fromRecord) .collect(ImmutableList.toImmutableList())) .build(); } catch (Exception ex) { if (ex instanceof AdempiereException && AdempiereException.isUserValidationError(ex)) { throw ex; } else { throw new AdempiereException("Invalid format: " + formatRecord.getName() + " (ID=" + formatRecord.getC_ScannableCode_Format_ID() + ")", ex); } } } private static ScannableCodeFormatPart fromRecord(@NotNull final I_C_ScannableCode_Format_Part record) { final ScannableCodeFormatPartType type = ScannableCodeFormatPartType.ofCode(record.getDataType()); final ScannableCodeFormatPart.ScannableCodeFormatPartBuilder builder = ScannableCodeFormatPart.builder() .startPosition(record.getStartNo()) .endPosition(record.getEndNo()) .type(type); if (type == ScannableCodeFormatPartType.Constant) { builder.constantValue(record.getConstantValue()); } else if (type.isDate()) { builder.dateFormat(PatternedDateTimeFormatter.ofNullablePattern((record.getDataFormat()))); } return builder.build(); }
public ScannableCodeFormat create(@NotNull final ScannableCodeFormatCreateRequest request) { final I_C_ScannableCode_Format record = InterfaceWrapperHelper.newInstance(I_C_ScannableCode_Format.class); record.setName(request.getName()); record.setDescription(request.getDescription()); InterfaceWrapperHelper.saveRecord(record); addToCache(record); final ScannableCodeFormatId formatId = ScannableCodeFormatId.ofRepoId(record.getC_ScannableCode_Format_ID()); request.getParts().forEach(part -> createPart(part, formatId)); return getById(formatId); } private void createPart(@NotNull final ScannableCodeFormatCreateRequest.Part part, @NotNull final ScannableCodeFormatId formatId) { final I_C_ScannableCode_Format_Part record = InterfaceWrapperHelper.newInstance(I_C_ScannableCode_Format_Part.class); record.setC_ScannableCode_Format_ID(formatId.getRepoId()); record.setStartNo(part.getStartPosition()); record.setEndNo(part.getEndPosition()); record.setDataType(part.getType().getCode()); record.setDataFormat(PatternedDateTimeFormatter.toPattern(part.getDateFormat())); record.setConstantValue(part.getConstantValue()); record.setDecimalPointPosition(part.getDecimalPointPosition()); record.setDescription(part.getDescription()); InterfaceWrapperHelper.saveRecord(record); addToCache(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\repository\ScannableCodeFormatLoaderAndSaver.java
2
请完成以下Java代码
public JsonGetStatsResponse getStats( @RequestParam(name = "cacheName", required = false) @Nullable final String cacheName, @RequestParam(name = "minSize", required = false) @Nullable final Integer minSize, @RequestParam(name = "labels", required = false) @Nullable final String labels, @RequestParam(name = "orderBy", required = false) @Nullable final String orderByString) { assertAuth(); return getStats( JsonCacheStatsQuery.builder() .cacheName(cacheName) .minSize(minSize) .labels(labels) .orderByString(orderByString) .build() ); } @PostMapping("/stats") public JsonGetStatsResponse getStats(@RequestBody @NonNull final JsonCacheStatsQuery jsonQuery) { assertAuth(); final CCacheStatsPredicate filter = jsonQuery.toCCacheStatsPredicate(); final CCacheStatsOrderBy orderBy = jsonQuery.toCCacheStatsOrderBy().orElse(DEFAULT_ORDER_BY); return cacheMgt.streamStats(filter) .sorted(orderBy) .map(JsonCacheStats::of) .collect(JsonGetStatsResponse.collect()); } @GetMapping("/byId/{cacheId}") public JsonCache getById( @PathVariable("cacheId") final String cacheIdStr, @RequestParam(name = "limit", required = false, defaultValue = "100") final int limit) { assertAuth(); final long cacheId = Long.parseLong(cacheIdStr); final CacheInterface cacheInterface = cacheMgt.getById(cacheId) .orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId)); if (cacheInterface instanceof CCache) { return JsonCache.of((CCache<?, ?>)cacheInterface, limit); } else { throw new AdempiereException("Cache of type " + cacheInterface.getClass().getSimpleName() + " is not supported"); } }
@GetMapping("/byId/{cacheId}/reset") public void resetCacheById(@PathVariable("cacheId") final String cacheIdStr) { assertAuth(); final long cacheId = Long.parseLong(cacheIdStr); final CacheInterface cacheInterface = cacheMgt.getById(cacheId) .orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId)); cacheInterface.reset(); } @GetMapping("/remoteCacheInvalidationTableNames") public Set<String> getRemoteCacheInvalidationTableNames() { return cacheMgt.getTableNamesToBroadcast() .stream() .sorted() .collect(ImmutableSet.toImmutableSet()); } @GetMapping("/remoteCacheInvalidationTableNames/add") public void enableRemoteCacheInvalidationForTableName(@RequestParam("tableName") final String tableName) { cacheMgt.enableRemoteCacheInvalidationForTableName(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\CacheRestControllerTemplate.java
1
请完成以下Java代码
public void setProcessed(boolean processed) { super.setProcessed(processed); String sql = "UPDATE C_CashLine SET Processed='" + (processed ? "Y" : "N") + "' WHERE C_Cash_ID=" + getC_Cash_ID(); int noLine = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); m_lines = null; log.debug(processed + " - Lines=" + noLine); } // setProcessed /** * String Representation * * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("MCash["); sb.append(get_ID()) .append("-").append(getName()) .append(", Balance=").append(getBeginningBalance()) .append("->").append(getEndingBalance()) .append("]"); return sb.toString(); } // toString /************************************************************************* * Get Summary * * @return Summary of Document */ @Override public String getSummary() { StringBuffer sb = new StringBuffer(); sb.append(getName()); // : Total Lines = 123.00 (#1) sb.append(": ") .append(Msg.translate(getCtx(), "BeginningBalance")).append("=").append(getBeginningBalance()) .append(",") .append(Msg.translate(getCtx(), "EndingBalance")).append("=").append(getEndingBalance()) .append(" (#").append(getLines(false).length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) { sb.append(" - ").append(getDescription()); } return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getStatementDate()); } /** * Get Process Message * * @return clear text error message */ @Override
public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * * @return AD_User_ID */ @Override public int getDoc_User_ID() { return getCreatedBy(); } // getDoc_User_ID /** * Get Document Approval Amount * * @return amount difference */ @Override public BigDecimal getApprovalAmt() { return getStatementDifference(); } // getApprovalAmt /** * Get Currency * * @return Currency */ @Override public int getC_Currency_ID() { return getCashBook().getC_Currency_ID(); } // getC_Currency_ID /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MCash
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MCash.java
1
请完成以下Java代码
public class Person { private int id; @JsonbProperty("person-name") private String name; @JsonbProperty(nillable = true) private String email; @JsonbTransient private int age; @JsonbDateFormat("dd-MM-yyyy") private LocalDate registeredDate; private BigDecimal salary; public Person() { this(0, "", "", 0, LocalDate.now(), new BigDecimal(0)); } public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) { this.id = id; this.name = name; this.email = email; this.age = age; this.registeredDate = registeredDate; this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonbNumberFormat(locale = "en_US", value = "#0.0") public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public LocalDate getRegisteredDate() { return registeredDate; }
public void setRegisteredDate(LocalDate registeredDate) { this.registeredDate = registeredDate; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Person [id="); builder.append(id); builder.append(", name="); builder.append(name); builder.append(", email="); builder.append(email); builder.append(", age="); builder.append(age); builder.append(", registeredDate="); builder.append(registeredDate); builder.append(", salary="); builder.append(salary); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (id != other.id) return false; return true; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonb\Person.java
1
请完成以下Java代码
protected Appender<T> getAppenderOne() { return this.one; } protected Appender<T> getAppenderTwo() { return this.two; } @Override public void setContext(Context context) { super.setContext(context); getAppenderOne().setContext(context); getAppenderTwo().setContext(context); } @Override
public Context getContext() { Context context = super.getContext(); context = context != null ? context : getAppenderOne().getContext(); context = context != null ? context : getAppenderTwo().getContext(); return context; } @Override protected void append(T eventObject) { getAppenderOne().doAppend(eventObject); getAppenderTwo().doAppend(eventObject); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\CompositeAppender.java
1
请完成以下Java代码
public void setWithholding_Acct (int Withholding_Acct) { set_Value (COLUMNNAME_Withholding_Acct, Integer.valueOf(Withholding_Acct)); } /** Get Einbehalt. @return Account for Withholdings */ @Override public int getWithholding_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_Withholding_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getWriteOff_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setWriteOff_A(org.compiere.model.I_C_ValidCombination WriteOff_A) { set_ValueFromPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, WriteOff_A); } /** Set Forderungsverluste.
@param WriteOff_Acct Konto für Forderungsverluste */ @Override public void setWriteOff_Acct (int WriteOff_Acct) { set_Value (COLUMNNAME_WriteOff_Acct, Integer.valueOf(WriteOff_Acct)); } /** Get Forderungsverluste. @return Konto für Forderungsverluste */ @Override public int getWriteOff_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_WriteOff_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Default.java
1
请完成以下Java代码
private Map<String, String> extractParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final Map<String, String> parameters = new HashMap<>(); final Map<String, String> childSpecificParams = extractExternalSystemParameters(externalSystemParentConfig); if (childSpecificParams != null && !childSpecificParams.isEmpty()) { parameters.putAll(childSpecificParams); } runtimeParametersRepository.getByConfigIdAndRequest(externalSystemParentConfig.getId(), externalRequest) .forEach(runtimeParameter -> parameters.put(runtimeParameter.getName(), runtimeParameter.getValue())); return parameters; } protected String getOrgCode(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { return orgDAO.getById(getOrgId()).getValue(); } @Nullable
protected Timestamp getSinceParameterValue() { return since; } protected abstract IExternalSystemChildConfigId getExternalChildConfigId(); protected abstract Map<String, String> extractExternalSystemParameters(ExternalSystemParentConfig externalSystemParentConfig); protected abstract String getTabName(); protected abstract ExternalSystemType getExternalSystemType(); protected abstract long getSelectedRecordCount(final IProcessPreconditionsContext context); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeExternalSystemProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerLocationRouteBuilder extends RouteBuilder { private static final String ROUTE_ID = "To-MF_Upsert-BPartnerLocation_V2"; @Override public void configure() { errorHandler(noErrorHandler()); from("{{" + ExternalSystemCamelConstants.MF_UPSERT_BPARTNER_LOCATION_V2_CAMEL_URI + "}}") .routeId(ROUTE_ID) .streamCache("true") .log("Route invoked!") .process(exchange -> { final var lookupRequest = exchange.getIn().getBody(); if (!(lookupRequest instanceof BPLocationCamelRequest)) {
throw new RuntimeCamelException("The route " + ROUTE_ID + " requires the body to be instanceof BPLocationCamelRequest V2." + " However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName())); } exchange.getIn().setHeader(HEADER_ORG_CODE, ((BPLocationCamelRequest)lookupRequest).getOrgCode()); exchange.getIn().setHeader(HEADER_BPARTNER_IDENTIFIER, ((BPLocationCamelRequest)lookupRequest).getBPartnerIdentifier()); final JsonRequestLocationUpsert jsonRequestLocationUpsert = ((BPLocationCamelRequest)lookupRequest).getJsonRequestLocationUpsert(); exchange.getIn().setBody(jsonRequestLocationUpsert); }) .marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonRequestLocationUpsert.class)) .removeHeaders("CamelHttp*") .setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.PUT)) .toD("{{metasfresh.upsert-bpartner-v2.api.uri}}/${header." + HEADER_ORG_CODE + "}/${header." + HEADER_BPARTNER_IDENTIFIER + "}/location") .to(direct(UNPACK_V2_API_RESPONSE)); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\BPartnerLocationRouteBuilder.java
2
请完成以下Java代码
public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(TranslatableStrings.adMessage(ARE_YOU_SURE).translate(jsonOpts.getAdLanguage())) .build()); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity) { final DistributionJob job = DistributionMobileApplication.getDistributionJob(wfProcess);
return computeActivityState(job); } public static WFActivityStatus computeActivityState(final DistributionJob job) { return job.isClosed() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.assertActivityType(HANDLED_ACTIVITY_TYPE); return DistributionMobileApplication.mapDocument(request.getWfProcess(), distributionRestService::complete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\workflows_api\activity_handlers\CompleteDistributionWFActivityHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void saveData(RpAccountCheckMistake rpAccountCheckMistake) { rpAccountCheckMistakeDao.insert(rpAccountCheckMistake); } @Override public void updateData(RpAccountCheckMistake rpAccountCheckMistake) { rpAccountCheckMistakeDao.update(rpAccountCheckMistake); } @Override public RpAccountCheckMistake getDataById(String id) { return rpAccountCheckMistakeDao.getById(id); } @Override
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) { return rpAccountCheckMistakeDao.listPage(pageParam, paramMap); } /** * 批量保存差错记录 * * @param mistakeList */ public void saveListDate(List<RpAccountCheckMistake> mistakeList) { for (RpAccountCheckMistake mistake : mistakeList) { rpAccountCheckMistakeDao.insert(mistake); } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\service\impl\RpAccountCheckMistakeServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class PPOrderSourceHURepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); public void addSourceHUs(final @NonNull PPOrderId ppOrderId, final @NonNull Set<HuId> huIds) { final Map<HuId, I_PP_Order_SourceHU> huId2ExistingSource = retrieveRecordsIfExist(ppOrderId, huIds); huIds.stream() .map(huId -> Optional .ofNullable(huId2ExistingSource.get(huId)) .orElseGet(() -> initRecord(huId, ppOrderId))) .peek(sourceRecord -> sourceRecord.setIsActive(true)) .forEach(InterfaceWrapperHelper::save); } public void addSourceHU(final @NonNull PPOrderId ppOrderId, final @NonNull HuId huId) { addSourceHUs(ppOrderId, ImmutableSet.of(huId)); } @NonNull private Map<HuId, I_PP_Order_SourceHU> retrieveRecordsIfExist( final @NonNull PPOrderId ppOrderId, final @NonNull Set<HuId> huIds) { return queryBL.createQueryBuilder(I_PP_Order_SourceHU.class) //.addOnlyActiveRecordsFilter() // all .addEqualsFilter(I_PP_Order_SourceHU.COLUMNNAME_PP_Order_ID, ppOrderId) .addInArrayFilter(I_PP_Order_SourceHU.COLUMNNAME_M_HU_ID, huIds) .create() .stream() .collect(ImmutableMap.toImmutableMap(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID()), Function.identity())); }
@NonNull public ImmutableSet<HuId> getSourceHUIds(final PPOrderId ppOrderId) { final List<HuId> huIds = queryBL.createQueryBuilder(I_PP_Order_SourceHU.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Order_SourceHU.COLUMNNAME_PP_Order_ID, ppOrderId) .create() .listDistinct(I_PP_Order_SourceHU.COLUMNNAME_M_HU_ID, HuId.class); return ImmutableSet.copyOf(huIds); } @NonNull private I_PP_Order_SourceHU initRecord(@NonNull final HuId huId, @NonNull final PPOrderId ppOrderId) { final I_PP_Order_SourceHU record = InterfaceWrapperHelper.newInstance(I_PP_Order_SourceHU.class); record.setPP_Order_ID(ppOrderId.getRepoId()); record.setM_HU_ID(huId.getRepoId()); return record; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHURepository.java
2
请完成以下Java代码
public int getMSV3_FaultInfo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_FaultInfo_ID); if (ii == null) return 0; return ii.intValue(); } /** * MSV3_FaultInfoType AD_Reference_ID=540827 * Reference name: MSV3_FaultInfoType */ public static final int MSV3_FAULTINFOTYPE_AD_Reference_ID=540827; /** AuthorizationFaultInfo = AuthorizationFaultInfo */ public static final String MSV3_FAULTINFOTYPE_AuthorizationFaultInfo = "AuthorizationFaultInfo"; /** DenialOfServiceFault = DenialOfServiceFault */ public static final String MSV3_FAULTINFOTYPE_DenialOfServiceFault = "DenialOfServiceFault"; /** LieferscheinOderBarcodeUnbekanntFaultInfo = LieferscheinOderBarcodeUnbekanntFaultInfo */ public static final String MSV3_FAULTINFOTYPE_LieferscheinOderBarcodeUnbekanntFaultInfo = "LieferscheinOderBarcodeUnbekanntFaultInfo"; /** ServerFaultInfo = ServerFaultInfo */ public static final String MSV3_FAULTINFOTYPE_ServerFaultInfo = "ServerFaultInfo"; /** ValidationFaultInfo = ValidationFaultInfo */ public static final String MSV3_FAULTINFOTYPE_ValidationFaultInfo = "ValidationFaultInfo"; /** Set FaultInfoType. @param MSV3_FaultInfoType FaultInfoType */ @Override public void setMSV3_FaultInfoType (java.lang.String MSV3_FaultInfoType) { set_Value (COLUMNNAME_MSV3_FaultInfoType, MSV3_FaultInfoType); } /** Get FaultInfoType. @return FaultInfoType */ @Override public java.lang.String getMSV3_FaultInfoType () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_FaultInfoType);
} /** Set TechnischerFehlertext. @param MSV3_TechnischerFehlertext TechnischerFehlertext */ @Override public void setMSV3_TechnischerFehlertext (java.lang.String MSV3_TechnischerFehlertext) { set_Value (COLUMNNAME_MSV3_TechnischerFehlertext, MSV3_TechnischerFehlertext); } /** Get TechnischerFehlertext. @return TechnischerFehlertext */ @Override public java.lang.String getMSV3_TechnischerFehlertext () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_TechnischerFehlertext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_FaultInfo.java
1
请完成以下Java代码
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return getSession(EventSubscriptionEntityManager.class); } public Map<Class<?>, SessionFactory> getSessionFactories() { return sessionFactories; } public HistoryManager getHistoryManager() { return getSession(HistoryManager.class); } // getters and setters ////////////////////////////////////////////////////// public TransactionContext getTransactionContext() { return transactionContext; } public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; }
public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public FlowableEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请在Spring Boot框架中完成以下Java代码
public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public @Nullable String getVirtualHost() { return this.virtualHost; } public void setVirtualHost(@Nullable String virtualHost) { this.virtualHost = virtualHost; } public @Nullable String getUsername() { return this.username; }
public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public @Nullable String getName() { return this.name; } public void setName(@Nullable String name) { this.name = name; } } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitProperties.java
2
请完成以下Java代码
private void deliverAndInvoice(final ImmutableSet<PickingCandidateId> validPickingCandidates) { final List<PickingCandidate> pickingCandidates = processAllPickingCandidates(validPickingCandidates); final Set<HuId> huIdsToDeliver = pickingCandidates .stream() .filter(PickingCandidate::isPacked) .map(PickingCandidate::getPackedToHuId) .collect(ImmutableSet.toImmutableSet()); final List<I_M_HU> husToDeliver = handlingUnitsRepo.getByIds(huIdsToDeliver); HUShippingFacade.builder() .hus(husToDeliver) .addToShipperTransportationId(shipperTransportationId) .completeShipments(true) .failIfNoShipmentCandidatesFound(true) .invoiceMode(BillAssociatedInvoiceCandidates.IF_INVOICE_SCHEDULE_PERMITS) .createShipperDeliveryOrders(true) .build() .generateShippingDocuments();
} private List<ProductsToPickRow> getRowsNotAlreadyProcessed() { return streamAllRows() .filter(row -> !row.isProcessed()) .collect(ImmutableList.toImmutableList()); } private boolean isPartialDeliveryAllowed() { return sysConfigBL.getBooleanValue(SYSCONFIG_AllowPartialDelivery, false); } private ImmutableList<PickingCandidate> processAllPickingCandidates(final ImmutableSet<PickingCandidateId> pickingCandidateIdsToProcess) { return trxManager.callInNewTrx(() -> pickingCandidatesService .process(pickingCandidateIdsToProcess) .getPickingCandidates()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_4EyesReview_ProcessAll.java
1
请完成以下Java代码
public static List<HUToReportWrapper> ofList(final List<I_M_HU> hus) { if (hus.isEmpty()) { return ImmutableList.of(); } return hus.stream().map(HUToReportWrapper::of).collect(ImmutableList.toImmutableList()); } private final I_M_HU hu; private final HuId huId; private final BPartnerId bpartnerId; private final HuUnitType huUnitType; private List<HUToReport> _includedHUs; // lazy private HUToReportWrapper(@NonNull final I_M_HU hu) { this.hu = hu; this.huId = HuId.ofRepoId(hu.getM_HU_ID()); this.bpartnerId = BPartnerId.ofRepoIdOrNull(hu.getC_BPartner_ID()); this.huUnitType = extractHUType(hu); } private static HuUnitType extractHUType(final I_M_HU hu) { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); if (handlingUnitsBL.isLoadingUnit(hu)) { return HuUnitType.LU; } else if (handlingUnitsBL.isTransportUnitOrAggregate(hu)) { return HuUnitType.TU; } else if (handlingUnitsBL.isVirtual(hu)) { return HuUnitType.VHU; } else { throw new HUException("Unknown HU type: " + hu); // shall hot happen } }
@Override public HuId getHUId() { return huId; } @Override public BPartnerId getBPartnerId() { return bpartnerId; } @Override public HuUnitType getHUUnitType() { return huUnitType; } @Override public boolean isTopLevel() { return Services.get(IHandlingUnitsBL.class).isTopLevel(hu); } @Override public List<HUToReport> getIncludedHUs() { if (_includedHUs == null) { final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); this._includedHUs = handlingUnitsDAO.retrieveIncludedHUs(hu) .stream() .map(HUToReportWrapper::of) .collect(ImmutableList.toImmutableList()); } return _includedHUs; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\HUToReportWrapper.java
1
请完成以下Java代码
public Boolean getDisableBackoffStrategy() { return disableBackoffStrategy; } public void setDisableBackoffStrategy(Boolean disableBackoffStrategy) { this.disableBackoffStrategy = disableBackoffStrategy; } public void fromAnnotation(EnableExternalTaskClient annotation) { String baseUrl = annotation.baseUrl(); setBaseUrl(isNull(baseUrl) ? null : baseUrl); int maxTasks = annotation.maxTasks(); setMaxTasks(isNull(maxTasks) ? null : maxTasks); String workerId = annotation.workerId(); setWorkerId(isNull(workerId) ? null : workerId); setUsePriority(annotation.usePriority()); setUseCreateTime(annotation.useCreateTime()); configureOrderByCreateTime(annotation); long asyncResponseTimeout = annotation.asyncResponseTimeout(); setAsyncResponseTimeout(isNull(asyncResponseTimeout) ? null : asyncResponseTimeout); setDisableAutoFetching(annotation.disableAutoFetching()); setDisableBackoffStrategy(annotation.disableBackoffStrategy()); long lockDuration = annotation.lockDuration(); setLockDuration(isNull(lockDuration) ? null : lockDuration); String dateFormat = annotation.dateFormat(); setDateFormat(isNull(dateFormat) ? null : dateFormat);
String serializationFormat = annotation.defaultSerializationFormat(); setDefaultSerializationFormat(isNull(serializationFormat) ? null : serializationFormat); } protected void configureOrderByCreateTime(EnableExternalTaskClient annotation) { if (EnableExternalTaskClient.STRING_NULL_VALUE.equals(annotation.orderByCreateTime())) { setOrderByCreateTime(null); } else { setOrderByCreateTime(annotation.orderByCreateTime()); } } protected static boolean isNull(String value) { return ExternalTaskSubscription.STRING_NULL_VALUE.equals(value); } protected static boolean isNull(long value) { return LONG_NULL_VALUE == value; } protected static boolean isNull(int value) { return INT_NULL_VALUE == value; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public PmsPermission getByPermissionNameNotEqId(String permissionName, Long id) { return pmsPermissionDao.getByPermissionNameNotEqId(permissionName, id); } /** * pmsPermissionDao 删除 * * @param permission */ public void delete(Long permissionId) { pmsPermissionDao.delete(permissionId); } /** * 根据角色查找角色对应的功能权限ID集 * * @param roleId * @return */ public String getPermissionIdsByRoleId(Long roleId) { List<PmsRolePermission> rmList = pmsRolePermissionDao.listByRoleId(roleId); StringBuffer actionIds = new StringBuffer();
if (rmList != null && !rmList.isEmpty()) { for (PmsRolePermission rm : rmList) { actionIds.append(rm.getPermissionId()).append(","); } } return actionIds.toString(); } /** * 查询所有的权限 */ public List<PmsPermission> listAll() { Map<String, Object> paramMap = new HashMap<String, Object>(); return pmsPermissionDao.listBy(paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsPermissionServiceImpl.java
2
请完成以下Java代码
public String loginError(Model model) { model.addAttribute("error", "Invalid Credentials"); return "comparison/login"; } @PostMapping("/login") public String doLogin(HttpServletRequest req) { return "redirect:/home"; } @GetMapping("/home") public String showHomePage(HttpServletRequest req, Model model) { addUserAttributes(model); return "comparison/home"; } @GetMapping("/admin") public String adminOnly(HttpServletRequest req, Model model) { addUserAttributes(model); model.addAttribute("adminContent", "only admin can view this"); return "comparison/home"; } private void addUserAttributes(Model model) { Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); if (auth != null && !auth.getClass() .equals(AnonymousAuthenticationToken.class)) { User user = (User) auth.getPrincipal(); model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities(); for (GrantedAuthority authority : authorities) { if (authority.getAuthority() .contains("USER")) { model.addAttribute("role", "USER"); model.addAttribute("permission", "READ"); } else if (authority.getAuthority() .contains("ADMIN")) { model.addAttribute("role", "ADMIN"); model.addAttribute("permission", "READ WRITE"); } } } } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\springsecurity\web\SpringController.java
1
请完成以下Java代码
public static DocumentFilterDescriptor createFilterDescriptor(@NonNull final LookupDescriptorProviders lookupDescriptorProviders) { return DocumentFilterDescriptor.builder() .setFilterId(FILTER_ID) .setFrequentUsed(false) //.setInlineRenderMode(DocumentFilterInlineRenderMode.INLINE_PARAMETERS) .setDisplayName("default") .addParameter(newParamDescriptor(PARAM_C_BPartner_ID) .widgetType(DocumentFieldWidgetType.Lookup) .lookupDescriptor(lookupDescriptorProviders.searchInTable(I_C_BPartner.Table_Name).provideForFilter())) .addParameter(newParamDescriptor(PARAM_C_Order_ID) .widgetType(DocumentFieldWidgetType.Lookup) .lookupDescriptor(lookupDescriptorProviders.searchInTable(I_C_Order.Table_Name).provideForFilter())) .addParameter(newParamDescriptor(PARAM_C_Cost_Type_ID) .widgetType(DocumentFieldWidgetType.Lookup) .lookupDescriptor(lookupDescriptorProviders.searchInTable(I_C_Cost_Type.Table_Name).provideForFilter())) .build(); } private static DocumentFilterParamDescriptor.Builder newParamDescriptor(final String fieldName) { return DocumentFilterParamDescriptor.builder() .fieldName(fieldName) .displayName(TranslatableStrings.adElementOrMessage(fieldName)); } public static InOutCostQuery toInOutCostQuery(
@NonNull final SOTrx soTrx, @Nullable final DocumentFilter filter) { return InOutCostQuery.builder() .limit(QueryLimit.ONE_HUNDRED) .bpartnerId(filter != null ? BPartnerId.ofRepoIdOrNull(filter.getParameterValueAsInt(PARAM_C_BPartner_ID, -1)) : null) .soTrx(soTrx) .orderId(filter != null ? OrderId.ofRepoIdOrNull(filter.getParameterValueAsInt(PARAM_C_Order_ID, -1)) : null) .costTypeId(filter != null ? OrderCostTypeId.ofRepoIdOrNull(filter.getParameterValueAsInt(PARAM_C_Cost_Type_ID, -1)) : null) .includeReversed(false) .onlyWithOpenAmountToInvoice(true) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsViewFilterHelper.java
1
请在Spring Boot框架中完成以下Java代码
public R<IPage<Tenant>> page(Tenant tenant, Query query) { IPage<Tenant> pages = tenantService.selectTenantPage(Condition.getPage(query), tenant); return R.data(pages); } /** * 新增或修改 */ @PostMapping("/submit") @Operation(summary = "新增或修改", description = "传入tenant") public R submit(@Valid @RequestBody Tenant tenant) { return R.status(tenantService.saveTenant(tenant)); } /** * 删除 */ @PostMapping("/remove") @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(tenantService.deleteLogic(Func.toLongList(ids))); } /**
* 根据域名查询信息 * * @param domain 域名 */ @GetMapping("/info") @Operation(summary = "配置信息", description = "传入domain") public R<Kv> info(String domain) { Tenant tenant = tenantService.getOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getDomain, domain)); Kv kv = Kv.init(); if (tenant != null) { kv.set("tenantId", tenant.getTenantId()).set("domain", tenant.getDomain()); } return R.data(kv); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TenantController.java
2
请完成以下Java代码
public void handleFailure(String externalTaskId, String errorMessage, String errorDetails, int retries, long retryTimeout, Map<String, Object> variables, Map<String, Object> locaclVariables) { try { engineClient.failure(externalTaskId, errorMessage, errorDetails, retries, retryTimeout, variables, locaclVariables); } catch (EngineClientException e) { throw LOG.handledEngineClientException("notifying a failure", e); } } @Override public void handleBpmnError(ExternalTask externalTask, String errorCode) { handleBpmnError(externalTask, errorCode, null, null); } @Override public void handleBpmnError(ExternalTask externalTask, String errorCode, String errorMessage) { handleBpmnError(externalTask, errorCode, errorMessage, null); } @Override public void handleBpmnError(ExternalTask externalTask, String errorCode, String errorMessage, Map<String, Object> variables) { handleBpmnError(externalTask.getId(), errorCode, errorMessage, variables); } @Override public void handleBpmnError(String externalTaskId, String errorCode, String errorMessage, Map<String, Object> variables) { try { engineClient.bpmnError(externalTaskId, errorCode, errorMessage, variables);
} catch (EngineClientException e) { throw LOG.handledEngineClientException("notifying a BPMN error", e); } } @Override public void extendLock(ExternalTask externalTask, long newDuration) { extendLock(externalTask.getId(), newDuration); } @Override public void extendLock(String externalTaskId, long newDuration) { try { engineClient.extendLock(externalTaskId, newDuration); } catch (EngineClientException e) { throw LOG.handledEngineClientException("extending lock", e); } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderProcessReq <T> extends AbsReq { /** 受理人ID */ private String userId; /** 订单ID */ private String orderId; /** 受理器枚举 */ private ProcessReqEnum processReqEnum; /** 自定义的请求参数 */ private T reqData; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; }
public ProcessReqEnum getProcessReqEnum() { return processReqEnum; } public void setProcessReqEnum(ProcessReqEnum processReqEnum) { this.processReqEnum = processReqEnum; } public T getReqData() { return reqData; } public void setReqData(T reqData) { this.reqData = reqData; } @Override public String toString() { return "OrderProcessReq{" + "userId='" + userId + '\'' + ", orderId='" + orderId + '\'' + ", processReqEnum=" + processReqEnum + ", reqData=" + reqData + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderProcessReq.java
2
请完成以下Java代码
protected AbstractResourceDefinitionManager<DecisionRequirementsDefinitionEntity> getManager() { return Context.getCommandContext().getDecisionRequirementsDefinitionManager(); } @Override protected void checkInvalidDefinitionId(String definitionId) { ensureNotNull("Invalid decision requirements definition id", "decisionRequirementsDefinitionId", definitionId); } @Override protected void checkDefinitionFound(String definitionId, DecisionRequirementsDefinitionEntity definition) { ensureNotNull("no deployed decision requirements definition found with id '" + definitionId + "'", "decisionRequirementsDefinition", definition); } @Override protected void checkInvalidDefinitionByKey(String definitionKey, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, DecisionRequirementsDefinitionEntity definition) {
// not needed } @Override protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, DecisionRequirementsDefinitionEntity definition) { ensureNotNull("deployment '" + deploymentId + "' didn't put decision requirements definition '" + definitionId + "' in the cache", "cachedDecisionRequirementsDefinition", definition); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\DecisionRequirementsDefinitionCache.java
1
请完成以下Java代码
void runClient() throws IOException { Path socketPath = Path.of(System.getProperty("user.home")) .resolve("baeldung.socket"); UnixDomainSocketAddress socketAddress = getAddress(socketPath); SocketChannel channel = openSocketChannel(socketAddress); String message = "Hello from Baeldung Unix domain socket article"; writeMessage(channel, message); } UnixDomainSocketAddress getAddress(Path socketPath) { return UnixDomainSocketAddress.of(socketPath); } SocketChannel openSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException { SocketChannel channel = SocketChannel .open(StandardProtocolFamily.UNIX);
channel.connect(socketAddress); return channel; } void writeMessage(SocketChannel socketChannel, String message) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.clear(); buffer.put(message.getBytes()); buffer.flip(); while (buffer.hasRemaining()) { socketChannel.write(buffer); } } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\socket\UnixDomainSocketClient.java
1
请完成以下Java代码
public ServletInputStream getInputStream() throws IOException { return servletInputStream; } }; } private static class ByteArrayServletInputStream extends ServletInputStream { private final ByteArrayInputStream body; ByteArrayServletInputStream(ByteArrayInputStream body) { body.reset(); this.body = body; } @Override public boolean isFinished() { return body.available() <= 0; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener listener) { } @Override public int read() { return body.read(); } } private static class FormContentRequestWrapper extends HttpServletRequestWrapper {
private final MultiValueMap<String, String> queryParams; FormContentRequestWrapper(HttpServletRequest request, MultiValueMap<String, String> params) { super(request); this.queryParams = params; } @Override @Nullable public String getParameter(String name) { return this.queryParams.getFirst(name); } @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> result = new LinkedHashMap<>(); Enumeration<String> names = getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); result.put(name, getParameterValues(name)); } return result; } @Override public Enumeration<String> getParameterNames() { return Collections.enumeration(this.queryParams.keySet()); } @Override @Nullable public String[] getParameterValues(String name) { return StringUtils.toStringArray(this.queryParams.get(name)); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\FormFilter.java
1
请完成以下Java代码
public Collection<Class<? extends AbstractTransactionEvent>> getHandledEventType() { return ImmutableList.of(TransactionCreatedEvent.class, TransactionDeletedEvent.class); } @Override public void handleEvent(@NonNull final AbstractTransactionEvent event) { final StockDataUpdateRequest dataUpdateRequest = createDataUpdateRequestForEvent(event); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } private StockDataUpdateRequest createDataUpdateRequestForEvent( @NonNull final AbstractTransactionEvent event) { final MaterialDescriptor materialDescriptor = event.getMaterialDescriptor();
final StockDataRecordIdentifier identifier = StockDataRecordIdentifier.builder() .clientId(event.getClientId()) .orgId(event.getOrgId()) .warehouseId(materialDescriptor.getWarehouseId()) .productId(ProductId.ofRepoId(materialDescriptor.getProductId())) .storageAttributesKey(materialDescriptor.getStorageAttributesKey()) .build(); final StockChangeSourceInfo stockChangeSourceInfo = StockChangeSourceInfo.ofTransactionId(event.getTransactionId()); return StockDataUpdateRequest.builder() .identifier(identifier) .onHandQtyChange(event.getQuantityDelta()) .sourceInfo(stockChangeSourceInfo) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\eventhandler\TransactionEventHandlerForStockRecords.java
1
请完成以下Java代码
public void setLineNetAmt (java.math.BigDecimal LineNetAmt) { set_Value (COLUMNNAME_LineNetAmt, LineNetAmt); } /** Get Zeilennetto. @return Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public java.math.BigDecimal getLineNetAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineNetAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Position. @param LineNo Zeile Nr. */ @Override public void setLineNo (int LineNo) { set_Value (COLUMNNAME_LineNo, Integer.valueOf(LineNo)); } /** Get Position. @return Zeile Nr. */ @Override public int getLineNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LineNo); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); }
@Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customs_Invoice_Line.java
1
请完成以下Java代码
public void setIsTimeBased (boolean IsTimeBased) { set_Value (COLUMNNAME_IsTimeBased, Boolean.valueOf(IsTimeBased)); } /** Get Time based. @return Time based Revenue Recognition rather than Service Level based */ public boolean isTimeBased () { Object oo = get_Value(COLUMNNAME_IsTimeBased); 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()); } /** Set Number of Months. @param NoMonths Number of Months */ public void setNoMonths (int NoMonths) { set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths)); } /** Get Number of Months. @return Number of Months */ public int getNoMonths () {
Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths); if (ii == null) return 0; return ii.intValue(); } /** RecognitionFrequency AD_Reference_ID=196 */ public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196; /** Month = M */ public static final String RECOGNITIONFREQUENCY_Month = "M"; /** Quarter = Q */ public static final String RECOGNITIONFREQUENCY_Quarter = "Q"; /** Year = Y */ public static final String RECOGNITIONFREQUENCY_Year = "Y"; /** Set Recognition frequency. @param RecognitionFrequency Recognition frequency */ public void setRecognitionFrequency (String RecognitionFrequency) { set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency); } /** Get Recognition frequency. @return Recognition frequency */ public String getRecognitionFrequency () { return (String)get_Value(COLUMNNAME_RecognitionFrequency); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java
1
请完成以下Java代码
public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } @Override
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Post)) { return false; } Post post = (Post) o; return getId().equals(post.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\aggregation\model\Post.java
1
请完成以下Java代码
public static boolean run(String args) { return run(args.split("\\s")); } public static boolean run(String[] args) { Option option = new Option(); List<String> unkownArgs = null; try { unkownArgs = Args.parse(option, args, false); } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); Args.usage(option); return false; } boolean convert = option.convert; boolean convertToText = option.convert_to_text; String[] restArgs = unkownArgs.toArray(new String[0]); if (option.help || ((convertToText || convert) && restArgs.length != 2) || (!convert && !convertToText && restArgs.length != 3)) { Args.usage(option); return option.help; } int freq = option.freq; int maxiter = option.maxiter; double C = option.cost; double eta = option.eta; boolean textmodel = option.textmodel; int threadNum = option.thread; if (threadNum <= 0) { threadNum = Runtime.getRuntime().availableProcessors(); } int shrinkingSize = option.shrinking_size; String algorithm = option.algorithm; algorithm = algorithm.toLowerCase(); Encoder.Algorithm algo = Encoder.Algorithm.CRF_L2; if (algorithm.equals("crf") || algorithm.equals("crf-l2")) { algo = Encoder.Algorithm.CRF_L2; } else if (algorithm.equals("crf-l1")) { algo = Encoder.Algorithm.CRF_L1; } else if (algorithm.equals("mira")) { algo = Encoder.Algorithm.MIRA; } else { System.err.println("unknown algorithm: " + algorithm); return false; } if (convert) { EncoderFeatureIndex featureIndex = new EncoderFeatureIndex(1);
if (!featureIndex.convert(restArgs[0], restArgs[1])) { System.err.println("fail to convert text model"); return false; } } else if (convertToText) { DecoderFeatureIndex featureIndex = new DecoderFeatureIndex(); if (!featureIndex.convert(restArgs[0], restArgs[1])) { System.err.println("fail to convert binary model"); return false; } } else { Encoder encoder = new Encoder(); if (!encoder.learn(restArgs[0], restArgs[1], restArgs[2], textmodel, maxiter, freq, eta, C, threadNum, shrinkingSize, algo)) { System.err.println("fail to learn model"); return false; } } return true; } public static void main(String[] args) { crf_learn.run(args); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\crf_learn.java
1
请完成以下Java代码
private static @NonNull Quantity getQuantity(final @NonNull SupplyRequiredDescriptor supplyRequiredDescriptor) { final IProductBL productBL = Services.get(IProductBL.class); final ProductId productId = ProductId.ofRepoId(supplyRequiredDescriptor.getProductId()); final BigDecimal qtyToSupplyBD = supplyRequiredDescriptor.getQtyToSupplyBD(); final I_C_UOM uom = productBL.getStockUOM(productId); return Quantity.of(qtyToSupplyBD, uom); } public void updateQtySupplyRequired( @NonNull final MaterialDescriptor materialDescriptor, @NonNull final EventDescriptor eventDescriptor, @NonNull final BigDecimal qtySupplyRequiredDelta) { if (qtySupplyRequiredDelta.signum() == 0) { return;
} final IOrgDAO orgDAO = Services.get(IOrgDAO.class); final ZoneId orgTimezone = orgDAO.getTimeZone(eventDescriptor.getOrgId()); final MainDataRecordIdentifier mainDataRecordIdentifier = MainDataRecordIdentifier.createForMaterial(materialDescriptor, orgTimezone); mainDataRequestHandler.handleDataUpdateRequest( UpdateMainDataRequest.builder() .identifier(mainDataRecordIdentifier) .qtySupplyRequired(qtySupplyRequiredDelta) .build() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandlerUtils.java
1
请完成以下Java代码
private boolean isEmailSendable(@NonNull final IDocOutboundDAO.LogWithLines logWithLines, @NonNull final I_C_Doc_Outbound_Log_Line currentLogLine, final boolean onlyNotSendMails) { if (ArchiveId.ofRepoIdOrNull(currentLogLine.getAD_Archive_ID()) == null) { final I_C_Doc_Outbound_Log log = logWithLines.getLog(); Loggables.addLog(msgBL.getMsg( MSG_EMPTY_AD_Archive_ID, ImmutableList.of(StringUtils.nullToEmpty(log.getDocumentNo())))); return false; } return !onlyNotSendMails || !logWithLines.wasEmailSentAtLeastOnce(); } private int sendMails(@NonNull final Stream<I_C_Doc_Outbound_Log_Line> lines, @Nullable final PInstanceId pInstanceId) { final AtomicInteger counter = new AtomicInteger(); final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(MailWorkpackageProcessor.class); lines.forEach(docOutboundLogLine -> { final IWorkPackageBuilder builder = queue.newWorkPackage()
.addElement(docOutboundLogLine) .bindToThreadInheritedTrx(); if (pInstanceId != null) { builder.setAD_PInstance_ID(pInstanceId); } builder.buildAndEnqueue(); counter.getAndIncrement(); }); return counter.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundService.java
1
请完成以下Java代码
public List<Deployer> getDeployers() { return deployers; } public void setDeployers(List<Deployer> deployers) { this.deployers = deployers; } public DeploymentCache<ProcessDefinitionCacheEntry> getProcessDefinitionCache() { return processDefinitionCache; } public void setProcessDefinitionCache(DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache) { this.processDefinitionCache = processDefinitionCache; } public DeploymentCache<BpmnModel> getBpmnModelCache() { return bpmnModelCache; } public void setBpmnModelCache(DeploymentCache<BpmnModel> bpmnModelCache) { this.bpmnModelCache = bpmnModelCache; }
public ProcessDefinitionInfoCache getProcessDefinitionInfoCache() { return processDefinitionInfoCache; } public void setProcessDefinitionInfoCache(ProcessDefinitionInfoCache processDefinitionInfoCache) { this.processDefinitionInfoCache = processDefinitionInfoCache; } public DeploymentCache<Object> getKnowledgeBaseCache() { return knowledgeBaseCache; } public void setKnowledgeBaseCache(DeploymentCache<Object> knowledgeBaseCache) { this.knowledgeBaseCache = knowledgeBaseCache; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\DeploymentManager.java
1
请完成以下Java代码
class CacheTrxParamDescriptor implements ICachedMethodPartDescriptor { private static final transient Logger logger = LogManager.getLogger(CacheTrxParamDescriptor.class); private final int parameterIndex; private final boolean isModel; CacheTrxParamDescriptor(final Class<?> parameterType, final int parameterIndex, final Annotation annotation) { super(); this.parameterIndex = parameterIndex; if (String.class.isAssignableFrom(parameterType)) { isModel = false; } else if (InterfaceWrapperHelper.isModelInterface(parameterType)) { isModel = true; } else { throw new CacheIntrospectionException("Parameter has unsupported type") .setParameter(parameterIndex, parameterType); } } @Override public void extractKeyParts(final CacheKeyBuilder keyBuilder, final Object targetObject, final Object[] params) { final Object trxNameObj = params[parameterIndex]; String trxName = null; boolean error = false; Exception errorException = null; if (trxNameObj == null) { trxName = null; } else if (isModel) { try { trxName = InterfaceWrapperHelper.getTrxName(trxNameObj); } catch (final Exception ex) { error = true; errorException = ex; } } else if (trxNameObj instanceof String) { trxName = (String)trxNameObj;
} else { error = true; } if (error) { keyBuilder.setSkipCaching(); final CacheGetException ex = new CacheGetException("Invalid parameter type.") .addSuppressIfNotNull(errorException) .setTargetObject(targetObject) .setMethodArguments(params) .setInvalidParameter(parameterIndex, trxNameObj) .setAnnotation(CacheTrx.class); logger.warn("Invalid parameter. Skip caching", ex); return; } // NOTE: we assume the caller will separate caches per transaction, so there is no point to have it as part of the cache key // More, // * consider the case of ThreadInherited transactions which we would have to resolve them here // * it shall be the responsibility of the builder to include it in key, in case it's really needed // keyBuilder.add(trxName); keyBuilder.setTrxName(trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheTrxParamDescriptor.java
1