instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public List<org.compiere.model.I_C_BP_BankAccount> getC_BP_BankAccounts() { final PaymentString paymentString = getPaymentString(); final String IBAN = paymentString.getIBAN(); final List<org.compiere.model.I_C_BP_BankAccount> bankAccounts = InterfaceWrapperHelper.createList( esrbpBankAccountDAO.retrieveQRBPBankAccounts(IBAN), org.compiere.model.I_C_BP_BankAccount.class); return bankAccounts; } @Override public I_C_BP_BankAccount createNewC_BP_BankAccount(final IContextAware contextProvider, final int bpartnerId) { final PaymentString paymentString = getPaymentString(); final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class, contextProvider); Check.assume(bpartnerId > 0, "We assume the bPartnerId to be greater than 0. This={}", this); bpBankAccount.setC_BPartner_ID(bpartnerId); final Currency currency = currencyDAO.getByCurrencyCode(CurrencyCode.CHF); // CHF, because it's ESR bpBankAccount.setC_Currency_ID(currency.getId().getRepoId()); bpBankAccount.setIsEsrAccount(true); // ..because we are creating this from an ESR/QRR string bpBankAccount.setIsACH(true);
final String bPartnerName = bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(bpartnerId)); bpBankAccount.setA_Name(bPartnerName); bpBankAccount.setName(bPartnerName); bpBankAccount.setQR_IBAN(paymentString.getIBAN()); bpBankAccount.setAccountNo(paymentString.getInnerAccountNo()); bpBankAccount.setESR_RenderedAccountNo(paymentString.getPostAccountNo()); // we can not know it InterfaceWrapperHelper.save(bpBankAccount); return bpBankAccount; } @Override public String toString() { return String.format("QRPaymentStringDataProvider [getPaymentString()=%s]", getPaymentString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\api\impl\QRPaymentStringDataProvider.java
1
请在Spring Boot框架中完成以下Java代码
void setAuthorizationManager(AuthorizationManager<Message<?>> authorizationManager) { this.authorizationManager = authorizationManager; } @Autowired(required = false) void setMessageAuthorizationManagerPostProcessor( ObjectPostProcessor<AuthorizationManager<Message<?>>> postProcessor) { this.postProcessor = postProcessor; } @Autowired(required = false) void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) { this.templateDefaults = templateDefaults; } @Override public void afterSingletonsInstantiated() { SimpleUrlHandlerMapping mapping = getBeanOrNull(SIMPLE_URL_HANDLER_MAPPING_BEAN_NAME, SimpleUrlHandlerMapping.class); if (mapping == null) { return; } configureCsrf(mapping); } private <T> T getBeanOrNull(String name, Class<T> type) { Map<String, T> beans = this.context.getBeansOfType(type); return beans.get(name); } private void configureCsrf(SimpleUrlHandlerMapping mapping) { Map<String, Object> mappings = mapping.getHandlerMap(); for (Object object : mappings.values()) { if (object instanceof SockJsHttpRequestHandler) { setHandshakeInterceptors((SockJsHttpRequestHandler) object); } else if (object instanceof WebSocketHttpRequestHandler) { setHandshakeInterceptors((WebSocketHttpRequestHandler) object); } else { throw new IllegalStateException( "Bean " + SIMPLE_URL_HANDLER_MAPPING_BEAN_NAME + " is expected to contain mappings to either a "
+ "SockJsHttpRequestHandler or a WebSocketHttpRequestHandler but got " + object); } } } private void setHandshakeInterceptors(SockJsHttpRequestHandler handler) { SockJsService sockJsService = handler.getSockJsService(); Assert.state(sockJsService instanceof TransportHandlingSockJsService, () -> "sockJsService must be instance of TransportHandlingSockJsService got " + sockJsService); TransportHandlingSockJsService transportHandlingSockJsService = (TransportHandlingSockJsService) sockJsService; List<HandshakeInterceptor> handshakeInterceptors = transportHandlingSockJsService.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); transportHandlingSockJsService.setHandshakeInterceptors(interceptorsToSet); } private void setHandshakeInterceptors(WebSocketHttpRequestHandler handler) { List<HandshakeInterceptor> handshakeInterceptors = handler.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); handler.setHandshakeInterceptors(interceptorsToSet); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\socket\WebSocketMessageBrokerSecurityConfiguration.java
2
请完成以下Java代码
private void mapCandidateId2Stock(@NonNull final List<Candidate> candidates) { final Function<Candidate, Candidate> locateMatchingStockCandidate = (candidate) -> candidates.stream() .filter(potentialStockCandidate -> CandidateType.STOCK.equals(potentialStockCandidate.getType())) .filter(potentialStockCandidate -> { final boolean isStockForDemandCandidate = CandidateId.isRegularNonNull(potentialStockCandidate.getParentId()) && potentialStockCandidate.getParentId().equals(candidate.getId()); final boolean isStockForSupplyCandidate = CandidateId.isRegularNonNull(candidate.getParentId()) && candidate.getParentId().equals(potentialStockCandidate.getId()); return isStockForDemandCandidate || isStockForSupplyCandidate; }) .findFirst() .orElseThrow(() -> new AdempiereException("No StockCandidate found for Candidate!") .appendParametersToMessage() .setParameter("MD_Candidate_ID", candidate.getId())); candidates.stream() .filter(candidate -> !CandidateType.STOCK.equals(candidate.getType())) .forEach(candidate -> candidateId2Stock.put(candidate.getId(), locateMatchingStockCandidate.apply(candidate))); } /** * We consider relevant only the candidates created till the point where the simulated demand is "resolved", * i.e. we reached a point in time where there is enough stock to fulfill the demand. */ @NonNull private ImmutableList<Candidate> removeNonRelevantCandidates(@NonNull final List<Candidate> candidates) { final ImmutableList.Builder<Candidate> onlyRelevantCandidatesCollector = ImmutableList.builder();
for (final Candidate candidate : candidates) { if (candidate.isSimulated() && candidate.getQuantity().signum() == 0) { continue; } if (CandidateType.STOCK.equals(candidate.getType())) { continue; } onlyRelevantCandidatesCollector.add(candidate); final boolean isEnoughStockToResolveDemand = candidateId2Stock.get(candidate.getId()).getQuantity().signum() >= 0; if (isEnoughStockToResolveDemand) { break; } } return onlyRelevantCandidatesCollector.build(); } private DocumentId buildRowId(@NonNull final Candidate candidate) { return DocumentId.of(candidate.getId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationRowsLoader.java
1
请在Spring Boot框架中完成以下Java代码
public String getHostnameForClients() { return this.hostnameForClients; } public void setHostnameForClients(String hostnameForClients) { this.hostnameForClients = hostnameForClients; } public long getLoadPollInterval() { return this.loadPollInterval; } public void setLoadPollInterval(long loadPollInterval) { this.loadPollInterval = loadPollInterval; } public int getMaxConnections() { return this.maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } public int getMaxMessageCount() { return this.maxMessageCount; } public void setMaxMessageCount(int maxMessageCount) { this.maxMessageCount = maxMessageCount; } public int getMaxThreads() { return this.maxThreads; } public void setMaxThreads(int maxThreads) { this.maxThreads = maxThreads; } public int getMaxTimeBetweenPings() { return this.maxTimeBetweenPings; } public void setMaxTimeBetweenPings(int maxTimeBetweenPings) { this.maxTimeBetweenPings = maxTimeBetweenPings; } public int getMessageTimeToLive() { return this.messageTimeToLive; } public void setMessageTimeToLive(int messageTimeToLive) { this.messageTimeToLive = messageTimeToLive; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public int getSocketBufferSize() { return this.socketBufferSize; }
public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; } public int getSubscriptionCapacity() { return this.subscriptionCapacity; } public void setSubscriptionCapacity(int subscriptionCapacity) { this.subscriptionCapacity = subscriptionCapacity; } public String getSubscriptionDiskStoreName() { return this.subscriptionDiskStoreName; } public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) { this.subscriptionDiskStoreName = subscriptionDiskStoreName; } public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() { return this.subscriptionEvictionPolicy; } public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) { this.subscriptionEvictionPolicy = subscriptionEvictionPolicy; } public boolean isTcpNoDelay() { return this.tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java
2
请完成以下Java代码
public boolean isDmnReturnBlankTableOutputAsNull() { return dmnReturnBlankTableOutputAsNull; } public ProcessEngineConfigurationImpl setDmnReturnBlankTableOutputAsNull(boolean dmnReturnBlankTableOutputAsNull) { this.dmnReturnBlankTableOutputAsNull = dmnReturnBlankTableOutputAsNull; return this; } public DiagnosticsCollector getDiagnosticsCollector() { return diagnosticsCollector; } public void setDiagnosticsCollector(DiagnosticsCollector diagnosticsCollector) { this.diagnosticsCollector = diagnosticsCollector; } public TelemetryDataImpl getTelemetryData() { return telemetryData; } public ProcessEngineConfigurationImpl setTelemetryData(TelemetryDataImpl telemetryData) { this.telemetryData = telemetryData; return this; } public boolean isReevaluateTimeCycleWhenDue() { return reevaluateTimeCycleWhenDue; } public ProcessEngineConfigurationImpl setReevaluateTimeCycleWhenDue(boolean reevaluateTimeCycleWhenDue) { this.reevaluateTimeCycleWhenDue = reevaluateTimeCycleWhenDue; return this; } public int getRemovalTimeUpdateChunkSize() { return removalTimeUpdateChunkSize; } public ProcessEngineConfigurationImpl setRemovalTimeUpdateChunkSize(int removalTimeUpdateChunkSize) { this.removalTimeUpdateChunkSize = removalTimeUpdateChunkSize; return this; }
/** * @return a exception code interceptor. The interceptor is not registered in case * {@code disableExceptionCode} is configured to {@code true}. */ protected ExceptionCodeInterceptor getExceptionCodeInterceptor() { return new ExceptionCodeInterceptor(builtinExceptionCodeProvider, customExceptionCodeProvider); } public DiagnosticsRegistry getDiagnosticsRegistry() { return diagnosticsRegistry; } public ProcessEngineConfiguration setDiagnosticsRegistry(DiagnosticsRegistry diagnosticsRegistry) { this.diagnosticsRegistry = diagnosticsRegistry; return this; } public boolean isLegacyJobRetryBehaviorEnabled() { return legacyJobRetryBehaviorEnabled; } public ProcessEngineConfiguration setLegacyJobRetryBehaviorEnabled(boolean legacyJobRetryBehaviorEnabled) { this.legacyJobRetryBehaviorEnabled = legacyJobRetryBehaviorEnabled; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请完成以下Java代码
public void setC_JobRemuneration_ID (int C_JobRemuneration_ID) { if (C_JobRemuneration_ID < 1) set_ValueNoCheck (COLUMNNAME_C_JobRemuneration_ID, null); else set_ValueNoCheck (COLUMNNAME_C_JobRemuneration_ID, Integer.valueOf(C_JobRemuneration_ID)); } /** Get Position Remuneration. @return Remuneration for the Position */ public int getC_JobRemuneration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_JobRemuneration_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Remuneration getC_Remuneration() throws RuntimeException { return (I_C_Remuneration)MTable.get(getCtx(), I_C_Remuneration.Table_Name) .getPO(getC_Remuneration_ID(), get_TrxName()); } /** Set Remuneration. @param C_Remuneration_ID Wage or Salary */ public void setC_Remuneration_ID (int C_Remuneration_ID) { if (C_Remuneration_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Remuneration_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Remuneration_ID, Integer.valueOf(C_Remuneration_ID)); } /** Get Remuneration. @return Wage or Salary */ public int getC_Remuneration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Remuneration_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobRemuneration.java
1
请完成以下Java代码
public void onMessage(ConsumerRecord<K, V> consumerRecord, Acknowledgment acknowledgment, Consumer<?, ?> consumer) throws KafkaBackoffException { this.kafkaConsumerBackoffManager.backOffIfNecessary(createContext(consumerRecord, consumerRecord.timestamp() + delaysPerTopic.getOrDefault(consumerRecord.topic(), this.defaultDelay) .toMillis(), consumer)); invokeDelegateOnMessage(consumerRecord, acknowledgment, consumer); } public void setDelayForTopic(String topic, Duration delay) { Objects.requireNonNull(topic, "Topic cannot be null"); Objects.requireNonNull(delay, "Delay cannot be null"); this.logger.debug(() -> String.format("Setting %s seconds delay for topic %s", delay, topic)); this.delaysPerTopic.put(topic, delay); } public void setDefaultDelay(Duration delay) { Objects.requireNonNull(delay, "Delay cannot be null"); this.logger.debug(() -> String.format("Setting %s seconds delay for listener id %s", delay, this.listenerId)); this.defaultDelay = delay; } private void invokeDelegateOnMessage(ConsumerRecord<K, V> consumerRecord, Acknowledgment acknowledgment, Consumer<?, ?> consumer) { switch (this.delegateType) { case ACKNOWLEDGING_CONSUMER_AWARE: this.delegate.onMessage(consumerRecord, acknowledgment, consumer); break; case ACKNOWLEDGING: this.delegate.onMessage(consumerRecord, acknowledgment); break; case CONSUMER_AWARE: this.delegate.onMessage(consumerRecord, consumer); break; case SIMPLE: this.delegate.onMessage(consumerRecord); } } private KafkaConsumerBackoffManager.Context createContext(ConsumerRecord<K, V> data, long nextExecutionTimestamp, Consumer<?, ?> consumer) { return this.kafkaConsumerBackoffManager.createContext(nextExecutionTimestamp, this.listenerId, new TopicPartition(data.topic(), data.partition()),
consumer); } @Override public void onMessage(ConsumerRecord<K, V> data) { onMessage(data, null, null); } @Override public void onMessage(ConsumerRecord<K, V> data, Acknowledgment acknowledgment) { onMessage(data, acknowledgment, null); } @Override public void onMessage(ConsumerRecord<K, V> data, Consumer<?, ?> consumer) { onMessage(data, null, consumer); } }
repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\delay\DelayedMessageListenerAdapter.java
1
请完成以下Java代码
public class PrimeNumbers extends RecursiveAction { private int lowerBound; private int upperBound; private int granularity; static final List<Integer> GRANULARITIES = Arrays.asList(1, 10, 100, 1000, 10000); private AtomicInteger noOfPrimeNumbers; PrimeNumbers(int lowerBound, int upperBound, int granularity, AtomicInteger noOfPrimeNumbers) { this.lowerBound = lowerBound; this.upperBound = upperBound; this.granularity = granularity; this.noOfPrimeNumbers = noOfPrimeNumbers; } PrimeNumbers(int upperBound) { this(1, upperBound, 100, new AtomicInteger(0)); } private PrimeNumbers(int lowerBound, int upperBound, AtomicInteger noOfPrimeNumbers) { this(lowerBound, upperBound, 100, noOfPrimeNumbers); } private List<PrimeNumbers> subTasks() { List<PrimeNumbers> subTasks = new ArrayList<>(); for (int i = 1; i <= this.upperBound / granularity; i++) { int upper = i * granularity; int lower = (upper - granularity) + 1; subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers)); } return subTasks; } @Override protected void compute() { if (((upperBound + 1) - lowerBound) > granularity) { ForkJoinTask.invokeAll(subTasks()); } else { findPrimeNumbers(); } }
void findPrimeNumbers() { for (int num = lowerBound; num <= upperBound; num++) { if (isPrime(num)) { noOfPrimeNumbers.getAndIncrement(); } } } private boolean isPrime(int number) { if (number == 2) { return true; } if (number == 1 || number % 2 == 0) { return false; } int noOfNaturalNumbers = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { noOfNaturalNumbers++; } } return noOfNaturalNumbers == 2; } public int noOfPrimeNumbers() { return noOfPrimeNumbers.intValue(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\workstealing\PrimeNumbers.java
1
请完成以下Java代码
public boolean isPublic () { Object oo = get_Value(COLUMNNAME_IsPublic); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Public Write. @param IsPublicWrite Public can write entries */ public void setIsPublicWrite (boolean IsPublicWrite) { set_Value (COLUMNNAME_IsPublicWrite, Boolean.valueOf(IsPublicWrite)); } /** Get Public Write. @return Public can write entries */ public boolean isPublicWrite () { Object oo = get_Value(COLUMNNAME_IsPublicWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Knowledge Topic. @param K_Topic_ID Knowledge Topic */ public void setK_Topic_ID (int K_Topic_ID) { if (K_Topic_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Topic_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Topic_ID, Integer.valueOf(K_Topic_ID)); } /** Get Knowledge Topic. @return Knowledge Topic */ public int getK_Topic_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID); if (ii == null) return 0; return ii.intValue(); } public I_K_Type getK_Type() throws RuntimeException { return (I_K_Type)MTable.get(getCtx(), I_K_Type.Table_Name) .getPO(getK_Type_ID(), get_TrxName()); } /** Set Knowldge Type. @param K_Type_ID Knowledge Type */ public void setK_Type_ID (int K_Type_ID) { if (K_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Type_ID, Integer.valueOf(K_Type_ID)); }
/** Get Knowldge Type. @return Knowledge Type */ public int getK_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Topic.java
1
请完成以下Java代码
public ITrxConstraints setTrxTimeoutSecs(final int secs, final boolean logOnly) { this.trxTimeoutSecs = secs; this.trxTimeoutLogOnly = logOnly; return this; } @Override public int getTrxTimeoutSecs() { return trxTimeoutSecs; } @Override public boolean isTrxTimeoutLogOnly() { return trxTimeoutLogOnly; } @Override public ITrxConstraints setMaxTrx(final int max) { this.maxTrx = max; return this; } @Override public ITrxConstraints incMaxTrx(final int num) { this.maxTrx += num; return this; } @Override public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow) { this.allowTrxAfterThreadEnd = allow; return this; } @Override public int getMaxTrx() { return maxTrx; } @Override public ITrxConstraints setMaxSavepoints(int maxSavepoints) { this.maxSavepoints = maxSavepoints; return this; } @Override public int getMaxSavepoints() { return maxSavepoints; } @Override public ITrxConstraints setActive(boolean active) { this.active = active; return this; } @Override public boolean isActive() { return active; } @Override public boolean isOnlyAllowedTrxNamePrefixes() { return onlyAllowedTrxNamePrefixes; } @Override public ITrxConstraints setOnlyAllowedTrxNamePrefixes(boolean onlyAllowedTrxNamePrefixes) { this.onlyAllowedTrxNamePrefixes = onlyAllowedTrxNamePrefixes; return this; } @Override public ITrxConstraints addAllowedTrxNamePrefix(final String trxNamePrefix) { allowedTrxNamePrefixes.add(trxNamePrefix); return this; }
@Override public ITrxConstraints removeAllowedTrxNamePrefix(final String trxNamePrefix) { allowedTrxNamePrefixes.remove(trxNamePrefix); return this; } @Override public Set<String> getAllowedTrxNamePrefixes() { return allowedTrxNamePrefixesRO; } @Override public boolean isAllowTrxAfterThreadEnd() { return allowTrxAfterThreadEnd; } @Override public void reset() { setActive(DEFAULT_ACTIVE); setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END); setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS); setMaxTrx(DEFAULT_MAX_TRX); setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY); setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES); allowedTrxNamePrefixes.clear(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("TrxConstraints["); sb.append("active=" + this.active); sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes()); sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd()); sb.append(", maxSavepoints=" + getMaxSavepoints()); sb.append(", maxTrx=" + getMaxTrx()); sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes()); sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly()); sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs()); sb.append("]"); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java
1
请在Spring Boot框架中完成以下Java代码
public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getSignalEventSubscriptionName() { return signalEventSubscriptionName; } public void setSignalEventSubscriptionName(String signalEventSubscriptionName) { this.signalEventSubscriptionName = signalEventSubscriptionName; } public String getMessageEventSubscriptionName() { return messageEventSubscriptionName; } public void setMessageEventSubscriptionName(String messageEventSubscriptionName) { this.messageEventSubscriptionName = messageEventSubscriptionName; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getTenantId() { return tenantId;
} public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(Set<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public JSONObject httpRequestMethodHandler() { return CommonUtil.errorJson(ErrorEnum.E_500); } /** * 本系统自定义错误的拦截器 * 拦截到此错误之后,就返回这个类里面的json给前端 * 常见使用场景是参数校验失败,抛出此错,返回错误信息给前端 */ @ExceptionHandler(CommonJsonException.class) public JSONObject commonJsonExceptionHandler(CommonJsonException commonJsonException) { return commonJsonException.getResultJson(); } /**
* 权限不足报错拦截 */ @ExceptionHandler(UnauthorizedException.class) public JSONObject unauthorizedExceptionHandler() { return CommonUtil.errorJson(ErrorEnum.E_502); } /** * 未登录报错拦截 * 在请求需要权限的接口,而连登录都还没登录的时候,会报此错 */ @ExceptionHandler(UnauthenticatedException.class) public JSONObject unauthenticatedException() { return CommonUtil.errorJson(ErrorEnum.E_20011); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\exception\GlobalExceptionHandler.java
2
请完成以下Java代码
public void setC_OrderLine(final org.compiere.model.I_C_OrderLine C_OrderLine) { set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine); } @Override public void setC_OrderLine_ID (final int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID); } @Override public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } /** * DocStatus AD_Reference_ID=131 * Reference name: _Document Status */ public static final int DOCSTATUS_AD_Reference_ID=131; /** Drafted = DR */ public static final String DOCSTATUS_Drafted = "DR"; /** Completed = CO */ public static final String DOCSTATUS_Completed = "CO"; /** Approved = AP */ public static final String DOCSTATUS_Approved = "AP"; /** NotApproved = NA */ public static final String DOCSTATUS_NotApproved = "NA"; /** Voided = VO */ public static final String DOCSTATUS_Voided = "VO"; /** Invalid = IN */ public static final String DOCSTATUS_Invalid = "IN"; /** Reversed = RE */ public static final String DOCSTATUS_Reversed = "RE"; /** Closed = CL */
public static final String DOCSTATUS_Closed = "CL"; /** Unknown = ?? */ public static final String DOCSTATUS_Unknown = "??"; /** InProgress = IP */ public static final String DOCSTATUS_InProgress = "IP"; /** WaitingPayment = WP */ public static final String DOCSTATUS_WaitingPayment = "WP"; /** WaitingConfirmation = WC */ public static final String DOCSTATUS_WaitingConfirmation = "WC"; @Override public void setDocStatus (final @Nullable java.lang.String DocStatus) { throw new IllegalArgumentException ("DocStatus is virtual column"); } @Override public java.lang.String getDocStatus() { return get_ValueAsString(COLUMNNAME_DocStatus); } @Override public void setQtyOrdered (final BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_Order_Line_Alloc.java
1
请完成以下Java代码
public String translate(@NonNull final String adLanguage) { return trlsCache.computeIfAbsent(adLanguage, this::buildTranslation); } private String buildTranslation(final String adLanguage) { return toTranslatableString().translate(adLanguage); } private String getFieldValue(@NonNull final String field, @NonNull final String adLanguage) { final ITranslatableString value = fieldValues.get(field); return value != null ? StringUtils.trimBlankToNull(value.translate(adLanguage)) : null; } private Comparable<?> getFieldComparingKey(@NonNull final String field, @NonNull final String adLanguage) { final Comparable<?> cmp = comparingKeys.get(field); if (cmp != null) { return cmp; } return getFieldValue(field, adLanguage); } public static Comparator<WorkflowLauncherCaption> orderBy(@NonNull final String adLanguage, @NonNull final List<OrderBy> orderBys) { // // Order by each given field Comparator<WorkflowLauncherCaption> result = null; for (final OrderBy orderBy : orderBys) { final Comparator<WorkflowLauncherCaption> cmp = toComparator(adLanguage, orderBy); result = result != null ? result.thenComparing(cmp) : cmp; } // Last, order by complete caption final Comparator<WorkflowLauncherCaption> completeCaptionComparator = toCompleteCaptionComparator(adLanguage); result = result != null ? result.thenComparing(completeCaptionComparator) : completeCaptionComparator; return result; } private static Comparator<WorkflowLauncherCaption> toComparator(@NonNull final String adLanguage, @NonNull final OrderBy orderBy) { final String field = orderBy.getField();
final Function<WorkflowLauncherCaption, Comparable<?>> keyExtractor = caption -> caption.getFieldComparingKey(field, adLanguage); //noinspection unchecked Comparator<Comparable<?>> keyComparator = (Comparator<Comparable<?>>)Comparator.naturalOrder(); if (!orderBy.isAscending()) { keyComparator = keyComparator.reversed(); } keyComparator = Comparator.nullsLast(keyComparator); return Comparator.comparing(keyExtractor, keyComparator); } private static Comparator<WorkflowLauncherCaption> toCompleteCaptionComparator(@NonNull final String adLanguage) { final Function<WorkflowLauncherCaption, String> keyExtractor = caption -> caption.translate(adLanguage); Comparator<String> keyComparator = Comparator.nullsLast(Comparator.naturalOrder()); return Comparator.comparing(keyExtractor, keyComparator); } // // // @Value @Builder public static class OrderBy { @NonNull String field; @Builder.Default boolean ascending = true; public static OrderBy descending(@NonNull final ReferenceListAwareEnum field) { return descending(field.getCode()); } public static OrderBy descending(@NonNull final String field) { return builder().field(field).ascending(false).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLauncherCaption.java
1
请完成以下Java代码
private void enqueueModels(final FTSConfig ftsConfig) { final FTSConfigSourceTablesMap sourceTables = FTSConfigSourceTablesMap.ofList(ftsConfigService.getSourceTables().getByConfigId(ftsConfig.getId())); for (final TableName sourceTableName : sourceTables.getTableNames()) { enqueueModels(sourceTableName, sourceTables); } } private void enqueueModels( @NonNull final TableName sourceTableName, @NonNull final FTSConfigSourceTablesMap sourceTablesMap) { final Stream<ModelToIndexEnqueueRequest> requestsStream = queryBL.createQueryBuilder(sourceTableName.getAsString()) .addOnlyActiveRecordsFilter() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .iterateAndStream()
.flatMap(model -> extractRequests(model, sourceTablesMap).stream()); GuavaCollectors.batchAndStream(requestsStream, 500) .forEach(requests -> { modelsToIndexQueueService.enqueueNow(requests); addLog("Enqueued {} records from {} table", requests.size(), sourceTableName); }); } private List<ModelToIndexEnqueueRequest> extractRequests( @NonNull final Object model, @NonNull final FTSConfigSourceTablesMap sourceTables) { return EnqueueSourceModelInterceptor.extractRequests( model, ModelToIndexEventType.CREATED_OR_UPDATED, sourceTables); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\process\ES_FTS_Config_Sync.java
1
请完成以下Java代码
public static void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic) { // note: we can assume that #setQtyOrdered() was already called ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially ic.setQtyDeliveredInUOM(ic.getQtyEntered()); ic.setDeliveryDate(ic.getDateOrdered()); } public static void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Flatrate_Term term = retrieveTerm(ic); InvoiceCandidateLocationAdapterFactory .billLocationAdapter(ic) .setFrom(ContractLocationHelper.extractBillLocation(term)); }
public static UomId retrieveUomId(@NonNull final I_C_Invoice_Candidate icRecord) { final I_C_Flatrate_Term term = retrieveTerm(icRecord); if (term.getC_UOM_ID() > 0) { return UomId.ofRepoId(term.getC_UOM_ID()); } if (term.getM_Product_ID() > 0) { final IProductBL productBL = Services.get(IProductBL.class); return productBL.getStockUOMId(term.getM_Product_ID()); } throw new AdempiereException("The term of param 'icRecord' needs to have a UOM; C_Invoice_Candidate_ID=" + icRecord.getC_Invoice_Candidate_ID()) .appendParametersToMessage() .setParameter("term", term) .setParameter("icRecord", icRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoicecandidate\HandlerTools.java
1
请完成以下Java代码
public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQualityInspectionCycle (final @Nullable java.lang.String QualityInspectionCycle) { set_ValueNoCheck (COLUMNNAME_QualityInspectionCycle, QualityInspectionCycle); } @Override
public java.lang.String getQualityInspectionCycle() { return get_ValueAsString(COLUMNNAME_QualityInspectionCycle); } @Override public void setRV_M_Material_Tracking_HU_Details_ID (final int RV_M_Material_Tracking_HU_Details_ID) { if (RV_M_Material_Tracking_HU_Details_ID < 1) set_ValueNoCheck (COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID, null); else set_ValueNoCheck (COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID, RV_M_Material_Tracking_HU_Details_ID); } @Override public int getRV_M_Material_Tracking_HU_Details_ID() { return get_ValueAsInt(COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_M_Material_Tracking_HU_Details.java
1
请完成以下Java代码
public boolean createPeriods() { int sumDays = 0; int C_Calendar_ID = DB.getSQLValueEx(get_TrxName(), "SELECT C_Calendar_ID FROM C_Year WHERE C_Year_ID = ?", getC_Year_ID()); if (C_Calendar_ID <= 0) return false; Timestamp StartDate = null; Timestamp EndDate = null ; MHRPayroll payroll = new MHRPayroll(getCtx(), getHR_Payroll_ID(), get_TrxName()); for (int period = 1; period <= getQty(); period++) { //arhipac: Cristina Ghita It is need this condition for a good generation periods //in case of correspondence between period and month if ((12 == getQty())&& (28 == getNetDays() || 29 == getNetDays() || 30 == getNetDays() || 31 == getNetDays())) { if (period >1) { StartDate = TimeUtil.addDays(EndDate, 1); } else { StartDate = TimeUtil.addDays(getStartDate(),0); } EndDate = TimeUtil.getMonthLastDay(StartDate); } else { sumDays = period == 1 ? 0 : (period-1) * (getNetDays()) ; StartDate = TimeUtil.addDays(getStartDate(),sumDays); EndDate = TimeUtil.addDays(StartDate,getNetDays()-1); } int C_Period_ID = DB.getSQLValueEx(get_TrxName(), "SELECT C_Period_ID FROM C_Period p " + " INNER JOIN C_Year y ON (p.C_Year_ID=y.C_Year_ID) "
+ " WHERE " + " ? BETWEEN p.startdate AND p.endDate" + " AND y.C_Calendar_ID=?", EndDate, C_Calendar_ID); if(C_Period_ID <= 0) return false; MPeriod m_period = MPeriod.get(getCtx(), C_Period_ID); MHRPeriod HR_Period = new MHRPeriod(getCtx(), 0, get_TrxName()); HR_Period.setAD_Org_ID(getAD_Org_ID()); HR_Period.setHR_Year_ID(getHR_Year_ID()); HR_Period.setHR_Payroll_ID(getHR_Payroll_ID()); HR_Period.setName(StartDate.toString().substring(0, 10)+" "+Msg.translate(getCtx(), "To")+" "+EndDate.toString().substring(0, 10) ); HR_Period.setDescription(Msg.translate(getCtx(), "HR_Payroll_ID")+" "+payroll.getName().trim()+" "+Msg.translate(getCtx(), "From")+ " "+period+" " +Msg.translate(getCtx(), "To")+" "+ StartDate.toString().substring(0, 10)+" al "+EndDate.toString().substring(0, 10)); HR_Period.setPeriodNo(period); HR_Period.setC_Period_ID(C_Period_ID); HR_Period.setC_Year_ID(m_period.getC_Year_ID()); HR_Period.setStartDate(StartDate); HR_Period.setEndDate(EndDate); HR_Period.setDateAcct(EndDate); HR_Period.setIsActive(true); HR_Period.saveEx(); } return true; } // createPeriods } // HRYear
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRYear.java
1
请完成以下Java代码
private static void performVersionChecks() { performVersionChecks(MIN_SPRING_VERSION); } /** * Perform version checks with specific min Spring Version * @param minSpringVersion */ private static void performVersionChecks(@Nullable String minSpringVersion) { if (minSpringVersion == null) { return; } // Check Spring Compatibility String springVersion = SpringVersion.getVersion(); String version = getVersion(); if (disableChecks(springVersion, version)) { return; } // should be disabled if springVersion is null Assert.notNull(springVersion, "springVersion cannot be null"); logger.info("You are running with Spring Security Core " + version); if (new ComparableVersion(springVersion).compareTo(new ComparableVersion(minSpringVersion)) < 0) { logger.warn("**** You are advised to use Spring " + minSpringVersion + " or later with this version. You are running: " + springVersion); } } public static @Nullable String getVersion() { Package pkg = SpringSecurityCoreVersion.class.getPackage(); return (pkg != null) ? pkg.getImplementationVersion() : null; } /** * Disable if springVersion and springSecurityVersion are the same to allow working * with Uber Jars. * @param springVersion * @param springSecurityVersion * @return */ private static boolean disableChecks(@Nullable String springVersion, @Nullable String springSecurityVersion) { if (springVersion == null || springVersion.equals(springSecurityVersion)) { return true; }
return Boolean.getBoolean(DISABLE_CHECKS); } /** * Loads the spring version or null if it cannot be found. * @return */ private static @Nullable String getSpringVersion() { Properties properties = new Properties(); try (InputStream is = SpringSecurityCoreVersion.class.getClassLoader() .getResourceAsStream("META-INF/spring-security.versions")) { properties.load(is); } catch (IOException | NullPointerException ex) { return null; } return properties.getProperty("org.springframework:spring-core"); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\SpringSecurityCoreVersion.java
1
请完成以下Java代码
public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } @Override public void setVolume (final @Nullable BigDecimal Volume) { set_Value (COLUMNNAME_Volume, Volume); } @Override public BigDecimal getVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeight (final @Nullable BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } @Override public BigDecimal getWeight() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOut.java
1
请完成以下Java代码
public Response putAmount(@PathParam("id") String id, @PathParam("amount") Double amount) { Optional<Wallet> wallet = wallets.findById(id); wallet.orElseThrow(IllegalArgumentException::new); if (amount < Wallet.MIN_CHARGE) { throw new InvalidTradeException(Wallet.MIN_CHARGE_MSG); } wallet.get() .addBalance(amount); wallets.save(wallet.get()); return Response.ok(wallet) .build(); } @POST @Path("/{wallet}/buy/{ticker}") @Produces(MediaType.APPLICATION_JSON) public Response postBuyStock(@PathParam("wallet") String walletId, @PathParam("ticker") String id) { Optional<Stock> stock = stocks.findById(id); stock.orElseThrow(InvalidTradeException::new); Optional<Wallet> w = wallets.findById(walletId); w.orElseThrow(InvalidTradeException::new); Wallet wallet = w.get(); Double price = stock.get() .getPrice();
if (!wallet.hasFunds(price)) { RestErrorResponse response = new RestErrorResponse(); response.setSubject(wallet); response.setMessage("insufficient balance"); throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE) .entity(response) .build()); } wallet.addBalance(-price); wallets.save(wallet); return Response.ok(wallet) .build(); } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\exceptionhandling\rest\WalletsResource.java
1
请完成以下Java代码
public class WeightTareAdjustAttributeValueCallout extends AbstractWeightAttributeValueCallout { /** * Fires WeightGross recalculation based on existing WeightNet & the new WeightTare value */ @Override public void onValueChanged0(final IAttributeValueContext attributeValueContext_IGNORED, final IAttributeSet attributeSet, final I_M_Attribute attribute_IGNORED, final Object valueOld_IGNORED, final Object valueNew_IGNORED) { recalculateWeightNet(attributeSet); } /** * Returns the summed weight of the packing material of the given <code>attributeSet</code>'s HU. * <p> * NOTE: does <b>not</b> descent into sub-HUs to also add their tare values. This is good, because this value is used in bottom-up-propagation, i.e. the children tare values are added during * propagation. */ @Override public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueInitialDefault) { // we don't support a value different from null Check.assumeNull(valueInitialDefault, "valueInitialDefault null"); return BigDecimal.ZERO; } @Override public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_Number; } @Override public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return true;
} @Override public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return BigDecimal.ZERO; } @Override protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { return !Objects.equals(valueOld, valueNew); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightTareAdjustAttributeValueCallout.java
1
请完成以下Java代码
public List<Criterion> getEntryCriteria() { return entryCriteria; } public List<Criterion> getExitCriteria() { return exitCriteria; } public List<Sentry> getSentries() { return sentries; } public List<SentryOnPart> getSentryOnParts() { return sentryOnParts; } public List<SentryIfPart> getSentryIfParts() { return sentryIfParts; } public List<PlanItem> getPlanItems() { return planItems; }
public List<PlanItemDefinition> getPlanItemDefinitions() { return planItemDefinitions; } public List<CmmnDiShape> getDiShapes() { return diShapes; } public List<CmmnDiEdge> getDiEdges() { return diEdges; } public GraphicInfo getCurrentLabelGraphicInfo() { return currentLabelGraphicInfo; } public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) { this.currentLabelGraphicInfo = labelGraphicInfo; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java
1
请完成以下Java代码
public BigDecimal toBigDecimal() { return money.toBigDecimal(); } public CurrencyId getCurrencyId() { return money.getCurrencyId(); } public ProductPrice withValueAndUomId(@NonNull final BigDecimal moneyAmount, @NonNull final UomId uomId) { return toBuilder() .money(Money.of(moneyAmount, getCurrencyId())) .uomId(uomId) .build(); } public ProductPrice negate() { return this.toBuilder().money(money.negate()).build(); }
public boolean isEqualByComparingTo(@Nullable final ProductPrice other) { if (other == null) { return false; } return other.uomId.equals(uomId) && other.money.isEqualByComparingTo(money); } public <T> T transform(@NonNull final Function<ProductPrice, T> mapper) { return mapper.apply(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\ProductPrice.java
1
请完成以下Java代码
public class ToolBox { @Tool(description = "Get the current time in a specific timezone.") public String getTimeInTimezone( @ToolArg(description = "Timezone ID (e.g., America/Los_Angeles)") String timezoneId) { try { ZoneId zoneId = ZoneId.of(timezoneId); ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(java.time.format.FormatStyle.FULL) .withLocale(Locale.getDefault()); return zonedDateTime.format(formatter); } catch (Exception e) { return "Invalid timezone ID: " + timezoneId + ". Please provide a valid IANA timezone ID."; } } @Tool(description = "Provides JVM system information such as available processors, free memory, total memory, and max memory.") public String getJVMInfo() { StringBuilder systemInfo = new StringBuilder(); // Get available processors int availableProcessors = Runtime.getRuntime().availableProcessors();
systemInfo.append("Available processors (cores): ").append(availableProcessors).append("\n"); // Get free memory long freeMemory = Runtime.getRuntime().freeMemory(); systemInfo.append("Free memory (bytes): ").append(freeMemory).append("\n"); // Get total memory long totalMemory = Runtime.getRuntime().totalMemory(); systemInfo.append("Total memory (bytes): ").append(totalMemory).append("\n"); // Get max memory long maxMemory = Runtime.getRuntime().maxMemory(); systemInfo.append("Max memory (bytes): ").append(maxMemory).append("\n"); return systemInfo.toString(); } }
repos\tutorials-master\quarkus-modules\quarkus-mcp-langchain\quarkus-mcp-server\src\main\java\com\baeldung\quarkus\mcp\ToolBox.java
1
请完成以下Java代码
public abstract class DocumentSalesRepDescriptor { @Getter @Setter private Beneficiary salesRep; @Getter @Setter private String salesPartnerCode; @Getter @Setter private boolean salesRepRequired; @Getter private SOTrx soTrx; @Getter private Customer customer; @Getter private OrgId orgId; @Getter private boolean inSyncWithRecord; public DocumentSalesRepDescriptor( @NonNull final OrgId orgId, @NonNull final SOTrx soTrx, @Nullable final Customer customer,
@Nullable final Beneficiary salesRep, @Nullable final String salesPartnerCode, final boolean salesRepRequired) { this.orgId = orgId; this.soTrx = soTrx; this.customer = customer; this.salesRep = salesRep; this.salesPartnerCode = salesPartnerCode; this.salesRepRequired = salesRepRequired; } public boolean validatesOK() { if (soTrx.isPurchase()) { return true; // we don't have any business with purchase documents } if (!isSalesRepRequired()) { return true; } // if a sales rep is required, then in order to be valid, we need to have a sales rep return salesRep != null; } public abstract void syncToRecord(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\salesrep\DocumentSalesRepDescriptor.java
1
请完成以下Java代码
public IModelMethodInfo createModelMethodInfo(final Method method) { String methodName = method.getName(); final Class<?>[] parameters = method.getParameterTypes(); final int parametersCount = parameters == null ? 0 : parameters.length; if (methodName.startsWith("set") && parametersCount == 1) { final String propertyName = methodName.substring(3); // method name without "set" prefix final Class<?> paramType = parameters[0]; if (InterfaceWrapperHelper.isModelInterface(paramType)) { final ModelSetterMethodInfo methodInfo = new ModelSetterMethodInfo(method, paramType, propertyName + "_ID"); return methodInfo; } else { final ValueSetterMethodInfo methodInfo = new ValueSetterMethodInfo(method, propertyName); return methodInfo; } } else if (methodName.startsWith("get") && (parametersCount == 0)) { String propertyName = methodName.substring(3); if (InterfaceWrapperHelper.isModelInterface(method.getReturnType())) { final String columnName = propertyName + "_ID"; final ModelGetterMethodInfo methodInfo = new ModelGetterMethodInfo(method, columnName); return methodInfo; } else { final ValueGetterMethodInfo methodInfo = new ValueGetterMethodInfo(method, propertyName); return methodInfo; } } else if (methodName.startsWith("is") && (parametersCount == 0)) { final String propertyName = methodName.substring(2); final BooleanGetterMethodInfo methodInfo = new BooleanGetterMethodInfo(method, propertyName); return methodInfo; } else if (methodName.equals("equals") && parametersCount == 1) { final EqualsMethodInfo methodInfo = new EqualsMethodInfo(method); return methodInfo; }
else { final InvokeParentMethodInfo methodInfo = new InvokeParentMethodInfo(method); return methodInfo; } } private static final String getTableNameOrNull(final Class<?> clazz) { try { final Field field = clazz.getField("Table_Name"); if (!field.isAccessible()) { field.setAccessible(true); } return (String)field.get(null); } catch (final Exception e) { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelClassIntrospector.java
1
请完成以下Java代码
public class EnvironmentVariableELResolver extends ELResolver { private static final String VAR_PREFIX = "vars"; public static final String VAR_PREFIX_WITH_DOT = VAR_PREFIX + "."; @Override public Object getValue(ELContext context, Object base, Object property) { if (base == null && VAR_PREFIX.equals(property)) { context.setPropertyResolved(true); return new EnvVar(); } if (base instanceof EnvVar && property != null) { String env = System.getenv(VAR_PREFIX_WITH_DOT + property); context.setPropertyResolved(true); return env; } return null; } @Override public Class<?> getType(ELContext elContext, Object o, Object o1) { return String.class; }
@Override public void setValue(ELContext elContext, Object o, Object o1, Object o2) { throw new UnsupportedOperationException("Environment variables are read-only"); } @Override public boolean isReadOnly(ELContext elContext, Object o, Object o1) { return true; } @Override public Class<?> getCommonPropertyType(ELContext elContext, Object o) { return String.class; } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\resolver\EnvironmentVariableELResolver.java
1
请完成以下Java代码
public ModelQuery orderByModelName() { return orderBy(ModelQueryProperty.MODEL_NAME); } @Override public ModelQuery orderByCreateTime() { return orderBy(ModelQueryProperty.MODEL_CREATE_TIME); } @Override public ModelQuery orderByLastUpdateTime() { return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME); } @Override public ModelQuery orderByTenantId() { return orderBy(ModelQueryProperty.MODEL_TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getModelEntityManager(commandContext).findModelCountByQueryCriteria(this); } @Override public List<Model> executeList(CommandContext commandContext) { return CommandContextUtil.getModelEntityManager(commandContext).findModelsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; }
public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ModelQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<HistoryJobEntity> findExpiredJobs(List<String> enabledCategories, Page page) { Map<String, Object> params = new HashMap<>(); params.put("jobExecutionScope", jobServiceConfiguration.getHistoryJobExecutionScope()); Date now = jobServiceConfiguration.getClock().getCurrentTime(); params.put("now", now); return getDbSqlSession().selectList("selectExpiredHistoryJobs", params, page); } @Override @SuppressWarnings("unchecked") public List<HistoryJob> findHistoryJobsByQueryCriteria(HistoryJobQueryImpl jobQuery) { final String query = "selectHistoryJobByQueryCriteria"; return getDbSqlSession().selectList(query, jobQuery); } @Override public long findHistoryJobCountByQueryCriteria(HistoryJobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectHistoryJobCountByQueryCriteria", jobQuery); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateHistoryJobTenantIdForDeployment", params); } @Override
public void bulkUpdateJobLockWithoutRevisionCheck(List<HistoryJobEntity> historyJobs, String lockOwner, Date lockExpirationTime) { Map<String, Object> params = new HashMap<>(3); params.put("lockOwner", lockOwner); params.put("lockExpirationTime", lockExpirationTime); bulkUpdateEntities("updateHistoryJobLocks", params, "historyJobs", historyJobs); } @Override public void resetExpiredJob(String jobId) { Map<String, Object> params = new HashMap<>(2); params.put("id", jobId); getDbSqlSession().directUpdate("resetExpiredHistoryJob", params); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisHistoryJobDataManager.java
2
请完成以下Java代码
private int fromBytes(String headerName) { byte[] header = getHeader(headerName, byte[].class); return header == null ? 1 : ByteBuffer.wrap(header).getInt(); } /** * Get a header value with a specific type. * @param <T> the type. * @param key the header name. * @param type the type's {@link Class}. * @return the value, if present. * @throws IllegalArgumentException if the type is not correct. */ @SuppressWarnings("unchecked") @Nullable public <T> T getHeader(String key, Class<T> type) { Object value = getHeader(key); if (value == null) { return null; } if (!type.isAssignableFrom(value.getClass())) { throw new IllegalArgumentException("Incorrect type specified for header '" + key + "'. Expected [" + type + "] but actual type is [" + value.getClass() + "]"); } return (T) value;
} @Override protected MessageHeaderAccessor createAccessor(Message<?> message) { return wrap(message); } /** * Create an instance from the payload and headers of the given Message. * @param message the message. * @return the accessor. */ public static KafkaMessageHeaderAccessor wrap(Message<?> message) { return new KafkaMessageHeaderAccessor(message); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\KafkaMessageHeaderAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public DataResponse<ActivityInstanceResponse> getActivityInstances(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { ActivityInstanceQueryRequest query = new ActivityInstanceQueryRequest(); // Populate query based on request if (allRequestParams.get("activityId") != null) { query.setActivityId(allRequestParams.get("activityId")); } if (allRequestParams.get("activityInstanceId") != null) { query.setActivityInstanceId(allRequestParams.get("activityInstanceId")); } if (allRequestParams.get("activityName") != null) { query.setActivityName(allRequestParams.get("activityName")); } if (allRequestParams.get("activityType") != null) { query.setActivityType(allRequestParams.get("activityType")); } if (allRequestParams.get("executionId") != null) { query.setExecutionId(allRequestParams.get("executionId")); } if (allRequestParams.get("finished") != null) { query.setFinished(Boolean.valueOf(allRequestParams.get("finished"))); } if (allRequestParams.get("taskAssignee") != null) { query.setTaskAssignee(allRequestParams.get("taskAssignee")); } if (allRequestParams.get("taskCompletedBy") != null) { query.setTaskCompletedBy(allRequestParams.get("taskCompletedBy")); } if (allRequestParams.get("processInstanceId") != null) {
query.setProcessInstanceId(allRequestParams.get("processInstanceId")); } if (allRequestParams.get("processInstanceIds") != null) { query.setProcessInstanceIds(RequestUtil.parseToSet(allRequestParams.get("processInstanceIds"))); } if (allRequestParams.get("processDefinitionId") != null) { query.setProcessDefinitionId(allRequestParams.get("processDefinitionId")); } if (allRequestParams.get("tenantId") != null) { query.setTenantId(allRequestParams.get("tenantId")); } if (allRequestParams.get("tenantIdLike") != null) { query.setTenantIdLike(allRequestParams.get("tenantIdLike")); } if (allRequestParams.get("withoutTenantId") != null) { query.setWithoutTenantId(Boolean.valueOf(allRequestParams.get("withoutTenantId"))); } return getQueryResponse(query, allRequestParams); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ActivityInstanceCollectionResource.java
2
请在Spring Boot框架中完成以下Java代码
public class AccountController { private final EventProducer eventProducer; public AccountController(EventProducer eventProducer) { this.eventProducer = eventProducer; } @PostMapping() public ResponseEntity<AccountId> createAccount(@RequestBody CreateAccountRequest request) { String accountId = UUID.randomUUID().toString(); CreateAccountAsyncEvent createAccountAsyncEvent = new CreateAccountAsyncEvent( UUID.randomUUID().toString(), accountId, request.getName(), request.getCredit() ); eventProducer.sendAccountMessage(createAccountAsyncEvent); return ResponseEntity.ok(new AccountId(accountId)); } @PutMapping("/deposit") public ResponseEntity<Void> depositAccount(@RequestBody DepositAccountRequest request) { DepositAccountAsyncEvent depositAccountAsyncEvent = new DepositAccountAsyncEvent( UUID.randomUUID().toString(), request.getAccountId(), request.getCredit() ); eventProducer.sendAccountMessage(depositAccountAsyncEvent); return ResponseEntity.ok().build(); }
@DeleteMapping("/{account-id}") public ResponseEntity<Void> deleteAccount(@PathVariable("account-id") String accountId) { DeleteAccountAsyncEvent deleteAccountAsyncEvent = new DeleteAccountAsyncEvent(UUID.randomUUID().toString(), accountId); eventProducer.sendAccountMessage(deleteAccountAsyncEvent); return ResponseEntity.ok().build(); } @PutMapping() public ResponseEntity<Void> transferFunds(@RequestBody TransferFundsRequest request) { TransferFundsAsyncEvent transferFundsAsyncEvent = new TransferFundsAsyncEvent(UUID.randomUUID().toString(), request.getSourceAccountId(), request.getDestinationAccountId(), request.getCredit()); eventProducer.sendAccountMessage(transferFundsAsyncEvent); return ResponseEntity.ok().build(); } }
repos\spring-examples-java-17\spring-kafka\kafka-producer\src\main\java\itx\examples\spring\kafka\producer\controller\AccountController.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PingResponseDto securedPingResponse = (PingResponseDto) o; return Objects.equals(this.pong, securedPingResponse.pong); } @Override public int hashCode() { return Objects.hash(pong); } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append("class PingResponseDto {\n"); sb.append(" pong: ") .append(toIndentedString(pong)) .append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString() .replace("\n", "\n "); } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\PingResponseDto.java
1
请在Spring Boot框架中完成以下Java代码
public List<QueryVariable> getTaskVariables() { return taskVariables; } public void setTaskVariables(List<QueryVariable> taskVariables) { this.taskVariables = taskVariables; } public void setWithoutDueDate(Boolean withoutDueDate) { this.withoutDueDate = withoutDueDate; } public Boolean getWithoutDueDate() { return withoutDueDate; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLike() { return tenantIdLike; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public Boolean getWithoutProcessInstanceId() { return withoutProcessInstanceId; } public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) { this.withoutProcessInstanceId = withoutProcessInstanceId; } public String getCandidateOrAssigned() { return candidateOrAssigned; } public void setCandidateOrAssigned(String candidateOrAssigned) { this.candidateOrAssigned = candidateOrAssigned; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public List<String> getCategoryIn() { return categoryIn; } public void setCategoryIn(List<String> categoryIn) { this.categoryIn = categoryIn; }
public List<String> getCategoryNotIn() { return categoryNotIn; } public void setCategoryNotIn(List<String> categoryNotIn) { this.categoryNotIn = categoryNotIn; } public Boolean getWithoutCategory() { return withoutCategory; } public void setWithoutCategory(Boolean withoutCategory) { this.withoutCategory = withoutCategory; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult delete(@PathVariable Long id) { int count = flashPromotionSessionService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取场次详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsFlashPromotionSession> getItem(@PathVariable Long id) { SmsFlashPromotionSession promotionSession = flashPromotionSessionService.getItem(id); return CommonResult.success(promotionSession); } @ApiOperation("获取全部场次")
@RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsFlashPromotionSession>> list() { List<SmsFlashPromotionSession> promotionSessionList = flashPromotionSessionService.list(); return CommonResult.success(promotionSessionList); } @ApiOperation("获取全部可选场次及其数量") @RequestMapping(value = "/selectList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsFlashPromotionSessionDetail>> selectList(Long flashPromotionId) { List<SmsFlashPromotionSessionDetail> promotionSessionList = flashPromotionSessionService.selectList(flashPromotionId); return CommonResult.success(promotionSessionList); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsFlashPromotionSessionController.java
2
请完成以下Java代码
public Boolean getLanguage() { return this.language; } public void setLanguage(Boolean language) { this.language = language; } public Boolean getConfigurationFileFormat() { return this.configurationFileFormat; } public void setConfigurationFileFormat(Boolean configurationFileFormat) { this.configurationFileFormat = configurationFileFormat; } public Boolean getPackaging() { return this.packaging; } public void setPackaging(Boolean packaging) { this.packaging = packaging; } public Boolean getType() { return this.type; } public void setType(Boolean type) { this.type = type; } public InvalidDependencyInformation getDependencies() { return this.dependencies; } public void triggerInvalidDependencies(List<String> dependencies) { this.dependencies = new InvalidDependencyInformation(dependencies); } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid) .add("javaVersion=" + this.javaVersion) .add("language=" + this.language) .add("configurationFileFormat=" + this.configurationFileFormat)
.add("packaging=" + this.packaging) .add("type=" + this.type) .add("dependencies=" + this.dependencies) .add("message='" + this.message + "'") .toString(); } } /** * Invalid dependencies information. */ public static class InvalidDependencyInformation { private boolean invalid = true; private final List<String> values; public InvalidDependencyInformation(List<String> values) { this.values = values; } public boolean isInvalid() { return this.invalid; } public List<String> getValues() { return this.values; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString(); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
1
请在Spring Boot框架中完成以下Java代码
public class DataLoader implements ApplicationRunner { private static final Logger logger = LoggerFactory.getLogger(DataLoader.class); private static final String[] KEYS = { "name", "abv", "ibu", "description" }; @Value("classpath:/data/beers.json.gz") private Resource data; private final RedisVectorStore vectorStore; private final RedisVectorStoreProperties properties; public DataLoader(RedisVectorStore vectorStore, RedisVectorStoreProperties properties) { this.vectorStore = vectorStore; this.properties = properties; } @Override public void run(ApplicationArguments args) throws Exception { Map<String, Object> indexInfo = vectorStore.getJedis().ftInfo(properties.getIndex()); Long sss= (Long) indexInfo.getOrDefault("num_docs", "0"); int numDocs=sss.intValue(); if (numDocs > 20000) { logger.info("Embeddings already loaded. Skipping");
return; } Resource file = data; if (data.getFilename().endsWith(".gz")) { GZIPInputStream inputStream = new GZIPInputStream(data.getInputStream()); file = new InputStreamResource(inputStream, "beers.json.gz"); } logger.info("Creating Embeddings..."); // tag::loader[] // Create a JSON reader with fields relevant to our use case JsonReader loader = new JsonReader(file, KEYS); // Use the autowired VectorStore to insert the documents into Redis vectorStore.add(loader.get()); // end::loader[] logger.info("Embeddings created."); } }
repos\springboot-demo-master\RedisVectorStore\src\main\java\com\et\config\DataLoader.java
2
请完成以下Java代码
public static FlowableCaseStageEndedEvent createStageEndedEvent(CaseInstance caseInstance, PlanItemInstance stageInstance, String endingState) { return new FlowableCaseStageEndedEventImpl(caseInstance, stageInstance, endingState); } public static FlowableEntityEvent createCaseBusinessStatusUpdatedEvent(CaseInstance caseInstance, String oldBusinessStatus, String newBusinessStatus) { return new FlowableCaseBusinessStatusUpdatedEventImpl(caseInstance, oldBusinessStatus, newBusinessStatus); } public static FlowableEntityEvent createTaskCreatedEvent(Task task) { FlowableEntityEventImpl event = new FlowableEntityEventImpl(task, FlowableEngineEventType.TASK_CREATED); event.setScopeId(task.getScopeId()); event.setScopeDefinitionId(task.getScopeDefinitionId()); event.setScopeType(task.getScopeType()); event.setSubScopeId(task.getId()); return event; } public static FlowableEntityEvent createTaskAssignedEvent(Task task) {
FlowableEntityEventImpl event = new FlowableEntityEventImpl(task, FlowableEngineEventType.TASK_ASSIGNED); event.setScopeId(task.getScopeId()); event.setScopeDefinitionId(task.getScopeDefinitionId()); event.setScopeType(task.getScopeType()); event.setSubScopeId(task.getId()); return event; } public static FlowableEntityEvent createTaskCompletedEvent(Task task) { FlowableEntityEventImpl event = new FlowableEntityEventImpl(task, FlowableEngineEventType.TASK_COMPLETED); event.setScopeId(task.getScopeId()); event.setScopeDefinitionId(task.getScopeDefinitionId()); event.setScopeType(task.getScopeType()); event.setSubScopeId(task.getId()); return event; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\event\FlowableCmmnEventBuilder.java
1
请完成以下Java代码
public class Operation extends BaseElement { protected String name; protected String implementationRef; protected String inMessageRef; protected String outMessageRef; protected List<String> errorMessageRef = new ArrayList<String>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImplementationRef() { return implementationRef; } public void setImplementationRef(String implementationRef) { this.implementationRef = implementationRef; } public String getInMessageRef() { return inMessageRef; } public void setInMessageRef(String inMessageRef) { this.inMessageRef = inMessageRef; } public String getOutMessageRef() { return outMessageRef; } public void setOutMessageRef(String outMessageRef) { this.outMessageRef = outMessageRef; }
public List<String> getErrorMessageRef() { return errorMessageRef; } public void setErrorMessageRef(List<String> errorMessageRef) { this.errorMessageRef = errorMessageRef; } public Operation clone() { Operation clone = new Operation(); clone.setValues(this); return clone; } public void setValues(Operation otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setImplementationRef(otherElement.getImplementationRef()); setInMessageRef(otherElement.getInMessageRef()); setOutMessageRef(otherElement.getOutMessageRef()); errorMessageRef = new ArrayList<String>(); if (otherElement.getErrorMessageRef() != null && !otherElement.getErrorMessageRef().isEmpty()) { errorMessageRef.addAll(otherElement.getErrorMessageRef()); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Operation.java
1
请完成以下Java代码
public boolean isWithIncident() { return withIncident; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } public String getCaseInstanceId() { return caseInstanceId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isRootProcessInstances() { return isRootProcessInstances; }
public boolean isProcessDefinitionWithoutTenantId() { return isProcessDefinitionWithoutTenantId; } public boolean isLeafProcessInstances() { return isLeafProcessInstances; } public String[] getTenantIds() { return tenantIds; } @Override public ProcessInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public ProcessInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public static JsonQRCode toJsonQRCode(final PickingSlotIdAndCaption pickingSlotIdAndCaption) { return JsonPickingJobLine.toJsonQRCode(pickingSlotIdAndCaption); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { final PickingJob pickingJob = getPickingJob(wfProcess); return computeActivityState(pickingJob); } public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getPickingSlot().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final PickingSlotQRCode pickingSlotQRCode = PickingSlotQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode()); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJob -> pickingJobRestService.allocateAndSetPickingSlot(pickingJob, pickingSlotQRCode) ); } @Override public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(@NonNull GetScannedBarcodeSuggestionsRequest request) { final PickingJob pickingJob = getPickingJob(request.getWfProcess()); final PickingSlotSuggestions pickingSlotSuggestions = pickingJobRestService.getPickingSlotsSuggestions(pickingJob); return toJson(pickingSlotSuggestions); } private static JsonScannedBarcodeSuggestions toJson(final PickingSlotSuggestions pickingSlotSuggestions) { if (pickingSlotSuggestions.isEmpty())
{ return JsonScannedBarcodeSuggestions.EMPTY; } return pickingSlotSuggestions.stream() .map(SetPickingSlotWFActivityHandler::toJson) .collect(JsonScannedBarcodeSuggestions.collect()); } private static JsonScannedBarcodeSuggestion toJson(final PickingSlotSuggestion pickingSlotSuggestion) { return JsonScannedBarcodeSuggestion.builder() .caption(pickingSlotSuggestion.getCaption()) .detail(pickingSlotSuggestion.getDeliveryAddress()) .qrCode(pickingSlotSuggestion.getQRCode().toGlobalQRCodeJsonString()) .property1("HU") .value1(String.valueOf(pickingSlotSuggestion.getCountHUs())) .additionalProperty("bpartnerLocationId", BPartnerLocationId.toRepoId(pickingSlotSuggestion.getDeliveryBPLocationId())) // for testing .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickingSlotWFActivityHandler.java
1
请完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", brandId=").append(brandId); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", feightTemplateId=").append(feightTemplateId); sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", pic=").append(pic); sb.append(", productSn=").append(productSn); sb.append(", deleteStatus=").append(deleteStatus); sb.append(", publishStatus=").append(publishStatus); sb.append(", newStatus=").append(newStatus); sb.append(", recommandStatus=").append(recommandStatus); sb.append(", verifyStatus=").append(verifyStatus); sb.append(", sort=").append(sort); sb.append(", sale=").append(sale); sb.append(", price=").append(price); sb.append(", promotionPrice=").append(promotionPrice); sb.append(", giftGrowth=").append(giftGrowth); sb.append(", giftPoint=").append(giftPoint); sb.append(", usePointLimit=").append(usePointLimit); sb.append(", subTitle=").append(subTitle); sb.append(", originalPrice=").append(originalPrice); sb.append(", stock=").append(stock);
sb.append(", lowStock=").append(lowStock); sb.append(", unit=").append(unit); sb.append(", weight=").append(weight); sb.append(", previewStatus=").append(previewStatus); sb.append(", serviceIds=").append(serviceIds); sb.append(", keywords=").append(keywords); sb.append(", note=").append(note); sb.append(", albumPics=").append(albumPics); sb.append(", detailTitle=").append(detailTitle); sb.append(", promotionStartTime=").append(promotionStartTime); sb.append(", promotionEndTime=").append(promotionEndTime); sb.append(", promotionPerLimit=").append(promotionPerLimit); sb.append(", promotionType=").append(promotionType); sb.append(", brandName=").append(brandName); sb.append(", productCategoryName=").append(productCategoryName); sb.append(", description=").append(description); sb.append(", detailDesc=").append(detailDesc); sb.append(", detailHtml=").append(detailHtml); sb.append(", detailMobileHtml=").append(detailMobileHtml); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProduct.java
1
请完成以下Java代码
public Builder addTotalNetAmt(BigDecimal amtToAdd, final boolean approved) { if (approved) { this.totalNetAmtApproved = totalNetAmtApproved.add(amtToAdd); } else { this.totalNetAmtNotApproved = totalNetAmtNotApproved.add(amtToAdd); } return this; } public Builder addCurrencySymbol(final String currencySymbol) { if (Check.isEmpty(currencySymbol, true)) { // NOTE: prevent adding null values because ImmutableSet.Builder will fail in this case this.currencySymbols.add("?"); } else { this.currencySymbols.add(currencySymbol); } return this; } public void addCountToRecompute(final int countToRecomputeToAdd) { Check.assume(countToRecomputeToAdd > 0, "countToRecomputeToAdd > 0"); this.countTotalToRecompute += countToRecomputeToAdd; }
public void addInvoiceCandidate(@NonNull final I_C_Invoice_Candidate ic) { final BigDecimal netAmt = ic.getNetAmtToInvoice(); final boolean isApprovedForInvoicing = ic.isApprovalForInvoicing(); addTotalNetAmt(netAmt, isApprovedForInvoicing); final String currencySymbol = getCurrencySymbolOrNull(ic); addCurrencySymbol(currencySymbol); if (ic.isToRecompute()) { addCountToRecompute(1); } } private String getCurrencySymbolOrNull(final I_C_Invoice_Candidate ic) { final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(ic.getC_Currency_ID()); if(currencyId == null) { return null; } final Currency currency = Services.get(ICurrencyDAO.class).getById(currencyId); return currency.getSymbol().getDefaultValue(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\ui\spi\impl\InvoiceCandidatesSelectionSummaryInfo.java
1
请完成以下Java代码
public AlbertaPatient toAlbertaPatient(@NonNull final I_C_BPartner_AlbertaPatient record) { final BPartnerAlbertaPatientId bPartnerAlbertaPatientId = BPartnerAlbertaPatientId.ofRepoId(record.getC_BPartner_AlbertaPatient_ID()); final BPartnerId bPartnerId = BPartnerId.ofRepoId(record.getC_BPartner_ID()); final BPartnerId hospitalId = BPartnerId.ofRepoIdOrNull(record.getC_BPartner_Hospital_ID()); final BPartnerId payerId = BPartnerId.ofRepoIdOrNull(record.getC_BPartner_Payer_ID()); final UserId fieldNurseId = UserId.ofRepoIdOrNull(record.getAD_User_FieldNurse_ID()); final UserId createdById = UserId.ofRepoIdOrNull(record.getAD_User_CreatedBy_ID()); final UserId updatedById = UserId.ofRepoIdOrNull(record.getAD_User_UpdatedBy_ID()); return AlbertaPatient.builder() .bPartnerAlbertaPatientId(bPartnerAlbertaPatientId) .bPartnerId(bPartnerId) .hospitalId(hospitalId) .dischargeDate(TimeUtil.asLocalDate(record.getDischargeDate(), SystemTime.zoneId())) .payerId(payerId) .payerType(PayerType.ofCodeNullable(record.getPayerType())) .numberOfInsured(record.getNumberOfInsured()) .copaymentFrom(TimeUtil.asLocalDate(record.getCopaymentFrom(), SystemTime.zoneId())) .copaymentTo(TimeUtil.asLocalDate(record.getCopaymentTo(), SystemTime.zoneId())) .isTransferPatient(record.isTransferPatient()) .isIVTherapy(record.isIVTherapy()) .fieldNurseId(fieldNurseId) .deactivationReason(DeactivationReasonType.ofCodeNullable(record.getDeactivationReason()))
.deactivationDate(TimeUtil.asLocalDate(record.getDeactivationDate(), SystemTime.zoneId())) .deactivationComment(record.getDeactivationComment()) .classification(record.getClassification()) .careDegree(record.getCareDegree()) .createdAt(TimeUtil.asInstant(record.getCreatedAt())) .createdById(createdById) .updatedAt(TimeUtil.asInstant(record.getUpdatedAt())) .updatedById(updatedById) .build(); } private int repoIdFromNullable(@Nullable final RepoIdAware repoIdAware) { if (repoIdAware == null) { return -1; } return repoIdAware.getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\patient\AlbertaPatientRepository.java
1
请完成以下Java代码
public void addTimeoutTaskListener(String timeoutId, TaskListener taskListener) { timeoutTaskListeners.put(timeoutId, taskListener); } public FormDefinition getFormDefinition() { return formDefinition; } public void setFormDefinition(FormDefinition formDefinition) { this.formDefinition = formDefinition; } public Expression getFormKey() { return formDefinition.getFormKey(); } public void setFormKey(Expression formKey) { this.formDefinition.setFormKey(formKey); } public Expression getCamundaFormDefinitionKey() { return formDefinition.getCamundaFormDefinitionKey();
} public String getCamundaFormDefinitionBinding() { return formDefinition.getCamundaFormDefinitionBinding(); } public Expression getCamundaFormDefinitionVersion() { return formDefinition.getCamundaFormDefinitionVersion(); } // helper methods /////////////////////////////////////////////////////////// protected void populateAllTaskListeners() { // reset allTaskListeners to build it from zero allTaskListeners = new HashMap<>(); // ensure builtinTaskListeners are executed before regular taskListeners CollectionUtil.mergeMapsOfLists(allTaskListeners, builtinTaskListeners); CollectionUtil.mergeMapsOfLists(allTaskListeners, taskListeners); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDefinition.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getSortParamName() { return this.sortParamName; } public void setSortParamName(@Nullable String sortParamName) { this.sortParamName = sortParamName; } public RepositoryDetectionStrategies getDetectionStrategy() { return this.detectionStrategy; } public void setDetectionStrategy(RepositoryDetectionStrategies detectionStrategy) { this.detectionStrategy = detectionStrategy; } public @Nullable MediaType getDefaultMediaType() { return this.defaultMediaType; } public void setDefaultMediaType(@Nullable MediaType defaultMediaType) { this.defaultMediaType = defaultMediaType; } public @Nullable Boolean getReturnBodyOnCreate() { return this.returnBodyOnCreate; } public void setReturnBodyOnCreate(@Nullable Boolean returnBodyOnCreate) { this.returnBodyOnCreate = returnBodyOnCreate; } public @Nullable Boolean getReturnBodyOnUpdate() { return this.returnBodyOnUpdate;
} public void setReturnBodyOnUpdate(@Nullable Boolean returnBodyOnUpdate) { this.returnBodyOnUpdate = returnBodyOnUpdate; } public @Nullable Boolean getEnableEnumTranslation() { return this.enableEnumTranslation; } public void setEnableEnumTranslation(@Nullable Boolean enableEnumTranslation) { this.enableEnumTranslation = enableEnumTranslation; } public void applyTo(RepositoryRestConfiguration rest) { PropertyMapper map = PropertyMapper.get(); map.from(this::getBasePath).to(rest::setBasePath); map.from(this::getDefaultPageSize).to(rest::setDefaultPageSize); map.from(this::getMaxPageSize).to(rest::setMaxPageSize); map.from(this::getPageParamName).to(rest::setPageParamName); map.from(this::getLimitParamName).to(rest::setLimitParamName); map.from(this::getSortParamName).to(rest::setSortParamName); map.from(this::getDetectionStrategy).to(rest::setRepositoryDetectionStrategy); map.from(this::getDefaultMediaType).to(rest::setDefaultMediaType); map.from(this::getReturnBodyOnCreate).to(rest::setReturnBodyOnCreate); map.from(this::getReturnBodyOnUpdate).to(rest::setReturnBodyOnUpdate); map.from(this::getEnableEnumTranslation).to(rest::setEnableEnumTranslation); } }
repos\spring-boot-4.0.1\module\spring-boot-data-rest\src\main\java\org\springframework\boot\data\rest\autoconfigure\DataRestProperties.java
2
请完成以下Java代码
protected Polyline createLine(double dx, double dy, Polyline next) { return new Polyline(dx, dy, next); } /** * */ protected static class TreeNode { /** * */ protected Object cell; /** * */ protected double x, y, width, height, offsetX, offsetY; /** * */ protected TreeNode child, next; // parent, sibling /** * */ protected Polygon contour = new Polygon(); /** * */ public TreeNode(Object cell) { this.cell = cell; } } /** * */ protected static class Polygon { /** *
*/ protected Polyline lowerHead, lowerTail, upperHead, upperTail; } /** * */ protected static class Polyline { /** * */ protected double dx, dy; /** * */ protected Polyline next; /** * */ protected Polyline(double dx, double dy, Polyline next) { this.dx = dx; this.dy = dy; this.next = next; } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BPMNLayout.java
1
请完成以下Java代码
public Money calculateTotalNetAmtFromLines() { final List<IInvoiceCandAggregate> lines = getLines(); Check.assume(lines != null && !lines.isEmpty(), "Invoice {} was not aggregated yet", this); Money totalNetAmt = Money.zero(currencyId); for (final IInvoiceCandAggregate lineAgg : lines) { for (final IInvoiceLineRW line : lineAgg.getAllLines()) { final Money lineNetAmt = line.getNetLineAmt(); totalNetAmt = totalNetAmt.add(lineNetAmt); } } return totalNetAmt; } public void setPaymentTermId(@Nullable final PaymentTermId paymentTermId) { this.paymentTermId = paymentTermId; } @Override public PaymentTermId getPaymentTermId() { return paymentTermId; } public void setPaymentRule(@Nullable final String paymentRule) { this.paymentRule = paymentRule; } @Override public String getPaymentRule() { return paymentRule; } @Override public String getExternalId() { return externalId; } @Override public int getC_Async_Batch_ID() { return C_Async_Batch_ID;
} public void setC_Async_Batch_ID(final int C_Async_Batch_ID) { this.C_Async_Batch_ID = C_Async_Batch_ID; } public String setExternalId(String externalId) { return this.externalId = externalId; } @Override public int getC_Incoterms_ID() { return C_Incoterms_ID; } public void setC_Incoterms_ID(final int C_Incoterms_ID) { this.C_Incoterms_ID = C_Incoterms_ID; } @Override public String getIncotermLocation() { return incotermLocation; } public void setIncotermLocation(final String incotermLocation) { this.incotermLocation = incotermLocation; } @Override public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;} public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<User> retrieveAllUsers() { return service.findAll(); } //http://localhost:8080/users //EntityModel //WebMvcLinkBuilder @GetMapping("/users/{id}") public EntityModel<User> retrieveUser(@PathVariable int id) { User user = service.findOne(id); if(user==null) throw new UserNotFoundException("id:"+id); EntityModel<User> entityModel = EntityModel.of(user); WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers()); entityModel.add(link.withRel("all-users")); return entityModel; } @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id) { service.deleteById(id); }
@PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { User savedUser = service.save(user); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\UserResource.java
2
请完成以下Java代码
public class SystemOutboundEventProcessor<T> implements OutboundEventProcessor { protected OutboundEventChannelAdapter<T> outboundEventChannelAdapter; protected OutboundEventProcessingPipeline<T> outboundEventProcessingPipeline; public SystemOutboundEventProcessor(OutboundEventChannelAdapter<T> outboundEventChannelAdapter, OutboundEventProcessingPipeline<T> outboundEventProcessingPipeline) { this.outboundEventChannelAdapter = outboundEventChannelAdapter; this.outboundEventProcessingPipeline = outboundEventProcessingPipeline; } @Override public void sendEvent(EventInstance eventInstance, Collection<ChannelModel> channelModels) { T rawEvent = outboundEventProcessingPipeline.run(eventInstance); outboundEventChannelAdapter.sendEvent(new DefaultOutboundEvent<>(rawEvent, eventInstance)); } public OutboundEventChannelAdapter<T> getOutboundEventChannelAdapter() {
return outboundEventChannelAdapter; } public void setOutboundEventChannelAdapter(OutboundEventChannelAdapter<T> outboundEventChannelAdapter) { this.outboundEventChannelAdapter = outboundEventChannelAdapter; } public OutboundEventProcessingPipeline<T> getOutboundEventProcessingPipeline() { return outboundEventProcessingPipeline; } public void setOutboundEventProcessingPipeline(OutboundEventProcessingPipeline<T> outboundEventProcessingPipeline) { this.outboundEventProcessingPipeline = outboundEventProcessingPipeline; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\SystemOutboundEventProcessor.java
1
请完成以下Java代码
public boolean productMatches(@NonNull final ProductAndCategoryAndManufacturerId product) { return productMatches(product.getProductId()) && productCategoryMatches(product.getProductCategoryId()) && productManufacturerMatches(product.getProductManufacturerId()); } private boolean productMatches(final ProductId productId) { if (this.productId == null) { return true; } return Objects.equals(this.productId, productId); } private boolean productCategoryMatches(final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) { return true; } return Objects.equals(this.productCategoryId, productCategoryId); } private boolean productManufacturerMatches(final BPartnerId productManufacturerId) {
if (this.productManufacturerId == null) { return true; } if (productManufacturerId == null) { return false; } return Objects.equals(this.productManufacturerId, productManufacturerId); } public boolean attributeMatches(@NonNull final ImmutableAttributeSet attributes) { final AttributeValueId breakAttributeValueId = this.attributeValueId; if (breakAttributeValueId == null) { return true; } return attributes.hasAttributeValueId(breakAttributeValueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakMatchCriteria.java
1
请在Spring Boot框架中完成以下Java代码
private void recalculatePartitions(List<ServiceInfo> otherServices, ServiceInfo currentService) { log.info("Recalculating partitions for SNMP transports"); List<ServiceInfo> snmpTransports = Stream.concat(otherServices.stream(), Stream.of(currentService)) .filter(service -> service.getTransportsList().contains(snmpTransportService.getName())) .sorted(Comparator.comparing(ServiceInfo::getServiceId)) .collect(Collectors.toList()); log.trace("Found SNMP transports: {}", snmpTransports); int previousCurrentTransportPartitionIndex = currentTransportPartitionIndex; int previousSnmpTransportsCount = snmpTransportsCount; if (!snmpTransports.isEmpty()) { for (int i = 0; i < snmpTransports.size(); i++) { if (snmpTransports.get(i).equals(currentService)) { currentTransportPartitionIndex = i;
break; } } snmpTransportsCount = snmpTransports.size(); } if (snmpTransportsCount != previousSnmpTransportsCount || currentTransportPartitionIndex != previousCurrentTransportPartitionIndex) { log.info("SNMP transports partitions have changed: transports count = {}, current transport partition index = {}", snmpTransportsCount, currentTransportPartitionIndex); eventPublisher.publishEvent(new SnmpTransportListChangedEvent()); } else { log.info("SNMP transports partitions have not changed"); } } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\SnmpTransportBalancingService.java
2
请完成以下Java代码
public class RabbitOperationsOutboundEventChannelAdapter implements OutboundEventChannelAdapter<String> { protected RabbitOperations rabbitOperations; protected String exchange; protected String routingKey; public RabbitOperationsOutboundEventChannelAdapter(RabbitOperations rabbitOperations, String exchange, String routingKey) { this.rabbitOperations = rabbitOperations; this.exchange = exchange; this.routingKey = routingKey; } @Override public void sendEvent(String rawEvent, Map<String, Object> headerMap) { if (exchange != null) { rabbitOperations.convertAndSend(exchange, routingKey, rawEvent, m -> { for (String headerKey : headerMap.keySet()) { m.getMessageProperties().getHeaders().put(headerKey, headerMap.get(headerKey)); } return m; }); } else { rabbitOperations.convertAndSend(routingKey, rawEvent, m -> { for (String headerKey : headerMap.keySet()) { m.getMessageProperties().getHeaders().put(headerKey, headerMap.get(headerKey)); } return m; });
} } public RabbitOperations getRabbitOperations() { return rabbitOperations; } public void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } public String getExchange() { return exchange; } public void setExchange(String exchange) { this.exchange = exchange; } public String getRoutingKey() { return routingKey; } public void setRoutingKey(String routingKey) { this.routingKey = routingKey; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitOperationsOutboundEventChannelAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public IntegrationFlow fileMover() { return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) .filter(onlyJpgs()) .handle(targetDirectory()) .get(); } // @Bean public IntegrationFlow fileMoverWithLambda() { return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) .filter(message -> ((File) message).getName() .endsWith(".jpg")) .handle(targetDirectory()) .get(); } @Bean public PriorityChannel alphabetically() { return new PriorityChannel(1000, (left, right) -> ((File) left.getPayload()).getName() .compareTo(((File) right.getPayload()).getName())); } // @Bean public IntegrationFlow fileMoverWithPriorityChannel() { return IntegrationFlow.from(sourceDirectory()) .filter(onlyJpgs()) .channel("alphabetically") .handle(targetDirectory()) .get(); } @Bean public MessageHandler anotherTargetDirectory() { FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR2)); handler.setExpectReply(false); // end of pipeline, reply not needed return handler; } @Bean public MessageChannel holdingTank() { return MessageChannels.queue().get();
} // @Bean public IntegrationFlow fileReader() { return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) .filter(onlyJpgs()) .channel("holdingTank") .get(); } // @Bean public IntegrationFlow fileWriter() { return IntegrationFlow.from("holdingTank") .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit())))) .handle(targetDirectory()) .get(); } // @Bean public IntegrationFlow anotherFileWriter() { return IntegrationFlow.from("holdingTank") .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit())))) .handle(anotherTargetDirectory()) .get(); } public static void main(final String... args) { final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); System.out.print("Please enter a string and press <enter>: "); while (true) { final String input = scanner.nextLine(); if ("q".equals(input.trim())) { context.close(); scanner.close(); break; } } System.exit(0); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\dsl\JavaDSLFileCopyConfig.java
2
请完成以下Java代码
public class BigIntegerExample { private static final Logger log = LoggerFactory.getLogger(BigIntegerExample.class); public static void main(String[] args) { BigInteger a = new BigInteger("1101001011010101010101010101010101010101010101010101010101010101010", 2); BigInteger b = new BigInteger("-10000", 2); log.info(getBinaryOperations(a, b)); BigInteger c = new BigInteger("11111111111111111111111111111000", 2); log.info("c = " + c.toString(2) + " (" + c + ")"); } public static String getBinaryOperations(BigInteger a, BigInteger b) { return "a = " + a.toString(2) + " (" + a + ")\n" + "b = " + b.toString(2) + " (" + b + ")\n" + "a + b = " + a.add(b).toString(2) + " (" + a.add(b) + ")\n" + "a - b = " + a.subtract(b).toString(2) + " (" + a.subtract(b) + ")\n" + "a * b = " + a.multiply(b).toString(2) + " (" + a.multiply(b) + ")\n" + "a / b = " + a.divide(b).toString(2) + " (" + a.divide(b) + ")";
} public static BigInteger add(BigInteger a, BigInteger b) { return a.add(b); } public static BigInteger subtract(BigInteger a, BigInteger b) { return a.subtract(b); } public static BigInteger multiply(BigInteger a, BigInteger b) { return a.multiply(b); } public static BigInteger divide(BigInteger a, BigInteger b) { return a.divide(b); } }
repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\arbitrarylengthbinaryintegers\BigIntegerExample.java
1
请在Spring Boot框架中完成以下Java代码
public class LockExclusiveJobCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(LockExclusiveJobCmd.class); protected JobServiceConfiguration jobServiceConfiguration; protected Job job; public LockExclusiveJobCmd(Job job, JobServiceConfiguration jobServiceConfiguration) { this.job = job; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public Object execute(CommandContext commandContext) { if (job == null) { throw new FlowableIllegalArgumentException("job is null"); }
if (LOGGER.isDebugEnabled()) { LOGGER.debug("Executing lock exclusive job {} {}", job.getId(), job.getExecutionId()); } if (job.isExclusive()) { if (job.getExecutionId() != null || job.getScopeId() != null) { InternalJobManager internalJobManager = jobServiceConfiguration.getInternalJobManager(); if (internalJobManager != null) { internalJobManager.lockJobScope(job); } } } return null; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\LockExclusiveJobCmd.java
2
请在Spring Boot框架中完成以下Java代码
public class RequestRestController { private static final Logger logger = LogManager.getLogger(RequestRestController.class); @NonNull private final RequestRestService requestRestService; @ApiResponses(value = { @ApiResponse(code = 201, message = "Successfully created or updated request"), @ApiResponse(code = 401, message = "You are not authorized to create or update the resource"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(code = 422, message = "The request entity could not be processed") }) @PostMapping public ResponseEntity<JsonRRequestUpsertResponse> createRequest(@RequestBody @NonNull final JsonRRequestUpsertRequest request) { try { return ResponseEntity.status(HttpStatus.CREATED) .body(requestRestService.upsert(request)); } catch (final Exception ex) { logger.error("Create request failed for {}", request, ex); final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.unprocessableEntity() .body(JsonRRequestUpsertResponse.builder() .error(JsonErrors.ofThrowable(ex, adLanguage)) .build()); } } @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully created or updated request"), @ApiResponse(code = 400, message = "The provided requestId is not a number"), @ApiResponse(code = 401, message = "You are not authorized to get the resource"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(code = 404, message = "The request entity could not be found") }) @GetMapping("/{requestId}") public ResponseEntity getById(@PathVariable(name = "requestId") @NonNull final String requestIdStr) {
try { final RequestId requestId = RequestId.ofRepoId(Integer.parseInt(requestIdStr)); final JsonRRequest response = requestRestService.getByIdOrNull(requestId); return response == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(response); } catch (final NumberFormatException ex) { logger.error("Invalid requestId: {}", requestIdStr); return ResponseEntity.badRequest().build(); } catch (final Exception ex) { logger.error("Get request failed for {}", requestIdStr, ex); final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.unprocessableEntity() .body(JsonErrors.ofThrowable(ex, adLanguage)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\request\RequestRestController.java
2
请完成以下Java代码
public void setItemToSelect(final E itemToSelect) { this.itemToSelect = itemToSelect; this.doSelectItem = true; } public boolean isDoSelectItem() { return doSelectItem; } public E getItemToSelect() { return itemToSelect; } public void setTextToSet(String textToSet) { this.textToSet = textToSet; this.doSetText = true; } public boolean isDoSetText() { return doSetText;
} public String getTextToSet() { return textToSet; } public void setHighlightTextStartPosition(int highlightTextStartPosition) { this.highlightTextStartPosition = highlightTextStartPosition; this.doHighlightText = true; } public boolean isDoHighlightText() { return doHighlightText; } public int getHighlightTextStartPosition() { return highlightTextStartPosition; } }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\ComboBoxAutoCompletion.java
1
请完成以下Java代码
public class BatchListenerFailedException extends KafkaException { private static final long serialVersionUID = 1L; private final int index; private transient @Nullable ConsumerRecord<?, ?> record; /** * Construct an instance with the provided properties. * @param message the message. * @param index the index in the batch of the failed record. */ public BatchListenerFailedException(String message, int index) { this(message, null, index); } /** * Construct an instance with the provided properties. * @param message the message. * @param cause the cause. * @param index the index in the batch of the failed record. */ public BatchListenerFailedException(String message, @Nullable Throwable cause, int index) { super(message, cause); this.index = index; this.record = null; } /** * Construct an instance with the provided properties. * @param message the message. * @param record the failed record. */ public BatchListenerFailedException(String message, ConsumerRecord<?, ?> record) { this(message, null, record); } /** * Construct an instance with the provided properties. * @param message the message. * @param cause the cause. * @param record the failed record. */ public BatchListenerFailedException(String message, @Nullable Throwable cause, ConsumerRecord<?, ?> record) { super(message, cause); this.record = record; this.index = -1; }
/** * Return the failed record. * @return the record. */ @Nullable public ConsumerRecord<?, ?> getRecord() { return this.record; } /** * Return the index in the batch of the failed record. * @return the index. */ public int getIndex() { return this.index; } @Override public String getMessage() { return super.getMessage() + " " + (this.record != null ? (this.record.topic() + "-" + this.record.partition() + "@" + this.record.offset()) : ("@-" + this.index)); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\BatchListenerFailedException.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Post> getPosts() { return posts; } public void setPosts(Set<Post> posts) { this.posts = posts; }
public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
repos\tutorials-master\persistence-modules\blaze-persistence\src\main\java\com\baeldung\model\Person.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDate() { return date; } public void setDate(String date) { this.date = date; }
public Date getSubmissionDate() { return submissionDate; } public void setSubmissionDate(Date submissionDate) { this.submissionDate = submissionDate; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\model\Post.java
1
请完成以下Java代码
public class EndpointHandlerMultiMethod extends EndpointHandlerMethod { @Nullable private Method defaultMethod; private List<Method> methods; /** * Construct an instance for the provided bean, defaultMethod and methods. * @param bean the bean. * @param defaultMethod the defaultMethod. * @param methods the methods. */ public EndpointHandlerMultiMethod(Object bean, @Nullable Method defaultMethod, List<Method> methods) { super(bean); this.defaultMethod = defaultMethod; this.methods = methods; } /** * Return the method list. * @return the method list. */ public List<Method> getMethods() { return this.methods; } /** * Set the method list. * @param methods the method list. */ public void setMethods(List<Method> methods) { this.methods = methods; }
/** * Return the default method. * @return the default method. */ public @Nullable Method getDefaultMethod() { return this.defaultMethod; } /** * Set the default method. * @param defaultMethod the default method. */ public void setDefaultMethod(Method defaultMethod) { this.defaultMethod = defaultMethod; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\EndpointHandlerMultiMethod.java
1
请完成以下Java代码
public String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); }
@Override public String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setVendor_ID (final int Vendor_ID) { if (Vendor_ID < 1) set_Value (COLUMNNAME_Vendor_ID, null); else set_Value (COLUMNNAME_Vendor_ID, Vendor_ID); } @Override public int getVendor_ID() { return get_ValueAsInt(COLUMNNAME_Vendor_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public ProductDocument getById(@PathVariable String id){ return esSearchService.getById(id); } /** * 根据获取全部 * @return */ @RequestMapping("get_all") public List<ProductDocument> getAll(){ return esSearchService.getAll(); } /** * 搜索 * @param keyword * @return */ @RequestMapping("query/{keyword}") public List<ProductDocument> query(@PathVariable String keyword){ return esSearchService.query(keyword,ProductDocument.class); } /** * 搜索,命中关键字高亮 * http://localhost:8080/query_hit?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc * @param keyword 关键字 * @param indexName 索引库名称 * @param fields 搜索字段名称,多个以“,”分割 * @return */ @RequestMapping("query_hit") public List<Map<String,Object>> queryHit(@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){ String[] fieldNames = {}; if(fields.contains(",")) fieldNames = fields.split(","); else fieldNames[0] = fields; return esSearchService.queryHit(keyword,indexName,fieldNames); } /** * 搜索,命中关键字高亮 * http://localhost:8080/query_hit_page?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc&pageNo=1&pageSize=1 * @param pageNo 当前页 * @param pageSize 每页显示的数据条数 * @param keyword 关键字
* @param indexName 索引库名称 * @param fields 搜索字段名称,多个以“,”分割 * @return */ @RequestMapping("query_hit_page") public Page<Map<String,Object>> queryHitByPage(@RequestParam int pageNo,@RequestParam int pageSize ,@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){ String[] fieldNames = {}; if(fields.contains(",")) fieldNames = fields.split(","); else fieldNames[0] = fields; return esSearchService.queryHitByPage(pageNo,pageSize,keyword,indexName,fieldNames); } /** * 删除索引库 * @param indexName * @return */ @RequestMapping("delete_index/{indexName}") public String deleteIndex(@PathVariable String indexName){ esSearchService.deleteIndex(indexName); return "success"; } }
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\controller\EsSearchController.java
2
请完成以下Java代码
public void setFailureKeyAttribute(String failureKeyAttribute) { this.failureKeyAttribute = failureKeyAttribute; } @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { // 1、设置验证码是否开启属性,页面可以根据该属性来决定是否显示验证码 request.setAttribute("captchaEbabled", captchaEbabled); HttpServletRequest httpServletRequest = WebUtils.toHttp(request); // 2、判断验证码是否禁用 或不是表单提交(允许访问) if (captchaEbabled == false || !"post".equalsIgnoreCase(httpServletRequest.getMethod())) { return true; } // 3、此时是表单提交,验证验证码是否正确 // 获取页面提交的验证码 String submitCaptcha = httpServletRequest.getParameter(captchaParam); // 获取session中的验证码
String captcha = (String) httpServletRequest.getSession().getAttribute("rcCaptcha"); if (submitCaptcha.equals(captcha)) { return true; } return false; } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { // 如果验证码失败了,存储失败key属性 request.setAttribute(failureKeyAttribute, "验证码错误!"); return true; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\filter\RcCaptchaValidateFilter.java
1
请完成以下Java代码
public void setDatevAcctExport_ID (final int DatevAcctExport_ID) { if (DatevAcctExport_ID < 1) set_ValueNoCheck (COLUMNNAME_DatevAcctExport_ID, null); else set_ValueNoCheck (COLUMNNAME_DatevAcctExport_ID, DatevAcctExport_ID); } @Override public int getDatevAcctExport_ID() { return get_ValueAsInt(COLUMNNAME_DatevAcctExport_ID); } @Override public void setExportBy_ID (final int ExportBy_ID) { if (ExportBy_ID < 1) set_ValueNoCheck (COLUMNNAME_ExportBy_ID, null); else set_ValueNoCheck (COLUMNNAME_ExportBy_ID, ExportBy_ID); } @Override public int getExportBy_ID() { return get_ValueAsInt(COLUMNNAME_ExportBy_ID); } @Override public void setExportDate (final @Nullable java.sql.Timestamp ExportDate) { set_ValueNoCheck (COLUMNNAME_ExportDate, ExportDate); } @Override public java.sql.Timestamp getExportDate() { return get_ValueAsTimestamp(COLUMNNAME_ExportDate); } /** * ExportType AD_Reference_ID=541172 * Reference name: DatevExportType */ public static final int EXPORTTYPE_AD_Reference_ID=541172; /** Payment = Payment */ public static final String EXPORTTYPE_Payment = "Payment"; /** Commission Invoice = CommissionInvoice */ public static final String EXPORTTYPE_CommissionInvoice = "CommissionInvoice"; /** Sales Invoice = SalesInvoice */
public static final String EXPORTTYPE_SalesInvoice = "SalesInvoice"; /** Credit Memo = CreditMemo */ public static final String EXPORTTYPE_CreditMemo = "CreditMemo"; @Override public void setExportType (final java.lang.String ExportType) { set_Value (COLUMNNAME_ExportType, ExportType); } @Override public java.lang.String getExportType() { return get_ValueAsString(COLUMNNAME_ExportType); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExport.java
1
请完成以下Java代码
public ExternalSystemOutboundEndpoint getById(@NonNull final ExternalSystemOutboundEndpointId id) { return endpointsCache.getOrLoad(id, this::retrieveById); } @NonNull private ExternalSystemOutboundEndpoint retrieveById(@NonNull final ExternalSystemOutboundEndpointId id) { final I_ExternalSystem_Outbound_Endpoint endpointRecord = InterfaceWrapperHelper.load(id, I_ExternalSystem_Outbound_Endpoint.class); if (endpointRecord == null) { throw new AdempiereException("No Outbound Endpoint found for " + id); } return fromRecord(endpointRecord); } @NonNull
private static ExternalSystemOutboundEndpoint fromRecord(@NonNull final I_ExternalSystem_Outbound_Endpoint endpointRecord) { return ExternalSystemOutboundEndpoint.builder() .id(ExternalSystemOutboundEndpointId.ofRepoId(endpointRecord.getExternalSystem_Outbound_Endpoint_ID())) .value(endpointRecord.getValue()) .endpointUrl(endpointRecord.getOutboundHttpEP()) .method(endpointRecord.getOutboundHttpMethod()) .authType(OutboundEndpointAuthType.ofCode(endpointRecord.getAuthType())) .clientId(endpointRecord.getClientId()) .clientSecret(endpointRecord.getClientSecret()) .token(endpointRecord.getAuthToken()) .user(endpointRecord.getLoginUsername()) .password(endpointRecord.getPassword()) .sasSignature(endpointRecord.getSasSignature()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\outboundendpoint\ExternalSystemOutboundEndpointRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductController { private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class); private final Map<Long, Product> productMap = new HashMap<>(); @Operation(summary = "Get a product by its id") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Found the product", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Product.class)) }), @ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content), @ApiResponse(responseCode = "404", description = "Product not found", content = @Content) }) @GetMapping(path = "/product/{id}") public Product getProduct(@Parameter(description = "id of product to be searched") @PathVariable("id") long productId){ LOGGER.info("Getting Product Details for Product Id {}", productId); return productMap.get(productId); } @PostConstruct private void setupRepo() { Product product1 = getProduct(100001, "apple"); productMap.put(100001L, product1); Product product2 = getProduct(100002, "pears"); productMap.put(100002L, product2);
Product product3 = getProduct(100003, "banana"); productMap.put(100003L, product3); Product product4 = getProduct(100004, "mango"); productMap.put(100004L, product4); } private static Product getProduct(int id, String name) { Product product = new Product(); product.setId(id); product.setName(name); return product; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-3\spring-backend-service\src\main\java\com\baeldung\productservice\controller\ProductController.java
2
请完成以下Java代码
public Integer getKeepAliveSeconds() { return keepAliveSeconds; } public void setKeepAliveSeconds(Integer keepAliveSeconds) { this.keepAliveSeconds = keepAliveSeconds; } public int getQueueCapacity() { return queueCapacity; } public void setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; } public Integer getLockTimeInMillis() { return lockTimeInMillis; } public void setLockTimeInMillis(Integer lockTimeInMillis) { this.lockTimeInMillis = lockTimeInMillis; } public Integer getMaxJobsPerAcquisition() { return maxJobsPerAcquisition; } public void setMaxJobsPerAcquisition(Integer maxJobsPerAcquisition) { this.maxJobsPerAcquisition = maxJobsPerAcquisition; } public Integer getWaitTimeInMillis() { return waitTimeInMillis; } public void setWaitTimeInMillis(Integer waitTimeInMillis) { this.waitTimeInMillis = waitTimeInMillis; } public Long getMaxWait() { return maxWait; } public void setMaxWait(Long maxWait) { this.maxWait = maxWait; } public Integer getBackoffTimeInMillis() { return backoffTimeInMillis; } public void setBackoffTimeInMillis(Integer backoffTimeInMillis) { this.backoffTimeInMillis = backoffTimeInMillis; } public Long getMaxBackoff() { return maxBackoff;
} public void setMaxBackoff(Long maxBackoff) { this.maxBackoff = maxBackoff; } public Integer getBackoffDecreaseThreshold() { return backoffDecreaseThreshold; } public void setBackoffDecreaseThreshold(Integer backoffDecreaseThreshold) { this.backoffDecreaseThreshold = backoffDecreaseThreshold; } public Float getWaitIncreaseFactor() { return waitIncreaseFactor; } public void setWaitIncreaseFactor(Float waitIncreaseFactor) { this.waitIncreaseFactor = waitIncreaseFactor; } @Override public String toString() { return joinOn(this.getClass()) .add("enabled=" + enabled) .add("deploymentAware=" + deploymentAware) .add("corePoolSize=" + corePoolSize) .add("maxPoolSize=" + maxPoolSize) .add("keepAliveSeconds=" + keepAliveSeconds) .add("queueCapacity=" + queueCapacity) .add("lockTimeInMillis=" + lockTimeInMillis) .add("maxJobsPerAcquisition=" + maxJobsPerAcquisition) .add("waitTimeInMillis=" + waitTimeInMillis) .add("maxWait=" + maxWait) .add("backoffTimeInMillis=" + backoffTimeInMillis) .add("maxBackoff=" + maxBackoff) .add("backoffDecreaseThreshold=" + backoffDecreaseThreshold) .add("waitIncreaseFactor=" + waitIncreaseFactor) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\JobExecutionProperty.java
1
请在Spring Boot框架中完成以下Java代码
public class UserAccessServiceImpl implements UserAccessService { private static final Logger LOG = LoggerFactory.getLogger(UserAccessServiceImpl.class); private final Map<SessionId, UserData> sessions; private final Map<UserId, UserData> users; public UserAccessServiceImpl() { this.sessions = new ConcurrentHashMap<>(); this.users = new HashMap<>(); this.users.put(UserId.from("joe"), new UserData(UserId.from("joe"), Password.from("secret"), "ROLE_USER")); this.users.put(UserId.from("jane"), new UserData(UserId.from("jane"), Password.from("secret"), "ROLE_ADMIN", "ROLE_USER")); this.users.put(UserId.from("alice"), new UserData(UserId.from("alice"), Password.from("secret"), "ROLE_PUBLIC")); } @Override public Optional<UserData> login(SessionId sessionId, LoginRequest loginRequest) { UserData userData = users.get(UserId.from(loginRequest.getUserName())); if (userData != null && userData.verifyPassword(loginRequest.getPassword())) { LOG.info("login OK: {} {}", sessionId, loginRequest.getUserName()); sessions.put(sessionId, userData); return Optional.of(userData); } LOG.info("login Failed: {} {}", sessionId, loginRequest.getUserName());
return Optional.empty(); } @Override public Optional<UserData> isAuthenticated(SessionId sessionId) { return Optional.ofNullable(sessions.get(sessionId)); } @Override public void logout(SessionId sessionId) { LOG.info("logout: {}", sessionId); sessions.remove(sessionId); } }
repos\spring-examples-java-17\spring-security\src\main\java\itx\examples\springboot\security\springsecurity\services\UserAccessServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isMeterNameEventTypeEnabled() { return this.meterNameEventTypeEnabled; } public void setMeterNameEventTypeEnabled(boolean meterNameEventTypeEnabled) { this.meterNameEventTypeEnabled = meterNameEventTypeEnabled; } public String getEventType() { return this.eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public ClientProviderType getClientProviderType() { return this.clientProviderType; } public void setClientProviderType(ClientProviderType clientProviderType) { this.clientProviderType = clientProviderType; } public @Nullable String getApiKey() { return this.apiKey; }
public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; } public @Nullable String getAccountId() { return this.accountId; } public void setAccountId(@Nullable String accountId) { this.accountId = accountId; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicProperties.java
2
请完成以下Java代码
public String get_ValueOldAsString(final String variableName) { throw new UnsupportedOperationException("not implemented"); } }; } public IModelInternalAccessor getModelInternalAccessor() { if (_modelInternalAccessor == null) { _modelInternalAccessor = new POJOModelInternalAccessor(this); } return _modelInternalAccessor; } POJOModelInternalAccessor _modelInternalAccessor = null;
public static IModelInternalAccessor getModelInternalAccessor(final Object model) { final POJOWrapper wrapper = getWrapper(model); if (wrapper == null) { return null; } return wrapper.getModelInternalAccessor(); } public boolean isProcessed() { return hasColumnName("Processed") ? StringUtils.toBoolean(getValue("Processed", Object.class)) : false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public List<User> getByMap(Map<String, Object> map) { return userDao.getByMap(map); } @Override public User getById(Integer id) { return userDao.getById(id); } @Override public User create(User user) { userDao.create(user); return user; } @Override
public User update(User user) { userDao.update(user); return user; } @Override public int delete(Integer id) { return userDao.delete(id); } @Override public User getByUserName(String userName) { return userDao.getByUserName(userName); } }
repos\springBoot-master\springboot-dubbo\abel-user-provider\src\main\java\cn\abel\user\service\impl\UserServiceImpl.java
2
请完成以下Java代码
public static HUType ofCodeOrNull(@Nullable final String code) { if (isEmpty(code, true)) { return null; } return ofCode(code); } public static HUType ofCode(@NonNull final String code) { HUType type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + HUType.class + " found for code: " + code); } return type; }
private static final ImmutableMap<String, HUType> typesByCode = ReferenceListAwareEnums.indexByCode(values()); public boolean isLU() { return this == LoadLogistiqueUnit; } public boolean isTU() { return this == TransportUnit; } public boolean isVHU() { return this == VirtualPI; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\HUType.java
1
请完成以下Java代码
public List<String> getDeploymentResourceNames(String deploymentId) { return commandExecutor.execute(new GetDeploymentResourceNamesCmd(deploymentId)); } @Override public InputStream getResourceAsStream(String deploymentId, String resourceName) { return commandExecutor.execute(new GetDeploymentResourceCmd(deploymentId, resourceName)); } @Override public void setDeploymentCategory(String deploymentId, String category) { commandExecutor.execute(new SetDeploymentCategoryCmd(deploymentId, category)); } @Override public void setDeploymentTenantId(String deploymentId, String newTenantId) { commandExecutor.execute(new SetDeploymentTenantIdCmd(deploymentId, newTenantId)); } @Override public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) { commandExecutor.execute(new SetDeploymentParentDeploymentIdCmd(deploymentId, newParentDeploymentId)); } @Override public DmnDeploymentQuery createDeploymentQuery() { return new DmnDeploymentQueryImpl(commandExecutor); } @Override public NativeDmnDeploymentQuery createNativeDeploymentQuery() { return new NativeDmnDeploymentQueryImpl(commandExecutor); } @Override public DmnDecision getDecision(String decisionId) { return commandExecutor.execute(new GetDeploymentDecisionCmd(decisionId)); }
@Override public DmnDefinition getDmnDefinition(String decisionId) { return commandExecutor.execute(new GetDmnDefinitionCmd(decisionId)); } @Override public InputStream getDmnResource(String decisionId) { return commandExecutor.execute(new GetDeploymentDmnResourceCmd(decisionId)); } @Override public void setDecisionCategory(String decisionId, String category) { commandExecutor.execute(new SetDecisionTableCategoryCmd(decisionId, category)); } @Override public InputStream getDecisionRequirementsDiagram(String decisionId) { return commandExecutor.execute(new GetDeploymentDecisionRequirementsDiagramCmd(decisionId)); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnRepositoryServiceImpl.java
1
请完成以下Java代码
public void setColumnName (java.lang.String ColumnName) { throw new IllegalArgumentException ("ColumnName is virtual column"); } /** Get Spaltenname. @return Name der Spalte in der Datenbank */ @Override public java.lang.String getColumnName () { return (java.lang.String)get_Value(COLUMNNAME_ColumnName); } /** 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); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */
@Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ColumnCallout.java
1
请在Spring Boot框架中完成以下Java代码
class AlreadyShippedHUsInPreviousSystemRepository { private static final Logger logger = LogManager.getLogger(AlreadyShippedHUsInPreviousSystemRepository.class); private final IQueryBL queryBL = Services.get(IQueryBL.class); public Optional<AlreadyShippedHUsInPreviousSystem> getBySerialNo(@Nullable final String serialNo) { final String serialNoNorm = StringUtils.trimBlankToNull(serialNo); if (serialNoNorm == null) { return Optional.empty(); } try { final List<I_ServiceRepair_Old_Shipped_HU> rows = queryBL .createQueryBuilder(I_ServiceRepair_Old_Shipped_HU.class) .addEqualsFilter(I_ServiceRepair_Old_Shipped_HU.COLUMNNAME_SerialNo, serialNoNorm) .addNotNull(I_ServiceRepair_Old_Shipped_HU.COLUMNNAME_M_Product_ID) .addOnlyActiveRecordsFilter() .setLimit(QueryLimit.ofInt(100)) .create() .list(); if (rows.isEmpty()) { return Optional.empty(); } else if (rows.size() == 1) { return Optional.of(fromRecord(rows.get(0)));
} else { logger.debug("More than result found for {}: {} => returning empty", serialNo, rows); return Optional.empty(); } } catch (final Exception ex) { logger.debug("Failed fetching for {}. Returning empty.", serialNo, ex); return Optional.empty(); } } private static AlreadyShippedHUsInPreviousSystem fromRecord(@NonNull final I_ServiceRepair_Old_Shipped_HU record) { return AlreadyShippedHUsInPreviousSystem.builder() .serialNo(record.getSerialNo()) .productId(ProductId.ofRepoId(record.getM_Product_ID())) .customerId(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_Customer_ID())) .warrantyStartDate(TimeUtil.asLocalDate(record.getWarrantyStartDate())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\customerreturns\AlreadyShippedHUsInPreviousSystemRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void setCharset(Charset charset) { this.charset = charset; } /** * Set the name of the charset to use. * @param charset the charset * @deprecated since 4.1.0 for removal in 4.3.0 in favor of * {@link #setCharset(Charset)} */ @Deprecated(since = "4.1.0", forRemoval = true) public void setCharset(String charset) { this.charset = Charset.forName(charset); } /**
* Set the resource loader. * @param resourceLoader the resource loader */ @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public Reader getTemplate(String name) throws Exception { return new InputStreamReader(this.resourceLoader.getResource(this.prefix + name + this.suffix).getInputStream(), this.charset); } }
repos\spring-boot-main\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\autoconfigure\MustacheResourceTemplateLoader.java
2
请完成以下Java代码
public final class OidcClientMetadataClaimNames extends OAuth2ClientMetadataClaimNames { /** * {@code post_logout_redirect_uris} - the post logout redirection {@code URI} values * used by the Client. The {@code post_logout_redirect_uri} parameter is used by the * client when requesting that the End-User's User Agent be redirected to after a * logout has been performed. */ public static final String POST_LOGOUT_REDIRECT_URIS = "post_logout_redirect_uris"; /** * {@code token_endpoint_auth_signing_alg} - the {@link JwsAlgorithm JWS} algorithm * that must be used for signing the {@link Jwt JWT} used to authenticate the Client * at the Token Endpoint for the {@link ClientAuthenticationMethod#PRIVATE_KEY_JWT * private_key_jwt} and {@link ClientAuthenticationMethod#CLIENT_SECRET_JWT * client_secret_jwt} authentication methods */ public static final String TOKEN_ENDPOINT_AUTH_SIGNING_ALG = "token_endpoint_auth_signing_alg"; /** * {@code id_token_signed_response_alg} - the {@link JwsAlgorithm JWS} algorithm
* required for signing the {@link OidcIdToken ID Token} issued to the Client */ public static final String ID_TOKEN_SIGNED_RESPONSE_ALG = "id_token_signed_response_alg"; /** * {@code registration_access_token} - the Registration Access Token that can be used * at the Client Configuration Endpoint */ public static final String REGISTRATION_ACCESS_TOKEN = "registration_access_token"; /** * {@code registration_client_uri} - the {@code URL} of the Client Configuration * Endpoint where the Registration Access Token can be used */ public static final String REGISTRATION_CLIENT_URI = "registration_client_uri"; private OidcClientMetadataClaimNames() { } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcClientMetadataClaimNames.java
1
请完成以下Java代码
public basefont setSize(int size) { addAttribute("size",Integer.toString(size)); return(this); } /** sets the size="" attribute. @param size sets the size="" attribute. */ public basefont setSize(String size) { addAttribute("size",size); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public basefont addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public basefont addElement(String hashcode,String element) {
addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public basefont addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public basefont addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public basefont removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\basefont.java
1
请完成以下Java代码
/* package */ final IncludedDetailInfo includedDetailInfo(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return includedDetailInfos.computeIfAbsent(detailId, IncludedDetailInfo::new); } /* package */final Optional<IncludedDetailInfo> includedDetailInfoIfExists(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return Optional.ofNullable(includedDetailInfos.get(detailId)); } /* package */void collectEvent(final IDocumentFieldChangedEvent event) { final boolean init_isKey = false; final boolean init_publicField = true; final boolean init_advancedField = false; final DocumentFieldWidgetType init_widgetType = event.getWidgetType(); fieldChangesOf(event.getFieldName(), init_isKey, init_publicField, init_advancedField, init_widgetType) .mergeFrom(event); } /* package */ void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning) { fieldChangesOf(documentField).setFieldWarning(fieldWarning); } public static final class IncludedDetailInfo { private final DetailId detailId; private boolean stale = false; private LogicExpressionResult allowNew; private LogicExpressionResult allowDelete; private IncludedDetailInfo(final DetailId detailId) { this.detailId = detailId; } public DetailId getDetailId() { return detailId; } IncludedDetailInfo setStale() { stale = true;
return this; } public boolean isStale() { return stale; } public LogicExpressionResult getAllowNew() { return allowNew; } IncludedDetailInfo setAllowNew(final LogicExpressionResult allowNew) { this.allowNew = allowNew; return this; } public LogicExpressionResult getAllowDelete() { return allowDelete; } IncludedDetailInfo setAllowDelete(final LogicExpressionResult allowDelete) { this.allowDelete = allowDelete; return this; } private void collectFrom(final IncludedDetailInfo from) { if (from.stale) { stale = from.stale; } if (from.allowNew != null) { allowNew = from.allowNew; } if (from.allowDelete != null) { allowDelete = from.allowDelete; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChanges.java
1
请完成以下Java代码
public IValidationContext createValidationContext(final Properties ctx, final String tableName, final GridTab gridTab, final int rowIndex) { final GridRowCtx ctxToUse = new GridRowCtx(ctx, gridTab, rowIndex); final int windowNo = gridTab.getWindowNo(); final int tabNo = gridTab.getTabNo(); return createValidationContext(ctxToUse, windowNo, tabNo, tableName); } @Override public IValidationContext createValidationContext(@NonNull final GridField gridField) { final GridTab gridTab = gridField.getGridTab(); // Check.assumeNotNull(gridTab, "gridTab not null"); if (gridTab == null) { return createValidationContext(gridField, ROWINDEX_None); } // If GridTab is not open we don't have an Row Index anyways // Case: open a window with High Volume. Instead of getting the window opened, // you will get a popup to filter records before window actually opens. // If you try to set on of the filtering fields you will get "===========> GridTab.verifyRow: Table not open". if (!gridTab.isOpen()) { return createValidationContext(gridField, ROWINDEX_None); } final int rowIndex = gridTab.getCurrentRow(); return createValidationContext(gridField, rowIndex); } @Override public IValidationContext createValidationContext(final GridField gridField, final int rowIndex) { final Properties ctx = Env.getCtx(); String tableName = null; final Lookup lookup = gridField.getLookup(); if (lookup != null) { final IValidationContext parentEvalCtx = lookup.getValidationContext(); if (parentEvalCtx != null) { tableName = parentEvalCtx.getTableName(); } }
if (tableName == null) { return IValidationContext.DISABLED; } // // Check if is a Process Parameter/Form field final GridFieldVO gridFieldVO = gridField.getVO(); if (gridFieldVO.isProcessParameter() || gridFieldVO.isFormField()) { return createValidationContext(ctx, gridField.getWindowNo(), Env.TAB_None, tableName); } final GridTab gridTab = gridField.getGridTab(); if (gridTab != null) { return createValidationContext(ctx, tableName, gridTab, rowIndex); } return IValidationContext.NULL; } @Override public IValidationContext createValidationContext(final Evaluatee evaluatee) { return new EvaluateeValidationContext(evaluatee); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\ValidationRuleFactory.java
1
请完成以下Java代码
public void setAD_UI_Column_ID (int AD_UI_Column_ID) { if (AD_UI_Column_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_Column_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_Column_ID, Integer.valueOf(AD_UI_Column_ID)); } /** Get UI Column. @return UI Column */ @Override public int getAD_UI_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Column_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_UI_Section getAD_UI_Section() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_UI_Section_ID, org.compiere.model.I_AD_UI_Section.class); } @Override public void setAD_UI_Section(org.compiere.model.I_AD_UI_Section AD_UI_Section) { set_ValueFromPO(COLUMNNAME_AD_UI_Section_ID, org.compiere.model.I_AD_UI_Section.class, AD_UI_Section); } /** Set UI Section. @param AD_UI_Section_ID UI Section */ @Override public void setAD_UI_Section_ID (int AD_UI_Section_ID) { if (AD_UI_Section_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, Integer.valueOf(AD_UI_Section_ID)); } /** Get UI Section. @return UI Section */ @Override public int getAD_UI_Section_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Section_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Column.java
1
请完成以下Java代码
public void completeBackwardDDOrders(final I_M_Forecast forecast) { // // Retrive backward DD Orders final List<I_DD_Order> ddOrders = ddOrderLowLevelDAO.retrieveBackwardDDOrderLinesQuery(forecast) // // Not already processed lines // NOTE: to avoid recursions, we relly on the fact that current DD Order which is about to be completed, // even if the DocStatus was not already set in database, // it's lines were already flagged as processed .addEqualsFilter(I_DD_OrderLine.COLUMN_Processed, false) // // Collect DD_Orders .andCollect(I_DD_OrderLine.COLUMN_DD_Order_ID) .addEqualsFilter(I_DD_Order.COLUMN_Processed, false) // only not processed DD_Orders // // Retrieve them .create() .list(); completeDDOrdersIfNeeded(ddOrders); } public void save(final I_DD_Order ddOrder) { ddOrderLowLevelDAO.save(ddOrder); } public void save(final I_DD_OrderLine ddOrderline) { ddOrderLowLevelDAO.save(ddOrderline); } public void save(final I_DD_OrderLine_Or_Alternative ddOrderLineOrAlternative) { ddOrderLowLevelDAO.save(ddOrderLineOrAlternative); }
public List<I_DD_OrderLine> retrieveLines(final I_DD_Order order) { return ddOrderLowLevelDAO.retrieveLines(order); } public List<I_DD_OrderLine_Alternative> retrieveAllAlternatives(final I_DD_OrderLine ddOrderLine) { return ddOrderLowLevelDAO.retrieveAllAlternatives(ddOrderLine); } public void updateUomFromProduct(final I_DD_OrderLine ddOrderLine) { final ProductId productId = ProductId.ofRepoIdOrNull(ddOrderLine.getM_Product_ID()); if (productId == null) { // nothing to do return; } final UomId stockingUomId = productBL.getStockUOMId(productId); ddOrderLine.setC_UOM_ID(stockingUomId.getRepoId()); } public void deleteOrders(@NonNull final DeleteOrdersQuery deleteOrdersQuery) { ddOrderLowLevelDAO.deleteOrders(deleteOrdersQuery); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\DDOrderLowLevelService.java
1
请完成以下Java代码
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } public boolean isInitialVariables() { return initialVariables; } public void setInitialVariables(boolean initialVariables) { this.initialVariables = initialVariables; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; }
public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } public boolean isWithoutBusinessKey() { return withoutBusinessKey; } public void setWithoutBusinessKey(boolean withoutBusinessKey) { this.withoutBusinessKey = withoutBusinessKey; } public void applyTo(RestartProcessInstanceBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) { for (ProcessInstanceModificationInstructionDto instruction : instructions) { instruction.applyTo(builder, processEngine, objectMapper); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\RestartProcessInstanceDto.java
1
请完成以下Java代码
public BigDecimal getAssetMarketValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetMarketValueAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Asset value. @param AssetValueAmt Book Value of the asset */ public void setAssetValueAmt (BigDecimal AssetValueAmt) { set_Value (COLUMNNAME_AssetValueAmt, AssetValueAmt); } /** Get Asset value. @return Book Value of the asset */ public BigDecimal getAssetValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetValueAmt); if (bd == null) return Env.ZERO; return bd; }
public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException { return (I_C_InvoiceLine)MTable.get(getCtx(), I_C_InvoiceLine.Table_Name) .getPO(getC_InvoiceLine_ID(), get_TrxName()); } /** Set Invoice Line. @param C_InvoiceLine_ID Invoice Detail Line */ public void setC_InvoiceLine_ID (int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_Value (COLUMNNAME_C_InvoiceLine_ID, null); else set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID)); } /** Get Invoice Line. @return Invoice Detail Line */ public int getC_InvoiceLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_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_A_Asset_Retirement.java
1
请完成以下Java代码
public class X_Carrier_ShipmentOrder_Log extends org.compiere.model.PO implements I_Carrier_ShipmentOrder_Log, org.compiere.model.I_Persistent { private static final long serialVersionUID = 115259953L; /** Standard Constructor */ public X_Carrier_ShipmentOrder_Log (final Properties ctx, final int Carrier_ShipmentOrder_Log_ID, @Nullable final String trxName) { super (ctx, Carrier_ShipmentOrder_Log_ID, trxName); } /** Load Constructor */ public X_Carrier_ShipmentOrder_Log (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setCarrier_ShipmentOrder_ID (final int Carrier_ShipmentOrder_ID) { if (Carrier_ShipmentOrder_ID < 1) set_Value (COLUMNNAME_Carrier_ShipmentOrder_ID, null); else set_Value (COLUMNNAME_Carrier_ShipmentOrder_ID, Carrier_ShipmentOrder_ID); } @Override public int getCarrier_ShipmentOrder_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_ID); } @Override public void setCarrier_ShipmentOrder_Log_ID (final int Carrier_ShipmentOrder_Log_ID) { if (Carrier_ShipmentOrder_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Log_ID, Carrier_ShipmentOrder_Log_ID); } @Override public int getCarrier_ShipmentOrder_Log_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Log_ID); } @Override public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() {
return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setRequestID (final java.lang.String RequestID) { set_Value (COLUMNNAME_RequestID, RequestID); } @Override public java.lang.String getRequestID() { return get_ValueAsString(COLUMNNAME_RequestID); } @Override public void setRequestMessage (final @Nullable java.lang.String RequestMessage) { set_Value (COLUMNNAME_RequestMessage, RequestMessage); } @Override public java.lang.String getRequestMessage() { return get_ValueAsString(COLUMNNAME_RequestMessage); } @Override public void setResponseMessage (final @Nullable java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } @Override public java.lang.String getResponseMessage() { return get_ValueAsString(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Log.java
1
请完成以下Java代码
public Icon getIcon() { final I_AD_Process adProcess = adProcessSupplier.get(); final String iconName; if (adProcess.getAD_Form_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WINDOW); } else if (adProcess.getAD_Workflow_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WORKFLOW); } else if (adProcess.isReport()) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_REPORT); } else { iconName = MTreeNode.getIconName(MTreeNode.TYPE_PROCESS); } return Images.getImageIcon2(iconName); } private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get();
} public boolean isEnabled() { return getPreconditionsResolution().isAccepted(); } public boolean isSilentRejection() { return getPreconditionsResolution().isInternal(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\SwingRelatedProcessDescriptor.java
1
请完成以下Java代码
public org.compiere.model.I_AD_User getTo_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setTo_User(org.compiere.model.I_AD_User To_User) { set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User); } /** Set To User. @param To_User_ID To User */ @Override public void setTo_User_ID (int To_User_ID) { if (To_User_ID < 1) set_Value (COLUMNNAME_To_User_ID, null);
else set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID)); } /** Get To User. @return To User */ @Override public int getTo_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_To_User_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Mail.java
1
请在Spring Boot框架中完成以下Java代码
public static class DingTalkNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.dingtalk") public DingTalkNotifier dingTalkNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) { return new DingTalkNotifier(repository, createNotifierRestTemplate(proxyProperties)); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "spring.boot.admin.notify.rocketchat", name = "url") @AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class }) @Lazy(false) public static class RocketChatNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.rocketchat") public RocketChatNotifier rocketChatNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) { return new RocketChatNotifier(repository, createNotifierRestTemplate(proxyProperties)); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "spring.boot.admin.notify.feishu", name = "webhook-url") @AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class }) @Lazy(false) public static class FeiShuNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.feishu") public FeiShuNotifier feiShuNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) {
return new FeiShuNotifier(repository, createNotifierRestTemplate(proxyProperties)); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "spring.boot.admin.notify.webex", name = "auth-token") @AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class }) @Lazy(false) public static class WebexNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.webex") public WebexNotifier webexNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) { return new WebexNotifier(repository, createNotifierRestTemplate(proxyProperties)); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerNotifierAutoConfiguration.java
2
请完成以下Java代码
public static CookieServerCsrfTokenRepository withHttpOnlyFalse() { CookieServerCsrfTokenRepository result = new CookieServerCsrfTokenRepository(); result.cookieHttpOnly = false; return result; } @Override public Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return Mono.fromCallable(this::createCsrfToken).subscribeOn(Schedulers.boundedElastic()); } @Override public Mono<Void> saveToken(ServerWebExchange exchange, @Nullable CsrfToken token) { return Mono.fromRunnable(() -> { String tokenValue = (token != null) ? token.getToken() : ""; // @formatter:off ResponseCookie.ResponseCookieBuilder cookieBuilder = ResponseCookie .from(this.cookieName, tokenValue) .domain(this.cookieDomain) .httpOnly(this.cookieHttpOnly) .maxAge(!tokenValue.isEmpty() ? this.cookieMaxAge : 0) .path((this.cookiePath != null) ? this.cookiePath : getRequestContext(exchange.getRequest())) .secure((this.secure != null) ? this.secure : (exchange.getRequest().getSslInfo() != null)); this.cookieCustomizer.accept(cookieBuilder); // @formatter:on exchange.getResponse().addCookie(cookieBuilder.build()); }); } @Override public Mono<CsrfToken> loadToken(ServerWebExchange exchange) { return Mono.fromCallable(() -> { HttpCookie csrfCookie = exchange.getRequest().getCookies().getFirst(this.cookieName); if ((csrfCookie == null) || !StringUtils.hasText(csrfCookie.getValue())) { return null; } return createCsrfToken(csrfCookie.getValue()); }); } /** * Sets the cookie name * @param cookieName The cookie name */ public void setCookieName(String cookieName) { Assert.hasLength(cookieName, "cookieName can't be null"); this.cookieName = cookieName; }
/** * Sets the parameter name * @param parameterName The parameter name */ public void setParameterName(String parameterName) { Assert.hasLength(parameterName, "parameterName can't be null"); this.parameterName = parameterName; } /** * Sets the header name * @param headerName The header name */ public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName can't be null"); this.headerName = headerName; } /** * Sets the cookie path * @param cookiePath The cookie path */ public void setCookiePath(String cookiePath) { this.cookiePath = cookiePath; } private CsrfToken createCsrfToken() { return createCsrfToken(createNewToken()); } private CsrfToken createCsrfToken(String tokenValue) { return new DefaultCsrfToken(this.headerName, this.parameterName, tokenValue); } private String createNewToken() { return UUID.randomUUID().toString(); } private String getRequestContext(ServerHttpRequest request) { String contextPath = request.getPath().contextPath().value(); return StringUtils.hasLength(contextPath) ? contextPath : "/"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CookieServerCsrfTokenRepository.java
1
请在Spring Boot框架中完成以下Java代码
public Flux<User> getUserByAge(Integer from, Integer to) { return this.userDao.findByAgeBetween(from, to); } public Flux<User> getUserByName(String name) { return this.userDao.findByNameEquals(name); } public Flux<User> getUserByDescription(String description) { return this.userDao.findByDescriptionIsLike(description); } /** * 分页查询,只返回分页后的数据,count值需要通过 getUserByConditionCount * 方法获取 */ public Flux<User> getUserByCondition(int size, int page, User user) { Query query = getQuery(user); Sort sort = new Sort(Sort.Direction.DESC, "age"); Pageable pageable = PageRequest.of(page, size, sort); return template.find(query.with(pageable), User.class); }
/** * 返回 count,配合 getUserByCondition使用 */ public Mono<Long> getUserByConditionCount(User user) { Query query = getQuery(user); return template.count(query, User.class); } private Query getQuery(User user) { Query query = new Query(); Criteria criteria = new Criteria(); if (!StringUtils.isEmpty(user.getName())) { criteria.and("name").is(user.getName()); } if (!StringUtils.isEmpty(user.getDescription())) { criteria.and("description").regex(user.getDescription()); } query.addCriteria(criteria); return query; } }
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\service\UserService.java
2
请完成以下Java代码
public void setShowHelp (final @Nullable java.lang.String ShowHelp) { set_Value (COLUMNNAME_ShowHelp, ShowHelp); } @Override public java.lang.String getShowHelp() { return get_ValueAsString(COLUMNNAME_ShowHelp); } /** * SpreadsheetFormat AD_Reference_ID=541369 * Reference name: SpreadsheetFormat */ public static final int SPREADSHEETFORMAT_AD_Reference_ID=541369; /** Excel = xls */ public static final String SPREADSHEETFORMAT_Excel = "xls"; /** CSV = csv */ public static final String SPREADSHEETFORMAT_CSV = "csv"; @Override public void setSpreadsheetFormat (final @Nullable java.lang.String SpreadsheetFormat) { set_Value (COLUMNNAME_SpreadsheetFormat, SpreadsheetFormat); } @Override public java.lang.String getSpreadsheetFormat() { return get_ValueAsString(COLUMNNAME_SpreadsheetFormat); } @Override public void setSQLStatement (final @Nullable java.lang.String SQLStatement) { set_Value (COLUMNNAME_SQLStatement, SQLStatement); } @Override public java.lang.String getSQLStatement() { return get_ValueAsString(COLUMNNAME_SQLStatement); } @Override public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } @Override public java.lang.String getTechnicalNote() { return get_ValueAsString(COLUMNNAME_TechnicalNote); } /** * Type AD_Reference_ID=540087 * Reference name: AD_Process Type */ public static final int TYPE_AD_Reference_ID=540087; /** SQL = SQL */ public static final String TYPE_SQL = "SQL"; /** Java = Java */ public static final String TYPE_Java = "Java"; /** Excel = Excel */ public static final String TYPE_Excel = "Excel"; /** JasperReportsSQL = JasperReportsSQL */ public static final String TYPE_JasperReportsSQL = "JasperReportsSQL"; /** JasperReportsJSON = JasperReportsJSON */ public static final String TYPE_JasperReportsJSON = "JasperReportsJSON";
/** PostgREST = PostgREST */ public static final String TYPE_PostgREST = "PostgREST"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWorkflowValue (final @Nullable java.lang.String WorkflowValue) { set_Value (COLUMNNAME_WorkflowValue, WorkflowValue); } @Override public java.lang.String getWorkflowValue() { return get_ValueAsString(COLUMNNAME_WorkflowValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process.java
1
请完成以下Java代码
public static HURow toHURowOrNull(final IViewRow viewRow) { if (viewRow instanceof HUEditorRow) { final HUEditorRow huRow = HUEditorRow.cast(viewRow); return HURow.builder() .huId(huRow.getHuId()) .topLevelHU(huRow.isTopLevel()) .huStatusActive(huRow.isHUStatusActive()) .build(); } else if (viewRow instanceof PPOrderLineRow) { final PPOrderLineRow ppOrderLineRow = PPOrderLineRow.cast(viewRow); // this process does not apply to source HUs if (ppOrderLineRow.isSourceHU()) { return null; } if (!ppOrderLineRow.getType().isHUOrHUStorage()) { return null; } return HURow.builder() .huId(ppOrderLineRow.getHuId()) .topLevelHU(ppOrderLineRow.isTopLevelHU()) .huStatusActive(ppOrderLineRow.isHUStatusActive()) .qty(ppOrderLineRow.getQty()) .build(); } else { //noinspection ThrowableNotThrown new AdempiereException("Row type not supported: " + viewRow).throwIfDeveloperModeOrLogWarningElse(logger); return null; } } public static ImmutableList<HURow> getHURowsFromIncludedRows(final PPOrderLinesView view) { return view.streamByIds(DocumentIdsSelection.ALL) .filter(row -> row.getType().isMainProduct() || row.isReceipt()) .flatMap(row -> row.getIncludedRows().stream()) .map(row -> toHURowOrNull(row)) .filter(Objects::nonNull) .filter(HURow::isTopLevelHU) .filter(HURow::isHuStatusActive)
.filter(row -> isEligibleHU(row)) .collect(ImmutableList.toImmutableList()); } public static void pickAndProcessSingleHU(@NonNull final PickRequest pickRequest, @NonNull final ProcessPickingRequest processRequest) { pickHU(pickRequest); processHUs(processRequest); } public static void pickHU(@NonNull final PickRequest request) { pickingCandidateService.pickHU(request); } public static void processHUs(@NonNull final ProcessPickingRequest request) { pickingCandidateService.processForHUIds(request.getHuIds(), request.getShipmentScheduleId(), OnOverDelivery.ofTakeWholeHUFlag(request.isTakeWholeHU()), request.getPpOrderId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\util\WEBUI_PP_Order_ProcessHelper.java
1
请完成以下Java代码
public Criteria andParamCountNotIn(List<Integer> values) { addCriterion("param_count not in", values, "paramCount"); return (Criteria) this; } public Criteria andParamCountBetween(Integer value1, Integer value2) { addCriterion("param_count between", value1, value2, "paramCount"); return (Criteria) this; } public Criteria andParamCountNotBetween(Integer value1, Integer value2) { addCriterion("param_count not between", value1, value2, "paramCount"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue;
} public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeCategoryExample.java
1
请完成以下Java代码
public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic) { ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially ic.setQtyDeliveredInUOM(ic.getQtyEntered()); ic.setDeliveryDate(ic.getDateOrdered()); } @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic) { final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(ic.getAD_Org_ID())); final I_C_OLCand olc = getOLCand(ic); final IPricingResult pricingResult = Services.get(IOLCandBL.class).computePriceActual( olc, null, PricingSystemId.NULL, TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olc), timeZone)); return PriceAndTax.builder()
.priceUOMId(pricingResult.getPriceUomId()) .priceActual(pricingResult.getPriceStd()) .taxIncluded(pricingResult.isTaxIncluded()) .invoicableQtyBasedOn(pricingResult.getInvoicableQtyBasedOn()) .build(); } @Override public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_OLCand olc = getOLCand(ic); InvoiceCandidateLocationAdapterFactory .billLocationAdapter(ic) .setFrom(olCandEffectiveValuesBL.getBuyerPartnerInfo(olc)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\invoicecandidate\spi\impl\C_OLCand_Handler.java
1
请完成以下Java代码
public void onBeforeComplete(final I_C_RfQ rfq) { for (final IRfQEventListener listener : listeners) { listener.onBeforeComplete(rfq); } } @Override public void onAfterComplete(final I_C_RfQ rfq) { for (final IRfQEventListener listener : listeners) { listener.onAfterComplete(rfq); } } @Override public void onBeforeClose(final I_C_RfQ rfq) { for (final IRfQEventListener listener : listeners) { listener.onBeforeClose(rfq); } } @Override public void onAfterClose(final I_C_RfQ rfq) { for (final IRfQEventListener listener : listeners) { listener.onAfterClose(rfq); } } @Override public void onDraftCreated(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners) { listener.onDraftCreated(rfqResponse); } } @Override public void onBeforeComplete(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners) { listener.onBeforeComplete(rfqResponse); } } @Override public void onAfterComplete(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners) { listener.onAfterComplete(rfqResponse); } } @Override public void onBeforeClose(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners)
{ listener.onBeforeClose(rfqResponse); } } @Override public void onAfterClose(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners) { listener.onAfterClose(rfqResponse); } } @Override public void onBeforeUnClose(final I_C_RfQ rfq) { for (final IRfQEventListener listener : listeners) { listener.onBeforeUnClose(rfq); } } @Override public void onAfterUnClose(final I_C_RfQ rfq) { for (final IRfQEventListener listener : listeners) { listener.onAfterUnClose(rfq); } } @Override public void onBeforeUnClose(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners) { listener.onBeforeUnClose(rfqResponse); } } @Override public void onAfterUnClose(final I_C_RfQResponse rfqResponse) { for (final IRfQEventListener listener : listeners) { listener.onAfterUnClose(rfqResponse); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\event\impl\CompositeRfQEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public class Student implements Serializable { /** * */ private static final long serialVersionUID = 1L; public Student() { } public Student(long id, String name, String gender, Integer age) { super(); this.id = id; this.name = name; this.gender = gender; this.age = age; } @Id private long id; @Column(nullable = false) private String name; @Column(nullable = false) private String gender; @Column(nullable = false) private Integer age; 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 getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
repos\tutorials-master\spring-web-modules\spring-rest-angular\src\main\java\com\baeldung\web\entity\Student.java
2
请完成以下Java代码
public void addBundleRegisterHandler(BiConsumer<String, SslBundle> registerHandler) { this.registerHandlers.add(registerHandler); } @Override public List<String> getBundleNames() { List<String> names = new ArrayList<>(this.registeredBundles.keySet()); Collections.sort(names); return Collections.unmodifiableList(names); } private RegisteredSslBundle getRegistered(String name) throws NoSuchSslBundleException { Assert.notNull(name, "'name' must not be null"); RegisteredSslBundle registered = this.registeredBundles.get(name); if (registered == null) { throw new NoSuchSslBundleException(name, "SSL bundle name '%s' cannot be found".formatted(name)); } return registered; } private static class RegisteredSslBundle { private final String name; private final List<Consumer<SslBundle>> updateHandlers = new CopyOnWriteArrayList<>(); private volatile SslBundle bundle; RegisteredSslBundle(String name, SslBundle bundle) { this.name = name; this.bundle = bundle; } void update(SslBundle updatedBundle) { Assert.notNull(updatedBundle, "'updatedBundle' must not be null"); this.bundle = updatedBundle; if (this.updateHandlers.isEmpty()) { logger.warn(LogMessage.format( "SSL bundle '%s' has been updated but may be in use by a technology that doesn't support SSL reloading",
this.name)); } this.updateHandlers.forEach((handler) -> handler.accept(updatedBundle)); } SslBundle getBundle() { return this.bundle; } void addUpdateHandler(Consumer<SslBundle> updateHandler) { Assert.notNull(updateHandler, "'updateHandler' must not be null"); this.updateHandlers.add(updateHandler); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\DefaultSslBundleRegistry.java
1