instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("executionId", executionId); persistentState.put("processDefinitionId", processDefinitionId); persistentState.put("activityId", activityId); persistentState.put("jobDefinitionId", jobDefinitionId); persistentState.put("annotation", annotation); return persistentState; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } public String getHistoryConfiguration() { return historyConfiguration; } public void setHistoryConfiguration(String historyConfiguration) { this.historyConfiguration = historyConfiguration; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", incidentTimestamp=" + incidentTimestamp + ", incidentType=" + incidentType + ", executionId=" + executionId + ", activityId=" + activityId + ", processInstanceId=" + processInstanceId + ", processDefinitionId=" + processDefinitionId + ", causeIncidentId=" + causeIncidentId + ", rootCauseIncidentId=" + rootCauseIncidentId + ", configuration=" + configuration + ", tenantId=" + tenantId + ", incidentMessage=" + incidentMessage
+ ", jobDefinitionId=" + jobDefinitionId + ", failedActivityId=" + failedActivityId + ", annotation=" + annotation + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IncidentEntity other = (IncidentEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentEntity.java
1
请完成以下Java代码
public class QualityNoteDAO implements IQualityNoteDAO { public static final AttributeCode QualityNoteAttribute = AttributeCode.ofString("QualityNotice"); @Override public I_M_QualityNote getById(@NonNull final QualityNoteId qualityNoteId) { return loadOutOfTrx(qualityNoteId, I_M_QualityNote.class); } @Override public I_M_QualityNote retrieveQualityNoteForValue(final Properties ctx, final String value) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_QualityNote.class, ctx, ITrx.TRXNAME_None) .addEqualsFilter(I_M_QualityNote.COLUMN_Value, value) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_M_QualityNote.class); } @Override public AttributeId getQualityNoteAttributeId() { final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class); return attributeDAO.retrieveActiveAttributeIdByValueOrNull(QualityNoteAttribute); } @Override public AttributeListValue retrieveAttribueValueForQualityNote(final I_M_QualityNote qualityNote) { final AttributeId attributeId = getQualityNoteAttributeId(); return Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(attributeId, qualityNote.getValue()); } @Override public void deleteAttribueValueForQualityNote(final I_M_QualityNote qualityNote) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
final AttributeId attributeId = getQualityNoteAttributeId(); attributesRepo.deleteAttributeValueByCode(attributeId, qualityNote.getValue()); } @Override public void modifyAttributeValueName(final I_M_QualityNote qualityNote) { final AttributeListValue attributeValueForQualityNote = retrieveAttribueValueForQualityNote(qualityNote); if (attributeValueForQualityNote == null) { // shall not happen. All M_QualityNote entries shall have a similar M_AttributeValue return; } final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValueForQualityNote.getId()) .name(qualityNote.getName()) .active(qualityNote.isActive()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\impl\QualityNoteDAO.java
1
请完成以下Java代码
public boolean isEmpty() { return deque.isEmpty(); } public String getCurrentValue() { return deque.peekFirst(); } public void pushCurrentValue(String value) { deque.addFirst(value != null ? value : NULL_VALUE); updateMdcWithCurrentValue(); } /** * @return true if a value was obtained from the mdc * and added to the stack */ public boolean pushCurrentValueFromMdc() { if (isNotBlank(mdcName)) { String mdcValue = MdcAccess.get(mdcName); deque.addFirst(mdcValue != null ? mdcValue : NULL_VALUE); return true; } else { return false; } } public void removeCurrentValue() { deque.removeFirst(); updateMdcWithCurrentValue(); } public void clearMdcProperty() { if (isNotBlank(mdcName)) { MdcAccess.remove(mdcName); } } public void updateMdcWithCurrentValue() { if (isNotBlank(mdcName)) { String currentValue = getCurrentValue(); if (isNull(currentValue)) { MdcAccess.remove(mdcName); } else { MdcAccess.put(mdcName, currentValue); } } } } protected static class ProcessDataSections {
/** * Keeps track of when we added values to which stack (as we do not add * a new value to every stack with every update, but only changed values) */ protected Deque<List<ProcessDataStack>> sections = new ArrayDeque<>(); protected boolean currentSectionSealed = true; /** * Adds a stack to the current section. If the current section is already sealed, * a new section is created. */ public void addToCurrentSection(ProcessDataStack stack) { List<ProcessDataStack> currentSection; if (currentSectionSealed) { currentSection = new ArrayList<>(); sections.addFirst(currentSection); currentSectionSealed = false; } else { currentSection = sections.peekFirst(); } currentSection.add(stack); } /** * Pops the current section and removes the * current values from the referenced stacks (including updates * to the MDC) */ public void popCurrentSection() { List<ProcessDataStack> section = sections.pollFirst(); if (section != null) { section.forEach(ProcessDataStack::removeCurrentValue); } currentSectionSealed = true; } /** * After a section is sealed, a new section will be created * with the next call to {@link #addToCurrentSection(ProcessDataStack)} */ public void sealCurrentSection() { currentSectionSealed = true; } public int size() { return sections.size(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\ProcessDataContext.java
1
请完成以下Java代码
public Q head() { return method(HttpHead.METHOD_NAME); } public Q options() { return method(HttpOptions.METHOD_NAME); } public Q trace() { return method(HttpTrace.METHOD_NAME); } public Map<String, Object> getConfigOptions() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG); } public Object getConfigOption(String field) { Map<String, Object> config = getConfigOptions(); if (config != null) { return config.get(field);
} return null; } @SuppressWarnings("unchecked") public Q configOption(String field, Object value) { if (field == null || field.isEmpty() || value == null) { LOG.ignoreConfig(field, value); } else { Map<String, Object> config = getConfigOptions(); if (config == null) { config = new HashMap<>(); setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config); } config.put(field, value); } return (Q) this; } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java
1
请在Spring Boot框架中完成以下Java代码
public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the charset. */ public String getCharset() { return charset;
} /** * @param charset The charset to set. */ public void setCharset(String charset) { this.charset = charset; } public HttpResultType getResultType() { return resultType; } public void setResultType(HttpResultType resultType) { this.resultType = resultType; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\httpClient\HttpRequest.java
2
请完成以下Java代码
public class ScheduledTask { private ListenableFuture<?> scheduledFuture; private boolean stopped = false; public void init(AsyncCallable<Void> task, long delayMs, ScheduledExecutorService scheduler) { schedule(task, delayMs, scheduler); } private void schedule(AsyncCallable<Void> task, long delayMs, ScheduledExecutorService scheduler) { scheduledFuture = Futures.scheduleAsync(() -> { if (stopped) { return Futures.immediateCancelledFuture(); } try { return task.call(); } catch (Throwable t) { log.error("Unhandled error in scheduled task", t);
return Futures.immediateFailedFuture(t); } }, delayMs, TimeUnit.MILLISECONDS, scheduler); if (!stopped) { scheduledFuture.addListener(() -> schedule(task, delayMs, scheduler), MoreExecutors.directExecutor()); } } public void cancel() { stopped = true; if (scheduledFuture != null) { scheduledFuture.cancel(true); } } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\session\ScheduledTask.java
1
请完成以下Java代码
private void pushToTarget(TopicPartitionInfo tpi, TbMsg msg, EntityId target, String fromRelationType) { if (tpi.isMyPartition()) { switch (target.getEntityType()) { case RULE_NODE: pushMsgToNode(nodeActors.get(new RuleNodeId(target.getId())), msg, fromRelationType); break; case RULE_CHAIN: parent.tell(new RuleChainToRuleChainMsg(new RuleChainId(target.getId()), entityId, msg, fromRelationType)); break; } } else { putToQueue(tpi, msg, new TbQueueTbMsgCallbackWrapper(msg.getCallback()), target); } } private void putToQueue(TopicPartitionInfo tpi, TbMsg newMsg, TbQueueCallback callbackWrapper) { ToRuleEngineMsg toQueueMsg = ToRuleEngineMsg.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setTbMsgProto(TbMsg.toProto(newMsg)) .build(); clusterService.pushMsgToRuleEngine(tpi, newMsg.getId(), toQueueMsg, callbackWrapper); } private boolean contains(Set<String> relationTypes, String type) { if (relationTypes == null) { return true; } for (String relationType : relationTypes) { if (relationType.equalsIgnoreCase(type)) { return true; } } return false; }
private void pushMsgToNode(RuleNodeCtx nodeCtx, TbMsg msg, String fromRelationType) { if (nodeCtx != null) { var tbCtx = new DefaultTbContext(systemContext, ruleChainName, nodeCtx); nodeCtx.getSelfActor().tell(new RuleChainToRuleNodeMsg(tbCtx, msg, fromRelationType)); } else { log.error("[{}][{}] RuleNodeCtx is empty", entityId, ruleChainName); msg.getCallback().onFailure(new RuleEngineException("Rule Node CTX is empty")); } } @Override protected RuleNodeException getInactiveException() { RuleNode firstRuleNode = firstNode != null ? firstNode.getSelf() : null; return new RuleNodeException("Rule Chain is not active! Failed to initialize.", ruleChainName, firstRuleNode); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleChainActorMessageProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public final class InfoContributorAutoConfiguration { /** * The default order for the core {@link InfoContributor} beans. */ public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; @Bean @ConditionalOnEnabledInfoContributor(value = "env", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) { return new EnvironmentInfoContributor(environment); } @Bean @ConditionalOnEnabledInfoContributor("git") @ConditionalOnSingleCandidate(GitProperties.class) @ConditionalOnMissingBean @Order(DEFAULT_ORDER) GitInfoContributor gitInfoContributor(GitProperties gitProperties, InfoContributorProperties infoContributorProperties) { return new GitInfoContributor(gitProperties, infoContributorProperties.getGit().getMode()); } @Bean @ConditionalOnEnabledInfoContributor("build") @ConditionalOnSingleCandidate(BuildProperties.class) @Order(DEFAULT_ORDER) InfoContributor buildInfoContributor(BuildProperties buildProperties) { return new BuildInfoContributor(buildProperties); } @Bean @ConditionalOnEnabledInfoContributor(value = "java", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) JavaInfoContributor javaInfoContributor() { return new JavaInfoContributor(); } @Bean @ConditionalOnEnabledInfoContributor(value = "os", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) OsInfoContributor osInfoContributor() { return new OsInfoContributor(); }
@Bean @ConditionalOnEnabledInfoContributor(value = "process", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) ProcessInfoContributor processInfoContributor() { return new ProcessInfoContributor(); } @Bean @ConditionalOnEnabledInfoContributor(value = "ssl", fallback = InfoContributorFallback.DISABLE) @Order(DEFAULT_ORDER) SslInfoContributor sslInfoContributor(SslInfo sslInfo) { return new SslInfoContributor(sslInfo); } @Bean @ConditionalOnMissingBean @ConditionalOnEnabledInfoContributor(value = "ssl", fallback = InfoContributorFallback.DISABLE) SslInfo sslInfo(SslBundles sslBundles) { return new SslInfo(sslBundles); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\info\InfoContributorAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
private Factory createThrowAwayFactory() { return new Factory() { @Override public @Nullable Propagation<String> get() { return null; } }; } @Bean BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer() { return (builder) -> { List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { builder.add(BaggagePropagationConfig.SingleBaggageField.remote(BaggageField.create(fieldName))); } List<String> localFields = this.tracingProperties.getBaggage().getLocalFields(); for (String localFieldName : localFields) { builder.add(BaggagePropagationConfig.SingleBaggageField.local(BaggageField.create(localFieldName))); } }; } @Bean @ConditionalOnMissingBean @ConditionalOnEnabledTracingExport Factory propagationFactory(BaggagePropagation.FactoryBuilder factoryBuilder) { return factoryBuilder.build(); } @Bean @ConditionalOnMissingBean CorrelationScopeDecorator.Builder mdcCorrelationScopeDecoratorBuilder( ObjectProvider<CorrelationScopeCustomizer> correlationScopeCustomizers) { CorrelationScopeDecorator.Builder builder = MDCScopeDecorator.newBuilder(); correlationScopeCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Order(0) @ConditionalOnBooleanProperty(name = "management.tracing.baggage.correlation.enabled", matchIfMissing = true) CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() { return (builder) -> { Correlation correlationProperties = this.tracingProperties.getBaggage().getCorrelation(); for (String field : correlationProperties.getFields()) { BaggageField baggageField = BaggageField.create(field); SingleCorrelationField correlationField = SingleCorrelationField.newBuilder(baggageField)
.flushOnUpdate() .build(); builder.add(correlationField); } }; } @Bean @ConditionalOnMissingBean(CorrelationScopeDecorator.class) ScopeDecorator correlationScopeDecorator(CorrelationScopeDecorator.Builder builder) { return builder.build(); } } /** * Propagates neither traces nor baggage. */ @Configuration(proxyBeanMethods = false) static class NoPropagation { @Bean @ConditionalOnMissingBean(Factory.class) CompositePropagationFactory noopPropagationFactory() { return CompositePropagationFactory.noop(); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-brave\src\main\java\org\springframework\boot\micrometer\tracing\brave\autoconfigure\BravePropagationConfigurations.java
2
请在Spring Boot框架中完成以下Java代码
public class ProductUpsertProcessor implements Processor { private final ProcessLogger processLogger; public ProductUpsertProcessor(@NonNull final ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void process(final Exchange exchange) throws Exception { final ImportProductsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_PRODUCTS_CONTEXT, ImportProductsRouteContext.class); final JsonProduct product = exchange.getIn().getBody(JsonProduct.class); context.setJsonProduct(product); final ProductUpsertRequestProducer productUpsertRequestProducer = ProductUpsertRequestProducer.builder() .product(product) .routeContext(context) .processLogger(processLogger) .build();
final JsonRequestProductUpsert productRequestProducerResult = productUpsertRequestProducer.run(); if (productRequestProducerResult.getRequestItems().isEmpty()) { exchange.getIn().setBody(null); return; } final ProductUpsertCamelRequest productUpsertCamelRequest = ProductUpsertCamelRequest.builder() .jsonRequestProductUpsert(productRequestProducerResult) .orgCode(context.getOrgCode()) .build(); exchange.getIn().setBody(productUpsertCamelRequest); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\processor\ProductUpsertProcessor.java
2
请完成以下Java代码
public Page<User> findAll(User sample, PageRequest pageRequest) { return userRepo.findAll(whereSpec(sample), pageRequest); } private Specification<User> whereSpec(final User sample){ return (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(); if (sample.getId()!=null){ predicates.add(cb.equal(root.<Long>get("id"), sample.getId())); } if (StringUtils.hasLength(sample.getUsername())){ predicates.add(cb.equal(root.<String>get("username"),sample.getUsername())); } return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User sample = new User(); sample.setUsername(username); User user = findBySample(sample); if( user == null ){ throw new UsernameNotFoundException(String.format("User with username=%s was not found", username)); } return user; } }
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\UserService.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingJobLockService { @NonNull private final ILockManager lockManager = Services.get(ILockManager.class); @NonNull private final ShipmentScheduleLockRepository shipmentScheduleLockRepository; public ScheduledPackageableLocks getLocks(@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { if (scheduleIds.isEmpty()) {return ScheduledPackageableLocks.EMPTY;} final ImmutableMap<TableRecordReference, ShipmentScheduleAndJobScheduleId> scheduleIdsByRecordRef = scheduleIds.stream() .collect(ImmutableMap.toImmutableMap( ShipmentScheduleAndJobScheduleId::toTableRecordReference, scheduleId -> scheduleId )); final TableRecordReferenceSet recordRefs = TableRecordReferenceSet.of(scheduleIdsByRecordRef.keySet()); return ScheduledPackageableLocks.of( CollectionUtils.mapKeys( lockManager.getLockInfosByRecordIds(recordRefs), scheduleIdsByRecordRef::get ) ); } public void lockSchedules( final @NonNull ShipmentScheduleAndJobScheduleIdSet scheduleIds, final @NonNull UserId lockedBy) { shipmentScheduleLockRepository.lock( ShipmentScheduleLockRequest.builder() // TODO: consider locking/unlocking per schedule too? .shipmentScheduleIds(scheduleIds.getShipmentScheduleIds()) .lockType(ShipmentScheduleLockType.PICKING) .lockedBy(lockedBy) .build()); } public void unlockSchedules(@NonNull final PickingJob pickingJob) { if (pickingJob.getLockedBy() == null)
{ return; } this.unlockSchedules(pickingJob.getScheduleIds(), pickingJob.getLockedBy()); } public void unlockSchedules( final @NonNull ShipmentScheduleAndJobScheduleIdSet scheduleIds, final @NonNull UserId lockedBy) { shipmentScheduleLockRepository.unlock( ShipmentScheduleUnLockRequest.builder() // TODO: consider locking/unlocking per schedule too? .shipmentScheduleIds(scheduleIds.getShipmentScheduleIds()) .lockType(ShipmentScheduleLockType.PICKING) .lockedBy(lockedBy) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobLockService.java
2
请完成以下Java代码
private String getBottomText() { if (Check.isEmpty(bottomURL, true)) { return null; } final String bottomURLText; if (html) { bottomURLText = new a(bottomURL, bottomURL).toString(); } else { bottomURLText = bottomURL; } String bottomText = msgBL.getTranslatableMsgText(MSG_BottomText, bottomURLText) .translate(getLanguage()); return bottomText; } // // // // // private static final class ReplaceAfterFormatCollector { private final Map<String, String> map = new HashMap<>(); public String addAndGetKey(@NonNull final String partToReplace) { final String key = "#{" + map.size() + 1 + "}"; map.put(key, partToReplace); return key; }
public String replaceAll(@NonNull final String string) { if (map.isEmpty()) { return string; } String result = string; for (final Map.Entry<String, String> e : map.entrySet()) { result = result.replace(e.getKey(), e.getValue()); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\NotificationMessageFormatter.java
1
请在Spring Boot框架中完成以下Java代码
public void setPublished(LocalDate published) { this.published = published; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BookDTO bookDTO = (BookDTO) o; if (bookDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), bookDTO.getId()); }
@Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "BookDTO{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", author='" + getAuthor() + "'" + ", published='" + getPublished() + "'" + ", quantity=" + getQuantity() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\BookDTO.java
2
请在Spring Boot框架中完成以下Java代码
class HmacSHA256JWTService implements JWTSerializer, JWTDeserializer { private static final String JWT_HEADER = base64URLFromString("{\"alg\":\"HS256\",\"type\":\"JWT\"}"); private static final String BASE64URL_PATTERN = "[\\w_\\-]+"; private static final Pattern JWT_PATTERN = compile(format("^(%s\\.)(%s\\.)(%s)$", BASE64URL_PATTERN, BASE64URL_PATTERN, BASE64URL_PATTERN)); private final byte[] secret; private final long durationSeconds; private final ObjectMapper objectMapper; HmacSHA256JWTService(byte[] secret, long durationSeconds, ObjectMapper objectMapper) { this.secret = secret; this.durationSeconds = durationSeconds; this.objectMapper = objectMapper; } @Override public String jwtFromUser(User user) { final var messageToSign = JWT_HEADER.concat(".").concat(jwtPayloadFromUser(user)); final var signature = HmacSHA256.sign(secret, messageToSign); return messageToSign.concat(".").concat(base64URLFromBytes(signature)); } private String jwtPayloadFromUser(User user) { var jwtPayload = UserJWTPayload.of(user, now().getEpochSecond() + durationSeconds); return base64URLFromString(jwtPayload.toString()); }
@Override public JWTPayload jwtPayloadFromJWT(String jwtToken) { if (!JWT_PATTERN.matcher(jwtToken).matches()) { throw new IllegalArgumentException("Malformed JWT: " + jwtToken); } final var splintedTokens = jwtToken.split("\\."); if (!splintedTokens[0].equals(JWT_HEADER)) { throw new IllegalArgumentException("Malformed JWT! Token must starts with header: " + JWT_HEADER); } final var signatureBytes = HmacSHA256.sign(secret, splintedTokens[0].concat(".").concat(splintedTokens[1])); if (!base64URLFromBytes(signatureBytes).equals(splintedTokens[2])) { throw new IllegalArgumentException("Token has invalid signature: " + jwtToken); } try { final var decodedPayload = stringFromBase64URL(splintedTokens[1]); final var jwtPayload = objectMapper.readValue(decodedPayload, UserJWTPayload.class); if (jwtPayload.isExpired()) { throw new IllegalArgumentException("Token expired"); } return jwtPayload; } catch (Exception exception) { throw new IllegalArgumentException(exception); } } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\infrastructure\jwt\HmacSHA256JWTService.java
2
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String uuid; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
repos\tutorials-master\persistence-modules\read-only-transactions\src\main\java\com\baeldung\readonlytransactions\h2\Book.java
2
请在Spring Boot框架中完成以下Java代码
public class CommonPayComponent extends BaseComponent { @Autowired private AlipayComponent alipayComponent; @Autowired private WechatPayComponent wechatPayComponent; @Autowired private UnionPayComponent unionPayComponent; @Override public void handle(OrderProcessContext orderProcessContext) { preHandle(orderProcessContext); // 处理支付请求 doPay(orderProcessContext); afterHandle(orderProcessContext); } /** * 处理支付请求 * @param orderProcessContext 订单受理上下文 */ private void doPay(OrderProcessContext orderProcessContext) { // 获取支付方式 PayModeEnum payModeEnum = getPayModeEnum(orderProcessContext); switch (payModeEnum) { case ALIPAY: alipayComponent.handle(orderProcessContext); break; case WECHAT: wechatPayComponent.handle(orderProcessContext); break; case UNIONPAY: unionPayComponent.handle(orderProcessContext); break; } } /** * 获取支付方式
* @param orderProcessContext * @return */ private PayModeEnum getPayModeEnum(OrderProcessContext orderProcessContext) { // 获取OrderInsertReq OrderInsertReq orderInsertReq = (OrderInsertReq) orderProcessContext.getOrderProcessReq().getReqData(); // 获取支付方式Code Integer payModeCode = orderInsertReq.getPayModeCode(); if (payModeCode == null) { throw new CommonSysException(ExpCodeEnum.PAYMODE_NULL); } // 获取支付方式 PayModeEnum payModeEnum = EnumUtil.codeOf(PayModeEnum.class, payModeCode); if (payModeEnum == null) { throw new CommonBizException(ExpCodeEnum.PAYMODECODE_ERROR); } return payModeEnum; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\pay\CommonPayComponent.java
2
请完成以下Java代码
default Builder<?> toBuilder() { return new SimpleAuthentication.Builder(this); } /** * A builder based on a given {@link Authentication} instance * * @author Josh Cummings * @since 7.0 */ interface Builder<B extends Builder<B>> { /** * Mutate the authorities with this {@link Consumer}. * <p> * Note that since a non-empty set of authorities implies an * {@link Authentication} is authenticated, this method also marks the * authentication as {@link #authenticated} by default. * </p> * @param authorities a consumer that receives the full set of authorities * @return the {@link Builder} for additional configuration * @see Authentication#getAuthorities */ B authorities(Consumer<Collection<GrantedAuthority>> authorities); /** * Use this credential. * <p> * Note that since some credentials are insecure to store, this method is * implemented as unsupported by default. Only implement or use this method if you * support secure storage of the credential or if your implementation also * implements {@link CredentialsContainer} and the credentials are thereby erased. * </p> * @param credentials the credentials to use * @return the {@link Builder} for additional configuration * @see Authentication#getCredentials */ default B credentials(@Nullable Object credentials) { throw new UnsupportedOperationException( String.format("%s does not store credentials", this.getClass().getSimpleName())); } /** * Use this details object. * <p> * Implementations may choose to use these {@code details} in combination with any
* principal from the pre-existing {@link Authentication} instance. * </p> * @param details the details to use * @return the {@link Builder} for additional configuration * @see Authentication#getDetails */ B details(@Nullable Object details); /** * Use this principal. * <p> * Note that in many cases, the principal is strongly-typed. Implementations may * choose to do a type check and are not necessarily expected to allow any object * as a principal. * </p> * <p> * Implementations may choose to use this {@code principal} in combination with * any principal from the pre-existing {@link Authentication} instance. * </p> * @param principal the principal to use * @return the {@link Builder} for additional configuration * @see Authentication#getPrincipal */ B principal(@Nullable Object principal); /** * Mark this authentication as authenticated or not * @param authenticated whether this is an authenticated {@link Authentication} * instance * @return the {@link Builder} for additional configuration * @see Authentication#isAuthenticated */ B authenticated(boolean authenticated); /** * Build an {@link Authentication} instance * @return the {@link Authentication} instance */ Authentication build(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\Authentication.java
1
请完成以下Java代码
public String toString() { return "BlackListItem [" + " packageProcessorId=" + packageProcessorId + ", classname=" + classname + ", hitCount=" + hitCount + ", dateFirstRequest=" + dateFirstRequest + ", dateLastRequest=" + dateLastRequest + ", exception=" + exception + "]"; } public Exception getException() { return exception; } public int incrementHitCount() { dateLastRequest = new Date(); return hitCount.incrementAndGet(); } } private final transient Logger logger = LogManager.getLogger(getClass()); private final Map<Integer, BlackListItem> blacklist = new ConcurrentHashMap<Integer, BlackListItem>(); public WorkpackageProcessorBlackList() { super(); } public boolean isBlacklisted(final int workpackageProcessorId) { return blacklist.containsKey(workpackageProcessorId); } public void addToBlacklist(final int packageProcessorId, String packageProcessorClassname, Exception e) { final ConfigurationException exception = ConfigurationException.wrapIfNeeded(e);
final BlackListItem blacklistItemToAdd = new BlackListItem(packageProcessorId, packageProcessorClassname, exception); blacklist.put(packageProcessorId, blacklistItemToAdd); logger.warn("Processor blacklisted: " + blacklistItemToAdd, exception); } public void removeFromBlacklist(final int packageProcessorId) { final BlackListItem blacklistItem = blacklist.remove(packageProcessorId); if (blacklistItem != null) { logger.info("Processor removed from blacklist: " + blacklistItem); } } public void assertNotBlacklisted(final int workpackageProcessorId) { final BlackListItem blacklistItem = blacklist.get(workpackageProcessorId); if (blacklistItem != null) { blacklistItem.incrementHitCount(); throw new ConfigurationException("Already blacklisted: " + blacklistItem, blacklistItem.getException()); } } public List<BlackListItem> getItems() { return new ArrayList<BlackListItem>(blacklist.values()); } public void clear() { blacklist.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorBlackList.java
1
请在Spring Boot框架中完成以下Java代码
public class CurrencyConversionTypeId implements RepoIdAware { @JsonCreator public static CurrencyConversionTypeId ofRepoId(final int repoId) { return new CurrencyConversionTypeId(repoId); } @Nullable public static CurrencyConversionTypeId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<CurrencyConversionTypeId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final CurrencyConversionTypeId CurrencyConversionTypeId) { return CurrencyConversionTypeId != null ? CurrencyConversionTypeId.getRepoId() : -1; } int repoId;
private CurrencyConversionTypeId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_ConversionType_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final CurrencyConversionTypeId currencyConversionTypeId1, @Nullable final CurrencyConversionTypeId currencyConversionTypeId2) { return Objects.equals(currencyConversionTypeId1, currencyConversionTypeId2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\CurrencyConversionTypeId.java
2
请完成以下Java代码
public synchronized void schedule(final ScheduledRequest request) { this.requestsQueue.add(request); if (executorFuture.isDone()) { executorFuture = executorFuture.thenRunAsync(this::run, executor); } } private void run() { try { while (!requestsQueue.isEmpty()) { final ScheduledRequest scheduleRequest = requestsQueue.poll(); try
{ final ApiResponse response = scheduleRequest.getHttpResponseSupplier().get(); scheduleRequest.getCompletableFuture().complete(response); } catch (final Exception exception) { scheduleRequest.getCompletableFuture().completeExceptionally(exception); } } } finally { executorFuture.complete(null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\HttpCallScheduler.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @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); } @Override public void setPP_Workstation_UserAssign_ID (final int PP_Workstation_UserAssign_ID) { if (PP_Workstation_UserAssign_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Workstation_UserAssign_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Workstation_UserAssign_ID, PP_Workstation_UserAssign_ID); } @Override public int getPP_Workstation_UserAssign_ID() { return get_ValueAsInt(COLUMNNAME_PP_Workstation_UserAssign_ID); }
@Override public org.compiere.model.I_S_Resource getWorkStation() { return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class); } @Override public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation) { set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation); } @Override public void setWorkStation_ID (final int WorkStation_ID) { if (WorkStation_ID < 1) set_ValueNoCheck (COLUMNNAME_WorkStation_ID, null); else set_ValueNoCheck (COLUMNNAME_WorkStation_ID, WorkStation_ID); } @Override public int getWorkStation_ID() { return get_ValueAsInt(COLUMNNAME_WorkStation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Workstation_UserAssign.java
1
请完成以下Java代码
public void afterSave(final I_C_AcctSchema_Element element) { // Default Value if (element.isMandatory() && InterfaceWrapperHelper.isValueChanged(element, COLUMNNAME_IsMandatory)) { final AcctSchemaElementType elementType = AcctSchemaElementType.ofCode(element.getElementType()); if (AcctSchemaElementType.Activity.equals(elementType)) { updateData(COLUMNNAME_C_Activity_ID, element.getC_Activity_ID(), element); } else if (AcctSchemaElementType.BPartner.equals(elementType)) { updateData(COLUMNNAME_C_BPartner_ID, element.getC_BPartner_ID(), element); } else if (AcctSchemaElementType.Product.equals(elementType)) { updateData(COLUMNNAME_M_Product_ID, element.getM_Product_ID(), element); } else if (AcctSchemaElementType.Project.equals(elementType)) { updateData(COLUMNNAME_C_Project_ID, element.getC_Project_ID(), element); } else if (AcctSchemaElementType.SalesOrder.equals(elementType)) { updateData(COLUMNNAME_C_OrderSO_ID, element.getC_OrderSO_ID(), element); } } // Re-sequence if (InterfaceWrapperHelper.isNew(element) || InterfaceWrapperHelper.isValueChanged(element, COLUMNNAME_SeqNo)) { MAccount.updateValueDescription(Env.getCtx(), "AD_Client_ID=" + element.getAD_Client_ID(), ITrx.TRXNAME_ThreadInherited); } } // afterSave /** * Update ValidCombination and Fact with mandatory value * * @param element element * @param id new default
*/ private void updateData(final String element, final int id, final I_C_AcctSchema_Element elementRecord) { MAccount.updateValueDescription(Env.getCtx(), element + "=" + id, ITrx.TRXNAME_ThreadInherited); // { final int clientId = elementRecord.getAD_Client_ID(); final String sql = "UPDATE C_ValidCombination SET " + element + "=? WHERE " + element + " IS NULL AND AD_Client_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { id, clientId }, ITrx.TRXNAME_ThreadInherited); } // { final int acctSchemaId = elementRecord.getC_AcctSchema_ID(); final String sql = "UPDATE Fact_Acct SET " + element + "=? WHERE " + element + " IS NULL AND C_AcctSchema_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { id, acctSchemaId }, ITrx.TRXNAME_ThreadInherited); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_C_AcctSchema_Element element) { final AcctSchemaElementType elementType = AcctSchemaElementType.ofCode(element.getElementType()); if (!elementType.isDeletable()) { throw new AdempiereException("@DeleteError@ @IsMandatory@"); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }) public void afterDelete(final I_C_AcctSchema_Element element) { MAccount.updateValueDescription(Env.getCtx(), "AD_Client_ID=" + element.getAD_Client_ID(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_AcctSchema_Element.java
1
请完成以下Java代码
public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public DynamicEmbeddedSubProcessBuilder processDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } public String getDynamicSubProcessId() { return dynamicSubProcessId; } public void setDynamicSubProcessId(String dynamicSubProcessId) { this.dynamicSubProcessId = dynamicSubProcessId; } public String nextSubProcessId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicSubProcess", flowElementMap); } public String nextTaskId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicTask", flowElementMap); } public String nextFlowId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicFlow", flowElementMap); } public String nextForkGatewayId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicForkGateway", flowElementMap); } public String nextJoinGatewayId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicJoinGateway", flowElementMap); } public String nextStartEventId(Map<String, FlowElement> flowElementMap) { return nextId("startEvent", flowElementMap); } public String nextEndEventId(Map<String, FlowElement> flowElementMap) {
return nextId("endEvent", flowElementMap); } protected String nextId(String prefix, Map<String, FlowElement> flowElementMap) { String nextId = null; boolean nextIdNotFound = true; while (nextIdNotFound) { if (!flowElementMap.containsKey(prefix + counter)) { nextId = prefix + counter; nextIdNotFound = false; } counter++; } return nextId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\DynamicEmbeddedSubProcessBuilder.java
1
请完成以下Java代码
public String getElementVariable() { return elementVariable; } public void setElementVariable(String elementVariable) { this.elementVariable = elementVariable; } public String getElementIndexVariable() { return elementIndexVariable; } public void setElementIndexVariable(String elementIndexVariable) { this.elementIndexVariable = elementIndexVariable; } public boolean isSequential() { return sequential; } public void setSequential(boolean sequential) { this.sequential = sequential; } public String getLoopDataOutputRef() { return loopDataOutputRef; } public void setLoopDataOutputRef(String loopDataOutputRef) { this.loopDataOutputRef = loopDataOutputRef; }
public String getOutputDataItem() { return outputDataItem; } public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; } public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; } public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setLoopDataOutputRef(otherLoopCharacteristics.getLoopDataOutputRef()); setOutputDataItem(otherLoopCharacteristics.getOutputDataItem()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请完成以下Java代码
public List<TransactionInterest2> getIntrst() { if (intrst == null) { intrst = new ArrayList<TransactionInterest2>(); } return this.intrst; } /** * Gets the value of the ntryDtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ntryDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNtryDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EntryDetails1 } * * */ public List<EntryDetails1> getNtryDtls() { if (ntryDtls == null) { ntryDtls = new ArrayList<EntryDetails1>(); } return this.ntryDtls; } /**
* Gets the value of the addtlNtryInf property. * * @return * possible object is * {@link String } * */ public String getAddtlNtryInf() { return addtlNtryInf; } /** * Sets the value of the addtlNtryInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlNtryInf(String value) { this.addtlNtryInf = 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\ReportEntry2.java
1
请完成以下Java代码
public PlainTrxManager setFailCommitIfTrxNotStarted(final boolean failCommitIfTrxNotStarted) { this.failCommitIfTrxNotStarted = failCommitIfTrxNotStarted; return this; } public boolean isFailCommitIfTrxNotStarted() { return failCommitIfTrxNotStarted; } public PlainTrxManager setFailRollbackIfTrxNotStarted(final boolean failRollbackIfTrxNotStarted) { this.failRollbackIfTrxNotStarted = failRollbackIfTrxNotStarted; return this; } public boolean isFailRollbackIfTrxNotStarted() { return failRollbackIfTrxNotStarted; } public void assertNoActiveTransactions() { final List<ITrx> activeTrxs = getActiveTransactionsList(); Check.assume(activeTrxs.isEmpty(), "Expected no active transactions but got: {}", activeTrxs); } /** * Ask the transactions to log their major events like COMMIT, ROLLBACK.
* Those events will be visible on {@link PlainTrx#toString()}. * * @param debugTrxLog */ public void setDebugTrxLog(boolean debugTrxLog) { this.debugTrxLog = debugTrxLog; } /** * @see #setDebugTrxLog(boolean) */ public boolean isDebugTrxLog() { return debugTrxLog; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrxManager.java
1
请完成以下Java代码
public class SwaggerDocConstants { public static final String BPARTNER_IDENTIFIER_DOC = "Identifier of the bPartner in question. Can be\n" + "* a plain `<C_BPartner_ID>`\n" + "* or something like `ext-<C_Bartner.ExternalId>` (This is deprecated and will no longer be available with v2)\n" + "* or something like `val-<C_Bartner.Value>`\n" + "* or something like `gln-<C_Bartner_Location.GLN>`\n"; public static final String INVOICE_IDENTIFIER_DOC = "Identifier of the Invoice in question. Can be\n" + "* a plain `<C_Invoice.C_Invoice_ID>`\n" + "* or something like `doc-<C_Invoice.documentNo>`" + "* or something like `ext-<C_Invoice.ExternalId>`"; public static final String ORDER_IDENTIFIER_DOC = "Identifier of the Order in question. Can be\n" + "* a plain `<C_Order.C_Order_ID>`\n" + "* or something like `doc-<C_Order.documentNo>`" + "* or something like `ext-<C_Order.ExternalId>`"; public static final String CONTACT_IDENTIFIER_DOC = "Identifier of the contact in question. Can be\n" + "* a plain `<AD_User_ID>`\n" + "* or something like `ext-<AD_User_ID.ExternalId>` (This is deprecated and will no longer be available with v2)"; public static final String LOCATION_IDENTIFIER_DOC = "Identifier of the location in question. Can be\n" + "* a plain `<C_BPartner_Location_ID>`\n"
+ "* or something like `ext-<C_BPartner_Location_ID.ExternalId>` (This is deprecated and will no longer be available with v2)\n" + "* or something like `gln-<C_BPartner_Location_ID.GLN>`\n"; public static final String DATASOURCE_IDENTIFIER_DOC = "An identifier can be\n" + "* a plain `<AD_InputDataSource_ID>`\n" + "* or something like `int-<AD_InputDataSource.InternalName>`\n" + "* or something like `val-<AD_InputDataSource.Value>`\n" + "* or something like `ext-<AD_InputDataSource.ExternalId>`\n"; public static final String PRODUCT_IDENTIFIER_DOC = "Identifier of the product in question. Can be\n" + "* a plain `<M_Product_ID>`\n" + "* or something like `ext-<M_Product_ID.ExternalId>`\n" + "* or something like `val-<M_Product_ID.Value>`"; public static final String NEXT_DOC = "Optional identifier for the next page that was provided to the client in the previous page.\n" + "If provided, any `since` value is ignored"; public static final String SINCE_DOC = "Optional epoch timestamp in ms. The enpoint returns all resources that were created or modified *after* the given time."; public static final String READ_ONLY_SYNC_ADVISE_DOC = "Defaults to READ_ONLY, if not specified"; public static final String CREATE_OR_MERGE_SYNC_ADVISE_DOC = "Defaults to CREATE_OR_MERGE, if not specified"; public static final String PARENT_SYNC_ADVISE_DOC = "Defaults to the parent resource's sync advise, if not specified"; }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\SwaggerDocConstants.java
1
请在Spring Boot框架中完成以下Java代码
public class TaskletsConfig { @Bean public LinesReader linesReader() { return new LinesReader(); } @Bean public LinesProcessor linesProcessor() { return new LinesProcessor(); } @Bean public LinesWriter linesWriter() { return new LinesWriter(); } @Bean protected Step readLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("readLines", jobRepository) .tasklet(linesReader(), transactionManager) .build(); } @Bean protected Step processLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("processLines", jobRepository) .tasklet(linesProcessor(), transactionManager)
.build(); } @Bean protected Step writeLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("writeLines", jobRepository) .tasklet(linesWriter(), transactionManager) .build(); } @Bean public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("taskletsJob", jobRepository) .start(readLines(jobRepository, transactionManager)) .next(processLines(jobRepository, transactionManager)) .next(writeLines(jobRepository, transactionManager)) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\config\TaskletsConfig.java
2
请完成以下Java代码
public int getRoundToPrecision() { return roundToPrecision; } /** * This value is used to configure the {@link ScalesGetWeightHandler}. * * @param roundToPrecision may be <code>null</code> in that case, not rounding will be done. * @see ScalesGetWeightHandler#setroundWeightToPrecision(int) */ public void setRoundToPrecision(final Integer roundToPrecision) { this.roundToPrecision = roundToPrecision == null ? -1 : roundToPrecision; } @Override public IDeviceResponseGetConfigParams getRequiredConfigParams() { final List<IDeviceConfigParam> params = new ArrayList<IDeviceConfigParam>(); // params.add(new DeviceConfigParamPojo("DeviceClass", "DeviceClass", "")); // if we can query this device for its params, then we already know the device class. params.add(new DeviceConfigParam(PARAM_ENDPOINT_CLASS, "Endpoint.Class", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_IP, "Endpoint.IP", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_PORT, "Endpoint.Port", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_RETURN_LAST_LINE, PARAM_ENDPOINT_RETURN_LAST_LINE, "N")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, "500")); params.add(new DeviceConfigParam(PARAM_ROUND_TO_PRECISION, "RoundToPrecision", "-1")); return new IDeviceResponseGetConfigParams() { @Override public List<IDeviceConfigParam> getParams() { return params;
} }; } @Override public IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler() { return new ConfigureDeviceHandler(this); } @Override public String toString() { return getClass().getSimpleName() + " with Endpoint " + endPoint.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\AbstractTcpScales.java
1
请完成以下Java代码
public void onCreate(VariableInstanceEntity variable, AbstractVariableScope sourceScope) { handleEvent(new VariableEvent(variable, VariableListener.CREATE, sourceScope)); } @Override public void onUpdate(VariableInstanceEntity variable, AbstractVariableScope sourceScope) { handleEvent(new VariableEvent(variable, VariableListener.UPDATE, sourceScope)); } @Override public void onDelete(VariableInstanceEntity variable, AbstractVariableScope sourceScope) { handleEvent(new VariableEvent(variable, VariableListener.DELETE, sourceScope)); } protected void handleEvent(VariableEvent event) { AbstractVariableScope sourceScope = event.getSourceScope(); if (sourceScope instanceof ExecutionEntity) { addEventToScopeExecution((ExecutionEntity) sourceScope, event); } else if (sourceScope instanceof TaskEntity) { TaskEntity task = (TaskEntity) sourceScope; ExecutionEntity execution = task.getExecution(); if (execution != null) { addEventToScopeExecution(execution, event);
} } else if(sourceScope.getParentVariableScope() instanceof ExecutionEntity) { addEventToScopeExecution((ExecutionEntity)sourceScope.getParentVariableScope(), event); } else { throw new ProcessEngineException("BPMN execution scope expected"); } } protected void addEventToScopeExecution(ExecutionEntity sourceScope, VariableEvent event) { // ignore events of variables that are not set in an execution ExecutionEntity sourceExecution = sourceScope; ExecutionEntity scopeExecution = sourceExecution.isScope() ? sourceExecution : sourceExecution.getParent(); scopeExecution.delayEvent((ExecutionEntity) targetScope, event); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableListenerInvocationListener.java
1
请完成以下Java代码
public String getExecutionExceptionTypeHeaderName() { return executionExceptionTypeHeaderName; } public void setExecutionExceptionTypeHeaderName(String executionExceptionTypeHeaderName) { this.executionExceptionTypeHeaderName = executionExceptionTypeHeaderName; } public String getExecutionExceptionMessageHeaderName() { return executionExceptionMessageHeaderName; } public void setExecutionExceptionMessageHeaderName(String executionExceptionMessageHeaderName) { this.executionExceptionMessageHeaderName = executionExceptionMessageHeaderName; } public String getRootCauseExceptionTypeHeaderName() {
return rootCauseExceptionTypeHeaderName; } public void setRootCauseExceptionTypeHeaderName(String rootCauseExceptionTypeHeaderName) { this.rootCauseExceptionTypeHeaderName = rootCauseExceptionTypeHeaderName; } public String getRootCauseExceptionMessageHeaderName() { return rootCauseExceptionMessageHeaderName; } public void setRootCauseExceptionMessageHeaderName(String rootCauseExceptionMessageHeaderName) { this.rootCauseExceptionMessageHeaderName = rootCauseExceptionMessageHeaderName; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\FallbackHeadersGatewayFilterFactory.java
1
请完成以下Java代码
public class MHRConceptCategory extends X_HR_Concept_Category { /** * */ private static final long serialVersionUID = 8470029939291479283L; private static CCache<Integer, MHRConceptCategory> s_cache = new CCache<Integer, MHRConceptCategory>(Table_Name, 20); private static CCache<String, MHRConceptCategory> s_cacheValue = new CCache<String, MHRConceptCategory>(Table_Name+"_Value", 20); public static MHRConceptCategory get(Properties ctx, int HR_Concept_Category_ID) { if (HR_Concept_Category_ID <= 0) { return null; } // Try cache MHRConceptCategory cc = s_cache.get(HR_Concept_Category_ID); if (cc != null) { return cc; } // Load from DB cc = new MHRConceptCategory(ctx, HR_Concept_Category_ID, null); if (cc.get_ID() != HR_Concept_Category_ID) { return null; } if (cc != null) { s_cache.put(HR_Concept_Category_ID, cc); } return cc; } public static MHRConceptCategory forValue(Properties ctx, String value) {
if (value == null) { return null; } final int AD_Client_ID = Env.getAD_Client_ID(ctx); // Try cache final String key = AD_Client_ID+"#"+value; MHRConceptCategory cc = s_cacheValue.get(key); if (cc != null) { return cc; } // Try database final String whereClause = COLUMNNAME_Value+"=? AND AD_Client_ID IN (?,?)"; cc = new Query(ctx, Table_Name, whereClause, null) .setParameters(new Object[]{value, 0, AD_Client_ID}) .setOnlyActiveRecords(true) .setOrderBy("AD_Client_ID DESC") .first(); if (cc != null) { s_cacheValue.put(key, cc); s_cache.put(cc.get_ID(), cc); } return cc; } public MHRConceptCategory(Properties ctx, int HR_Concept_Category_ID, String trxName) { super(ctx, HR_Concept_Category_ID, trxName); } public MHRConceptCategory(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRConceptCategory.java
1
请完成以下Java代码
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected DeleteProcessInstanceBatchConfiguration createJobConfiguration(DeleteProcessInstanceBatchConfiguration configuration, List<String> processIdsForJob) { return new DeleteProcessInstanceBatchConfiguration( processIdsForJob, null, configuration.getDeleteReason(), configuration.isSkipCustomListeners(), configuration.isSkipSubprocesses(), configuration.isFailIfNotExists(), configuration.isSkipIoMappings() ); } @Override public void executeHandler(DeleteProcessInstanceBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { commandContext.executeWithOperationLogPrevented( new DeleteProcessInstancesCmd( batchConfiguration.getIds(), batchConfiguration.getDeleteReason(), batchConfiguration.isSkipCustomListeners(), true, batchConfiguration.isSkipSubprocesses(), batchConfiguration.isFailIfNotExists(),
batchConfiguration.isSkipIoMappings() )); } @Override protected void createJobEntities(BatchEntity batch, DeleteProcessInstanceBatchConfiguration configuration, String deploymentId, List<String> processIds, int invocationsPerBatchJob) { // handle legacy batch entities (no up-front deployment mapping has been done) if (deploymentId == null && (configuration.getIdMappings() == null || configuration.getIdMappings().isEmpty())) { // create deployment mappings for the ids to process BatchElementConfiguration elementConfiguration = new BatchElementConfiguration(); ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl(); query.processInstanceIds(new HashSet<>(configuration.getIds())); elementConfiguration.addDeploymentMappings(query.listDeploymentIdMappings(), configuration.getIds()); // create jobs by deployment id elementConfiguration.getMappings().forEach(mapping -> super.createJobEntities(batch, configuration, mapping.getDeploymentId(), mapping.getIds(processIds), invocationsPerBatchJob)); } else { super.createJobEntities(batch, configuration, deploymentId, processIds, invocationsPerBatchJob); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\deletion\DeleteProcessInstancesJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void saveOrUpdate( @Nullable final StockChangeDetail stockChangeDetail, @NonNull final I_MD_Candidate candidateRecord) { if (stockChangeDetail == null) { return; } final CandidateId candidateId = CandidateId.ofRepoId(candidateRecord.getMD_Candidate_ID()); I_MD_Candidate_StockChange_Detail recordToUpdate = RepositoryCommons.retrieveSingleCandidateDetail( candidateId, I_MD_Candidate_StockChange_Detail.class); if (recordToUpdate == null) { recordToUpdate = newInstance(I_MD_Candidate_StockChange_Detail.class, candidateRecord); recordToUpdate.setMD_Candidate_ID(candidateId.getRepoId()); } recordToUpdate.setFresh_QtyOnHand_ID(NumberUtils.asInteger(stockChangeDetail.getFreshQuantityOnHandRepoId(), -1)); recordToUpdate.setFresh_QtyOnHand_Line_ID(NumberUtils.asInteger(stockChangeDetail.getFreshQuantityOnHandLineRepoId(), -1)); recordToUpdate.setM_Inventory_ID(NumberUtils.asInteger(stockChangeDetail.getInventoryId(), -1)); recordToUpdate.setM_InventoryLine_ID(NumberUtils.asInteger(stockChangeDetail.getInventoryLineId(), -1)); recordToUpdate.setIsReverted(Boolean.TRUE.equals(stockChangeDetail.getIsReverted())); recordToUpdate.setEventDateMaterialDispo(TimeUtil.asTimestamp(stockChangeDetail.getEventDate())); saveRecord(recordToUpdate); } @Nullable private StockChangeDetail ofRecord(@Nullable final I_MD_Candidate_StockChange_Detail record) { if (record == null) {
return null; } final Integer computedFreshQtyOnHandId = NumberUtils.asIntegerOrNull(record.getFresh_QtyOnHand_ID()); final Integer computedFreshQtyOnHandLineId = NumberUtils.asIntegerOrNull(record.getFresh_QtyOnHand_Line_ID()); return StockChangeDetail.builder() .candidateStockChangeDetailId(CandidateStockChangeDetailId.ofRepoId(record.getMD_Candidate_StockChange_Detail_ID())) .candidateId(CandidateId.ofRepoId(record.getMD_Candidate_ID())) .freshQuantityOnHandRepoId(computedFreshQtyOnHandId) .freshQuantityOnHandLineRepoId(computedFreshQtyOnHandLineId) .inventoryId(InventoryId.ofRepoIdOrNull(record.getM_Inventory_ID())) .inventoryLineId(InventoryLineId.ofRepoIdOrNull(record.getM_InventoryLine_ID())) .isReverted(record.isReverted()) .eventDate(TimeUtil.asInstantNonNull(record.getEventDateMaterialDispo())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\repohelpers\StockChangeDetailRepo.java
2
请在Spring Boot框架中完成以下Java代码
public String getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is * {@link String } * */ public void setTown(String value) { this.town = value; } /** * ZIP code. * * @return * possible object is * {@link String } * */ public String getZIP() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link String } * */ public void setZIP(String value) { this.zip = value; } /** * Country information. * * @return * possible object is * {@link CountryType } * */ public CountryType getCountry() { return country; }
/** * Sets the value of the country property. * * @param value * allowed object is * {@link CountryType } * */ public void setCountry(CountryType value) { this.country = value; } /** * Any further elements or attributes which are necessary for an address may be provided here. * Note that extensions should be used with care and only those extensions shall be used, which are officially provided by ERPEL. * Gets the value of the addressExtension property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addressExtension property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddressExtension().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddressExtension() { if (addressExtension == null) { addressExtension = new ArrayList<String>(); } return this.addressExtension; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AddressType.java
2
请在Spring Boot框架中完成以下Java代码
public class UnpaidInvoiceMatchingAmtQuery { @Nullable IQueryFilter<I_C_Invoice> additionalFilter; @NonNull ImmutableSet<DocStatus> onlyDocStatuses; @NonNull QueryLimit queryLimit; @Nullable Amount openAmountAtDate; @Nullable ZonedDateTime openAmountEvaluationDate; @Builder private UnpaidInvoiceMatchingAmtQuery( @Nullable final IQueryFilter<I_C_Invoice> additionalFilter, @NonNull final ImmutableSet<DocStatus> onlyDocStatuses, @NonNull final QueryLimit queryLimit, @Nullable final Amount openAmountAtDate, @Nullable final ZonedDateTime openAmountEvaluationDate) { if (openAmountAtDate != null) { Check.assumeNotNull(openAmountEvaluationDate, "OpenAmountEvaluationDate must be specified when OpenAmountAtDate is specified"); } this.additionalFilter = additionalFilter; this.onlyDocStatuses = onlyDocStatuses; this.queryLimit = queryLimit; this.openAmountAtDate = openAmountAtDate; this.openAmountEvaluationDate = openAmountEvaluationDate; }
@NonNull public Optional<CurrencyCode> getCurrencyCode() { return Optional.ofNullable(openAmountAtDate).map(Amount::getCurrencyCode); } @NonNull public UnpaidInvoiceQuery getUnpaidInvoiceQuery() { return UnpaidInvoiceQuery.builder() .additionalFilter(additionalFilter) .onlyDocStatuses(onlyDocStatuses) .queryLimit(queryLimit) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\invoice\UnpaidInvoiceMatchingAmtQuery.java
2
请在Spring Boot框架中完成以下Java代码
public class GraphiteProperties { /** * Whether exporting of metrics to Graphite is enabled. */ private boolean enabled = true; /** * Step size (i.e. reporting frequency) to use. */ private Duration step = Duration.ofMinutes(1); /** * Base time unit used to report rates. */ private TimeUnit rateUnits = TimeUnit.SECONDS; /** * Base time unit used to report durations. */ private TimeUnit durationUnits = TimeUnit.MILLISECONDS; /** * Host of the Graphite server to receive exported metrics. */ private String host = "localhost"; /** * Port of the Graphite server to receive exported metrics. */ private Integer port = 2004; /** * Protocol to use while shipping data to Graphite. */ private GraphiteProtocol protocol = GraphiteProtocol.PICKLED; /** * Whether Graphite tags should be used, as opposed to a hierarchical naming * convention. Enabled by default unless "tagsAsPrefix" is set. */ private @Nullable Boolean graphiteTagsEnabled; /** * For the hierarchical naming convention, turn the specified tag keys into part of * the metric prefix. Ignored if "graphiteTagsEnabled" is true. */ private String[] tagsAsPrefix = new String[0]; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Duration getStep() { return this.step; } public void setStep(Duration step) { this.step = step; } public TimeUnit getRateUnits() { return this.rateUnits; } public void setRateUnits(TimeUnit rateUnits) { this.rateUnits = rateUnits; } public TimeUnit getDurationUnits() { return this.durationUnits; }
public void setDurationUnits(TimeUnit durationUnits) { this.durationUnits = durationUnits; } public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; } public GraphiteProtocol getProtocol() { return this.protocol; } public void setProtocol(GraphiteProtocol protocol) { this.protocol = protocol; } public Boolean getGraphiteTagsEnabled() { return (this.graphiteTagsEnabled != null) ? this.graphiteTagsEnabled : ObjectUtils.isEmpty(this.tagsAsPrefix); } public void setGraphiteTagsEnabled(Boolean graphiteTagsEnabled) { this.graphiteTagsEnabled = graphiteTagsEnabled; } public String[] getTagsAsPrefix() { return this.tagsAsPrefix; } public void setTagsAsPrefix(String[] tagsAsPrefix) { this.tagsAsPrefix = tagsAsPrefix; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\graphite\GraphiteProperties.java
2
请完成以下Java代码
public boolean isEnableConfiguratorServiceLoader() { return enableConfiguratorServiceLoader; } public AbstractEngineConfiguration setEnableConfiguratorServiceLoader(boolean enableConfiguratorServiceLoader) { this.enableConfiguratorServiceLoader = enableConfiguratorServiceLoader; return this; } public List<EngineConfigurator> getConfigurators() { return configurators; } public AbstractEngineConfiguration addConfigurator(EngineConfigurator configurator) { if (configurators == null) { configurators = new ArrayList<>(); } configurators.add(configurator); return this; } /** * @return All {@link EngineConfigurator} instances. Will only contain values after init of the engine. * Use the {@link #getConfigurators()} or {@link #addConfigurator(EngineConfigurator)} methods otherwise. */ public List<EngineConfigurator> getAllConfigurators() { return allConfigurators; } public AbstractEngineConfiguration setConfigurators(List<EngineConfigurator> configurators) { this.configurators = configurators; return this; } public EngineConfigurator getIdmEngineConfigurator() { return idmEngineConfigurator; } public AbstractEngineConfiguration setIdmEngineConfigurator(EngineConfigurator idmEngineConfigurator) { this.idmEngineConfigurator = idmEngineConfigurator;
return this; } public EngineConfigurator getEventRegistryConfigurator() { return eventRegistryConfigurator; } public AbstractEngineConfiguration setEventRegistryConfigurator(EngineConfigurator eventRegistryConfigurator) { this.eventRegistryConfigurator = eventRegistryConfigurator; return this; } public AbstractEngineConfiguration setForceCloseMybatisConnectionPool(boolean forceCloseMybatisConnectionPool) { this.forceCloseMybatisConnectionPool = forceCloseMybatisConnectionPool; return this; } public boolean isForceCloseMybatisConnectionPool() { return forceCloseMybatisConnectionPool; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractEngineConfiguration.java
1
请完成以下Java代码
public class SpringBeanFactoryProxyMap implements Map<Object, Object> { protected BeanFactory beanFactory; public SpringBeanFactoryProxyMap(BeanFactory beanFactory) { this.beanFactory = beanFactory; } public Object get(Object key) { if ((key == null) || (!String.class.isAssignableFrom(key.getClass()))) { return null; } return beanFactory.getBean((String) key); } public boolean containsKey(Object key) { if ((key == null) || (!String.class.isAssignableFrom(key.getClass()))) { return false; } return beanFactory.containsBean((String) key); } public Set<Object> keySet() { throw new ActivitiException("unsupported operation on configuration beans"); // List<String> beanNames = // asList(beanFactory.getBeanDefinitionNames()); // return new HashSet<Object>(beanNames); } public void clear() { throw new ActivitiException("can't clear configuration beans"); } public boolean containsValue(Object value) {
throw new ActivitiException("can't search values in configuration beans"); } public Set<Map.Entry<Object, Object>> entrySet() { throw new ActivitiException("unsupported operation on configuration beans"); } public boolean isEmpty() { throw new ActivitiException("unsupported operation on configuration beans"); } public Object put(Object key, Object value) { throw new ActivitiException("unsupported operation on configuration beans"); } public void putAll(Map<? extends Object, ? extends Object> m) { throw new ActivitiException("unsupported operation on configuration beans"); } public Object remove(Object key) { throw new ActivitiException("unsupported operation on configuration beans"); } public int size() { throw new ActivitiException("unsupported operation on configuration beans"); } public Collection<Object> values() { throw new ActivitiException("unsupported operation on configuration beans"); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\SpringBeanFactoryProxyMap.java
1
请完成以下Java代码
public List<Fact> createFacts(final AcctSchema as) { setC_Currency_ID(as.getCurrencyId()); final Fact fact = new Fact(this, as, PostingType.Actual); getDocLines().forEach(line -> createFactsForInventoryLine(fact, line)); return ImmutableList.of(fact); } /** * <pre> * Inventory * Inventory DR CR * InventoryDiff DR CR (or Charge) * </pre> */ private void createFactsForInventoryLine(final Fact fact, final DocLine_Inventory line) { final AcctSchema as = fact.getAcctSchema(); final CostAmount costs = line.getCreateCosts(as); // // Inventory DR/CR fact.createLine() .setDocLine(line)
.setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as)) .setAmtSourceDrOrCr(costs.toMoney()) .setQty(line.getQty()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); // // Charge/InventoryDiff CR/DR final Account invDiff = line.getInvDifferencesAccount(as, costs.toBigDecimal().negate()); final FactLine cr = fact.createLine() .setDocLine(line) .setAccount(invDiff) .setAmtSourceDrOrCr(costs.toMoney().negate()) .setQty(line.getQty().negate()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); if (line.getC_Charge_ID().isPresent()) // explicit overwrite for charge { cr.setAD_Org_ID(line.getOrgId()); } } } // Doc_Inventory
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Inventory.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceDimensionFactory implements DimensionFactory<I_C_Invoice> { @Override public String getHandledTableName() { return I_C_Invoice.Table_Name; } @Override @NonNull public Dimension getFromRecord(@NonNull final I_C_Invoice record) { return Dimension.builder() .projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID())) .campaignId(record.getC_Campaign_ID()) .activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.user1_ID(record.getUser1_ID()) .user2_ID(record.getUser2_ID()) .build(); } @Override public void updateRecord(@NonNull final I_C_Invoice record, @NonNull final Dimension from) { record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId())); record.setC_Campaign_ID(from.getCampaignId()); record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId())); record.setUser1_ID(from.getUser1_ID()); record.setUser2_ID(from.getUser2_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\InvoiceDimensionFactory.java
2
请完成以下Java代码
public void setRfQ_SelectedWinners_Count (int RfQ_SelectedWinners_Count) { throw new IllegalArgumentException ("RfQ_SelectedWinners_Count is virtual column"); } /** Get Selected winners count. @return Selected winners count */ @Override public int getRfQ_SelectedWinners_Count () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_SelectedWinners_Count); if (ii == null) return 0; return ii.intValue(); } /** Set Selected winners Qty. @param RfQ_SelectedWinners_QtySum Selected winners Qty */ @Override public void setRfQ_SelectedWinners_QtySum (java.math.BigDecimal RfQ_SelectedWinners_QtySum) { throw new IllegalArgumentException ("RfQ_SelectedWinners_QtySum is virtual column"); } /** Get Selected winners Qty. @return Selected winners Qty */ @Override public java.math.BigDecimal getRfQ_SelectedWinners_QtySum () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RfQ_SelectedWinners_QtySum); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Use line quantity. @param UseLineQty Use line quantity */ @Override public void setUseLineQty (boolean UseLineQty) { set_Value (COLUMNNAME_UseLineQty, Boolean.valueOf(UseLineQty));
} /** Get Use line quantity. @return Use line quantity */ @Override public boolean isUseLineQty () { Object oo = get_Value(COLUMNNAME_UseLineQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLine.java
1
请在Spring Boot框架中完成以下Java代码
public class H2InitDemoApplication { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(H2InitDemoApplication.class, args); initDatabaseUsingPlainJDBCWithURL(); initDatabaseUsingPlainJDBCWithFile(); initDatabaseUsingSpring(ctx.getBean(DataSource.class)); } /** * Initialize in-memory database using plain JDBC and SQL * statements in the URL. */ private static void initDatabaseUsingPlainJDBCWithURL() { try (Connection conn = DriverManager. getConnection("jdbc:h2:mem:baeldung;INIT=CREATE SCHEMA IF NOT EXISTS baeldung\\;SET SCHEMA baeldung;", "admin", "password")) { conn.createStatement().execute("create table users (name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL);"); System.out.println("Created table users"); conn.createStatement().execute("insert into users (name, email) values ('Mike', 'mike@baeldung.com')"); System.out.println("Added user mike"); } catch (Exception e) { e.printStackTrace(); } } /** * Initialize in-memory database using plain JDBC and SQL * statements in a file. */ private static void initDatabaseUsingPlainJDBCWithFile() { try (Connection conn = DriverManager. getConnection("jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'src/main/resources/h2init.sql';", "admin", "password")) {
conn.createStatement().execute("insert into users (name, email) values ('Mike', 'mike@baeldung.com')"); System.out.println("Added user mike"); } catch (Exception e) { e.printStackTrace(); } } /** * Initialize in-memory database using Spring Boot * properties. See article for full details of required * properties for this method to work. */ private static void initDatabaseUsingSpring(DataSource ds) { try (Connection conn = ds.getConnection()) { conn.createStatement().execute("insert into users (name, email) values ('Mike', 'mike@baeldung.com')"); System.out.println("Added user mike"); } catch (Exception e) { e.printStackTrace(); } } }
repos\tutorials-master\libraries-data-db\src\main\java\com\baeldung\libraries\h2\H2InitDemoApplication.java
2
请完成以下Java代码
public java.lang.String getDK_CustomerNumber () { return (java.lang.String)get_Value(COLUMNNAME_DK_CustomerNumber); } /** Set Gewünschte Lieferuhrzeit von. @param DK_DesiredDeliveryTime_From Gewünschte Lieferuhrzeit von */ @Override public void setDK_DesiredDeliveryTime_From (java.sql.Timestamp DK_DesiredDeliveryTime_From) { set_Value (COLUMNNAME_DK_DesiredDeliveryTime_From, DK_DesiredDeliveryTime_From); } /** Get Gewünschte Lieferuhrzeit von. @return Gewünschte Lieferuhrzeit von */ @Override public java.sql.Timestamp getDK_DesiredDeliveryTime_From () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_From); } /** Set Gewünschte Lieferuhrzeit bis. @param DK_DesiredDeliveryTime_To Gewünschte Lieferuhrzeit bis */ @Override public void setDK_DesiredDeliveryTime_To (java.sql.Timestamp DK_DesiredDeliveryTime_To) { set_Value (COLUMNNAME_DK_DesiredDeliveryTime_To, DK_DesiredDeliveryTime_To); } /** Get Gewünschte Lieferuhrzeit bis. @return Gewünschte Lieferuhrzeit bis */ @Override public java.sql.Timestamp getDK_DesiredDeliveryTime_To () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_To); } /** Set EMail Empfänger. @param EMail_To EMail address to send requests to - e.g. edi@manufacturer.com */ @Override public void setEMail_To (java.lang.String EMail_To) { set_Value (COLUMNNAME_EMail_To, EMail_To); }
/** Get EMail Empfänger. @return EMail address to send requests to - e.g. edi@manufacturer.com */ @Override public java.lang.String getEMail_To () { return (java.lang.String)get_Value(COLUMNNAME_EMail_To); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_Shipper_Config.java
1
请完成以下Java代码
public void setLastAccessedTime(Instant lastAccessedTime) { this.lastAccessedTime = lastAccessedTime; } @Override public Instant getCreationTime() { return this.creationTime; } @Override public String getId() { return this.id; } /** * Get the original session id. * @return the original session id * @see #changeSessionId() */ public String getOriginalId() { return this.originalId; } @Override public String changeSessionId() { String changedId = this.sessionIdGenerator.generate(); setId(changedId); return changedId; } @Override public Instant getLastAccessedTime() { return this.lastAccessedTime; } @Override public void setMaxInactiveInterval(Duration interval) { this.maxInactiveInterval = interval; } @Override public Duration getMaxInactiveInterval() { return this.maxInactiveInterval; } @Override public boolean isExpired() { return isExpired(Instant.now()); } boolean isExpired(Instant now) { if (this.maxInactiveInterval.isNegative()) { return false; } return now.minus(this.maxInactiveInterval).compareTo(this.lastAccessedTime) >= 0; } @Override @SuppressWarnings("unchecked") public <T> T getAttribute(String attributeName) { return (T) this.sessionAttrs.get(attributeName); } @Override public Set<String> getAttributeNames() { return new HashSet<>(this.sessionAttrs.keySet()); } @Override public void setAttribute(String attributeName, Object attributeValue) { if (attributeValue == null) { removeAttribute(attributeName); } else { this.sessionAttrs.put(attributeName, attributeValue); } } @Override public void removeAttribute(String attributeName) { this.sessionAttrs.remove(attributeName); } /**
* Sets the time that this {@link Session} was created. The default is when the * {@link Session} was instantiated. * @param creationTime the time that this {@link Session} was created. */ public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } /** * Sets the identifier for this {@link Session}. The id should be a secure random * generated value to prevent malicious users from guessing this value. The default is * a secure random generated identifier. * @param id the identifier for this session. */ public void setId(String id) { this.id = id; } @Override public boolean equals(Object obj) { return obj instanceof Session && this.id.equals(((Session) obj).getId()); } @Override public int hashCode() { return this.id.hashCode(); } private static String generateId() { return UUID.randomUUID().toString(); } /** * Sets the {@link SessionIdGenerator} to use when generating a new session id. * @param sessionIdGenerator the {@link SessionIdGenerator} to use. * @since 3.2 */ public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } private static final long serialVersionUID = 7160779239673823561L; }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSession.java
1
请在Spring Boot框架中完成以下Java代码
public String getREFERENCEQUAL() { return referencequal; } /** * Sets the value of the referencequal property. * * @param value * allowed object is * {@link String } * */ public void setREFERENCEQUAL(String value) { this.referencequal = value; } /** * Gets the value of the reference property. * * @return * possible object is * {@link String } * */ public String getREFERENCE() { return reference; } /** * Sets the value of the reference property. * * @param value * allowed object is * {@link String } * */ public void setREFERENCE(String value) { this.reference = value; } /** * Gets the value of the referenceline property. * * @return * possible object is * {@link String } * */ public String getREFERENCELINE() { return referenceline; } /** * Sets the value of the referenceline property. * * @param value * allowed object is * {@link String } * */ public void setREFERENCELINE(String value) { this.referenceline = value; } /** * Gets the value of the referencedate1 property. * * @return * possible object is * {@link String }
* */ public String getREFERENCEDATE1() { return referencedate1; } /** * Sets the value of the referencedate1 property. * * @param value * allowed object is * {@link String } * */ public void setREFERENCEDATE1(String value) { this.referencedate1 = value; } /** * Gets the value of the referencedate2 property. * * @return * possible object is * {@link String } * */ public String getREFERENCEDATE2() { return referencedate2; } /** * Sets the value of the referencedate2 property. * * @param value * allowed object is * {@link String } * */ public void setREFERENCEDATE2(String value) { this.referencedate2 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DREFE1.java
2
请完成以下Java代码
public ImmutableList<RuntimeParameter> getByConfigIdAndRequest(@NonNull final ExternalSystemParentConfigId configId, @NonNull final String externalRequest) { return queryBL.createQueryBuilder(I_ExternalSystem_RuntimeParameter.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_ExternalSystem_Config_ID, configId.getRepoId()) .addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_External_Request, externalRequest) .create() .list() .stream() .map(this::recordToModel) .collect(ImmutableList.toImmutableList()); } @NonNull private RuntimeParameter recordToModel(@NonNull final I_ExternalSystem_RuntimeParameter record) { return RuntimeParameter.builder() .runtimeParameterId(RuntimeParameterId.ofRepoId(record.getExternalSystem_RuntimeParameter_ID())) .externalSystemParentConfigId(ExternalSystemParentConfigId.ofRepoId(record.getExternalSystem_Config_ID())) .request(record.getExternal_Request()) .name(record.getName())
.value(record.getValue()) .build(); } @NonNull private Optional<I_ExternalSystem_RuntimeParameter> getRecordByUniqueKey(@NonNull final RuntimeParamUniqueKey uniqueKey) { return queryBL.createQueryBuilder(I_ExternalSystem_RuntimeParameter.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_External_Request, uniqueKey.getRequest()) .addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_Name, uniqueKey.getName()) .addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_ExternalSystem_Config_ID, uniqueKey.getExternalSystemParentConfigId().getRepoId()) .create() .firstOnlyOptional(I_ExternalSystem_RuntimeParameter.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\runtimeparameters\RuntimeParametersRepository.java
1
请完成以下Java代码
public DelegateExecution getExecution() { return execution; } public void setExecution(DelegateExecution execution) { this.execution = execution; } @Override public String getSignalName() { return signalName; } public void setSignalName(String signalName) { this.signalName = signalName; } @Override public Object getSignalData() { return signalData;
} public void setSignalData(Object signalData) { this.signalData = signalData; } @Override public void doNotLeave() { shouldLeave = false; } public boolean shouldLeave() { return shouldLeave; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\TriggerableJavaDelegateContextImpl.java
1
请完成以下Java代码
public List<PrinterHWMediaSize> getPrinterHWMediaSizes() { return this.printerHWMediaSizes; } public void setPrinterHWMediaSizes(List<PrinterHWMediaSize> printerHWMediaSizes) { this.printerHWMediaSizes = printerHWMediaSizes; } public List<PrinterHWMediaTray> getPrinterHWMediaTrays() { return this.printerHWMediaTrays; } public void setPrinterHWMediaTrays(List<PrinterHWMediaTray> printerHWMediaTrays) { this.printerHWMediaTrays = printerHWMediaTrays; } @Override public String toString() { return "PrinterHW [name=" + name + ", printerHWMediaSizes=" + printerHWMediaSizes + ", printerHWMediaTrays=" + printerHWMediaTrays + "]"; } /** * Printer HW Media Size Object * * @author al */ public static class PrinterHWMediaSize implements Serializable { /** * */ private static final long serialVersionUID = 5962990173434911764L; private String name; private String isDefault; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaSize [name=" + name + ", isDefault=" + isDefault + "]"; } } /** * Printer HW Media Tray Object * * @author al */
public static class PrinterHWMediaTray implements Serializable { /** * */ private static final long serialVersionUID = -1833627999553124042L; private String name; private String trayNumber; private String isDefault; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTrayNumber() { return trayNumber; } public void setTrayNumber(String trayNumber) { this.trayNumber = trayNumber; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaTray [name=" + name + ", trayNumber=" + trayNumber + ", isDefault=" + isDefault + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrinterHW.java
1
请在Spring Boot框架中完成以下Java代码
static ToCoreNotificationMsg toProto(EntityId entityId, List<TsKvEntry> updates) { return toProto(true, null, entityId, updates); } static ToCoreNotificationMsg toProto(String scope, EntityId entityId, List<TsKvEntry> updates) { return toProto(false, scope, entityId, updates); } static ToCoreNotificationMsg toProto(boolean timeSeries, String scope, EntityId entityId, List<TsKvEntry> updates) { TransportProtos.TbSubUpdateProto.Builder builder = TransportProtos.TbSubUpdateProto.newBuilder(); builder.setEntityIdMSB(entityId.getId().getMostSignificantBits()); builder.setEntityIdLSB(entityId.getId().getLeastSignificantBits()); Map<String, List<TransportProtos.TsValueProto>> data = new TreeMap<>(); for (TsKvEntry tsEntry : updates) { data.computeIfAbsent(tsEntry.getKey(), k -> new ArrayList<>()).add(toTsValueProto(tsEntry.getTs(), tsEntry)); } data.forEach((key, value) -> { TransportProtos.TsValueListProto.Builder dataBuilder = TransportProtos.TsValueListProto.newBuilder(); dataBuilder.setKey(key);
dataBuilder.addAllTsValue(value); builder.addData(dataBuilder.build()); }); var result = TransportProtos.LocalSubscriptionServiceMsgProto.newBuilder(); if (timeSeries) { result.setTsUpdate(builder); } else { builder.setScope(scope); result.setAttrUpdate(builder); } return ToCoreNotificationMsg.newBuilder().setToLocalSubscriptionServiceMsg(result).build(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbSubscriptionUtils.java
2
请完成以下Java代码
protected void checkReadProcessDefinition(ActivityStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext(); if (isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String processDefinitionId = query.getProcessDefinitionId(); ProcessDefinitionEntity definition = getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); ensureNotNull("no deployed process definition found with id '" + processDefinitionId + "'", "processDefinition", definition); getAuthorizationManager().checkAuthorization(READ, PROCESS_DEFINITION, definition.getKey()); } } public long getStatisticsCountGroupedByDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl decisionRequirementsDefinitionStatisticsQuery) { configureQuery(decisionRequirementsDefinitionStatisticsQuery); return (Long) getDbEntityManager().selectOne("selectDecisionDefinitionStatisticsCount", decisionRequirementsDefinitionStatisticsQuery); } protected void configureQuery(HistoricDecisionInstanceStatisticsQueryImpl decisionRequirementsDefinitionStatisticsQuery) { checkReadDecisionRequirementsDefinition(decisionRequirementsDefinitionStatisticsQuery); getTenantManager().configureQuery(decisionRequirementsDefinitionStatisticsQuery);
} protected void checkReadDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext(); if (isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String decisionRequirementsDefinitionId = query.getDecisionRequirementsDefinitionId(); DecisionRequirementsDefinition definition = getDecisionRequirementsDefinitionManager().findDecisionRequirementsDefinitionById(decisionRequirementsDefinitionId); ensureNotNull("no deployed decision requirements definition found with id '" + decisionRequirementsDefinitionId + "'", "decisionRequirementsDefinition", definition); getAuthorizationManager().checkAuthorization(READ, DECISION_REQUIREMENTS_DEFINITION, definition.getKey()); } } public List<HistoricDecisionInstanceStatistics> getStatisticsGroupedByDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl query, Page page) { configureQuery(query); return getDbEntityManager().selectList("selectDecisionDefinitionStatistics", query, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\StatisticsManager.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribut substitute. @param M_AttributeValue_Mapping_ID Attribut substitute */ @Override public void setM_AttributeValue_Mapping_ID (int M_AttributeValue_Mapping_ID) { if (M_AttributeValue_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, Integer.valueOf(M_AttributeValue_Mapping_ID)); } /** Get Attribut substitute. @return Attribut substitute */
@Override public int getM_AttributeValue_Mapping_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_Mapping_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Merkmals-Wert Nach. @param M_AttributeValue_To_ID Product Attribute Value To */ @Override public void setM_AttributeValue_To_ID (int M_AttributeValue_To_ID) { if (M_AttributeValue_To_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_To_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_To_ID, Integer.valueOf(M_AttributeValue_To_ID)); } /** Get Merkmals-Wert Nach. @return Product Attribute Value To */ @Override public int getM_AttributeValue_To_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_To_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_M_AttributeValue_Mapping.java
1
请完成以下Java代码
public List<CashBalance3> getBal() { if (bal == null) { bal = new ArrayList<CashBalance3>(); } return this.bal; } /** * Gets the value of the txsSummry property. * * @return * possible object is * {@link TotalTransactions2 } * */ public TotalTransactions2 getTxsSummry() { return txsSummry; } /** * Sets the value of the txsSummry property. * * @param value * allowed object is * {@link TotalTransactions2 } * */ public void setTxsSummry(TotalTransactions2 value) { this.txsSummry = value; } /** * Gets the value of the ntry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ntry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReportEntry2 } * * */ public List<ReportEntry2> getNtry() { if (ntry == null) { ntry = new ArrayList<ReportEntry2>(); }
return this.ntry; } /** * Gets the value of the addtlStmtInf property. * * @return * possible object is * {@link String } * */ public String getAddtlStmtInf() { return addtlStmtInf; } /** * Sets the value of the addtlStmtInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlStmtInf(String value) { this.addtlStmtInf = 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\AccountStatement2.java
1
请完成以下Java代码
public int getDIM_Dimension_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Interner Name. @param InternalName Generally used to give records a name that can be safely referenced from code. */ @Override public void setInternalName (java.lang.String InternalName) { set_ValueNoCheck (COLUMNNAME_InternalName, InternalName); } /** Get Interner Name. @return Generally used to give records a name that can be safely referenced from code. */ @Override
public java.lang.String getInternalName () { return (java.lang.String)get_Value(COLUMNNAME_InternalName); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Type.java
1
请完成以下Java代码
public Money getFreightRate( @NonNull final ShipperId shipperId, @NonNull final CountryId countryId, @NonNull final LocalDate date, @NonNull final Money shipmentValueAmt) { return getBreak(shipperId, countryId, date, shipmentValueAmt) .map(FreightCostBreak::getFreightRate) .orElseGet(shipmentValueAmt::toZero); } public Optional<FreightCostBreak> getBreak( @NonNull final ShipperId shipperId, @NonNull final CountryId countryId, @NonNull final LocalDate date, @NonNull final Money shipmentValueAmt) { final FreightCostShipper shipper = getShipperIfExists(shipperId, date).orElse(null); if (shipper == null) { return Optional.empty(); } return shipper.getBreak(countryId, shipmentValueAmt); } public FreightCostShipper getShipper(@NonNull final ShipperId shipperId, @NonNull final LocalDate date) {
Optional<FreightCostShipper> shipperIfExists = getShipperIfExists(shipperId, date); return shipperIfExists.orElseThrow(() -> new AdempiereException("@NotFound@ @M_FreightCostShipper_ID@ (@M_Shipper_ID@:" + shipperId + ", @M_FreightCost_ID@:" + getName() + ")")); } public Optional<FreightCostShipper> getShipperIfExists(@NonNull final ShipperId shipperId, @NonNull final LocalDate date) { return shippers.stream() .filter(shipper -> shipper.isMatching(shipperId, date)) .sorted(Comparator.comparing(FreightCostShipper::getValidFrom)) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCost.java
1
请完成以下Java代码
public String getLocatorName(final LocatorId locatorId) { return getWarehouseLocators(locatorId.getWarehouseId()).getLocatorName(locatorId); } private WarehouseLocatorsInfo getWarehouseLocators(@NonNull final WarehouseId warehouseId) { return locatorsByWarehouseId.computeIfAbsent(warehouseId, this::retrieveWarehouseLocators); } private WarehouseLocatorsInfo retrieveWarehouseLocators(@NonNull final WarehouseId warehouseId) { return WarehouseLocatorsInfo.builder() .warehouseId(warehouseId) .locators(dao.getLocators(warehouseId)
.stream() .map(WarehousesLoadingCache::fromRecord) .collect(ImmutableList.toImmutableList())) .build(); } private static LocatorInfo fromRecord(final I_M_Locator record) { return LocatorInfo.builder() .locatorId(LocatorId.ofRepoId(record.getM_Warehouse_ID(), record.getM_Locator_ID())) .locatorName(record.getValue()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\warehouse\WarehousesLoadingCache.java
1
请完成以下Java代码
private ITranslatableString getAttributeValueAsDisplayString() { final AttributeValueType valueType = attribute.getValueType(); if (AttributeValueType.STRING.equals(valueType)) { final String valueStr = attributeValue != null ? attributeValue.toString() : null; return ASIDescriptionBuilderCommand.formatStringValue(valueStr); } else if (AttributeValueType.NUMBER.equals(valueType)) { final BigDecimal valueBD = attributeValue != null ? NumberUtils.asBigDecimal(attributeValue, null) : null; if (valueBD == null && !verboseDescription) { return null; } else { return ASIDescriptionBuilderCommand.formatNumber(valueBD, attribute.getNumberDisplayType()); } } else if (AttributeValueType.DATE.equals(valueType)) { final Date valueDate = attributeValue != null ? TimeUtil.asDate(attributeValue) : null; if (valueDate == null && !verboseDescription) { return null; } else
{ return ASIDescriptionBuilderCommand.formatDateValue(valueDate); } } else if (AttributeValueType.LIST.equals(valueType)) { final AttributeListValue attributeValue = attributeValueId != null ? attributesRepo.retrieveAttributeValueOrNull(attribute, attributeValueId) : null; if (attributeValue != null) { return ASIDescriptionBuilderCommand.formatStringValue(attributeValue.getName()); } else { return ASIDescriptionBuilderCommand.formatStringValue(null); } } else { // Unknown attributeValueType final String valueStr = attributeValue != null ? attributeValue.toString() : null; return ASIDescriptionBuilderCommand.formatStringValue(valueStr); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDescriptionPatternEvalCtx.java
1
请完成以下Java代码
public void setSchemaLocations(@Nullable List<String> schemaLocations) { this.schemaLocations = schemaLocations; } /** * Returns the locations of data (DML) scripts to apply to the database. * @return the locations of the data scripts */ public @Nullable List<String> getDataLocations() { return this.dataLocations; } /** * Sets the locations of data (DML) scripts to apply to the database. By default, * initialization will fail if a location does not exist. To prevent a failure, a * location can be made optional by prefixing it with {@code optional:}. * @param dataLocations locations of the data scripts */ public void setDataLocations(@Nullable List<String> dataLocations) { this.dataLocations = dataLocations; } /** * Returns whether to continue when an error occurs while applying a schema or data * script. * @return whether to continue on error */ public boolean isContinueOnError() { return this.continueOnError; } /** * Sets whether initialization should continue when an error occurs when applying a * schema or data script. * @param continueOnError whether to continue when an error occurs. */ public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } /** * Returns the statement separator used in the schema and data scripts. * @return the statement separator */ public String getSeparator() { return this.separator; } /** * Sets the statement separator to use when reading the schema and data scripts. * @param separator statement separator used in the schema and data scripts */ public void setSeparator(String separator) { this.separator = separator;
} /** * Returns the encoding to use when reading the schema and data scripts. * @return the script encoding */ public @Nullable Charset getEncoding() { return this.encoding; } /** * Sets the encoding to use when reading the schema and data scripts. * @param encoding encoding to use when reading the schema and data scripts */ public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; } /** * Gets the mode to use when determining whether database initialization should be * performed. * @return the initialization mode * @since 2.5.1 */ public DatabaseInitializationMode getMode() { return this.mode; } /** * Sets the mode the use when determining whether database initialization should be * performed. * @param mode the initialization mode * @since 2.5.1 */ public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\DatabaseInitializationSettings.java
1
请完成以下Java代码
public void setStatisticsInfo (String StatisticsInfo) { set_ValueNoCheck (COLUMNNAME_StatisticsInfo, StatisticsInfo); } /** Get Statistics. @return Information to help profiling the system for solving support issues */ public String getStatisticsInfo () { return (String)get_Value(COLUMNNAME_StatisticsInfo); } /** SystemStatus AD_Reference_ID=374 */ public static final int SYSTEMSTATUS_AD_Reference_ID=374; /** Evaluation = E */ public static final String SYSTEMSTATUS_Evaluation = "E"; /** Implementation = I */ public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */ public static final String SYSTEMSTATUS_Production = "P"; /** Set System Status. @param SystemStatus Status of the system - Support priority depends on system status */ public void setSystemStatus (String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } /** Get System Status. @return Status of the system - Support priority depends on system status */ public String getSystemStatus () { return (String)get_Value(COLUMNNAME_SystemStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueSystem.java
1
请完成以下Java代码
public void afterPropertiesSet() { Assert.notNull(this.key, "A Key is required and should match that configured for the RunAsImplAuthenticationProvider"); } @Override public @Nullable Authentication buildRunAs(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { List<GrantedAuthority> newAuthorities = new ArrayList<>(); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { GrantedAuthority extraAuthority = new SimpleGrantedAuthority( getRolePrefix() + attribute.getAttribute()); newAuthorities.add(extraAuthority); } } if (newAuthorities.isEmpty()) { return null; } // Add existing authorities newAuthorities.addAll(authentication.getAuthorities()); return new RunAsUserToken(this.key, authentication.getPrincipal(), authentication.getCredentials(), newAuthorities, authentication.getClass()); } public String getKey() { return this.key; } public String getRolePrefix() { return this.rolePrefix; } public void setKey(String key) { this.key = key; } /** * Allows the default role prefix of <code>ROLE_</code> to be overridden. May be set
* to an empty value, although this is usually not desirable. * @param rolePrefix the new prefix */ public void setRolePrefix(String rolePrefix) { this.rolePrefix = rolePrefix; } @Override public boolean supports(ConfigAttribute attribute) { return attribute.getAttribute() != null && attribute.getAttribute().startsWith("RUN_AS_"); } /** * This implementation supports any type of class, because it does not query the * presented secure object. * @param clazz the secure object * @return always <code>true</code> */ @Override public boolean supports(Class<?> clazz) { return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\RunAsManagerImpl.java
1
请完成以下Java代码
class MariaDbJdbcDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<JdbcConnectionDetails> { protected MariaDbJdbcDockerComposeConnectionDetailsFactory() { super("mariadb"); } @Override protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new MariaDbJdbcDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link JdbcConnectionDetails} backed by a {@code mariadb} {@link RunningService}. */ static class MariaDbJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements JdbcConnectionDetails { private static final JdbcUrlBuilder jdbcUrlBuilder = new JdbcUrlBuilder("mariadb", 3306); private final MariaDbEnvironment environment; private final String jdbcUrl; MariaDbJdbcDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new MariaDbEnvironment(service.env()); this.jdbcUrl = jdbcUrlBuilder.build(service, this.environment.getDatabase()); } @Override public String getUsername() { return this.environment.getUsername();
} @Override public String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\MariaDbJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
private void createAndSaveDetailRecords( @NonNull final I_C_Invoice_Candidate newInvoiceCandidate, @NonNull final FlatrateDataEntry entry, @NonNull final List<FlatrateDataEntryDetail> matchingDetails, @NonNull final ICsCreationContext context) { for (final FlatrateDataEntryDetail detail : matchingDetails) { final I_C_Invoice_Detail newDetailRecord = InterfaceWrapperHelper.newInstance(I_C_Invoice_Detail.class); newDetailRecord.setC_Invoice_Candidate_ID(newInvoiceCandidate.getC_Invoice_Candidate_ID()); newDetailRecord.setC_Period_ID(entry.getPeriod().getId().getRepoId()); newDetailRecord.setSeqNo(detail.getSeqNo()); newDetailRecord.setIsPrinted(true); newDetailRecord.setIsPrintBefore(false); final Quantity detailQuantity = detail.getQuantity(); if (detailQuantity != null) { newDetailRecord.setQty(detailQuantity.toBigDecimal()); newDetailRecord.setC_UOM_ID(detailQuantity.getUomId().getRepoId()); } else { newDetailRecord.setQty(null); newDetailRecord.setC_UOM_ID(entry.getUomId().getRepoId()); } newDetailRecord.setM_Product_ID(newInvoiceCandidate.getM_Product_ID()); newDetailRecord.setM_AttributeSetInstance_ID(detail.getAsiId().getRepoId()); final BPartnerDepartment bPartnerDepartment = detail.getBPartnerDepartment(); newDetailRecord.setLabel(bPartnerDepartment.getSearchKey()); newDetailRecord.setDescription(bPartnerDepartment.getSearchKey() + " - " + bPartnerDepartment.getName()); final FlatrateTerm flatrateTerm = context.getFlatrateTerm(); final BPartnerLocationAndCaptureId dropShipLocation = flatrateTerm.getDropshipPartnerLocationAndCaptureId(); if (dropShipLocation != null)
{ newDetailRecord.setDropShip_Location_ID(dropShipLocation.getBpartnerLocationId().getRepoId()); newDetailRecord.setDropShip_BPartner_ID(dropShipLocation.getBpartnerId().getRepoId()); } InterfaceWrapperHelper.saveRecord(newDetailRecord); } } @Data private static class ICsCreationContext { @NonNull final FlatrateTerm flatrateTerm; @NonNull final CountryId countryId; @NonNull final PricingSystemId pricingSystemId; @NonNull final ProductId productId; @NonNull final FlatrateDataEntryHandler flatrateDataEntryHandler; PriceListVersionId priceListVersionId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\invoice\FlatrateDataEntryToICService.java
1
请在Spring Boot框架中完成以下Java代码
public class ReconciliationFactoryImpl implements ReconciliationFactory, ApplicationContextAware { private static ApplicationContext applicationContext; /** * 去Spring容器中根据beanName获取对象(也可以直接根据名字创建实例,可以参考后面流程中的parser) * * @param payInterface * @return */ public Object getService(String payInterface) { return applicationContext.getBean(payInterface); } /** * 账单下载 * * @param payInterface * 支付渠道 * * @param billDate
* 账单日 */ public File fileDown(String payInterface, Date billDate) throws Exception { // 找到具体的FileDown实现,做向上转型 FileDown fileDown = (FileDown) this.getService(payInterface); // 加载配置文件,获取下载的对账文件保存路径 String dir = ReconciliationConfigUtil.readConfig("dir") + payInterface.toLowerCase(); return fileDown.fileDown(billDate, dir); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\fileDown\impl\ReconciliationFactoryImpl.java
2
请完成以下Java代码
public String getTableName() { return I_C_Invoice_Candidate.Table_Name; } @Override public List<String> getDependsOnColumnNames() { return columnNames; } @Override public AggregationKey buildAggregationKey(I_C_Invoice_Candidate model) { final List<Object> keyValues = getValues(model); final ArrayKey key = Util.mkKey(keyValues.toArray()); final AggregationId aggregationId = null; return new AggregationKey(key, aggregationId); } private List<Object> getValues(@NonNull final I_C_Invoice_Candidate ic) { final List<Object> values = new ArrayList<>(); final I_C_DocType invoiceDocType = Optional.ofNullable(DocTypeId.ofRepoIdOrNull(ic.getC_DocTypeInvoice_ID())) .map(docTypeBL::getById) .orElse(null); final DocTypeId docTypeIdToBeUsed = Optional.ofNullable(invoiceDocType) .filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() <= 0) .map(I_C_DocType::getC_DocType_ID) .map(DocTypeId::ofRepoId) .orElse(null); values.add(docTypeIdToBeUsed); values.add(ic.getAD_Org_ID()); final BPartnerLocationAndCaptureId billLocation = invoiceCandBL.getBillLocationId(ic, false); values.add(billLocation.getBpartnerRepoId()); values.add(billLocation.getBPartnerLocationRepoId()); final int currencyId = ic.getC_Currency_ID(); values.add(currencyId <= 0 ? 0 : currencyId); // Dates // 08511 workaround - we don't add dates in header aggregation key
values.add(null); // ic.getDateInvoiced()); values.add(null); // ic.getDateAcct()); // task 08437 // IsSOTrx values.add(ic.isSOTrx()); // Pricing System final int pricingSystemId = IPriceListDAO.M_PricingSystem_ID_None; // 08511 workaround values.add(pricingSystemId); values.add(invoiceCandBL.isTaxIncluded(ic)); // task 08451 final Boolean compact = true; values.add(compact ? toHashcode(ic.getDescriptionHeader()) : ic.getDescriptionHeader()); values.add(compact ? toHashcode(ic.getDescriptionBottom()) : ic.getDescriptionBottom()); final DocTypeInvoicingPoolId docTypeInvoicingPoolId = Optional.ofNullable(invoiceDocType) .filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() > 0) .map(I_C_DocType::getC_DocType_Invoicing_Pool_ID) .map(DocTypeInvoicingPoolId::ofRepoId) .orElse(null); values.add(docTypeInvoicingPoolId); return values; } private static int toHashcode(final String s) { if (Check.isEmpty(s, true)) { return 0; } return s.hashCode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\agg\key\impl\ICHeaderAggregationKeyBuilder_OLD.java
1
请完成以下Java代码
public class Result<T> implements Serializable { private static final long serialVersionUID = 5925101851082556646L; private T data; private Status status; private String code; private String message; public static Result success() { Result result = new Result<>(); result.setCode("200"); result.setStatus(Status.SUCCESS); result.setMessage(Status.SUCCESS.name()); return result; } public static <T> Result success(T data) { Result<T> result = new Result<>(); result.setCode("200"); result.setStatus(Status.SUCCESS); result.setMessage(Status.SUCCESS.name()); result.setData(data); return result; } public static <T> Result error(String msg) { Result<T> result = new Result<>(); result.setCode("500"); result.setStatus(Status.ERROR); result.setMessage(msg); return result; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }
public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public static enum Status { SUCCESS("OK"), ERROR("ERROR"); private String code; private Status(String code) { this.code = code; } public String code() { return this.code; } } }
repos\spring-boot-student-master\spring-boot-student-hystrix\src\main\java\com\xiaolyuh\entity\Result.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { continueB_actionPerformed(e); } }); continueB.setText(Local.getString("Find next")); continueB.setPreferredSize(new Dimension(120, 26)); continueB.setMinimumSize(new Dimension(80, 26)); continueB.setMaximumSize(new Dimension(120, 26)); continueB.setFocusable(false); flowLayout1.setAlignment(FlowLayout.RIGHT); buttonsPanel.setLayout(flowLayout1); jLabel1.setText(" "+Local.getString("Search for")+": "); jLabel1.setIcon(new ImageIcon(HTMLEditor.class.getResource("resources/icons/findbig.png"))) ; this.add(jLabel1, BorderLayout.WEST); this.add(textF,BorderLayout.CENTER);
buttonsPanel.add(continueB, null); buttonsPanel.add(cancelB, null); this.add(buttonsPanel, BorderLayout.EAST); } void cancelB_actionPerformed(ActionEvent e) { cont = true; cancel = true; thread.resume(); } void continueB_actionPerformed(ActionEvent e) { cont = true; thread.resume(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\ContinueSearchDialog.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public java.math.BigDecimal getQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
} @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStorageAttributesKey (java.lang.String StorageAttributesKey) { set_ValueNoCheck (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_ATP_QueryResult.java
1
请在Spring Boot框架中完成以下Java代码
public class KeyVaultProperties { private String vaultUrl; private String tenantId; private String clientId; private String clientSecret; public KeyVaultProperties(String vaultUrl, String tenantId, String clientId, String clientSecret) { this.vaultUrl = vaultUrl; this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } public String getVaultUrl() { return vaultUrl; } public void setVaultUrl(String vaultUrl) { this.vaultUrl = vaultUrl; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-azure\src\main\java\com\baeldung\spring\cloud\azure\keyvault\data\KeyVaultProperties.java
2
请完成以下Java代码
public String getBPartnerAddress() { return delegate.getBPartnerAddress_Override(); } @Override public void setBPartnerAddress(final String address) { delegate.setBPartnerAddress_Override(address); } } @Override public int updateDatePromisedOverrideAndPOReference(@NonNull final PInstanceId pinstanceId, @Nullable final LocalDate datePromisedOverride, @Nullable final String poReference) { if (datePromisedOverride == null && Check.isBlank(poReference)) { throw new AdempiereException(MSG_DATEPROMISEDOVERRIDE_POREFERENCE_VALIDATION_ERROR) .markAsUserValidationError(); } final ICompositeQueryUpdater<I_M_ReceiptSchedule> updater = queryBL .createCompositeQueryUpdater(I_M_ReceiptSchedule.class); if (datePromisedOverride != null)
{ updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_DatePromised_Override, datePromisedOverride); } if (!Check.isBlank(poReference)) { updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_POReference, poReference); } return queryBL.createQueryBuilder(I_M_ReceiptSchedule.class) .setOnlySelection(pinstanceId) .create() .update(updater); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleBL.java
1
请完成以下Java代码
public final String getDescription() { return m_description; } /** * Returns Key or Value as String * * @return String or null */ public abstract String getID(); /** * Comparator Interface (based on toString value) * * @param o1 Object 1 * @param o2 Object 2 * @return compareTo value */ @Override public final int compare(Object o1, Object o2) { String s1 = o1 == null ? "" : o1.toString(); String s2 = o2 == null ? "" : o2.toString(); return s1.compareTo(s2); // sort order ?? } // compare /** * Comparator Interface (based on toString value) * * @param o1 Object 1 * @param o2 Object 2 * @return compareTo value */ public final int compare(NamePair o1, NamePair o2) { String s1 = o1 == null ? "" : o1.toString(); String s2 = o2 == null ? "" : o2.toString(); return s1.compareTo(s2); // sort order ?? } // compare /** * Comparable Interface (based on toString value) * * @param o the Object to be compared. * @return a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ @Override public final int compareTo(Object o) { return compare(this, o); } // compareTo /** * Comparable Interface (based on toString value) *
* @param o the Object to be compared. * @return a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ public final int compareTo(NamePair o) { return compare(this, o); } // compareTo /** * To String - returns name */ @Override public String toString() { return m_name; } /** * To String - detail * * @return String in format ID=Name */ public final String toStringX() { StringBuilder sb = new StringBuilder(getID()); sb.append("=").append(m_name); return sb.toString(); } // toStringX } // NamePair
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\NamePair.java
1
请在Spring Boot框架中完成以下Java代码
public class FTSJoinColumnList implements Iterable<FTSJoinColumn> { private final ImmutableList<FTSJoinColumn> joinColumns; private FTSJoinColumnList(@NonNull final List<FTSJoinColumn> joinColumns) { Check.assumeNotEmpty(joinColumns, "at least one JOIN column shall be defined"); this.joinColumns = ImmutableList.copyOf(joinColumns); } public static FTSJoinColumnList ofList(@NonNull final List<FTSJoinColumn> joinColumns) { return new FTSJoinColumnList(joinColumns); } public int size() { return joinColumns.size(); } @Override public Iterator<FTSJoinColumn> iterator() { return joinColumns.iterator(); } public String buildJoinCondition( @NonNull final String targetTableNameOrAlias, @Nullable final String selectionTableNameOrAlias) { Check.assumeNotEmpty(targetTableNameOrAlias, "targetTableNameOrAlias not empty"); final String selectionTableNameOrAliasWithDot = StringUtils.trimBlankToOptional(selectionTableNameOrAlias) .map(alias -> alias + ".") .orElse(""); final StringBuilder sql = new StringBuilder(); for (final FTSJoinColumn joinColumn : joinColumns)
{ if (sql.length() > 0) { sql.append(" AND "); } if (joinColumn.isNullable()) { sql.append("(") .append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()).append(" IS NULL") .append(" OR ") .append(targetTableNameOrAlias).append(".").append(joinColumn.getTargetTableColumnName()) .append(" IS NOT DISTINCT FROM ") .append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()) .append(")"); } else { sql.append(targetTableNameOrAlias).append(".").append(joinColumn.getTargetTableColumnName()) .append("=") .append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()); } } return sql.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSJoinColumnList.java
2
请在Spring Boot框架中完成以下Java代码
private void withThreadContextClassLoader(ClassLoader classLoader, Runnable action) { ClassLoader previous = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); action.run(); } finally { Thread.currentThread().setContextClassLoader(previous); } } private List<String> getConnectionUrls(ObjectProvider<DataSource> dataSources) { return dataSources.orderedStream(ObjectProvider.UNFILTERED) .map(this::getConnectionUrl) .filter(Objects::nonNull) .toList(); } private @Nullable String getConnectionUrl(DataSource dataSource) { try (Connection connection = dataSource.getConnection()) {
return "'" + connection.getMetaData().getURL() + "'"; } catch (Exception ex) { return null; } } private void log(List<String> urls, String path) { if (!urls.isEmpty()) { logger.info(LogMessage.format("H2 console available at '%s'. %s available at %s", path, (urls.size() > 1) ? "Databases" : "Database", String.join(", ", urls))); } } } }
repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleAutoConfiguration.java
2
请完成以下Java代码
public I_PP_Product_BOM createBOM(@NonNull final BOMCreateRequest request) { final ProductId productId = request.getProductId(); final ProductBOMVersionsId bomVersionsId = bomVersionsDAO.retrieveBOMVersionsId(productId) .orElseGet(() -> bomVersionsDAO.createBOMVersions(BOMVersionsCreateRequest.of(request))); final I_PP_Product_BOM createdBOM = bomRepo.createBOM(bomVersionsId, request); documentBL.processEx(createdBOM, IDocument.ACTION_Complete, IDocument.STATUS_Completed); return createdBOM; } public void verifyBOMAssignment(@NonNull final ProductPlanning planning, @NonNull final I_PP_Product_BOM productBom) { if (!planning.isAttributeDependant()) { return; } final AttributeSetInstanceId planningASIId = planning.getAttributeSetInstanceId();
final AttributesKey planningAttributesKeys = AttributesKeys.createAttributesKeyFromASIStorageAttributes(planningASIId).orElse(AttributesKey.NONE); if (planningAttributesKeys.isNone()) { return; } final AttributeSetInstanceId productBomASIId = AttributeSetInstanceId.ofRepoIdOrNone(productBom.getM_AttributeSetInstance_ID()); final AttributesKey productBOMAttributesKeys = AttributesKeys.createAttributesKeyFromASIStorageAttributes(productBomASIId).orElse(AttributesKey.NONE); if (!productBOMAttributesKeys.contains(planningAttributesKeys)) { throw new AdempiereException(PP_PRODUCT_PLANNING_BOM_ATTR_ERROR); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMService.java
1
请在Spring Boot框架中完成以下Java代码
static class RedisController { private RedisTemplate<String, String> redisTemplate; public RedisController(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } @GetMapping("/publish") public void publish(@RequestParam String message) { // 发送消息 redisTemplate.convertAndSend(CHANNEL, message); } } @Slf4j
@Service static class MessageSubscriber { public MessageSubscriber(RedisTemplate redisTemplate) { RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection(); redisConnection.subscribe(new MessageListener() { @Override public void onMessage(Message message, byte[] bytes) { // 收到消息的处理逻辑 log.info("Receive message : " + message); } }, CHANNEL.getBytes(StandardCharsets.UTF_8)); } } }
repos\SpringBoot-Learning-master\2.x\chapter5-5\src\main\java\com\didispace\chapter55\Chapter55Application.java
2
请完成以下Java代码
public String getOptionType() { return optionType; } public void setOptionType(String optionType) { this.optionType = optionType; } public Boolean getHasEmptyValue() { return hasEmptyValue; } public void setHasEmptyValue(Boolean hasEmptyValue) { this.hasEmptyValue = hasEmptyValue; } public List<Option> getOptions() { return options;
} public void setOptions(List<Option> options) { this.options = options; } public String getOptionsExpression() { return optionsExpression; } public void setOptionsExpression(String optionsExpression) { this.optionsExpression = optionsExpression; } }
repos\flowable-engine-main\modules\flowable-form-model\src\main\java\org\flowable\form\model\OptionFormField.java
1
请完成以下Java代码
public String getFormat() { String raw = "Your response should be in JSON format.\nThe data structure for the JSON should match this Java class: %s\n" + "For the map values, here is the JSON Schema instance your output must adhere to:\n```%s```\n" + "Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.\n"; return String.format(raw, HashMap.class.getName(), this.jsonSchema); } protected ObjectMapper getObjectMapper() { return JsonMapper.builder() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .build(); } private String trimMarkdown(String text) { if (text.startsWith("```json") && text.endsWith("```")) { text = text.substring(7, text.length() - 3); } return text; }
private String generateJsonSchemaForValueType(Class<V> valueType) { try { JacksonModule jacksonModule = new JacksonModule(); SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON) .with(jacksonModule) .build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonNode = generator.generateSchema(valueType); ObjectWriter objectWriter = new ObjectMapper().writer(new DefaultPrettyPrinter().withObjectIndenter(new DefaultIndenter().withLinefeed(System.lineSeparator()))); return objectWriter.writeValueAsString(jsonNode); } catch (JsonProcessingException e) { throw new RuntimeException("Could not generate JSON schema for value type: " + valueType.getName(), e); } } }
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\converters\GenericMapOutputConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; private String password; public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Collection<Role> getRoles() { return roles; } public void setRoles(Collection<Role> roles) { this.roles = roles; }
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable( name = "users_roles", joinColumns = @JoinColumn( name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn( name = "role_id", referencedColumnName = "id")) private Collection<Role> roles; public User() { } public User(String firstName, String lastName, String email, String password) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public User(String firstName, String lastName, String email, String password, Collection<Role> roles) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; this.roles = roles; } public Long getId() { return id; } @Override public String toString() { return "User{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", password='" + "admin123" + '\'' + ", roles=" + roles + '}'; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Project\src\main\java\spring\security\model\User.java
2
请在Spring Boot框架中完成以下Java代码
public class DataRestController { private static final Logger LOG = LoggerFactory.getLogger(DataRestController.class); @Autowired private DataService dataService; @Secured({"ROLE_USER", "ROLE_ADMIN"}) @GetMapping("/users/all") public ResponseEntity<ServerData> getForUsersData(Authentication authentication) { LOG.info("getData: authentication={}", authentication.getName()); authentication.getAuthorities().forEach(a->{ LOG.info(" authority={}", a.getAuthority()); }); return ResponseEntity.ok().body(dataService.getSecuredData("Secured for USER/ADMIN " + authentication.getName())); } @Secured("ROLE_ADMIN") @GetMapping("/admins/all") public ResponseEntity<ServerData> getDataForAdmins(Authentication authentication) { LOG.info("getData: authentication={}", authentication.getName()); authentication.getAuthorities().forEach(a->{ LOG.info(" authority={}", a.getAuthority()); });
return ResponseEntity.ok().body(dataService.getSecuredData("Secured for ADMIN " + authentication.getName())); } @Secured("ROLE_ADMIN") @PutMapping("/admins/state/{state}") public ResponseEntity<ServerData> setStateForAdmins(Authentication authentication, @PathVariable String state) { LOG.info("setState: authentication={} state={}", authentication.getName(), state); authentication.getAuthorities().forEach(a->{ LOG.info(" authority={}", a.getAuthority()); }); dataService.setState(state); return ResponseEntity.ok().build(); } }
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\rest\DataRestController.java
2
请完成以下Java代码
public String getA_Entry_Type () { return (String)get_Value(COLUMNNAME_A_Entry_Type); } /** Set Period/Yearly. @param A_Period Period/Yearly */ public void setA_Period (int A_Period) { set_Value (COLUMNNAME_A_Period, Integer.valueOf(A_Period)); } /** Get Period/Yearly. @return Period/Yearly */ public int getA_Period () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Period); if (ii == null) return 0; return ii.intValue(); } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date. @return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Expense. @param Expense Expense */ public void setExpense (BigDecimal Expense) { set_Value (COLUMNNAME_Expense, Expense); } /** Get Expense. @return Expense */ public BigDecimal getExpense () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Expense); if (bd == null) return Env.ZERO; return bd; } /** Set Depreciate. @param IsDepreciated The asset will be depreciated */ public void setIsDepreciated (boolean IsDepreciated) { set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated)); }
/** Get Depreciate. @return The asset will be depreciated */ public boolean isDepreciated () { Object oo = get_Value(COLUMNNAME_IsDepreciated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Exp.java
1
请完成以下Java代码
public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the mimeType property. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value;
} /** * Gets the value of the encoding property. * * @return * possible object is * {@link String } * */ public String getEncoding() { return encoding; } /** * Sets the value of the encoding property. * * @param value * allowed object is * {@link String } * */ public void setEncoding(String value) { this.encoding = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptedType.java
1
请完成以下Java代码
public ChequeType2Code getChqTp() { return chqTp; } /** * Sets the value of the chqTp property. * * @param value * allowed object is * {@link ChequeType2Code } * */ public void setChqTp(ChequeType2Code value) { this.chqTp = value; } /** * Gets the value of the dlvryMtd property. * * @return * possible object is * {@link ChequeDeliveryMethod1Choice } *
*/ public ChequeDeliveryMethod1Choice getDlvryMtd() { return dlvryMtd; } /** * Sets the value of the dlvryMtd property. * * @param value * allowed object is * {@link ChequeDeliveryMethod1Choice } * */ public void setDlvryMtd(ChequeDeliveryMethod1Choice value) { this.dlvryMtd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\Cheque6CH.java
1
请完成以下Java代码
public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant) { set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant); } @Override public void setPP_Plant_ID (final int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID); } @Override public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public void setProductGroup (final @Nullable java.lang.String ProductGroup) { throw new IllegalArgumentException ("ProductGroup is virtual column"); } @Override public java.lang.String getProductGroup() { return get_ValueAsString(COLUMNNAME_ProductGroup); } @Override public void setProductName (final @Nullable java.lang.String ProductName)
{ throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyCount (final BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "flowable-app-examples") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00") public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @ApiModelProperty(example = "examples")
public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @ApiModelProperty(example = "http://localhost:8081/app-api/app-repository/deployments/10") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDeploymentResponse.java
2
请在Spring Boot框架中完成以下Java代码
public DynatraceApiVersion apiVersion() { return obtain((properties) -> (properties.getV1().getDeviceId() != null) ? DynatraceApiVersion.V1 : DynatraceApiVersion.V2, DynatraceConfig.super::apiVersion); } @Override public String metricKeyPrefix() { return obtain(v2(V2::getMetricKeyPrefix), DynatraceConfig.super::metricKeyPrefix); } @Override public Map<String, String> defaultDimensions() { return obtain(v2(V2::getDefaultDimensions), DynatraceConfig.super::defaultDimensions); } @Override public boolean enrichWithDynatraceMetadata() { return obtain(v2(V2::isEnrichWithDynatraceMetadata), DynatraceConfig.super::enrichWithDynatraceMetadata); } @Override public boolean useDynatraceSummaryInstruments() { return obtain(v2(V2::isUseDynatraceSummaryInstruments), DynatraceConfig.super::useDynatraceSummaryInstruments); }
@Override public boolean exportMeterMetadata() { return obtain(v2(V2::isExportMeterMetadata), DynatraceConfig.super::exportMeterMetadata); } private <V> Getter<DynatraceProperties, V> v1(Getter<V1, V> getter) { return (properties) -> getter.get(properties.getV1()); } private <V> Getter<DynatraceProperties, V> v2(Getter<V2, V> getter) { return (properties) -> getter.get(properties.getV2()); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatracePropertiesConfigAdapter.java
2
请完成以下Java代码
public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public String getVariableName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getName() { return name; } @Override public VariableType getVariableType() { return variableType; } @Override public void setVariableType(VariableType variableType) { this.variableType = variableType; } @Override public Long getLongValue() { return longValue; } @Override public void setLongValue(Long longValue) { this.longValue = longValue; } @Override public Double getDoubleValue() { return doubleValue; } @Override public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } @Override public String getTextValue() { return textValue; } @Override public void setTextValue(String textValue) { this.textValue = textValue; } @Override public String getTextValue2() { return textValue2; } @Override public void setTextValue2(String textValue2) { this.textValue2 = textValue2; } @Override public Object getCachedValue() { return cachedValue; } @Override public void setCachedValue(Object cachedValue) {
this.cachedValue = cachedValue; } // common methods /////////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricDetailVariableInstanceUpdateEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntityImpl.java
1
请完成以下Java代码
public boolean contains(@NonNull final String contextVariable) { if (contextVariables.contains(contextVariable)) { return true; } if (knownMissing.contains(contextVariable)) { return true; } return parent != null && parent.contains(contextVariable); } @Override @Deprecated public String toString() {return toSummaryString();} public String toSummaryString()
{ StringBuilder sb = new StringBuilder(); sb.append(name).append(":"); sb.append("\n\tContext variables: ").append(String.join(",", contextVariables)); if (!knownMissing.isEmpty()) { sb.append("\n\tKnown missing context variables: ").append(String.join(",", knownMissing)); } if (parent != null) { sb.append("\n--- parent: ----\n"); sb.append(parent.toSummaryString()); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariables.java
1
请完成以下Java代码
public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setMD_Available_For_Sales_ID (final int MD_Available_For_Sales_ID) { if (MD_Available_For_Sales_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, MD_Available_For_Sales_ID); } @Override public int getMD_Available_For_Sales_ID() { return get_ValueAsInt(COLUMNNAME_MD_Available_For_Sales_ID); } @Override public void setQtyOnHandStock (final @Nullable BigDecimal QtyOnHandStock) { set_Value (COLUMNNAME_QtyOnHandStock, QtyOnHandStock); } @Override public BigDecimal getQtyOnHandStock() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandStock); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped) { set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped); }
@Override public BigDecimal getQtyToBeShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setStorageAttributesKey (final java.lang.String StorageAttributesKey) { set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return get_ValueAsString(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MD_Available_For_Sales.java
1
请完成以下Java代码
public String getClickTargetURL() { getMClickCount(); if (m_clickCount == null) return "-"; return m_clickCount.getTargetURL(); } // getClickTargetURL /** * Set Click Target URL (in ClickCount) * @param TargetURL url */ public void setClickTargetURL(String TargetURL) { getMClickCount(); if (m_clickCount == null) m_clickCount = new MClickCount(this); if (m_clickCount != null) { m_clickCount.setTargetURL(TargetURL); m_clickCount.save(get_TrxName()); } } // getClickTargetURL /** * Get Weekly Count * @return weekly count */ public ValueNamePair[] getClickCountWeek () { getMClickCount(); if (m_clickCount == null) return new ValueNamePair[0]; return m_clickCount.getCountWeek(); } // getClickCountWeek /** * Get CounterCount * @return Counter Count */
public MCounterCount getMCounterCount() { if (getW_CounterCount_ID() == 0) return null; if (m_counterCount == null) m_counterCount = new MCounterCount (getCtx(), getW_CounterCount_ID(), get_TrxName()); return m_counterCount; } // MCounterCount /** * Get Sales Rep ID. * (AD_User_ID of oldest BP user) * @return Sales Rep ID */ public int getSalesRep_ID() { if (m_SalesRep_ID == 0) { m_SalesRep_ID = getAD_User_ID(); if (m_SalesRep_ID == 0) m_SalesRep_ID = DB.getSQLValue(null, "SELECT AD_User_ID FROM AD_User " + "WHERE C_BPartner_ID=? AND IsActive='Y' ORDER BY AD_User_ID", getC_BPartner_ID()); } return m_SalesRep_ID; } // getSalesRep_ID } // MAdvertisement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAdvertisement.java
1
请完成以下Java代码
public SolrProductDO setDescription(String description) { this.description = description; return this; } public Integer getCid() { return cid; } public SolrProductDO setCid(Integer cid) { this.cid = cid; return this; } public String getCategoryName() { return categoryName; } public SolrProductDO setCategoryName(String categoryName) {
this.categoryName = categoryName; return this; } @Override public String toString() { return "SolrProductDO{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", cid=" + cid + ", categoryName='" + categoryName + '\'' + '}'; } }
repos\SpringBoot-Labs-master\lab-66\lab-66-spring-data-solr\src\main\java\cn\iocoder\springboot\lab15\springdatasolr\dataobject\SolrProductDO.java
1
请完成以下Java代码
public Object getPrincipal() { return this.principal; } @Override public Object getCredentials() { return ""; } /** * Returns the authorization URI. * @return the authorization URI */ public String getAuthorizationUri() { return this.authorizationUri; } /** * Returns the client identifier. * @return the client identifier */ public String getClientId() { return this.clientId; } /** * Returns the redirect uri. * @return the redirect uri */ @Nullable public String getRedirectUri() { return this.redirectUri; } /**
* Returns the state. * @return the state */ @Nullable public String getState() { return this.state; } /** * Returns the requested (or authorized) scope(s). * @return the requested (or authorized) scope(s), or an empty {@code Set} if not * available */ public Set<String> getScopes() { return this.scopes; } /** * Returns the additional parameters. * @return the additional parameters, or an empty {@code Map} if not available */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\AbstractOAuth2AuthorizationCodeRequestAuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
public List<Job> executeList(CommandContext commandContext) { return jobServiceConfiguration.getDeadLetterJobEntityManager().findJobsByQueryCriteria(this); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public boolean isWithoutProcessInstanceId() { return withoutProcessInstanceId; } public String getExecutionId() { return executionId; } public String getHandlerType() { return handlerType; } public Collection<String> getHandlerTypes() { return handlerTypes; } public boolean getExecutable() { return executable; } public Date getNow() { return jobServiceConfiguration.getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getElementId() { return elementId; } public String getElementName() { return elementName; } public String getScopeId() { return scopeId; } public boolean isWithoutScopeId() { return withoutScopeId; } public String getSubScopeId() { return subScopeId; } public String getScopeType() {
return scopeType; } public boolean isWithoutScopeType() { return withoutScopeType; } public String getScopeDefinitionId() { return scopeDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCorrelationId() { return correlationId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public boolean isExecutable() { return executable; } public boolean isOnlyExternalWorkers() { return onlyExternalWorkers; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\DeadLetterJobQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public UserDetailsManager users(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(encoder()); authenticationManagerBuilder.authenticationProvider(authenticationProvider()); AuthenticationManager authenticationManager = authenticationManagerBuilder.build(); JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource); jdbcUserDetailsManager.setAuthenticationManager(authenticationManager); return jdbcUserDetailsManager; } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return web -> web.ignoring().requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/login").permitAll()) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.permitAll().successHandler(successHandler)) .csrf(AbstractHttpConfigurer::disable); return http.build(); }
@Bean public DaoAuthenticationProvider authenticationProvider() { final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(encoder()); return authProvider; } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(11); } @Bean public SecurityEvaluationContextExtension securityEvaluationContextExtension() { return new SecurityEvaluationContextExtension(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\SpringSecurityConfig.java
2
请完成以下Java代码
public static List<String> getTimeLine() throws TwitterException { Twitter twitter = getTwitterinstance(); List<Status> statuses = twitter.getHomeTimeline(); return statuses.stream().map( item -> item.getText()).collect( Collectors.toList()); } public static String sendDirectMessage(String recipientName, String msg) throws TwitterException { Twitter twitter = getTwitterinstance(); DirectMessage message = twitter.sendDirectMessage(recipientName, msg); return message.getText(); } public static List<String> searchtweets() throws TwitterException { Twitter twitter = getTwitterinstance(); Query query = new Query("source:twitter4j baeldung"); QueryResult result = twitter.search(query); List<Status> statuses = result.getTweets(); return statuses.stream().map( item -> item.getText()).collect( Collectors.toList()); } public static void streamFeed() { StatusListener listener = new StatusListener(){ @Override public void onException(Exception e) { e.printStackTrace(); } @Override public void onDeletionNotice(StatusDeletionNotice arg) {
System.out.println("Got a status deletion notice id:" + arg.getStatusId()); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); } @Override public void onStatus(Status status) { System.out.println(status.getUser().getName() + " : " + status.getText()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); } }
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
1
请完成以下Java代码
private static String getHint(LoadBalancerClientFactory clientFactory, String serviceId) { LoadBalancerProperties loadBalancerProperties = clientFactory.getProperties(serviceId); Map<String, String> hints = loadBalancerProperties.getHint(); String defaultHint = hints.getOrDefault("default", "default"); String hintPropertyValue = hints.get(serviceId); return hintPropertyValue != null ? hintPropertyValue : defaultHint; } private static MultiValueMap<String, String> buildCookies(MultiValueMap<String, Cookie> cookies) { LinkedMultiValueMap<String, String> newCookies = new LinkedMultiValueMap<>(cookies.size()); if (cookies != null) { cookies.forEach((key, value) -> value .forEach(cookie -> newCookies.put(cookie.getName(), Collections.singletonList(cookie.getValue())))); } return newCookies; } static class DelegatingServiceInstance implements ServiceInstance { final ServiceInstance delegate; private String overrideScheme; DelegatingServiceInstance(ServiceInstance delegate, String overrideScheme) { this.delegate = delegate; this.overrideScheme = overrideScheme; } @Override public String getServiceId() { return delegate.getServiceId(); } @Override public String getHost() { return delegate.getHost(); } @Override public int getPort() { return delegate.getPort();
} @Override public boolean isSecure() { // TODO: move to map if ("https".equals(this.overrideScheme) || "wss".equals(this.overrideScheme)) { return true; } return delegate.isSecure(); } @Override public URI getUri() { return delegate.getUri(); } @Override public @Nullable Map<String, String> getMetadata() { return delegate.getMetadata(); } @Override public String getScheme() { String scheme = delegate.getScheme(); if (scheme != null) { return scheme; } return this.overrideScheme; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\LoadBalancerFilterFunctions.java
1
请完成以下Java代码
public java.lang.String getLot () { return (java.lang.String)get_Value(COLUMNNAME_Lot); } @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(); } /** Set M_Product_LotNumber_Quarantine. @param M_Product_LotNumber_Quarantine_ID M_Product_LotNumber_Quarantine */ @Override public void setM_Product_LotNumber_Quarantine_ID (int M_Product_LotNumber_Quarantine_ID) { if (M_Product_LotNumber_Quarantine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, Integer.valueOf(M_Product_LotNumber_Quarantine_ID)); } /** Get M_Product_LotNumber_Quarantine. @return M_Product_LotNumber_Quarantine */ @Override public int getM_Product_LotNumber_Quarantine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_LotNumber_Quarantine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\product\model\X_M_Product_LotNumber_Quarantine.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final BookstoreService bookstoreService; public MainApplication(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { Page<Author> authorscq = bookstoreService.fetchWithBooksByGenreCQ(); authorscq.forEach(a -> System.out.println(a.getName() + ": " + a.getBooks())); System.out.println("Number of elements: " + authorscq.getNumberOfElements()); System.out.println("Total elements: " + authorscq.getTotalElements());
Page<Author> authorseg = bookstoreService.fetchWithBooksByGenreEG(); authorseg.forEach(a -> System.out.println(a.getName() + ": " + a.getBooks())); System.out.println("Number of elements: " + authorseg.getNumberOfElements()); System.out.println("Total elements: " + authorseg.getTotalElements()); Page<Book> bookscq = bookstoreService.fetchWithAuthorsByIsbnCQ(); bookscq.forEach(a -> System.out.println(a.getTitle() + ": " + a.getAuthor())); System.out.println("Number of elements: " + bookscq.getNumberOfElements()); System.out.println("Total elements: " + bookscq.getTotalElements()); Page<Book> bookseg = bookstoreService.fetchWithAuthorsByIsbnEG(); bookseg.forEach(a -> System.out.println(a.getTitle() + ": " + a.getAuthor())); System.out.println("Number of elements: " + bookseg.getNumberOfElements()); System.out.println("Total elements: " + bookseg.getTotalElements()); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinFetchPageable\src\main\java\com\bookstore\MainApplication.java
2
请在Spring Boot框架中完成以下Java代码
private void init(Workbook workbook) { this.headerStyle = initHeaderStyle(workbook); this.titleStyle = initTitleStyle(workbook); } @Override public CellStyle getHeaderStyle(short color) { return headerStyle; } @Override public CellStyle getTitleStyle(short color) { return titleStyle; } @Override public CellStyle getStyles(boolean parity, ExcelExportEntity entity) { return styles; } @Override public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) { return getStyles(true, entity); } @Override public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) { return null; } /** * init --HeaderStyle * * @param workbook * @return */ private CellStyle initHeaderStyle(Workbook workbook) { CellStyle style = getBaseCellStyle(workbook); style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true)); return style; } /** * init-TitleStyle * * @param workbook * @return
*/ private CellStyle initTitleStyle(Workbook workbook) { CellStyle style = getBaseCellStyle(workbook); style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false)); // ForegroundColor style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); return style; } /** * BaseCellStyle * * @return */ private CellStyle getBaseCellStyle(Workbook workbook) { CellStyle style = workbook.createCellStyle(); style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setWrapText(true); return style; } /** * Font * * @param size * @param isBold * @return */ private Font getFont(Workbook workbook, short size, boolean isBold) { Font font = workbook.createFont(); font.setFontName("宋体"); font.setBold(isBold); font.setFontHeightInPoints(size); return font; } }
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\service\ExcelExportStyler.java
2
请在Spring Boot框架中完成以下Java代码
public class WorkspaceMigrateConfig { public static final String PROP_DB_URL_DEFAULT = "jdbc:postgresql://localhost/metasfresh"; public static final String PROP_DB_USERNAME_DEFAULT = "metasfresh"; public static final String PROP_DB_PASSWORD_DEFAULT = "metasfresh"; public static final String PROP_LABELS_DEFAULT = "mf15,common"; @NonNull File workspaceDir; @NonNull @Builder.Default String dbUrl = PROP_DB_URL_DEFAULT; @NonNull @Builder.Default String dbUsername = PROP_DB_USERNAME_DEFAULT; @NonNull @Builder.Default String dbPassword = PROP_DB_PASSWORD_DEFAULT;
boolean dryRunMode; boolean skipExecutingAfterScripts; @NonNull @Builder.Default ImmutableSet<Label> labels = Label.ofCommaSeparatedString(PROP_LABELS_DEFAULT); public enum OnScriptFailure { ASK, FAIL; } @NonNull @Builder.Default OnScriptFailure onScriptFailure = OnScriptFailure.ASK; }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\WorkspaceMigrateConfig.java
2
请完成以下Java代码
private void addTransitionFeatures(TagSet tagSet) { for (int i = 0; i < tagSet.size(); i++) { idOf("BL=" + tagSet.stringOf(i)); } idOf("BL=_BL_"); } public MutableFeatureMap(TagSet tagSet, Map<String, Integer> featureIdMap) { super(tagSet); this.featureIdMap = featureIdMap; addTransitionFeatures(tagSet); } @Override public Set<Map.Entry<String, Integer>> entrySet() { return featureIdMap.entrySet(); } @Override public int idOf(String string) { Integer id = featureIdMap.get(string); if (id == null) { id = featureIdMap.size(); featureIdMap.put(string, id); } return id; } public int size()
{ return featureIdMap.size(); } public Set<String> featureSet() { return featureIdMap.keySet(); } @Override public int[] allLabels() { return tagSet.allTags(); } @Override public int bosTag() { return tagSet.size(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\MutableFeatureMap.java
1