instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class BatchingRabbitTemplate extends RabbitTemplate { private final Lock lock = new ReentrantLock(); private final BatchingStrategy batchingStrategy; private final TaskScheduler scheduler; private volatile @Nullable ScheduledFuture<?> scheduledTask; /** * Create an instance with the supplied parameters. * @param batchingStrategy the batching strategy. * @param scheduler the scheduler. */ public BatchingRabbitTemplate(BatchingStrategy batchingStrategy, TaskScheduler scheduler) { this.batchingStrategy = batchingStrategy; this.scheduler = scheduler; } /** * Create an instance with the supplied parameters. * @param connectionFactory the connection factory. * @param batchingStrategy the batching strategy. * @param scheduler the scheduler. * @since 2.2 */ public BatchingRabbitTemplate(ConnectionFactory connectionFactory, BatchingStrategy batchingStrategy, TaskScheduler scheduler) { super(connectionFactory); this.batchingStrategy = batchingStrategy; this.scheduler = scheduler; } @Override public void send(@Nullable String exchange, @Nullable String routingKey, Message message, @Nullable CorrelationData correlationData) throws AmqpException { this.lock.lock(); try { if (correlationData != null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Cannot use batching with correlation data"); } super.send(exchange, routingKey, message, correlationData); } else { if (this.scheduledTask != null) { this.scheduledTask.cancel(false); }
MessageBatch batch = this.batchingStrategy.addToBatch(exchange, routingKey, message); if (batch != null) { super.send(batch.exchange(), batch.routingKey(), batch.message(), null); } Date next = this.batchingStrategy.nextRelease(); if (next != null) { this.scheduledTask = this.scheduler.schedule(this::releaseBatches, next.toInstant()); } } } finally { this.lock.unlock(); } } /** * Flush any partial in-progress batches. */ public void flush() { releaseBatches(); } private void releaseBatches() { this.lock.lock(); try { for (MessageBatch batch : this.batchingStrategy.releaseBatches()) { super.send(batch.exchange(), batch.routingKey(), batch.message(), null); } } finally { this.lock.unlock(); } } @Override public void doStart() { } @Override public void doStop() { flush(); } @Override public boolean isRunning() { return true; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BatchingRabbitTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public EventRegistryEngine eventRegistryEngine(@SuppressWarnings("unused") ProcessEngine processEngine) { // The process engine needs to be injected, as otherwise it won't be initialized, which means that the EventRegistryEngine is not initialized yet if (!EventRegistryEngines.isInitialized()) { throw new IllegalStateException("Event registry has not been initialized"); } return EventRegistryEngines.getDefaultEventRegistryEngine(); } } /** * If an app engine is present that means that the EventRegistryEngine was created as part of the app engine. * Therefore extract it from the EventRegistryEngines. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(type = { "org.flowable.eventregistry.impl.EventRegistryEngine" }) @ConditionalOnBean(type = { "org.flowable.app.engine.AppEngine" }) static class AlreadyInitializedAppEngineConfiguration { @Bean public EventRegistryEngine eventRegistryEngine(@SuppressWarnings("unused") AppEngine appEngine) { // The app engine needs to be injected, as otherwise it won't be initialized, which means that the EventRegistryEngine is not initialized yet if (!EventRegistryEngines.isInitialized()) { throw new IllegalStateException("Event registry has not been initialized"); } return EventRegistryEngines.getDefaultEventRegistryEngine(); } } /** * If there is no process engine configuration, then trigger a creation of the event registry. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(type = { "org.flowable.eventregistry.impl.EventRegistryEngine",
"org.flowable.engine.ProcessEngine", "org.flowable.app.engine.AppEngine" }) static class StandaloneEventRegistryConfiguration extends BaseEngineConfigurationWithConfigurers<SpringEventRegistryEngineConfiguration> { @Bean public EventRegistryFactoryBean formEngine(SpringEventRegistryEngineConfiguration eventEngineConfiguration) { EventRegistryFactoryBean factory = new EventRegistryFactoryBean(); factory.setEventEngineConfiguration(eventEngineConfiguration); invokeConfigurers(eventEngineConfiguration); return factory; } } @Bean public EventRepositoryService eventRepositoryService(EventRegistryEngine eventRegistryEngine) { return eventRegistryEngine.getEventRepositoryService(); } @Bean public EventManagementService eventManagementService(EventRegistryEngine eventRegistryEngine) { return eventRegistryEngine.getEventManagementService(); } @Bean public EventRegistry eventRegistry(EventRegistryEngine eventRegistryEngine) { return eventRegistryEngine.getEventRegistry(); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\EventRegistryServicesAutoConfiguration.java
2
请完成以下Java代码
public void setDate1 (java.sql.Timestamp Date1) { set_Value (COLUMNNAME_Date1, Date1); } /** Get Datum. @return Date when business is not conducted */ @Override public java.sql.Timestamp getDate1 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_Date1); } /** Set Enddatum. @param EndDate Last effective date (inclusive) */ @Override public void setEndDate (java.sql.Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get Enddatum. @return Last effective date (inclusive) */ @Override public java.sql.Timestamp getEndDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_EndDate); } /** * Frequency AD_Reference_ID=540870 * Reference name: C_NonBusinessDay_Frequency */ public static final int FREQUENCY_AD_Reference_ID=540870; /** Weekly = W */ public static final String FREQUENCY_Weekly = "W"; /** Yearly = Y */ public static final String FREQUENCY_Yearly = "Y"; /** Set Häufigkeit. @param Frequency Häufigkeit von Ereignissen */ @Override public void setFrequency (java.lang.String Frequency) { set_Value (COLUMNNAME_Frequency, Frequency); } /** Get Häufigkeit. @return Häufigkeit von Ereignissen */ @Override public java.lang.String getFrequency () {
return (java.lang.String)get_Value(COLUMNNAME_Frequency); } /** Set Repeat. @param IsRepeat Repeat */ @Override public void setIsRepeat (boolean IsRepeat) { set_Value (COLUMNNAME_IsRepeat, Boolean.valueOf(IsRepeat)); } /** Get Repeat. @return Repeat */ @Override public boolean isRepeat () { Object oo = get_Value(COLUMNNAME_IsRepeat); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_NonBusinessDay.java
1
请完成以下Java代码
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_EVENT_THROW_NONE, ThrowEventJsonConverter.class); convertersToBpmnMap.put(STENCIL_EVENT_THROW_SIGNAL, ThrowEventJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { convertersToJsonMap.put(ThrowEvent.class, ThrowEventJsonConverter.class); } protected String getStencilId(BaseElement baseElement) { ThrowEvent throwEvent = (ThrowEvent) baseElement; List<EventDefinition> eventDefinitions = throwEvent.getEventDefinitions(); if (eventDefinitions.size() != 1) { // return none event as default; return STENCIL_EVENT_THROW_NONE; } EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { return STENCIL_EVENT_THROW_SIGNAL; } else {
return STENCIL_EVENT_THROW_NONE; } } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { ThrowEvent throwEvent = (ThrowEvent) baseElement; addEventProperties(throwEvent, propertiesNode); } protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { ThrowEvent throwEvent = new ThrowEvent(); String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode); if (STENCIL_EVENT_THROW_SIGNAL.equals(stencilId)) { convertJsonToSignalDefinition(elementNode, throwEvent); } return throwEvent; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\ThrowEventJsonConverter.java
1
请完成以下Java代码
public void migrateDependentEntities() { for (MigratingInstance dependentEntity : migratingDependentInstances) { dependentEntity.migrateState(); } } @Override public void setParent(MigratingScopeInstance parentInstance) { if (this.parentInstance != null) { this.parentInstance.removeChild(this); } this.parentInstance = parentInstance; if (parentInstance != null) { parentInstance.addChild(this); } } @Override public void addMigratingDependentInstance(MigratingInstance migratingInstance) { migratingDependentInstances.add(migratingInstance); } @Override public ExecutionEntity resolveRepresentativeExecution() { return eventScopeExecution; } @Override public void removeChild(MigratingScopeInstance migratingScopeInstance) { childInstances.remove(migratingScopeInstance); } @Override public void addChild(MigratingScopeInstance migratingScopeInstance) { if (migratingScopeInstance instanceof MigratingEventScopeInstance) { childInstances.add((MigratingEventScopeInstance) migratingScopeInstance); } else { throw MIGRATION_LOGGER.cannotHandleChild(this, migratingScopeInstance); } } @Override public void addChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) { this.childCompensationSubscriptionInstances.add(migratingEventSubscription); } @Override public void removeChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) { this.childCompensationSubscriptionInstances.remove(migratingEventSubscription); } @Override public boolean migrates() { return targetScope != null;
} @Override public void detachChildren() { Set<MigratingProcessElementInstance> childrenCopy = new HashSet<MigratingProcessElementInstance>(getChildren()); for (MigratingProcessElementInstance child : childrenCopy) { child.detachState(); } } @Override public void remove(boolean skipCustomListeners, boolean skipIoMappings) { // never invokes listeners and io mappings because this does not remove an active // activity instance eventScopeExecution.remove(); migratingEventSubscription.remove(); setParent(null); } @Override public Collection<MigratingProcessElementInstance> getChildren() { Set<MigratingProcessElementInstance> children = new HashSet<MigratingProcessElementInstance>(childInstances); children.addAll(childCompensationSubscriptionInstances); return children; } @Override public Collection<MigratingScopeInstance> getChildScopeInstances() { return new HashSet<MigratingScopeInstance>(childInstances); } @Override public void removeUnmappedDependentInstances() { } public MigratingCompensationEventSubscriptionInstance getEventSubscription() { return migratingEventSubscription; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingEventScopeInstance.java
1
请完成以下Java代码
public class AccountStatusUserDetailsChecker implements UserDetailsChecker, MessageSourceAware { private final Log logger = LogFactory.getLog(getClass()); protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); @Override public void check(UserDetails user) { if (!user.isAccountNonLocked()) { this.logger.debug("Failed to authenticate since user account is locked"); throw new LockedException( this.messages.getMessage("AccountStatusUserDetailsChecker.locked", "User account is locked")); } if (!user.isEnabled()) { this.logger.debug("Failed to authenticate since user account is disabled"); throw new DisabledException( this.messages.getMessage("AccountStatusUserDetailsChecker.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { this.logger.debug("Failed to authenticate since user account is expired"); throw new AccountExpiredException( this.messages.getMessage("AccountStatusUserDetailsChecker.expired", "User account has expired")); } if (!user.isCredentialsNonExpired()) {
this.logger.debug("Failed to authenticate since user account credentials have expired"); throw new CredentialsExpiredException(this.messages .getMessage("AccountStatusUserDetailsChecker.credentialsExpired", "User credentials have expired")); } } /** * @since 5.2 */ @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AccountStatusUserDetailsChecker.java
1
请在Spring Boot框架中完成以下Java代码
static class SpringBoot2AndLaterKotlinProjectGenerationConfiguration { @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) KotlinMavenBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { return new KotlinMavenBuildCustomizer(kotlinProjectSettings); } @Bean MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor( ProjectDescription description) { return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main") .parameters(Parameter.of("args", "Array<String>")) .body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication", description.getApplicationName()))); } } /** * Kotlin source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) {
return (typeDeclaration) -> { KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure") .modifiers(KotlinModifier.OVERRIDE) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("return application.sources($L::class.java)", description.getApplicationName())); typeDeclaration.addFunctionDeclaration(configure); }; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationDefaultContributorsConfiguration.java
2
请完成以下Java代码
public static boolean equals(@Nullable final AccountConceptualName o1, @Nullable final AccountConceptualName o2) {return Objects.equals(o1, o2);} public boolean isAnyOf(@Nullable final AccountConceptualName... names) { if (names == null) { return false; } for (final AccountConceptualName name : names) { if (name != null && equals(this, name)) { return true; }
} return false; } public boolean isProductMandatory() { return isAnyOf(P_Asset_Acct); } public boolean isWarehouseLocatorMandatory() { return isAnyOf(P_Asset_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\AccountConceptualName.java
1
请在Spring Boot框架中完成以下Java代码
public class OmsOrderReturnApplyServiceImpl implements OmsOrderReturnApplyService { @Autowired private OmsOrderReturnApplyDao returnApplyDao; @Autowired private OmsOrderReturnApplyMapper returnApplyMapper; @Override public List<OmsOrderReturnApply> list(OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); return returnApplyDao.getList(queryParam); } @Override public int delete(List<Long> ids) { OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample(); example.createCriteria().andIdIn(ids).andStatusEqualTo(3); return returnApplyMapper.deleteByExample(example); } @Override public int updateStatus(Long id, OmsUpdateStatusParam statusParam) { Integer status = statusParam.getStatus(); OmsOrderReturnApply returnApply = new OmsOrderReturnApply(); if(status.equals(1)){ //确认退货 returnApply.setId(id); returnApply.setStatus(1); returnApply.setReturnAmount(statusParam.getReturnAmount()); returnApply.setCompanyAddressId(statusParam.getCompanyAddressId()); returnApply.setHandleTime(new Date()); returnApply.setHandleMan(statusParam.getHandleMan()); returnApply.setHandleNote(statusParam.getHandleNote()); }else if(status.equals(2)){
//完成退货 returnApply.setId(id); returnApply.setStatus(2); returnApply.setReceiveTime(new Date()); returnApply.setReceiveMan(statusParam.getReceiveMan()); returnApply.setReceiveNote(statusParam.getReceiveNote()); }else if(status.equals(3)){ //拒绝退货 returnApply.setId(id); returnApply.setStatus(3); returnApply.setHandleTime(new Date()); returnApply.setHandleMan(statusParam.getHandleMan()); returnApply.setHandleNote(statusParam.getHandleNote()); }else{ return 0; } return returnApplyMapper.updateByPrimaryKeySelective(returnApply); } @Override public OmsOrderReturnApplyResult getItem(Long id) { return returnApplyDao.getDetail(id); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\OmsOrderReturnApplyServiceImpl.java
2
请完成以下Java代码
protected final String doIt() { this.countOK = 0; this.countError = 0; final Iterator<GenericPO> documents = retrieveDocumentsToProcess(); processDocuments(documents, getDocAction()); return "@Processed@ (OK=#" + countOK + ", Error=#" + countError + ")"; } protected abstract Iterator<GenericPO> retrieveDocumentsToProcess(); protected abstract String getDocAction(); private void processDocuments(final Iterator<GenericPO> documents, final String docAction) { while (documents.hasNext()) { final Object doc = documents.next(); trxManager.runInNewTrx(new TrxRunnable2() { @Override public void run(final String localTrxName) { InterfaceWrapperHelper.refresh(doc, localTrxName); docActionBL.processEx(doc, docAction, null); // expectedDocStatus=null because it is *not* always equal to the docAaction (Prepay-Order)
addLog("Document " + doc + ": Processed"); countOK++; } @Override public boolean doCatch(final Throwable e) { final String msg = "Processing of document " + doc + ": Failed - ProccessMsg: " + documentBL.getDocument(doc).getProcessMsg() + "; ExceptionMsg: " + e.getMessage(); addLog(msg); log.warn(msg, e); countError++; return true; // rollback } @Override public void doFinally() { // nothing } }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\AbstractProcessDocumentsTemplate.java
1
请完成以下Java代码
public void setSerNo (final @Nullable java.lang.String SerNo) { set_Value (COLUMNNAME_SerNo, SerNo); } @Override public java.lang.String getSerNo() { return get_ValueAsString(COLUMNNAME_SerNo); } @Override public void setSubProducer_BPartner_ID (final int SubProducer_BPartner_ID) { if (SubProducer_BPartner_ID < 1) set_Value (COLUMNNAME_SubProducer_BPartner_ID, null); else set_Value (COLUMNNAME_SubProducer_BPartner_ID, SubProducer_BPartner_ID); } @Override public int getSubProducer_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_SubProducer_BPartner_ID); } /** * SubProducerBPartner_Value AD_Reference_ID=138 * Reference name: C_BPartner (Trx) */ public static final int SUBPRODUCERBPARTNER_VALUE_AD_Reference_ID=138; @Override public void setSubProducerBPartner_Value (final @Nullable java.lang.String SubProducerBPartner_Value) { set_Value (COLUMNNAME_SubProducerBPartner_Value, SubProducerBPartner_Value); } @Override public java.lang.String getSubProducerBPartner_Value() { return get_ValueAsString(COLUMNNAME_SubProducerBPartner_Value); } @Override public void setTE (final @Nullable java.lang.String TE) { set_Value (COLUMNNAME_TE, TE); } @Override public java.lang.String getTE() { return get_ValueAsString(COLUMNNAME_TE); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setWarehouseLocatorIdentifier (final @Nullable java.lang.String WarehouseLocatorIdentifier) { set_Value (COLUMNNAME_WarehouseLocatorIdentifier, WarehouseLocatorIdentifier); } @Override
public java.lang.String getWarehouseLocatorIdentifier() { return get_ValueAsString(COLUMNNAME_WarehouseLocatorIdentifier); } @Override public void setWarehouseValue (final @Nullable java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } @Override public void setX (final @Nullable java.lang.String X) { set_Value (COLUMNNAME_X, X); } @Override public java.lang.String getX() { return get_ValueAsString(COLUMNNAME_X); } @Override public void setX1 (final @Nullable java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } @Override public java.lang.String getX1() { return get_ValueAsString(COLUMNNAME_X1); } @Override public void setY (final @Nullable java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); } @Override public java.lang.String getY() { return get_ValueAsString(COLUMNNAME_Y); } @Override public void setZ (final @Nullable java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } @Override public java.lang.String getZ() { return get_ValueAsString(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java
1
请完成以下Java代码
public class MigratingActivityInstanceVisitor extends MigratingProcessElementInstanceVisitor { protected boolean skipCustomListeners; protected boolean skipIoMappings; public MigratingActivityInstanceVisitor(boolean skipCustomListeners, boolean skipIoMappings) { this.skipCustomListeners = skipCustomListeners; this.skipIoMappings = skipIoMappings; } @Override protected boolean canMigrate(MigratingProcessElementInstance instance) { return instance instanceof MigratingActivityInstance || instance instanceof MigratingTransitionInstance; } protected void instantiateScopes( MigratingScopeInstance ancestorScopeInstance, MigratingScopeInstanceBranch executionBranch, List<ScopeImpl> scopesToInstantiate) { if (scopesToInstantiate.isEmpty()) { return; }
// must always be an activity instance MigratingActivityInstance ancestorActivityInstance = (MigratingActivityInstance) ancestorScopeInstance; ExecutionEntity newParentExecution = ancestorActivityInstance.createAttachableExecution(); Map<PvmActivity, PvmExecutionImpl> createdExecutions = newParentExecution.instantiateScopes((List) scopesToInstantiate, skipCustomListeners, skipIoMappings); for (ScopeImpl scope : scopesToInstantiate) { ExecutionEntity createdExecution = (ExecutionEntity) createdExecutions.get(scope); createdExecution.setActivity(null); createdExecution.setActive(false); executionBranch.visited(new MigratingActivityInstance(scope, createdExecution)); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingActivityInstanceVisitor.java
1
请在Spring Boot框架中完成以下Java代码
public SAPGLJournal copy(@NonNull final SAPGLJournalCopyRequest copyRequest) { final SAPGLJournal journalToBeCopied = glJournalRepository.getById(copyRequest.getSourceJournalId()); final SAPGLJournalCreateRequest createRequest = SAPGLJournalCreateRequest.of(journalToBeCopied, copyRequest.getDateDoc(), copyRequest.getNegateAmounts()); return glJournalRepository.create(createRequest, currencyConverter); } public void updateTrxInfo(final I_SAP_GLJournalLine glJournalLine) { final FAOpenItemTrxInfo openItemTrxInfo; final AccountId accountId = AccountId.ofRepoIdOrNull(glJournalLine.getC_ValidCombination_ID()); if (accountId != null) { final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(glJournalLine.getSAP_GLJournal_ID()); final SAPGLJournalLineId lineId; if (glJournalLine.getSAP_GLJournalLine_ID() <= 0) { lineId = glJournalRepository.acquireLineId(glJournalId); glJournalLine.setSAP_GLJournalLine_ID(lineId.getRepoId()); } else { lineId = SAPGLJournalLineId.ofRepoId(glJournalId, glJournalLine.getSAP_GLJournalLine_ID()); } openItemTrxInfo = computeTrxInfo(accountId, lineId).orElse(null); } else { openItemTrxInfo = null; } SAPGLJournalLoaderAndSaver.updateRecordFromOpenItemTrxInfo(glJournalLine, openItemTrxInfo); }
private Optional<FAOpenItemTrxInfo> computeTrxInfo( @NonNull final AccountId accountId, @NonNull final SAPGLJournalLineId sapGLJournalLineId) { return Optional.empty(); } public void fireAfterComplete(final I_SAP_GLJournal record) { final SAPGLJournal glJournal = glJournalRepository.getByRecord(record); faOpenItemsService.fireGLJournalCompleted(glJournal); } public void fireAfterReactivate(final I_SAP_GLJournal record) { final SAPGLJournal glJournal = glJournalRepository.getByRecord(record); faOpenItemsService.fireGLJournalReactivated(glJournal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalService.java
2
请完成以下Java代码
public TreePath[] getCheckingRoots() { return getCheckingModel().getCheckingRoots(); } /** * Clears the checking. */ public void clearChecking() { getCheckingModel().clearChecking(); } /** * Add paths in the checking. */ public void addCheckingPaths(TreePath[] paths) { getCheckingModel().addCheckingPaths(paths); } /** * Add a path in the checking. */ public void addCheckingPath(TreePath path) { getCheckingModel().addCheckingPath(path); } /** * Set path in the checking. */ public void setCheckingPath(TreePath path) { getCheckingModel().setCheckingPath(path); } /** * Set paths that are in the checking. */ public void setCheckingPaths(TreePath[] paths) { getCheckingModel().setCheckingPaths(paths); } /** * @return Returns the paths that are in the greying. */ public TreePath[] getGreyingPaths() { return getCheckingModel().getGreyingPaths(); } /** * Adds a listener for <code>TreeChecking</code> events. * * @param tsl the <code>TreeCheckingListener</code> that will be * notified when a node is checked */ public void addTreeCheckingListener(TreeCheckingListener tsl) { this.checkingModel.addTreeCheckingListener(tsl); } /** * Removes a <code>TreeChecking</code> listener.
* * @param tsl the <code>TreeChckingListener</code> to remove */ public void removeTreeCheckingListener(TreeCheckingListener tsl) { this.checkingModel.removeTreeCheckingListener(tsl); } /** * Expand completely a tree */ public void expandAll() { expandSubTree(getPathForRow(0)); } private void expandSubTree(TreePath path) { expandPath(path); Object node = path.getLastPathComponent(); int childrenNumber = getModel().getChildCount(node); TreePath[] childrenPath = new TreePath[childrenNumber]; for (int childIndex = 0; childIndex < childrenNumber; childIndex++) { childrenPath[childIndex] = path.pathByAddingChild(getModel().getChild(node, childIndex)); expandSubTree(childrenPath[childIndex]); } } /** * @return a string representation of the tree, including the checking, * enabling and greying sets. */ @Override public String toString() { String retVal = super.toString(); TreeCheckingModel tcm = getCheckingModel(); if (tcm != null) { return retVal + "\n" + tcm.toString(); } return retVal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\CheckboxTree.java
1
请完成以下Java代码
public class UmsResource implements Serializable { private Long id; @ApiModelProperty(value = "创建时间") private Date createTime; @ApiModelProperty(value = "资源名称") private String name; @ApiModelProperty(value = "资源URL") private String url; @ApiModelProperty(value = "描述") private String description; @ApiModelProperty(value = "资源分类ID") private Long categoryId; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", createTime=").append(createTime); sb.append(", name=").append(name); sb.append(", url=").append(url); sb.append(", description=").append(description); sb.append(", categoryId=").append(categoryId); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsResource.java
1
请完成以下Java代码
public void setM_IolCandHandler(final de.metas.inoutcandidate.model.I_M_IolCandHandler M_IolCandHandler) { set_ValueFromPO(COLUMNNAME_M_IolCandHandler_ID, de.metas.inoutcandidate.model.I_M_IolCandHandler.class, M_IolCandHandler); } @Override public void setM_IolCandHandler_ID (final int M_IolCandHandler_ID) { if (M_IolCandHandler_ID < 1) set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, null); else set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, M_IolCandHandler_ID); } @Override public int getM_IolCandHandler_ID() { return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_ID); } @Override public void setM_IolCandHandler_Log_ID (final int M_IolCandHandler_Log_ID) { if (M_IolCandHandler_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_Log_ID, M_IolCandHandler_Log_ID); } @Override public int getM_IolCandHandler_Log_ID() { return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_Log_ID);
} @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setStatus (final @Nullable java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_IolCandHandler_Log.java
1
请完成以下Java代码
public int getC_Invoice_Candidate_Assignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Assignment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) { if (C_Invoice_Candidate_Term_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugeordnete Menge wird in Summe einbez.. @param IsAssignedQuantityIncludedInSum Zugeordnete Menge wird in Summe einbez. */ @Override public void setIsAssignedQuantityIncludedInSum (boolean IsAssignedQuantityIncludedInSum) {
set_Value (COLUMNNAME_IsAssignedQuantityIncludedInSum, Boolean.valueOf(IsAssignedQuantityIncludedInSum)); } /** Get Zugeordnete Menge wird in Summe einbez.. @return Zugeordnete Menge wird in Summe einbez. */ @Override public boolean isAssignedQuantityIncludedInSum () { Object oo = get_Value(COLUMNNAME_IsAssignedQuantityIncludedInSum); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment.java
1
请完成以下Spring Boot application配置
server: port: 8088 spring: application: name: manyDatasource datasource: # spring.datasource.test1 # druid: test1: jdbcurl: jdbc:mysql://localhost:3333/demo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 username: root password: 123456 initial-size: 1 min-idle: 1 max-active: 20 test-on-borrow: true driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource minPoolSize: 3 maxPoolSize: 25 maxLifetime: 20000 borrowConnectionTimeout: 30 loginTimeout: 30 maintenanceInterval: 60 maxIdleTime: 60 test2: jdbcurl: jdbc:mysql://localhost:3334/demo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource
minPoolSize: 3 maxPoolSize: 25 maxLifetime: 20000 borrowConnectionTimeout: 30 loginTimeout: 30 maintenanceInterval: 60 maxIdleTime: 60 mybatis: mapper-locations: classpath:mapper/*.xml spring.resources.static-locations: classpath:static/,file:static/ logging: level: czs: debug org.springframework: WARN org.spring.springboot.dao: debug
repos\springboot-demo-master\atomikos\src\main\resources\application.yaml
2
请完成以下Java代码
public class MPrintGraph extends X_AD_PrintGraph { /** * */ private static final long serialVersionUID = 4827755559898685764L; /** * Standard Constructor * @param ctx context * @param AD_PrintGraph_ID graph id * @param trxName trx */ public MPrintGraph (Properties ctx, int AD_PrintGraph_ID, String trxName) {
super (ctx, AD_PrintGraph_ID, trxName); } // MPrintGraph /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MPrintGraph (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MPrintGraph } // MPrintGraph
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintGraph.java
1
请完成以下Java代码
protected void writeTerminateDefinition( Event parentEvent, TerminateEventDefinition terminateDefinition, XMLStreamWriter xtw ) throws Exception { xtw.writeStartElement(ELEMENT_EVENT_TERMINATEDEFINITION); if (terminateDefinition.isTerminateAll()) { writeQualifiedAttribute(ATTRIBUTE_TERMINATE_ALL, "true", xtw); } if (terminateDefinition.isTerminateMultiInstance()) { writeQualifiedAttribute(ATTRIBUTE_TERMINATE_MULTI_INSTANCE, "true", xtw); } boolean didWriteExtensionStartElement = BpmnXMLUtil.writeExtensionElements(terminateDefinition, false, xtw); if (didWriteExtensionStartElement) { xtw.writeEndElement(); } xtw.writeEndElement(); }
protected void writeDefaultAttribute(String attributeName, String value, XMLStreamWriter xtw) throws Exception { BpmnXMLUtil.writeDefaultAttribute(attributeName, value, xtw); } protected void writeQualifiedAttribute(String attributeName, String value, XMLStreamWriter xtw) throws Exception { BpmnXMLUtil.writeQualifiedAttribute(attributeName, value, xtw); } protected void writeIncomingOutgoingFlowElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { if (FlowNode.class.isAssignableFrom(element.getClass())) { BpmnXMLUtil.writeIncomingAndOutgoingFlowElement((FlowNode) element, xtw); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\BaseBpmnXMLConverter.java
1
请完成以下Java代码
public class ProcessEngineContext { /** * Declares to the Process Engine that a new, separate context, * bound to the current thread, needs to be created for all subsequent * Process Engine database operations. The method should always be used * in a try-finally block to ensure that {@link #clear()} is called * under any circumstances. * * Please see the {@link ProcessEngineContext} class documentation for * a more detailed description on the purpose of this method. */ public static void requiresNew() { ProcessEngineContextImpl.set(true); } /** * Declares to the Process Engine that the new Context created * by the {@link #requiresNew()} method can be closed. Please * see the {@link ProcessEngineContext} class documentation for * a more detailed description on the purpose of this method. */ public static void clear() { ProcessEngineContextImpl.clear(); } /** * <p>Takes a callable and executes all engine API invocations * within that callable in a new Process Engine Context. Please * see the {@link ProcessEngineContext} class documentation for * a more detailed description on the purpose of this method.</p> * * An alternative to calling: *
* <code> * try { * requiresNew(); * callable.call(); * } finally { * clear(); * } * </code> * * @param callable the callable to execute * @return what is defined by the callable passed to the method * @throws Exception */ public static <T> T withNewProcessEngineContext(Callable<T> callable) throws Exception { try { requiresNew(); return callable.call(); } finally { clear(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\context\ProcessEngineContext.java
1
请完成以下Java代码
public Address deepCopy(Address value) { if (Objects.isNull(value)) { return null; } Address newEmpAdd = new Address(); newEmpAdd.setAddressLine1(value.getAddressLine1()); newEmpAdd.setAddressLine2(value.getAddressLine2()); newEmpAdd.setCity(value.getCity()); newEmpAdd.setCountry(value.getCountry()); newEmpAdd.setZipCode(value.getZipCode()); return newEmpAdd; } @Override public boolean isMutable() { return true; } @Override public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value); } @Override public Address assemble(Serializable cached, Object owner) { return deepCopy((Address) cached); } @Override public Address replace(Address detached, Address managed, Object owner) { return detached; } @Override public boolean isInstance(Object object) { return CompositeUserType.super.isInstance(object); } @Override public boolean isSameClass(Object object) { return CompositeUserType.super.isSameClass(object); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\AddressType.java
1
请完成以下Java代码
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 boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AcquirableJobEntity other = (AcquirableJobEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }
@Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", duedate=" + duedate + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java
1
请完成以下Java代码
final class WebsocketEventsLog { private static final Logger logger = LogManager.getLogger(WebsocketEventsLog.class); private final AtomicBoolean logEventsEnabled = new AtomicBoolean(false); private final AtomicInteger logEventsMaxSize = new AtomicInteger(500); private final List<WebsocketEventLogRecord> loggedEvents = new LinkedList<>(); public void logEvent(final WebsocketTopicName destination, @Nullable final Object event) { if (!logEventsEnabled.get()) { return; } synchronized (loggedEvents) { logger.info("{}: {}", destination, event); loggedEvents.add(new WebsocketEventLogRecord(destination, event)); final int maxSize = logEventsMaxSize.get(); while (loggedEvents.size() > maxSize) { loggedEvents.remove(0); } } } public void setLogEventsEnabled(final boolean enabled) { final boolean enabledOld = logEventsEnabled.getAndSet(enabled); logger.info("Changed logEventsEnabled from {} to {}", enabledOld, enabled);
} public void setLogEventsMaxSize(final int logEventsMaxSizeNew) { Preconditions.checkArgument(logEventsMaxSizeNew > 0, "logEventsMaxSize > 0"); final int logEventsMaxSizeOld = logEventsMaxSize.getAndSet(logEventsMaxSizeNew); logger.info("Changed logEventsMaxSize from {} to {}", logEventsMaxSizeOld, logEventsMaxSizeNew); } public List<WebsocketEventLogRecord> getLoggedEvents() { synchronized (loggedEvents) { return new ArrayList<>(loggedEvents); } } public List<WebsocketEventLogRecord> getLoggedEvents(final String destinationFilter) { return getLoggedEvents() .stream() .filter(websocketEvent -> websocketEvent.isDestinationMatching(destinationFilter)) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\sender\WebsocketEventsLog.java
1
请在Spring Boot框架中完成以下Java代码
public class EverhourImportProcess extends JavaProcess { @Param(parameterName = "DateFrom") private LocalDate dateFrom; @Param(parameterName = "DateTo") private LocalDate dateTo; private final EverhourImporterService everhourImporterService = SpringContextHolder.instance.getBean(EverhourImporterService.class); private final TimeBookingsImporterService timeBookingsImporterService = SpringContextHolder.instance.getBean(TimeBookingsImporterService.class); private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); @Override protected String doIt() throws Exception { final ImportTimeBookingsRequest timeBookingsRequest = ImportTimeBookingsRequest .builder()
.orgId(Env.getOrgId()) .authToken(sysConfigBL.getValue(ACCESS_TOKEN.getName())) .startDate(dateFrom) .endDate(dateTo) .build(); timeBookingsImporterService.importTimeBookings(everhourImporterService, timeBookingsRequest); return MSG_OK; } protected void overwriteParameters(@NonNull final LocalDate dateFrom, @NonNull final LocalDate dateTo) { this.dateFrom = dateFrom; this.dateTo = dateTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\everhour\EverhourImportProcess.java
2
请完成以下Java代码
public class MRegistrationAttribute extends X_A_RegistrationAttribute { /** * */ private static final long serialVersionUID = 5306354702182270968L; /** * Get All Asset Registration Attributes (not cached). * Refreshes Cache for direct addess * @param ctx context * @return array of Registration Attributes */ public static MRegistrationAttribute[] getAll (Properties ctx) { // Store/Refresh Cache and add to List ArrayList<MRegistrationAttribute> list = new ArrayList<MRegistrationAttribute>(); String sql = "SELECT * FROM A_RegistrationAttribute " + "WHERE AD_Client_ID=? " + "ORDER BY SeqNo"; int AD_Client_ID = Env.getAD_Client_ID(ctx); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, AD_Client_ID); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { MRegistrationAttribute value = new MRegistrationAttribute(ctx, rs, null); Integer key = new Integer(value.getA_RegistrationAttribute_ID()); s_cache.put(key, value); list.add(value); } rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { s_log.error(sql, e); } try { if (pstmt != null) pstmt.close(); pstmt = null; } catch (Exception e) { pstmt = null;
} // MRegistrationAttribute[] retValue = new MRegistrationAttribute[list.size()]; list.toArray(retValue); return retValue; } // getAll /** * Get Registration Attribute (cached) * @param ctx context * @param A_RegistrationAttribute_ID id * @return Registration Attribute */ public static MRegistrationAttribute get (Properties ctx, int A_RegistrationAttribute_ID, String trxName) { Integer key = new Integer(A_RegistrationAttribute_ID); MRegistrationAttribute retValue = (MRegistrationAttribute)s_cache.get(key); if (retValue == null) { retValue = new MRegistrationAttribute (ctx, A_RegistrationAttribute_ID, trxName); s_cache.put(key, retValue); } return retValue; } // getAll /** Static Logger */ private static Logger s_log = LogManager.getLogger(MRegistrationAttribute.class); /** Cache */ private static CCache<Integer,MRegistrationAttribute> s_cache = new CCache<Integer,MRegistrationAttribute>("A_RegistrationAttribute", 20); /************************************************************************** * Standard Constructor * @param ctx context * @param A_RegistrationAttribute_ID id */ public MRegistrationAttribute (Properties ctx, int A_RegistrationAttribute_ID, String trxName) { super(ctx, A_RegistrationAttribute_ID, trxName); } // MRegistrationAttribute /** * Load Constructor * @param ctx context * @param rs result set */ public MRegistrationAttribute (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MRegistrationAttribute } // MRegistrationAttribute
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistrationAttribute.java
1
请完成以下Java代码
public static final class Builder { private OrgId orgId; private String docTypeName; private int C_Payment_ID; private String documentNo; private int C_BPartner_ID; private String BPartnerName; private Date paymentDate; // task 09643 private Date dateAcct; private CurrencyCode currencyISOCode; private BigDecimal payAmt; private BigDecimal payAmtConv; private BigDecimal openAmtConv; private BigDecimal multiplierAP; private Builder() { super(); } public PaymentRow build() { return new PaymentRow(this); } public Builder setOrgId(final OrgId orgId) { this.orgId = orgId; return this; } public Builder setDocTypeName(final String docTypeName) { this.docTypeName = docTypeName; return this; } public Builder setC_Payment_ID(final int C_Payment_ID) { this.C_Payment_ID = C_Payment_ID; return this; } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; } public Builder setBPartnerName(final String bPartnerName) { BPartnerName = bPartnerName; return this; } public Builder setPaymentDate(final Date paymentDate) { this.paymentDate = paymentDate; return this; } /** * task 09643: separate transaction date from the accounting date * * @param dateAcct * @return */ public Builder setDateAcct(final Date dateAcct) { this.dateAcct = dateAcct; return this; } public Builder setCurrencyISOCode(@Nullable final CurrencyCode currencyISOCode) { this.currencyISOCode = currencyISOCode;
return this; } public Builder setPayAmt(final BigDecimal payAmt) { this.payAmt = payAmt; return this; } public Builder setPayAmtConv(final BigDecimal payAmtConv) { this.payAmtConv = payAmtConv; return this; } public Builder setC_BPartner_ID(final int C_BPartner_ID) { this.C_BPartner_ID = C_BPartner_ID; return this; } public Builder setOpenAmtConv(final BigDecimal openAmtConv) { this.openAmtConv = openAmtConv; return this; } public Builder setMultiplierAP(final BigDecimal multiplierAP) { this.multiplierAP = multiplierAP; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentRow.java
1
请在Spring Boot框架中完成以下Java代码
public class ClassificationType { @XmlElementRef(name = "Feature", namespace = "http://erpel.at/schemas/1p0/documents", type = JAXBElement.class, required = false) @XmlMixed protected List<Serializable> content; @XmlAttribute(name = "ClassificationSchema", namespace = "http://erpel.at/schemas/1p0/documents") protected String classificationSchema; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link FeatureType }{@code >} * {@link String } * * */ public List<Serializable> getContent() { if (content == null) { content = new ArrayList<Serializable>(); } return this.content; }
/** * The schema of the classification - e.g. eCl@ss. * * @return * possible object is * {@link String } * */ public String getClassificationSchema() { return classificationSchema; } /** * Sets the value of the classificationSchema property. * * @param value * allowed object is * {@link String } * */ public void setClassificationSchema(String value) { this.classificationSchema = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ClassificationType.java
2
请完成以下Java代码
public String getSql() { buildSqlIfNeeded(); return sql; } @Override public List<Object> getSqlParams(final Properties ctx) { return Collections.emptyList(); } private final void buildSqlIfNeeded() { if (sqlBuilt) { return; } final String columnNameInvoiceCandidateId = I_C_Invoice_Candidate_Recompute.Table_Name + "." + I_C_Invoice_Candidate_Recompute.COLUMNNAME_C_Invoice_Candidate_ID; final String lockedWhereClause; // // Case: no Lock was mentioned // => we consider only those records which were NOT locked if (lock == null) { lockedWhereClause = lockManager.getNotLockedWhereClause(I_C_Invoice_Candidate.Table_Name, columnNameInvoiceCandidateId); } // // Case: Lock is set // => we consider only those records which were locked by given lock else { lockedWhereClause = lockManager.getLockedWhereClause(I_C_Invoice_Candidate.class, columnNameInvoiceCandidateId, lock.getOwner()); } sql = "(" + lockedWhereClause + ")"; sqlBuilt = true; } @Override public boolean accept(final I_C_Invoice_Candidate_Recompute model) { if (model == null) {
return false; } final int invoiceCandidateId = model.getC_Invoice_Candidate_ID(); return acceptInvoiceCandidateId(invoiceCandidateId); } public boolean acceptInvoiceCandidateId(final int invoiceCandidateId) { // // Case: no Lock was mentioned // => we consider only those records which were NOT locked if (lock == null) { return !lockManager.isLocked(I_C_Invoice_Candidate.class, invoiceCandidateId); } // // Case: Lock is set // => we consider only those records which were locked by given lock else { return lockManager.isLocked(I_C_Invoice_Candidate.class, invoiceCandidateId, lock.getOwner()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\LockedByOrNotLockedAtAllFilter.java
1
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Host. @param Host Host */ public void setHost (String Host) { set_Value (COLUMNNAME_Host, Host); } /** Get Host. @return Host */ public String getHost () { return (String)get_Value(COLUMNNAME_Host); } /** 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); } /** Set Password Info. @param PasswordInfo Password Info */ public void setPasswordInfo (String PasswordInfo) { set_Value (COLUMNNAME_PasswordInfo, PasswordInfo); } /** Get Password Info. @return Password Info */ public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) {
set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor.java
1
请完成以下Java代码
public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Order By Value. @param IsOrderByValue Order list using the value column instead of the name column */ @Override public void setIsOrderByValue (boolean IsOrderByValue) { set_Value (COLUMNNAME_IsOrderByValue, Boolean.valueOf(IsOrderByValue)); } /** Get Order By Value. @return Order list using the value column instead of the name column */ @Override public boolean isOrderByValue () { Object oo = get_Value(COLUMNNAME_IsOrderByValue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /**
* ValidationType AD_Reference_ID=2 * Reference name: AD_Reference Validation Types */ public static final int VALIDATIONTYPE_AD_Reference_ID=2; /** ListValidation = L */ public static final String VALIDATIONTYPE_ListValidation = "L"; /** DataType = D */ public static final String VALIDATIONTYPE_DataType = "D"; /** TableValidation = T */ public static final String VALIDATIONTYPE_TableValidation = "T"; /** Set Validation type. @param ValidationType Different method of validating data */ @Override public void setValidationType (java.lang.String ValidationType) { set_Value (COLUMNNAME_ValidationType, ValidationType); } /** Get Validation type. @return Different method of validating data */ @Override public java.lang.String getValidationType () { return (java.lang.String)get_Value(COLUMNNAME_ValidationType); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public void setVFormat (java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public java.lang.String getVFormat () { return (java.lang.String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Reference.java
1
请在Spring Boot框架中完成以下Java代码
public class Product { @Id private Long id; private String name; private String category; private double price; public Product(Long id, String name, String category, double price) { this.id = id; this.name = name; this.category = category; this.price = price; } 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 getCategory() { return category; } public void setCategory(String category) { this.category = category; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
repos\tutorials-master\persistence-modules\hibernate-reactive\src\main\java\com\baeldung\hibernate\entities\Product.java
2
请在Spring Boot框架中完成以下Java代码
public <I extends EntityId> void removeById(TenantId tenantId, I id) { EntityType entityType = id.getEntityType(); EntityDaoService entityService = entityServiceRegistry.getServiceByEntityType(entityType); entityService.deleteEntity(tenantId, id, false); } private <I extends EntityId, E extends ExportableEntity<I>> ExportableEntityDao<I, E> getExportableEntityDao(EntityType entityType) { Dao<E> dao = getDao(entityType); if (dao instanceof ExportableEntityDao) { return (ExportableEntityDao<I, E>) dao; } else { return null; } }
@SuppressWarnings("unchecked") private <E> Dao<E> getDao(EntityType entityType) { return (Dao<E>) daos.get(entityType); } @Autowired private void setDaos(Collection<Dao<?>> daos) { daos.forEach(dao -> { if (dao.getEntityType() != null) { this.daos.put(dao.getEntityType(), dao); } }); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\exporting\DefaultExportableEntitiesService.java
2
请完成以下Java代码
protected class EnumerablePropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction { @Override public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) { if (propertySource instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource; String[] propertyNames = enumerablePropertySource.getPropertyNames(); Arrays.sort(propertyNames); logProperties(Arrays.asList(propertyNames), enumerablePropertySource::getProperty); } return propertySource; } } // The PropertySource may not be enumerable but may use a Map as its source. protected class MapPropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction { @Override @SuppressWarnings("unchecked") public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) { if (!(propertySource instanceof EnumerablePropertySource)) { Object source = propertySource != null
? propertySource.getSource() : null; if (source instanceof Map) { Map<String, Object> map = new TreeMap<>((Map<String, Object>) source); logProperties(map.keySet(), map::get); } } return propertySource; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\logging\EnvironmentLoggingApplicationListener.java
1
请完成以下Java代码
public int getParameterCount() { return 0; } @Override public String getLabel(final int index) { return null; } @Override public Object getParameterComponent(final int index) { return null; } @Override public Object getParameterToComponent(final int index) { return null; } @Override public Object getParameterValue(final int index, final boolean returnValueTo) { return null; } @Override public String[] getWhereClauses(final List<Object> params) { return new String[0]; } @Override public String getText() { return null; } @Override public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders) { for (final Map.Entry<Integer, Integer> e : recordId2asi.entrySet())
{ final Integer recordId = e.getKey(); if (recordId == null || recordId <= 0) { continue; } final Integer asiId = e.getValue(); if (asiId == null || asiId <= 0) { continue; } final OrderLineProductASIGridRowBuilder productQtyBuilder = new OrderLineProductASIGridRowBuilder(); productQtyBuilder.setSource(recordId, asiId); builders.addGridTabRowBuilder(recordId, productQtyBuilder); } } @Override public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel) { final VPAttributeContext attributeContext = new VPAttributeContext(rowIndexModel); editor.putClientProperty(IVPAttributeContext.ATTR_NAME, attributeContext); // nothing } @Override public String getProductCombinations() { // nothing to do return null; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductASIController.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class MultipleIdsRepositoryImpl<T, ID extends Serializable> implements MultipleIdsRepository<T, ID> { @PersistenceContext private EntityManager entityManager; private final Class<T> entityClass; public MultipleIdsRepositoryImpl(Class<T> entityClass) { this.entityClass = entityClass; } @Override public List<T> fetchByMultipleIds(List<ID> ids) { Session session = entityManager.unwrap(Session.class); MultiIdentifierLoadAccess<T> multiLoadAccess = session.byMultipleIds(entityClass); List<T> result = multiLoadAccess.multiLoad(ids); return result; } @Override public List<T> fetchInBatchesByMultipleIds(List<ID> ids, int batchSize) { List<T> result = getMultiLoadAccess().withBatchSize(batchSize).multiLoad(ids); return result; } @Override
public List<T> fetchBySessionCheckMultipleIds(List<ID> ids) { List<T> result = getMultiLoadAccess().enableSessionCheck(true).multiLoad(ids); return result; } @Override public List<T> fetchInBatchesBySessionCheckMultipleIds(List<ID> ids, int batchSize) { List<T> result = getMultiLoadAccess().enableSessionCheck(true) .withBatchSize(batchSize).multiLoad(ids); return result; } private MultiIdentifierLoadAccess<T> getMultiLoadAccess() { Session session = entityManager.unwrap(Session.class); return session.byMultipleIds(entityClass); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLoadMultipleIds\src\main\java\com\bookstore\multipleids\MultipleIdsRepositoryImpl.java
2
请完成以下Java代码
public void dynamicRouteByNacosListener(String dataId, String group) { try { configService.addListener(dataId, group, new Listener() { @Override public void receiveConfigInfo(String configInfo) { log.info("进行网关更新:\n\r{}", configInfo); List<MyRouteDefinition> definitionList = JSON.parseArray(configInfo, MyRouteDefinition.class); for (MyRouteDefinition definition : definitionList) { log.info("update route : {}", definition.toString()); dynamicRouteService.update(definition); } } @Override public Executor getExecutor() { log.info("getExecutor\n\r"); return null; } }); } catch (Exception e) { log.error("从nacos接收动态路由配置出错!!!", e); } } /** * 创建ConfigService * * @return */ private ConfigService createConfigService() { try { Properties properties = new Properties(); properties.setProperty("serverAddr", gatewayRoutersConfig.getServerAddr()); if(StringUtils.isNotBlank(gatewayRoutersConfig.getNamespace())){
properties.setProperty("namespace", gatewayRoutersConfig.getNamespace()); } if(StringUtils.isNotBlank( gatewayRoutersConfig.getUsername())){ properties.setProperty("username", gatewayRoutersConfig.getUsername()); } if(StringUtils.isNotBlank(gatewayRoutersConfig.getPassword())){ properties.setProperty("password", gatewayRoutersConfig.getPassword()); } return configService = NacosFactory.createConfigService(properties); } catch (Exception e) { log.error("创建ConfigService异常", e); return null; } } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\DynamicRouteLoader.java
1
请完成以下Java代码
protected boolean beforeSave (boolean newRecord) { // Create Trees if (newRecord) { MTree_Base tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMContainer, MTree_Base.TREETYPE_CMContainer, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMC_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMContainerStage, MTree_Base.TREETYPE_CMContainerStage, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMS_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMTemplate, MTree_Base.TREETYPE_CMTemplate, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMT_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMMedia, MTree_Base.TREETYPE_CMMedia, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMM_ID(tree.getAD_Tree_ID()); } return true; } // beforeSave /** * After Save. * Insert
* - create tree * @param newRecord insert * @param success save success * @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (!newRecord) { // Clean Web Project Cache } return success; } // afterSave } // MWebProject
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWebProject.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public String getState() { return state; } public Date getCreateTime() { return createTime; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricVariableInstanceDto fromHistoricVariableInstance(HistoricVariableInstance historicVariableInstance) { HistoricVariableInstanceDto dto = new HistoricVariableInstanceDto(); dto.id = historicVariableInstance.getId(); dto.name = historicVariableInstance.getName(); dto.processDefinitionKey = historicVariableInstance.getProcessDefinitionKey(); dto.processDefinitionId = historicVariableInstance.getProcessDefinitionId(); dto.processInstanceId = historicVariableInstance.getProcessInstanceId(); dto.executionId = historicVariableInstance.getExecutionId(); dto.activityInstanceId = historicVariableInstance.getActivityInstanceId(); dto.caseDefinitionKey = historicVariableInstance.getCaseDefinitionKey();
dto.caseDefinitionId = historicVariableInstance.getCaseDefinitionId(); dto.caseInstanceId = historicVariableInstance.getCaseInstanceId(); dto.caseExecutionId = historicVariableInstance.getCaseExecutionId(); dto.taskId = historicVariableInstance.getTaskId(); dto.tenantId = historicVariableInstance.getTenantId(); dto.state = historicVariableInstance.getState(); dto.createTime = historicVariableInstance.getCreateTime(); dto.removalTime = historicVariableInstance.getRemovalTime(); dto.rootProcessInstanceId = historicVariableInstance.getRootProcessInstanceId(); if(historicVariableInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, historicVariableInstance.getTypedValue()); } else { dto.errorMessage = historicVariableInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(historicVariableInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableInstanceDto.java
1
请在Spring Boot框架中完成以下Java代码
private List<EndpointExposureOutcomeContributor> loadExposureOutcomeContributors(@Nullable ClassLoader classLoader, Environment environment) { ArgumentResolver argumentResolver = ArgumentResolver.of(Environment.class, environment); return SpringFactoriesLoader.forDefaultResourceLocation(classLoader) .load(EndpointExposureOutcomeContributor.class, argumentResolver); } /** * Standard {@link EndpointExposureOutcomeContributor}. */ private static class StandardExposureOutcomeContributor implements EndpointExposureOutcomeContributor { private final EndpointExposure exposure; private final String property; private final IncludeExcludeEndpointFilter<?> filter; StandardExposureOutcomeContributor(Environment environment, EndpointExposure exposure) { this.exposure = exposure; String name = exposure.name().toLowerCase(Locale.ROOT).replace('_', '-');
this.property = "management.endpoints." + name + ".exposure"; this.filter = new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, environment, this.property, exposure.getDefaultIncludes()); } @Override public @Nullable ConditionOutcome getExposureOutcome(EndpointId endpointId, Set<EndpointExposure> exposures, ConditionMessage.Builder message) { if (exposures.contains(this.exposure) && this.filter.match(endpointId)) { return ConditionOutcome .match(message.because("marked as exposed by a '" + this.property + "' property")); } return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\condition\OnAvailableEndpointCondition.java
2
请完成以下Java代码
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 Payroll Contract. @param HR_Contract_ID Payroll Contract */ public void setHR_Contract_ID (int HR_Contract_ID) { if (HR_Contract_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Contract_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Contract_ID, Integer.valueOf(HR_Contract_ID)); } /** Get Payroll Contract. @return Payroll Contract */ public int getHR_Contract_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Contract_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()); } /** Set Net Days. @param NetDays Net Days in which payment is due */ public void setNetDays (int NetDays) { set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays)); } /** Get Net Days. @return Net Days in which payment is due
*/ public int getNetDays () { Integer ii = (Integer)get_Value(COLUMNNAME_NetDays); if (ii == null) return 0; return ii.intValue(); } /** 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); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java
1
请完成以下Java代码
public Builder errorCode(String errorCode) { this.errorCode = errorCode; return this; } /** * Sets the error description. * @param errorDescription the error description * @return the {@link Builder} */ public Builder errorDescription(String errorDescription) { this.errorDescription = errorDescription; return this; } /** * Sets the error uri. * @param errorUri the error uri * @return the {@link Builder} */ public Builder errorUri(String errorUri) { this.errorUri = errorUri; return this; } /** * Builds a new {@link OAuth2AuthorizationResponse}. * @return a {@link OAuth2AuthorizationResponse} */ public OAuth2AuthorizationResponse build() { if (StringUtils.hasText(this.code) && StringUtils.hasText(this.errorCode)) { throw new IllegalArgumentException("code and errorCode cannot both be set");
} Assert.hasText(this.redirectUri, "redirectUri cannot be empty"); OAuth2AuthorizationResponse authorizationResponse = new OAuth2AuthorizationResponse(); authorizationResponse.redirectUri = this.redirectUri; authorizationResponse.state = this.state; if (StringUtils.hasText(this.code)) { authorizationResponse.code = this.code; } else { authorizationResponse.error = new OAuth2Error(this.errorCode, this.errorDescription, this.errorUri); } return authorizationResponse; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationResponse.java
1
请完成以下Java代码
public static<T> Result<T> OK(T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setResult(data); return r; } public static<T> Result<T> OK(String msg, T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setMessage(msg); r.setResult(data); return r; } public static<T> Result<T> error(String msg, T data) { Result<T> r = new Result<T>(); r.setSuccess(false); r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500); r.setMessage(msg); r.setResult(data); return r; } public static<T> Result<T> error(String msg) { return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
} public static<T> Result<T> error(int code, String msg) { Result<T> r = new Result<T>(); r.setCode(code); r.setMessage(msg); r.setSuccess(false); return r; } public Result<T> error500(String message) { this.message = message; this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500; this.success = false; return this; } /** * 无权限访问返回结果 */ public static<T> Result<T> noauth(String msg) { return error(CommonConstant.SC_JEECG_NO_AUTHZ, msg); } @JsonIgnore private String onlTable; }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\vo\Result.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(TimerEventDefinition.class, BPMN_ELEMENT_TIMER_EVENT_DEFINITION) .namespaceUri(BPMN20_NS) .extendsType(EventDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<TimerEventDefinition>() { public TimerEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new TimerEventDefinitionImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); timeDateChild = sequenceBuilder.element(TimeDate.class) .build(); timeDurationChild = sequenceBuilder.element(TimeDuration.class) .build(); timeCycleChild = sequenceBuilder.element(TimeCycle.class) .build(); typeBuilder.build(); } public TimerEventDefinitionImpl(ModelTypeInstanceContext context) { super(context); }
public TimeDate getTimeDate() { return timeDateChild.getChild(this); } public void setTimeDate(TimeDate timeDate) { timeDateChild.setChild(this, timeDate); } public TimeDuration getTimeDuration() { return timeDurationChild.getChild(this); } public void setTimeDuration(TimeDuration timeDuration) { timeDurationChild.setChild(this, timeDuration); } public TimeCycle getTimeCycle() { return timeCycleChild.getChild(this); } public void setTimeCycle(TimeCycle timeCycle) { timeCycleChild.setChild(this, timeCycle); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TimerEventDefinitionImpl.java
1
请完成以下Java代码
public String getStartEventType() { return startEventType; } public void setStartEventType(String startEventType) { this.startEventType = startEventType; } public List<String> getCandidateStarterUsers() { return candidateStarterUsers; } public void setCandidateStarterUsers(List<String> candidateStarterUsers) { this.candidateStarterUsers = candidateStarterUsers; } public List<String> getCandidateStarterGroups() { return candidateStarterGroups; } public void setCandidateStarterGroups(List<String> candidateStarterGroups) { this.candidateStarterGroups = candidateStarterGroups; } public boolean isAsync() { return async; } public void setAsync(boolean async) { this.async = async; }
public Map<String, CaseElement> getAllCaseElements() { return allCaseElements; } public void setAllCaseElements(Map<String, CaseElement> allCaseElements) { this.allCaseElements = allCaseElements; } public <T extends PlanItemDefinition> List<T> findPlanItemDefinitionsOfType(Class<T> type) { return planModel.findPlanItemDefinitionsOfType(type, true); } public ReactivateEventListener getReactivateEventListener() { return reactivateEventListener; } public void setReactivateEventListener(ReactivateEventListener reactivateEventListener) { this.reactivateEventListener = reactivateEventListener; } @Override public List<FlowableListener> getLifecycleListeners() { return this.lifecycleListeners; } @Override public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) { this.lifecycleListeners = lifecycleListeners; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Case.java
1
请完成以下Java代码
public String toEventMessage(String message) { String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } return eventMessage; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", type=" + type + ", userId=" + userId + ", time=" + time + ", taskId=" + taskId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", revision= "+ revision + ", removalTime=" + removalTime + ", action=" + action + ", message=" + message + ", fullMessage=" + fullMessage
+ ", tenantId=" + tenantId + "]"; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java
1
请完成以下Java代码
protected Transaction getTransaction() { try { return transactionManager.getTransaction(); } catch (SystemException e) { throw new ActivitiException("SystemException while getting transaction ", e); } } public void addTransactionListener( TransactionState transactionState, final TransactionListener transactionListener ) { Transaction transaction = getTransaction(); CommandContext commandContext = Context.getCommandContext(); try { transaction.registerSynchronization( new TransactionStateSynchronization(transactionState, transactionListener, commandContext) ); } catch (IllegalStateException e) { throw new ActivitiException("IllegalStateException while registering synchronization ", e); } catch (RollbackException e) { throw new ActivitiException("RollbackException while registering synchronization ", e); } catch (SystemException e) { throw new ActivitiException("SystemException while registering synchronization ", e); } } public static class TransactionStateSynchronization implements Synchronization { protected final TransactionListener transactionListener; protected final TransactionState transactionState; private final CommandContext commandContext;
public TransactionStateSynchronization( TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext ) { this.transactionState = transactionState; this.transactionListener = transactionListener; this.commandContext = commandContext; } public void beforeCompletion() { if ( TransactionState.COMMITTING.equals(transactionState) || TransactionState.ROLLINGBACK.equals(transactionState) ) { transactionListener.execute(commandContext); } } public void afterCompletion(int status) { if (Status.STATUS_ROLLEDBACK == status && TransactionState.ROLLED_BACK.equals(transactionState)) { transactionListener.execute(commandContext); } else if (Status.STATUS_COMMITTED == status && TransactionState.COMMITTED.equals(transactionState)) { transactionListener.execute(commandContext); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\jta\JtaTransactionContext.java
1
请完成以下Java代码
public static ExchangeFilterFunction countingFilter(AtomicInteger getCounter) { ExchangeFilterFunction countingFilter = (clientRequest, nextFilter) -> { HttpMethod httpMethod = clientRequest.method(); if (httpMethod == HttpMethod.GET) { getCounter.incrementAndGet(); } return nextFilter.exchange(clientRequest); }; return countingFilter; } public static ExchangeFilterFunction urlModifyingFilter(String version) { ExchangeFilterFunction urlModifyingFilter = (clientRequest, nextFilter) -> { String oldUrl = clientRequest.url() .toString(); URI newUrl = URI.create(oldUrl + "/" + version);
ClientRequest filteredRequest = ClientRequest.from(clientRequest) .url(newUrl) .build(); return nextFilter.exchange(filteredRequest); }; return urlModifyingFilter; } public static ExchangeFilterFunction loggingFilter(PrintStream printStream) { ExchangeFilterFunction loggingFilter = (clientRequest, nextFilter) -> { printStream.print("Sending request " + clientRequest.method() + " " + clientRequest.url()); return nextFilter.exchange(clientRequest); }; return loggingFilter; } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-filters\src\main\java\com\baeldung\reactive\filters\WebClientFilters.java
1
请完成以下Java代码
public void setExternalId(final JsonExternalId externalId) { this.externalId = externalId; this.externalIdSet = true; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setName(final String name) { this.name = name; this.nameSet = true; } public void setBpartnerName(final String bpartnerName) { this.bpartnerName = bpartnerName; this.bpartnerNameSet = true; } public void setAddress1(final String address1) { this.address1 = address1; this.address1Set = true; } public void setAddress2(final String address2) { this.address2 = address2; this.address2Set = true; } public void setAddress3(final String address3) { this.address3 = address3; this.address3Set = true; } public void setAddress4(final String address4) { this.address4 = address4; this.address4Set = true; } public void setPoBox(final String poBox) { this.poBox = poBox; this.poBoxSet = true; } public void setPostal(final String postal) { this.postal = postal; this.postalSet = true; } public void setCity(final String city) { this.city = city; this.citySet = true; } public void setDistrict(final String district) { this.district = district; this.districtSet = true; }
public void setRegion(final String region) { this.region = region; this.regionSet = true; } public void setCountryCode(final String countryCode) { this.countryCode = countryCode; this.countryCodeSet = true; } public void setGln(final String gln) { this.gln = gln; this.glnSet = true; } public void setShipTo(final Boolean shipTo) { this.shipTo = shipTo; this.shipToSet = true; } public void setShipToDefault(final Boolean shipToDefault) { this.shipToDefault = shipToDefault; this.shipToDefaultSet = true; } public void setBillTo(final Boolean billTo) { this.billTo = billTo; this.billToSet = true; } public void setBillToDefault(final Boolean billToDefault) { this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestLocation.java
1
请完成以下Java代码
public static boolean dbTypeIsOracle(DbType dbType) { return dbTypeIf(dbType, DbType.ORACLE, DbType.ORACLE_12C, DbType.DM); } /** * 是否是达梦 */ public static boolean dbTypeIsDm(DbType dbType) { return dbTypeIf(dbType, DbType.DM); } public static boolean dbTypeIsSqlServer(DbType dbType) { return dbTypeIf(dbType, DbType.SQL_SERVER, DbType.SQL_SERVER2005); } public static boolean dbTypeIsPostgre(DbType dbType) { return dbTypeIf(dbType, DbType.POSTGRE_SQL, DbType.KINGBASE_ES, DbType.GAUSS); } /** * 根据枚举类 获取数据库类型的字符串 * @param dbType * @return */ public static String getDbTypeString(DbType dbType){ if(DbType.DB2.equals(dbType)){ return DataBaseConstant.DB_TYPE_DB2; }else if(DbType.HSQL.equals(dbType)){ return DataBaseConstant.DB_TYPE_HSQL; }else if(dbTypeIsOracle(dbType)){ return DataBaseConstant.DB_TYPE_ORACLE; }else if(dbTypeIsSqlServer(dbType)){
return DataBaseConstant.DB_TYPE_SQLSERVER; }else if(dbTypeIsPostgre(dbType)){ return DataBaseConstant.DB_TYPE_POSTGRESQL; } return DataBaseConstant.DB_TYPE_MYSQL; } /** * 根据枚举类 获取数据库方言字符串 * @param dbType * @return */ public static String getDbDialect(DbType dbType){ return dialectMap.get(dbType.getDb()); } /** * 判断数据库类型 */ public static boolean dbTypeIf(DbType dbType, DbType... correctTypes) { for (DbType type : correctTypes) { if (type.equals(dbType)) { return true; } } return false; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\dynamic\db\DbTypeUtils.java
1
请在Spring Boot框架中完成以下Java代码
public Role getRole(Long id) { return roleService.getById(id); } @Override public String getRoleIds(String tenantId, String roleNames) { return roleService.getRoleIds(tenantId, roleNames); } @Override @GetMapping(API_PREFIX + "/getRoleName") public String getRoleName(Long id) { return roleService.getById(id).getRoleName(); } @Override public List<String> getRoleNames(String roleIds) { return roleService.getRoleNames(roleIds); }
@Override @GetMapping(API_PREFIX + "/getRoleAlias") public String getRoleAlias(Long id) { return roleService.getById(id).getRoleAlias(); } @Override @GetMapping(API_PREFIX + "/tenant") public R<Tenant> getTenant(Long id) { return R.data(tenantService.getById(id)); } @Override @GetMapping(API_PREFIX + "/tenant-id") public R<Tenant> getTenant(String tenantId) { return R.data(tenantService.getByTenantId(tenantId)); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\feign\SysClient.java
2
请完成以下Java代码
public Boolean getFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public void setFallbackToDefaultTenant(Boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; } public void setCalledElementType(String calledElementType) { this.calledElementType = calledElementType; } public String getCalledElementType() { return calledElementType; } public String getProcessInstanceIdVariableName() { return processInstanceIdVariableName; } public void setProcessInstanceIdVariableName(String processInstanceIdVariableName) { this.processInstanceIdVariableName = processInstanceIdVariableName; } @Override public CallActivity clone() { CallActivity clone = new CallActivity(); clone.setValues(this); return clone; } public void setValues(CallActivity otherElement) { super.setValues(otherElement); setCalledElement(otherElement.getCalledElement()); setCalledElementType(otherElement.getCalledElementType()); setBusinessKey(otherElement.getBusinessKey()); setInheritBusinessKey(otherElement.isInheritBusinessKey()); setInheritVariables(otherElement.isInheritVariables()); setSameDeployment(otherElement.isSameDeployment());
setUseLocalScopeForOutParameters(otherElement.isUseLocalScopeForOutParameters()); setCompleteAsync(otherElement.isCompleteAsync()); setFallbackToDefaultTenant(otherElement.getFallbackToDefaultTenant()); inParameters = new ArrayList<>(); if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<>(); if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CallActivity.java
1
请完成以下Java代码
private List<AttributesChangedEvent> createMaterialEvent(final HUAttributeChanges changes) { if (changes.isEmpty()) { return ImmutableList.of(); } final HuId huId = changes.getHuId(); final I_M_HU hu = handlingUnitsBL.getById(huId); // // Consider only those HUs which have QtyOnHand if (!huStatusBL.isQtyOnHand(hu.getHUStatus())) { return ImmutableList.of(); } // // Consider only VHUs if (!handlingUnitsBL.isVirtual(hu)) { return ImmutableList.of(); } final EventDescriptor eventDescriptor = EventDescriptor.ofClientAndOrg(hu.getAD_Client_ID(), hu.getAD_Org_ID()); final Instant date = changes.getLastChangeDate(); final WarehouseId warehouseId = warehousesRepo.getWarehouseIdByLocatorRepoId(hu.getM_Locator_ID()); final AttributesKeyWithASI oldStorageAttributes = toAttributesKeyWithASI(changes.getOldAttributesKey()); final AttributesKeyWithASI newStorageAttributes = toAttributesKeyWithASI(changes.getNewAttributesKey()); final List<IHUProductStorage> productStorages = handlingUnitsBL.getStorageFactory() .getStorage(hu) .getProductStorages(); final List<AttributesChangedEvent> events = new ArrayList<>(); for (final IHUProductStorage productStorage : productStorages) { events.add(AttributesChangedEvent.builder() .eventDescriptor(eventDescriptor) .warehouseId(warehouseId) .date(date) .productId(productStorage.getProductId().getRepoId())
.qty(productStorage.getQtyInStockingUOM().toBigDecimal()) .oldStorageAttributes(oldStorageAttributes) .newStorageAttributes(newStorageAttributes) .huId(productStorage.getHuId().getRepoId()) .build()); } return events; } private AttributesKeyWithASI toAttributesKeyWithASI(final AttributesKey attributesKey) { return attributesKeyWithASIsCache.computeIfAbsent(attributesKey, this::createAttributesKeyWithASI); } private AttributesKeyWithASI createAttributesKeyWithASI(final AttributesKey attributesKey) { final AttributeSetInstanceId asiId = AttributesKeys.createAttributeSetInstanceFromAttributesKey(attributesKey); return AttributesKeyWithASI.of(attributesKey, asiId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChangesCollector.java
1
请完成以下Java代码
public String toString() { return value.toString(); } public BigDecimal toBigDecimal() {return value;} @Override @NonNull public BigDecimal getValue() { return value; } @Override public void setValue(@Nullable final BigDecimal value) { this.value = value != null ? value : BigDecimal.ZERO; } @Override public byte byteValue() { return value.byteValue(); } @Override public double doubleValue() { return value.doubleValue(); } @Override public float floatValue() { return value.floatValue(); } @Override public int intValue() { return value.intValue(); } @Override public long longValue() { return value.longValue(); } @Override public short shortValue() { return value.shortValue(); } public void add(final BigDecimal augend) { value = value.add(augend); } public void subtract(final BigDecimal subtrahend) { value = value.subtract(subtrahend); } public void multiply(final BigDecimal multiplicand) { value = value.multiply(multiplicand); } public void divide(final BigDecimal divisor, final int scale, final RoundingMode roundingMode) {
value = value.divide(divisor, scale, roundingMode); } public boolean comparesEqualTo(final BigDecimal val) { return value.compareTo(val) == 0; } public int signum() { return value.signum(); } public MutableBigDecimal min(final MutableBigDecimal value) { if (this.value.compareTo(value.getValue()) <= 0) { return this; } else { return value; } } public MutableBigDecimal max(final MutableBigDecimal value) { if (this.value.compareTo(value.getValue()) >= 0) { return this; } else { return value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\MutableBigDecimal.java
1
请在Spring Boot框架中完成以下Java代码
public class WebConfiguration implements WebMvcConfigurer { /** * Uses session storage to remember the user’s language setting across requests. * Defaults to English if nothing is specified. * @return session-based {@link LocaleResolver} */ @Bean public LocaleResolver localeResolver() { SessionLocaleResolver resolver = new SessionLocaleResolver(); resolver.setDefaultLocale(Locale.ENGLISH); return resolver; } /** * Allows the app to switch languages using a URL parameter like * <code>?lang=es</code>. * @return a {@link LocaleChangeInterceptor} that handles the change */ @Bean public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); interceptor.setParamName("lang"); return interceptor; } /** * Registers the locale change interceptor so it can run on each request. * @param registry where interceptors are added */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\system\WebConfiguration.java
2
请完成以下Java代码
protected Capacity retrieveTotalCapacity() { checkStaled(); // // Get shipment schedule's target quantity (i.e. how much we need to deliver in total) // * in case we have QtyToDeliver_Override we consider this right away // * else we consider the QtyOrdered final BigDecimal qtyTarget; if (!InterfaceWrapperHelper.isNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override)) { qtyTarget = shipmentSchedule.getQtyToDeliver_Override(); } else { // task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule final BigDecimal qtyOrdered = Services.get(IShipmentScheduleEffectiveBL.class).computeQtyOrdered(shipmentSchedule); qtyTarget = qtyOrdered; } // // Create the total capacity based on qtyTarget final ProductId productId = ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()); final I_C_UOM uom = shipmentScheduleBL.getUomOfProduct(shipmentSchedule); return Capacity.createCapacity( qtyTarget, // qty productId, // product uom, // uom false // allowNegativeCapacity ); } @Override protected void beforeMarkingStalled()
{ staled = true; } private final void checkStaled() { if (!staled) { return; } InterfaceWrapperHelper.refresh(shipmentSchedule); staled = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\ShipmentScheduleQtyPickedProductStorage.java
1
请完成以下Java代码
public boolean removeAll(Collection<?> c) { if (referenceSourceCollection.isImmutable()) { throw new UnsupportedModelOperationException("removeAll()", "collection is immutable"); } else { boolean result = false; for (Object o: c) { result |= remove(o); } return result; } } public boolean retainAll(Collection<?> c) { throw new UnsupportedModelOperationException("retainAll()", "not implemented"); }
public void clear() { if (referenceSourceCollection.isImmutable()) { throw new UnsupportedModelOperationException("clear()", "collection is immutable"); } else { Collection<DomElement> view = new ArrayList<DomElement>(); for (Source referenceSourceElement : referenceSourceCollection.get(referenceSourceParentElement)) { view.add(referenceSourceElement.getDomElement()); } performClearOperation(referenceSourceParentElement, view); } } }; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ElementReferenceCollectionImpl.java
1
请完成以下Java代码
public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public void setNickName(String nickName) { this.nickName = nickName; } public ShiroUser(Long userId, String loginName, String nickName) { this.userId = userId; this.loginName = loginName; this.nickName = nickName; } public String getNickName() { return nickName; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } /** * 本函数输出将作为默认的<shiro:principal/>输出. */ @Override public String toString() { return loginName; }
/** * 重载hashCode,只计算loginName; */ @Override public int hashCode() { return Objects.hashCode(loginName); } /** * 重载equals,只计算loginName; */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ShiroUser other = (ShiroUser) obj; if (loginName == null) { if (other.loginName != null) { return false; } } else if (!loginName.equals(other.loginName)) { return false; } return true; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroUser.java
1
请完成以下Java代码
private List<RelatedProcessDescriptor> getInvoiceRelatedProcessDescriptors() { return ImmutableList.of( createProcessDescriptor(10, InvoicesView_MarkPreparedForAllocation.class), createProcessDescriptor(20, InvoicesView_UnMarkPreparedForAllocation.class), createProcessDescriptor(30, InvoicesView_AddAdditionalInvoice.class)); } protected final RelatedProcessDescriptor createProcessDescriptor(final int sortNo, @NonNull final Class<?> processClass) { final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass); if (processId == null) { throw new AdempiereException("No processId found for " + processClass); } return RelatedProcessDescriptor.builder() .processId(processId) .anyTable().anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .sortNo(sortNo) .build(); } @Override public WindowId getWindowId() { return WINDOW_ID; } @Override public void put(final IView view) { views.put(view); } @Nullable @Override public PaymentsView getByIdOrNull(final ViewId viewId) {
return PaymentsView.cast(views.getByIdOrNull(viewId)); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { views.closeById(viewId, closeAction); } @Override public Stream<IView> streamAllViews() { return views.streamAllViews(); } @Override public void invalidateView(final ViewId viewId) { views.invalidateView(viewId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\PaymentsViewFactory.java
1
请完成以下Java代码
public String toString() { return getDelegate().toString(); } @Override public Set<Object> keySet() { return getDelegate().keySet(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { return getDelegate().entrySet(); } @Override public Collection<Object> values() { return getDelegate().values(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); } @SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override
public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请在Spring Boot框架中完成以下Java代码
public String getContextPath() { return this.contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public @Nullable String getSecret() { return this.secret; } public void setSecret(@Nullable String secret) { this.secret = secret; } public String getSecretHeaderName() { return this.secretHeaderName; } public void setSecretHeaderName(String secretHeaderName) { this.secretHeaderName = secretHeaderName; } public Restart getRestart() { return this.restart; } public Proxy getProxy() { return this.proxy; } public static class Restart { /** * Whether to enable remote restart. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Proxy { /** * The host of the proxy to use to connect to the remote application. */ private @Nullable String host; /** * The port of the proxy to use to connect to the remote application. */ private @Nullable Integer port; public @Nullable String getHost() { return this.host; } public void setHost(@Nullable String host) { this.host = host; } public @Nullable Integer getPort() { return this.port; } public void setPort(@Nullable Integer port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsProperties.java
2
请完成以下Java代码
public int getS_ResourceType_ID() { return get_ValueAsInt(COLUMNNAME_S_ResourceType_ID); } @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 setWaitingTime (final @Nullable BigDecimal WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public BigDecimal getWaitingTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WaitingTime); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Resource.java
1
请完成以下Java代码
public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setDocument_Acct_Log_ID (final int Document_Acct_Log_ID) { if (Document_Acct_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, Document_Acct_Log_ID); } @Override public int getDocument_Acct_Log_ID() { return get_ValueAsInt(COLUMNNAME_Document_Acct_Log_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); }
@Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } /** * Type AD_Reference_ID=541967 * Reference name: Document_Acct_Log_Type */ public static final int TYPE_AD_Reference_ID=541967; /** Enqueued = enqueued */ public static final String TYPE_Enqueued = "enqueued"; /** Posting Done = posting_ok */ public static final String TYPE_PostingDone = "posting_ok"; /** Posting Error = posting_error */ public static final String TYPE_PostingError = "posting_error"; @Override public void setType (final @Nullable java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Document_Acct_Log.java
1
请完成以下Java代码
private JSONOptions newJSONOptions() { return JSONOptions.of(userSession); } @PostMapping public WebuiImageId uploadImage(@RequestParam("file") final MultipartFile file) throws IOException { userSession.assertLoggedIn(); return imageService.uploadImage(file); } @GetMapping("/{imageId}") @ResponseBody public ResponseEntity<byte[]> getImage( @PathVariable("imageId") final int imageIdInt, @RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth, @RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight, final WebRequest request) { userSession.assertLoggedIn(); final WebuiImageId imageId = WebuiImageId.ofRepoIdOrNull(imageIdInt); return ETagResponseEntityBuilder.ofETagAware(request, getWebuiImage(imageId, maxWidth, maxHeight)) .includeLanguageInETag() .cacheMaxAge(userSession.getHttpCacheMaxAge()) .jsonOptions(this::newJSONOptions) .toResponseEntity((responseBuilder, webuiImage) -> webuiImage.toResponseEntity(responseBuilder)); }
private WebuiImage getWebuiImage(final WebuiImageId imageId, final int maxWidth, final int maxHeight) { final WebuiImage image = imageService.getWebuiImage(imageId, maxWidth, maxHeight); assertUserHasAccess(image); return image; } private void assertUserHasAccess(final WebuiImage image) { final BooleanWithReason hasAccess = userSession.getUserRolePermissions().checkCanView(image.getAdClientId(), image.getAdOrgId(), I_AD_Image.Table_ID, image.getAdImageId().getRepoId()); if (hasAccess.isFalse()) { throw new EntityNotFoundException(hasAccess.getReason()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\ImageRestController.java
1
请完成以下Java代码
public int getArg0() { return arg0; } /** * Sets the value of the arg0 property. * */ public void setArg0(int value) { this.arg0 = value; } /** * Gets the value of the arg1 property. * * @return * possible object is * {@link String } * */ public String getArg1() { return arg1;
} /** * Sets the value of the arg1 property. * * @param value * allowed object is * {@link String } * */ public void setArg1(String value) { this.arg1 = value; } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\AddEmployee.java
1
请完成以下Java代码
public void setM_DiscountSchema_Calculated_Surcharge_ID (final int M_DiscountSchema_Calculated_Surcharge_ID) { if (M_DiscountSchema_Calculated_Surcharge_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, M_DiscountSchema_Calculated_Surcharge_ID); } @Override public int getM_DiscountSchema_Calculated_Surcharge_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() {
return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSurcharge_Calc_SQL (final java.lang.String Surcharge_Calc_SQL) { set_Value (COLUMNNAME_Surcharge_Calc_SQL, Surcharge_Calc_SQL); } @Override public java.lang.String getSurcharge_Calc_SQL() { return get_ValueAsString(COLUMNNAME_Surcharge_Calc_SQL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema_Calculated_Surcharge.java
1
请在Spring Boot框架中完成以下Java代码
class LayoutFactorySupportingServices { @NonNull @Getter private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); @NonNull @Getter private final SqlDocumentsRepository documentsRepository; @NonNull @Getter private final LookupDataSourceFactory lookupDataSourceFactory; @NonNull private final QuickInputDescriptorFactoryService quickInputDescriptors; @NonNull @Getter private final AttributesIncludedTabDescriptorService attributesIncludedTabDescriptorService; @NonNull private final Optional<List<IDocumentDecorator>> documentDecorators; public List<IDocumentDecorator> getDocumentDecorators() { return documentDecorators.orElseGet(ImmutableList::of); } @SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean getSysConfigBooleanValue(final String name, final boolean defaultValue) { return sysConfigBL.getBooleanValue(name, defaultValue); } public boolean hasQuickInputEntityDescriptor(final DocumentEntityDescriptor.Builder entityDescriptor) { return quickInputDescriptors.hasQuickInputEntityDescriptor( entityDescriptor.getDocumentType(), entityDescriptor.getDocumentTypeId(), entityDescriptor.getTableName(), entityDescriptor.getDetailId(), entityDescriptor.getSOTrx() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\LayoutFactorySupportingServices.java
2
请在Spring Boot框架中完成以下Java代码
public void drop(String tableName) { logger.warn("drop table {} from naive", tableName); System.out.println("drop table " + tableName + " from naive"); try { mongoTemplate.dropCollection(tableName.trim()); } catch (Exception e) { logger.error("drop tableName error "+ tableName, e); } } public void insertData(String schemaName, String tableName, Document obj) { try { String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.INSERT.getNumber(); mongoTemplate.save(obj,tableName); } catch (MongoClientException | MongoSocketException clientException) { //客户端连接异常抛出,阻塞同步,防止mongodb宕机 throw clientException; } catch (DuplicateKeyException dke) { //主键冲突异常,跳过 logger.warn("DuplicateKeyException:", dke); } catch (Exception e) { logger.error(schemaName, tableName, obj, e); } } public void updateData(String schemaName, String tableName, DBObject query, Document obj) { String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.UPDATE.getNumber(); Document options = new Document(query.toMap()); try { obj.remove("id"); mongoTemplate.getCollection(tableName).replaceOne(options,obj); obj.putAll(query.toMap()); } catch (MongoClientException | MongoSocketException clientException) { //客户端连接异常抛出,阻塞同步,防止mongodb宕机 throw clientException; } catch (Exception e) {
logger.error(schemaName, tableName, obj, e); } } public void deleteData(String schemaName, String tableName, Document obj) { String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.DELETE.getNumber(); //保存原始数据 try { if (obj.containsKey("id")) { obj.put("_id", obj.get("id")); obj.remove("id"); mongoTemplate.remove(new BasicQuery(obj),tableName); } } catch (MongoClientException | MongoSocketException clientException) { //客户端连接异常抛出,阻塞同步,防止mongodb宕机 throw clientException; } catch (Exception e) { logger.error(schemaName, tableName, obj, e); } } }
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\service\DataService.java
2
请完成以下Java代码
public class WEBUI_Picking_M_Source_HU_Delete extends PickingSlotViewBasedProcess { private boolean sourceWasDeleted = false; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PickingSlotRow pickingSlotRow = getSingleSelectedRow(); if (!pickingSlotRow.isPickingSourceHURow()) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_SOURCE_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final PickingSlotRow rowToProcess = getSingleSelectedRow(); final HuId huId = rowToProcess.getHuId(); this.sourceWasDeleted = SourceHUsService.get().deleteSourceHuMarker(huId); return MSG_OK; }
@Override protected void postProcess(final boolean success) { if (!success) { return; } if (sourceWasDeleted) { // unselect the row we just deleted the record of, to avoid an 'EntityNotFoundException' invalidatePickingSlotsView(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_M_Source_HU_Delete.java
1
请完成以下Java代码
public MQuery getDrillAcross (Point relativePoint) { MQuery retValue = null; for (int i = 0; i < m_elements.size() && retValue == null; i++) { PrintElement element = m_elements.get(i); retValue = element.getDrillAcross (relativePoint, m_pageNo); } return retValue; } // getDrillAcross /** * set Background Image * @param image */ public void setBackgroundImage(Image image) { m_image = image; } /** * get Background Image * @return */ public Image getBackgroundImage() {
return m_image; } /** * String Representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("Page["); sb.append(m_pageNo).append(",Elements=").append(m_elements.size()); sb.append("]"); return sb.toString(); } // toString } // Page
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Page.java
1
请在Spring Boot框架中完成以下Java代码
public class RoleNotificationsConfigRepository implements IRoleNotificationsConfigRepository { private final CCache<RoleId, RoleNotificationsConfig> roleNotificationsConfigsByRoleId = CCache.<RoleId, RoleNotificationsConfig> builder() .tableName(I_AD_Role_NotificationGroup.Table_Name) .initialCapacity(10) .additionalTableNameToResetFor(I_AD_Role.Table_Name) .additionalTableNameToResetFor(I_AD_Role_NotificationGroup.Table_Name) .build(); @Override public RoleNotificationsConfig getByRoleId(@NonNull final RoleId adRoleId) { return roleNotificationsConfigsByRoleId.getOrLoad(adRoleId, this::retrieveRoleNotificationsConfig); } private RoleNotificationsConfig retrieveRoleNotificationsConfig(@NonNull final RoleId adRoleId) { final List<UserNotificationsGroup> notificationGroups = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Role_NotificationGroup.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_Role_NotificationGroup.COLUMN_AD_Role_ID, adRoleId) .create() .stream() .map(this::toNotificationGroup) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); return RoleNotificationsConfig.builder() .roleId(adRoleId) .notificationGroups(notificationGroups) .build(); } private UserNotificationsGroup toNotificationGroup(final I_AD_Role_NotificationGroup record) { final INotificationGroupRepository notificationGroupRepo = Services.get(INotificationGroupRepository.class); final NotificationGroupName groupInternalName = notificationGroupRepo.getNameById(NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID())).orElse(null); if (groupInternalName == null) { // group does not exist or it was deactivated return null; }
return UserNotificationsGroup.builder() .groupInternalName(groupInternalName) .notificationTypes(UserNotificationsConfigRepository.toNotificationTypes(record.getNotificationType())) .build(); } @Override public ImmutableSet<RoleId> getRoleIdsContainingNotificationGroupName(@NonNull final NotificationGroupName notificationGroupName) { final INotificationGroupRepository notificationGroupRepo = Services.get(INotificationGroupRepository.class); final NotificationGroupId notificationGroupId = notificationGroupRepo.getNotificationGroupId(notificationGroupName).orElse(null); if(notificationGroupId == null) { return ImmutableSet.of(); } return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Role_NotificationGroup.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_Role_NotificationGroup.COLUMN_AD_NotificationGroup_ID, notificationGroupId) .create() .listDistinct(I_AD_Role_NotificationGroup.COLUMNNAME_AD_Role_ID, Integer.class) .stream() .map(RoleId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\RoleNotificationsConfigRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class GlobalProperties { // @Value("${thread-pool}") // access the value from application.properties via @Value @Max(5) @Min(0) private int threadPool; //@Value("${email}") @NotEmpty private String email; public int getThreadPool() { return threadPool; } public void setThreadPool(int threadPool) { this.threadPool = threadPool; } public String getEmail() {
return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "GlobalProperties{" + "threadPool=" + threadPool + ", email='" + email + '\'' + '}'; } }
repos\spring-boot-master\spring-boot-externalize-config\src\main\java\com\mkyong\global\GlobalProperties.java
2
请在Spring Boot框架中完成以下Java代码
private ClientAndOrgId getFallbackClientAndOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { if (!clientAndOrgId.getOrgId().isAny()) { return clientAndOrgId.withAnyOrgId(); } else if (!clientAndOrgId.getClientId().isSystem()) { return clientAndOrgId.withSystemClientId(); } else { return null; } } public Optional<String> getValueAsString(@NonNull final ClientAndOrgId clientAndOrgId) { for (ClientAndOrgId currentClientAndOrgId = clientAndOrgId; currentClientAndOrgId != null; currentClientAndOrgId = getFallbackClientAndOrgId(currentClientAndOrgId)) { final SysConfigEntryValue entryValue = entryValues.get(currentClientAndOrgId); if (entryValue != null) { return Optional.of(entryValue.getValue()); } }
return Optional.empty(); } // // // ------------------------------- // // public static class SysConfigEntryBuilder { public String getName() { return name; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigEntry.java
2
请在Spring Boot框架中完成以下Java代码
public static DemandDetailsQuery ofSupplyRequiredDescriptor(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor) { return ofDemandDetail(DemandDetail.forSupplyRequiredDescriptor(supplyRequiredDescriptor)); } public static DemandDetailsQuery forDocumentLine( @NonNull final DocumentLineDescriptor documentLineDescriptor) { if (documentLineDescriptor instanceof OrderLineDescriptor) { final OrderLineDescriptor orderLineDescriptor = OrderLineDescriptor.cast(documentLineDescriptor); return new DemandDetailsQuery( UNSPECIFIED_REPO_ID, orderLineDescriptor.getOrderLineId(), UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID); } else if (documentLineDescriptor instanceof SubscriptionLineDescriptor) { final SubscriptionLineDescriptor subscriptionLineDescriptor = SubscriptionLineDescriptor.cast(documentLineDescriptor); return new DemandDetailsQuery( UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, subscriptionLineDescriptor.getSubscriptionProgressId(), UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID); } else { //noinspection ThrowableNotThrown Check.fail("documentLineDescriptor has unsupported type={}; documentLineDescriptor={}", documentLineDescriptor.getClass(), documentLineDescriptor); } return null; } public static DemandDetailsQuery ofShipmentLineId(final int inOutLineId) { Check.assumeGreaterThanZero(inOutLineId, "inOutLineId"); return new DemandDetailsQuery( UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, UNSPECIFIED_REPO_ID, inOutLineId); } int shipmentScheduleId; int orderLineId; int subscriptionLineId;
int forecastLineId; int inOutLineId; private DemandDetailsQuery( final int shipmentScheduleId, final int orderLineId, final int subscriptionLineId, final int forecastLineId, final int inOutLineId) { this.shipmentScheduleId = shipmentScheduleId; this.orderLineId = orderLineId; this.subscriptionLineId = subscriptionLineId; this.forecastLineId = forecastLineId; this.inOutLineId = inOutLineId; IdConstants.assertValidId(shipmentScheduleId, "shipmentScheduleId"); IdConstants.assertValidId(orderLineId, "orderLineId"); IdConstants.assertValidId(subscriptionLineId, "subscriptionLineId"); IdConstants.assertValidId(forecastLineId, "forecastLineId"); IdConstants.assertValidId(inOutLineId, "inOutLineId"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\query\DemandDetailsQuery.java
2
请完成以下Java代码
private static int getCodePointSize(byte[] bytes, int i) { int b = Byte.toUnsignedInt(bytes[i]); if ((b & 0b1_0000000) == 0b0_0000000) { return 1; } if ((b & 0b111_00000) == 0b110_00000) { return 2; } if ((b & 0b1111_0000) == 0b1110_0000) { return 3; } return 4; } private static int getCodePoint(byte[] bytes, int i, int codePointSize) { int codePoint = Byte.toUnsignedInt(bytes[i]); codePoint &= INITIAL_BYTE_BITMASK[codePointSize - 1]; for (int j = 1; j < codePointSize; j++) {
codePoint = (codePoint << 6) + (bytes[i + j] & SUBSEQUENT_BYTE_BITMASK); } return codePoint; } /** * Supported compare types. */ private enum CompareType { MATCHES, MATCHES_ADDING_SLASH, STARTS_WITH } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\ZipString.java
1
请完成以下Java代码
private ReferenceId getTarget_Reference_ID() { return Check.assumeNotNull(targetReferenceId, "targetReferenceId is set"); } private ADRefTable getTargetTableRefInfoOrNull() { if (targetTableRefInfo == null) { targetTableRefInfo = retrieveTableRefInfo(getTarget_Reference_ID()); } return targetTableRefInfo; } public Builder setTargetRoleDisplayName(final ITranslatableString targetRoleDisplayName) { this.targetRoleDisplayName = targetRoleDisplayName; return this; }
public ITranslatableString getTargetRoleDisplayName() { return targetRoleDisplayName; } public Builder setIsTableRecordIdTarget(final boolean isReferenceTarget) { isTableRecordIDTarget = isReferenceTarget; return this; } private boolean isTableRecordIdTarget() { return isTableRecordIDTarget; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\relation_type\SpecificRelationTypeRelatedDocumentsProvider.java
1
请完成以下Java代码
public final class ServletContextInitializers implements Iterable<ServletContextInitializer> { private final List<ServletContextInitializer> initializers; private ServletContextInitializers(List<ServletContextInitializer> initializers) { this.initializers = initializers; } @Override public Iterator<ServletContextInitializer> iterator() { return this.initializers.iterator(); } /** * Creates a new instance from the given {@code settings} and {@code initializers}. * @param settings the settings * @param initializers the initializers * @return the new instance */ public static ServletContextInitializers from(ServletWebServerSettings settings, ServletContextInitializer... initializers) { List<ServletContextInitializer> mergedInitializers = new ArrayList<>(); mergedInitializers .add((servletContext) -> settings.getInitParameters().forEach(servletContext::setInitParameter)); mergedInitializers.add(new SessionConfiguringInitializer(settings.getSession())); mergedInitializers.addAll(Arrays.asList(initializers)); mergedInitializers.addAll(settings.getInitializers()); return new ServletContextInitializers(mergedInitializers); } private static final class SessionConfiguringInitializer implements ServletContextInitializer { private final Session session; private SessionConfiguringInitializer(Session session) { this.session = session; } @Override public void onStartup(ServletContext servletContext) throws ServletException { if (this.session.getTrackingModes() != null) { servletContext.setSessionTrackingModes(unwrap(this.session.getTrackingModes())); } configureSessionCookie(servletContext.getSessionCookieConfig()); } private void configureSessionCookie(SessionCookieConfig config) { Cookie cookie = this.session.getCookie(); PropertyMapper map = PropertyMapper.get(); map.from(cookie::getName).to(config::setName); map.from(cookie::getDomain).to(config::setDomain);
map.from(cookie::getPath).to(config::setPath); map.from(cookie::getHttpOnly).to(config::setHttpOnly); map.from(cookie::getSecure).to(config::setSecure); map.from(cookie::getMaxAge).asInt(Duration::getSeconds).to(config::setMaxAge); map.from(cookie::getPartitioned) .as(Object::toString) .to((partitioned) -> config.setAttribute("Partitioned", partitioned)); } @Contract("!null -> !null") private @Nullable Set<jakarta.servlet.SessionTrackingMode> unwrap( @Nullable Set<Session.SessionTrackingMode> modes) { if (modes == null) { return null; } Set<jakarta.servlet.SessionTrackingMode> result = new LinkedHashSet<>(); for (Session.SessionTrackingMode mode : modes) { result.add(jakarta.servlet.SessionTrackingMode.valueOf(mode.name())); } return result; } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletContextInitializers.java
1
请在Spring Boot框架中完成以下Java代码
public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Override public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) { converters.add(byteArrayHttpMessageConverter()); } @Bean public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() { final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes()); return arrayHttpMessageConverter; } private List<MediaType> getSupportedMediaTypes() { final List<MediaType> list = new ArrayList<MediaType>(); list.add(MediaType.IMAGE_JPEG); list.add(MediaType.IMAGE_PNG); list.add(MediaType.APPLICATION_OCTET_STREAM);
return list; } @Override public void configurePathMatch(final PathMatchConfigurer configurer) { final UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); } @Bean(name = "multipartResolver") public StandardServletMultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\spring\web\config\WebConfig.java
2
请完成以下Java代码
protected final void assertValidSessionId(final String sessionId) { if (sessionId == null || sessionId.trim().isEmpty()) { throw new RuntimeException("SessionId is empty"); } try { final int sessionIdInt = Integer.parseInt(sessionId.trim()); if (sessionIdInt <= 0) { throw new RuntimeException("SessionId '" + sessionId + "' is not valid"); } } catch (final NumberFormatException e) { throw new RuntimeException("SessionId '" + sessionId + "' is not valid"); } } protected LoginResponse sendLoginRequest(final LoginRequest loginRequest) throws LoginFailedPrintConnectionEndpointException { final byte[] data = beanEncoder.encode(loginRequest); final Map<String, String> params = new HashMap<>(); params.put(Context.CTX_SessionId, "0"); // no session final URL url = getURL(PRTRestServiceConstants.PATH_Login, params); final PostMethod httpPost = new PostMethod(url.toString()); addApiTokenIfAvailable(httpPost); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; InputStream in = null; try { result = executeHttpPost(httpPost); in = httpPost.getResponseBodyAsStream(); if (result != 200) { final String errorMsg = in == null ? "code " + result : Util.toString(in);
throw new PrintConnectionEndpointException("Error " + result + " while posting on " + url + ": " + errorMsg); } final LoginResponse loginResponse = beanEncoder.decodeStream(in, LoginResponse.class); return loginResponse; } catch (final Exception e) { log.info("Exception " + e); throw e instanceof LoginFailedPrintConnectionEndpointException ? (LoginFailedPrintConnectionEndpointException)e : new LoginFailedPrintConnectionEndpointException("Cannot POST to " + url, e); } finally { Util.close(in); in = null; } } private void addApiTokenIfAvailable(final PostMethod httpPost) { final String apiToken = getContext().getProperty(Context.CTX_Login_ApiToken); if (apiToken != null && apiToken.trim().length() > 0) { httpPost.setRequestHeader("Authorization", apiToken.trim()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\RestHttpPrintConnectionEndpoint.java
1
请完成以下Java代码
public void save(DataOutputStream out) throws IOException { if (!(featureMap instanceof ImmutableFeatureMDatMap)) { featureMap = new ImmutableFeatureMDatMap(featureMap.entrySet(), tagSet()); } featureMap.save(out); for (float aParameter : this.parameter) { out.writeFloat(aParameter); } } @Override public boolean load(ByteArray byteArray) { if (byteArray == null) return false; featureMap = new ImmutableFeatureMDatMap(); featureMap.load(byteArray); int size = featureMap.size(); TagSet tagSet = featureMap.tagSet; if (tagSet.type == TaskType.CLASSIFICATION) { parameter = new float[size]; for (int i = 0; i < size; i++)
{ parameter[i] = byteArray.nextFloat(); } } else { parameter = new float[size * tagSet.size()]; for (int i = 0; i < size; i++) { for (int j = 0; j < tagSet.size(); ++j) { parameter[i * tagSet.size() + j] = byteArray.nextFloat(); } } } // assert !byteArray.hasMore(); // byteArray.close(); if (!byteArray.hasMore()) byteArray.close(); return true; } public TaskType taskType() { return featureMap.tagSet.type; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\model\LinearModel.java
1
请完成以下Java代码
public class ReferredDocumentType1Choice { @XmlElement(name = "Cd") @XmlSchemaType(name = "string") protected DocumentType5Code cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link DocumentType5Code } * */ public DocumentType5Code getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link DocumentType5Code } * */ public void setCd(DocumentType5Code value) { this.cd = value; } /**
* Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ReferredDocumentType1Choice.java
1
请完成以下Java代码
public void checkRegisterDeployment() { } @Override public void checkUnregisterDeployment() { } @Override public void checkDeleteMetrics() { } @Override public void checkDeleteTaskMetrics() { } @Override public void checkReadSchemaLog() { } // helper ////////////////////////////////////////////////// protected TenantManager getTenantManager() { return Context.getCommandContext().getTenantManager(); } protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) {
return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); } protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) { return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId); } protected ExecutionEntity findExecutionById(String processInstanceId) { return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId); } protected DeploymentEntity findDeploymentById(String deploymentId) { return Context.getCommandContext().getDeploymentManager().findDeploymentById(deploymentId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantCommandChecker.java
1
请完成以下Java代码
protected void initializeTaskAssignee(TaskEntity task, VariableScope variableScope) { Expression assigneeExpression = taskDefinition.getAssigneeExpression(); if (assigneeExpression != null) { task.setAssignee((String) assigneeExpression.getValue(variableScope)); } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void initializeTaskCandidateGroups(TaskEntity task, VariableScope variableScope) { Set<Expression> candidateGroupIdExpressions = taskDefinition.getCandidateGroupIdExpressions(); for (Expression groupIdExpr : candidateGroupIdExpressions) { Object value = groupIdExpr.getValue(variableScope); if (value instanceof String) { List<String> candiates = extractCandidates((String) value); task.addCandidateGroups(candiates); } else if (value instanceof Collection) { task.addCandidateGroups((Collection) value); } else { throw new ProcessEngineException("Expression did not resolve to a string or collection of strings"); } } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void initializeTaskCandidateUsers(TaskEntity task, VariableScope variableScope) { Set<Expression> candidateUserIdExpressions = taskDefinition.getCandidateUserIdExpressions(); for (Expression userIdExpr : candidateUserIdExpressions) { Object value = userIdExpr.getValue(variableScope); if (value instanceof String) { List<String> candiates = extractCandidates((String) value); task.addCandidateUsers(candiates); } else if (value instanceof Collection) { task.addCandidateUsers((Collection) value);
} else { throw new ProcessEngineException("Expression did not resolve to a string or collection of strings"); } } } /** * Extract a candidate list from a string. */ protected List<String> extractCandidates(String str) { return Arrays.asList(str.split("[\\s]*,[\\s]*")); } // getters /////////////////////////////////////////////////////////////// public TaskDefinition getTaskDefinition() { return taskDefinition; } public ExpressionManager getExpressionManager() { return expressionManager; } protected BusinessCalendar getBusinessCalender() { return Context .getProcessEngineConfiguration() .getBusinessCalendarManager() .getBusinessCalendar(DueDateBusinessCalendar.NAME); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDecorator.java
1
请完成以下Java代码
public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setDocument_Acct_Log_ID (final int Document_Acct_Log_ID) { if (Document_Acct_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, Document_Acct_Log_ID);
} @Override public int getDocument_Acct_Log_ID() { return get_ValueAsInt(COLUMNNAME_Document_Acct_Log_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } /** * Type AD_Reference_ID=541967 * Reference name: Document_Acct_Log_Type */ public static final int TYPE_AD_Reference_ID=541967; /** Enqueued = enqueued */ public static final String TYPE_Enqueued = "enqueued"; /** Posting Done = posting_ok */ public static final String TYPE_PostingDone = "posting_ok"; /** Posting Error = posting_error */ public static final String TYPE_PostingError = "posting_error"; @Override public void setType (final @Nullable java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Document_Acct_Log.java
1
请在Spring Boot框架中完成以下Java代码
private static Saml2X509Credential getSaml2Credential(String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(certificate, credentialType); } private static RSAPrivateKey readPrivateKey(String privateKeyLocation) { Resource privateKey = resourceLoader.getResource(privateKeyLocation); try (InputStream inputStream = privateKey.getInputStream()) { return RsaKeyConverters.pkcs8().convert(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } }
private static X509Certificate readCertificate(String certificateLocation) { Resource certificate = resourceLoader.getResource(certificateLocation); try (InputStream inputStream = certificate.getInputStream()) { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static String resolveAttribute(ParserContext pc, String value) { return pc.getReaderContext().getEnvironment().resolvePlaceholders(value); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\saml2\RelyingPartyRegistrationsBeanDefinitionParser.java
2
请完成以下Java代码
public class App extends Jooby { { setServerOptions(new ServerOptions().setPort(8080) .setSecurePort(8433)); } { get("/", ctx -> "Hello World!"); } { get("/user/{id}", ctx -> "Hello user : " + ctx.path("id") .value()); get("/user/:id", ctx -> "Hello user: " + ctx.path("id") .value()); get("/uid:{id}", ctx -> "Hello User with id : uid = " + ctx.path("id") .value()); } { onStarting(() -> System.out.println("starting app")); onStop(() -> System.out.println("stopping app")); onStarted(() -> System.out.println("app started")); } { get("/login", ctx -> "Hello from Baeldung"); } { post("/save", ctx -> { String userId = ctx.query("id") .value(); return userId; }); } { { assets("/employee", "public/form.html"); } post("/submitForm", ctx -> { Employee employee = ctx.path(Employee.class); // ... return "employee data saved successfully"; }); } { decorator(next -> ctx -> { System.out.println("first"); // Moves execution to next handler: second return next.apply(ctx); }); decorator(next -> ctx -> {
System.out.println("second"); // Moves execution to next handler: third return next.apply(ctx); }); get("/handler", ctx -> "third"); } { get("/sessionInMemory", ctx -> { Session session = ctx.session(); session.put("token", "value"); return session.get("token") .value(); }); } { String secret = "super secret token"; setSessionStore(SessionStore.signed(secret)); get("/signedSession", ctx -> { Session session = ctx.session(); session.put("token", "value"); return session.get("token") .value(); }); } { get("/sessionInMemoryRedis", ctx -> { Session session = ctx.session(); session.put("token", "value"); return session.get("token") .value(); }); } /* This will work once redis is installed locally { install(new RedisModule("redis")); setSessionStore(new RedisSessionStore(require(RedisClient.class))); get("/redisSession", ctx -> { Session session = ctx.session(); session.put("token", "value"); return session.get("token"); }); }*/ public static void main(final String[] args) { runApp(args, App::new); } }
repos\tutorials-master\web-modules\jooby\src\main\java\com\baeldung\jooby\App.java
1
请完成以下Java代码
public void add(final Object keyPart) { keyParts.add(keyPart); } public void setTrxName(String trxName) { this.trxName = trxName; } public String getTrxName() { return trxName; } public void setSkipCaching() { this.skipCaching = true; } public boolean isSkipCaching() { return skipCaching;
} /** * Advices the caching engine to refresh the cached value, instead of checking the cache. * * NOTE: this option will have NO affect if {@link #isSkipCaching()}. */ public void setCacheReload() { this.cacheReload = true; } /** @return true if instead the underlying method shall be invoked and cache shall be refreshed with that value */ public boolean isCacheReload() { return cacheReload; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheKeyBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public String getAckRequest() { return ackRequest; } /** * Sets the value of the ackRequest property. * * @param value * allowed object is * {@link String } * */ public void setAckRequest(String value) { this.ackRequest = value; } /** * Gets the value of the agreementId property. * * @return * possible object is * {@link String } * */ public String getAgreementId() { return agreementId; } /** * Sets the value of the agreementId property. * * @param value * allowed object is * {@link String } * */
public void setAgreementId(String value) { this.agreementId = value; } /** * Gets the value of the testIndicator property. * * @return * possible object is * {@link String } * */ public String getTestIndicator() { return testIndicator; } /** * Sets the value of the testIndicator property. * * @param value * allowed object is * {@link String } * */ public void setTestIndicator(String value) { this.testIndicator = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\InterchangeHeaderType.java
2
请完成以下Java代码
public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null; }
@Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "CmmnDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityImpl.java
1
请完成以下Java代码
public void traversePreOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current; stack.push(root); while(! stack.isEmpty()) { current = stack.pop(); visit(current.value); if(current.right != null) stack.push(current.right); if(current.left != null) stack.push(current.left); } } public void traversePostOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node prev = root; Node current; stack.push(root); while (!stack.isEmpty()) { current = stack.peek(); boolean hasChild = (current.left != null || current.right != null); boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); if (!hasChild || isPrevLastChild) { current = stack.pop(); visit(current.value); prev = current; } else { if (current.right != null) { stack.push(current.right); } if (current.left != null) { stack.push(current.left); } } }
} private void visit(int value) { System.out.print(" " + value); } static class Node { int value; Node left; Node right; Node(int value) { this.value = value; right = null; left = null; } } }
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\dfs\BinaryTree.java
1
请完成以下Java代码
public TenantResource getTenant(String id) { id = PathUtil.decodePathParam(id); return new TenantResourceImpl(getProcessEngine().getName(), id, relativeRootResourcePath, getObjectMapper()); } @Override public List<TenantDto> queryTenants(UriInfo uriInfo, Integer firstResult, Integer maxResults) { TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); TenantQuery query = queryDto.toQuery(getProcessEngine()); List<Tenant> tenants = QueryUtil.list(query, firstResult, maxResults); return TenantDto.fromTenantList(tenants ); } @Override public CountResultDto getTenantCount(UriInfo uriInfo) { TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); TenantQuery query = queryDto.toQuery(getProcessEngine()); long count = query.count(); return new CountResultDto(count); } @Override public void createTenant(TenantDto dto) { if (getIdentityService().isReadOnly()) { throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only."); } Tenant newTenant = getIdentityService().newTenant(dto.getId()); dto.update(newTenant); getIdentityService().saveTenant(newTenant); } @Override public ResourceOptionsDto availableOperations(UriInfo context) { UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(TenantRestService.PATH); ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); // GET /
URI baseUri = baseUriBuilder.build(); resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); // GET /count URI countUri = baseUriBuilder.clone().path("/count").build(); resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); // POST /create if (!getIdentityService().isReadOnly() && isAuthorized(CREATE)) { URI createUri = baseUriBuilder.clone().path("/create").build(); resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); } return resourceOptionsDto; } protected IdentityService getIdentityService() { return getProcessEngine().getIdentityService(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TenantRestServiceImpl.java
1
请完成以下Java代码
public class Compilation { @Id private String id; private String name; public Compilation() { } public Compilation(String name) { super(); this.name = name; } public String getId() {
return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\collection\name\data\Compilation.java
1
请在Spring Boot框架中完成以下Java代码
QueueChannel remainderIsTwoChannel() { return new QueueChannel(); } boolean isMultipleOfThree(Integer number) { return number % 3 == 0; } boolean isRemainderOne(Integer number) { return number % 3 == 1; } boolean isRemainderTwo(Integer number) { return number % 3 == 2; } @Bean public IntegrationFlow multipleOfThreeFlow() { return flow -> flow.split() .<Integer> filter(this::isMultipleOfThree) .channel("multipleOfThreeChannel"); }
@Bean public IntegrationFlow remainderIsOneFlow() { return flow -> flow.split() .<Integer> filter(this::isRemainderOne) .channel("remainderIsOneChannel"); } @Bean public IntegrationFlow remainderIsTwoFlow() { return flow -> flow.split() .<Integer> filter(this::isRemainderTwo) .channel("remainderIsTwoChannel"); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\separateflows\SeparateFlowsExample.java
2
请完成以下Java代码
public BigDecimal getUnitPric() { return unitPric; } /** * Sets the value of the unitPric property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setUnitPric(BigDecimal value) { this.unitPric = value; } /** * Gets the value of the pdctAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getPdctAmt() { return pdctAmt; } /** * Sets the value of the pdctAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setPdctAmt(BigDecimal value) { this.pdctAmt = value; } /** * Gets the value of the taxTp property. * * @return * possible object is * {@link String } * */ public String getTaxTp() { return taxTp; } /** * Sets the value of the taxTp property. * * @param value
* allowed object is * {@link String } * */ public void setTaxTp(String value) { this.taxTp = value; } /** * Gets the value of the addtlPdctInf property. * * @return * possible object is * {@link String } * */ public String getAddtlPdctInf() { return addtlPdctInf; } /** * Sets the value of the addtlPdctInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlPdctInf(String value) { this.addtlPdctInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Product2.java
1
请完成以下Java代码
public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setC_BPartner(org.compiere.model.I_C_BPartner C_BPartner) { set_ValueFromPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class, C_BPartner); } /** Set Geschäftspartner. @param C_BPartner_ID Bezeichnet einen Geschäftspartner */ @Override public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Geschäftspartner. @return Bezeichnet einen Geschäftspartner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Geschäftspartner Document Line Sorting Preferences. @param C_BP_DocLine_Sort_ID Geschäftspartner Document Line Sorting Preferences */ @Override public void setC_BP_DocLine_Sort_ID (int C_BP_DocLine_Sort_ID) { if (C_BP_DocLine_Sort_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BP_DocLine_Sort_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BP_DocLine_Sort_ID, Integer.valueOf(C_BP_DocLine_Sort_ID)); } /** Get Geschäftspartner Document Line Sorting Preferences. @return Geschäftspartner Document Line Sorting Preferences */ @Override public int getC_BP_DocLine_Sort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_DocLine_Sort_ID); if (ii == null) return 0; return ii.intValue(); }
@Override public org.compiere.model.I_C_DocLine_Sort getC_DocLine_Sort() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class); } @Override public void setC_DocLine_Sort(org.compiere.model.I_C_DocLine_Sort C_DocLine_Sort) { set_ValueFromPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class, C_DocLine_Sort); } /** Set Document Line Sorting Preferences. @param C_DocLine_Sort_ID Document Line Sorting Preferences */ @Override public void setC_DocLine_Sort_ID (int C_DocLine_Sort_ID) { if (C_DocLine_Sort_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, Integer.valueOf(C_DocLine_Sort_ID)); } /** Get Document Line Sorting Preferences. @return Document Line Sorting Preferences */ @Override public int getC_DocLine_Sort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_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_BP_DocLine_Sort.java
1
请完成以下Java代码
public MReportColumn[] getColumns() { return m_columns; } // getColumns /** * List Info */ public void list() { System.out.println(toString()); if (m_columns == null) return; for (int i = 0; i < m_columns.length; i++) System.out.println("- " + m_columns[i].toString()); } // list
/*************************************************************************/ /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MReportColumnSet[") .append(get_ID()).append(" - ").append(getName()) .append ("]"); return sb.toString (); } } // MReportColumnSet
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportColumnSet.java
1
请完成以下Java代码
public Builder expiresAt(Instant expiresAt) { return claim(OAuth2TokenClaimNames.EXP, expiresAt); } /** * Sets the not before {@code (nbf)} claim, which identifies the time before which * the OAuth 2.0 Token MUST NOT be accepted for processing. * @param notBefore the time before which the OAuth 2.0 Token MUST NOT be accepted * for processing * @return the {@link Builder} */ public Builder notBefore(Instant notBefore) { return claim(OAuth2TokenClaimNames.NBF, notBefore); } /** * Sets the issued at {@code (iat)} claim, which identifies the time at which the * OAuth 2.0 Token was issued. * @param issuedAt the time at which the OAuth 2.0 Token was issued * @return the {@link Builder} */ public Builder issuedAt(Instant issuedAt) { return claim(OAuth2TokenClaimNames.IAT, issuedAt); } /** * Sets the ID {@code (jti)} claim, which provides a unique identifier for the * OAuth 2.0 Token. * @param jti the unique identifier for the OAuth 2.0 Token * @return the {@link Builder} */ public Builder id(String jti) { return claim(OAuth2TokenClaimNames.JTI, jti); } /** * Sets the claim. * @param name the claim name * @param value the claim value * @return the {@link Builder} */ public Builder claim(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.claims.put(name, value); return this; } /** * A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove. * @param claimsConsumer a {@code Consumer} of the claims * @return the {@link Builder} */ public Builder claims(Consumer<Map<String, Object>> claimsConsumer) { claimsConsumer.accept(this.claims); return this; } /** * Builds a new {@link OAuth2TokenClaimsSet}. * @return a {@link OAuth2TokenClaimsSet} */ public OAuth2TokenClaimsSet build() { Assert.notEmpty(this.claims, "claims cannot be empty"); // The value of the 'iss' claim is a String or URL (StringOrURI). // Attempt to convert to URL. Object issuer = this.claims.get(OAuth2TokenClaimNames.ISS); if (issuer != null) { URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class); if (convertedValue != null) { this.claims.put(OAuth2TokenClaimNames.ISS, convertedValue); } } return new OAuth2TokenClaimsSet(this.claims); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimsSet.java
1
请完成以下Java代码
public I_C_AggregationItem build() { final I_C_Aggregation aggregation = getC_Aggregation(); final I_C_AggregationItem aggregationItem = InterfaceWrapperHelper.newInstance(I_C_AggregationItem.class, aggregation); aggregationItem.setC_Aggregation(aggregation); aggregationItem.setType(getType()); aggregationItem.setAD_Column_ID(AdColumnId.toRepoId(getAD_Column_ID())); aggregationItem.setIncluded_Aggregation(getIncluded_Aggregation()); aggregationItem.setC_Aggregation_Attribute(getC_Aggregation_Attribute()); aggregationItem.setIncludeLogic(getIncludeLogic()); InterfaceWrapperHelper.save(aggregationItem); return aggregationItem; } public C_Aggregation_Builder end() { return parentBuilder; } @Override public String toString() { return ObjectUtils.toString(this); } public C_AggregationItem_Builder setC_Aggregation(final I_C_Aggregation aggregation) { this.aggregation = aggregation; return this; } private I_C_Aggregation getC_Aggregation() { Check.assumeNotNull(aggregation, "aggregation not null"); return aggregation; } public C_AggregationItem_Builder setType(final String type) { this.type = type; return this; } private String getType() { Check.assumeNotEmpty(type, "type not empty"); return type; } public C_AggregationItem_Builder setAD_Column(@Nullable final String columnName) { if (isBlank(columnName)) { this.adColumnId = null; }
else { this.adColumnId = Services.get(IADTableDAO.class).retrieveColumnId(adTableId, columnName); } return this; } private AdColumnId getAD_Column_ID() { return adColumnId; } public C_AggregationItem_Builder setIncluded_Aggregation(final I_C_Aggregation includedAggregation) { this.includedAggregation = includedAggregation; return this; } private I_C_Aggregation getIncluded_Aggregation() { return includedAggregation; } public C_AggregationItem_Builder setIncludeLogic(final String includeLogic) { this.includeLogic = includeLogic; return this; } private String getIncludeLogic() { return includeLogic; } public C_AggregationItem_Builder setC_Aggregation_Attribute(I_C_Aggregation_Attribute attribute) { this.attribute = attribute; return this; } private I_C_Aggregation_Attribute getC_Aggregation_Attribute() { return this.attribute; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_AggregationItem_Builder.java
1
请完成以下Java代码
public class Ticket { @Id private TicketId id; private String event; public Ticket() { } public Ticket(TicketId id, String event) { super(); this.id = id; this.event = event; } public TicketId getId() {
return id; } public void setId(TicketId id) { this.id = id; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\composite\key\data\Ticket.java
1