instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void removeEventListener(FlowableEventListener listenerToRemove) { commandExecutor.execute(new RemoveEventListenerCommand(listenerToRemove)); } @Override public void dispatchEvent(FlowableEvent event) { commandExecutor.execute(new DispatchEventCommand(event)); } @Override public CaseInstanceStartEventSubscriptionBuilder createCaseInstanceStartEventSubscriptionBuilder() { return new CaseInstanceStartEventSubscriptionBuilderImpl(this); } @Override public CaseInstanceStartEventSubscriptionModificationBuilder createCaseInstanceStartEventSubscriptionModificationBuilder() { return new CaseInstanceStartEventSubscriptionModificationBuilderImpl(this); } @Override public CaseInstanceStartEventSubscriptionDeletionBuilder createCaseInstanceStartEventSubscriptionDeletionBuilder() {
return new CaseInstanceStartEventSubscriptionDeletionBuilderImpl(this); } public EventSubscription registerCaseInstanceStartEventSubscription(CaseInstanceStartEventSubscriptionBuilderImpl builder) { return commandExecutor.execute(new RegisterCaseInstanceStartEventSubscriptionCmd(builder)); } public void migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(CaseInstanceStartEventSubscriptionModificationBuilderImpl builder) { commandExecutor.execute(new ModifyCaseInstanceStartEventSubscriptionCmd(builder)); } public void deleteCaseInstanceStartEventSubscriptions(CaseInstanceStartEventSubscriptionDeletionBuilderImpl builder) { commandExecutor.execute(new DeleteCaseInstanceStartEventSubscriptionCmd(builder)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnRuntimeServiceImpl.java
1
请完成以下Java代码
public int getC_Print_Job_Instructions_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID); } @Override public void setc_print_job_name (java.lang.String c_print_job_name) { set_ValueNoCheck (COLUMNNAME_c_print_job_name, c_print_job_name); } @Override public java.lang.String getc_print_job_name() { return (java.lang.String)get_Value(COLUMNNAME_c_print_job_name); } @Override public de.metas.printing.model.I_C_Print_Package getC_Print_Package() { return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class); } @Override public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package) { set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package); } @Override public void setC_Print_Package_ID (int C_Print_Package_ID) { if (C_Print_Package_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID)); } @Override public int getC_Print_Package_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID); } @Override public void setDateInvoiced (java.sql.Timestamp DateInvoiced) { set_ValueNoCheck (COLUMNNAME_DateInvoiced, DateInvoiced); } @Override public java.sql.Timestamp getDateInvoiced() { return get_ValueAsTimestamp(COLUMNNAME_DateInvoiced); } @Override public void setdocument (java.lang.String document) { set_ValueNoCheck (COLUMNNAME_document, document); } @Override public java.lang.String getdocument() { return (java.lang.String)get_Value(COLUMNNAME_document); } @Override public void setDocumentNo (java.lang.String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); }
@Override public java.lang.String getDocumentNo() { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } @Override public void setFirstname (java.lang.String Firstname) { set_ValueNoCheck (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return (java.lang.String)get_Value(COLUMNNAME_Firstname); } @Override public void setGrandTotal (java.math.BigDecimal GrandTotal) { set_ValueNoCheck (COLUMNNAME_GrandTotal, GrandTotal); } @Override public java.math.BigDecimal getGrandTotal() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_GrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setLastname (java.lang.String Lastname) { set_ValueNoCheck (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return (java.lang.String)get_Value(COLUMNNAME_Lastname); } @Override public void setprintjob (java.lang.String printjob) { set_ValueNoCheck (COLUMNNAME_printjob, printjob); } @Override public java.lang.String getprintjob() { return (java.lang.String)get_Value(COLUMNNAME_printjob); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_RV_Prt_Bericht_Statistik_List_Per_Org.java
1
请完成以下Java代码
public GridWorkbench getGridWorkbench() { return m_mWorkbench; } // metas-2009_0021_AP1_CR064 @Override public void requestFocus() { m_curGC.requestFocus(); } @Override public boolean requestFocusInWindow() { return m_curGC.requestFocusInWindow(); } public GridController getCurrentGridController() { return this.m_curGC; } public final AppsAction getIgnoreAction() { return aIgnore; } public final boolean isAlignVerticalTabsWithHorizontalTabs() { return alignVerticalTabsWithHorizontalTabs; } /** * For a given component, it removes component's key bindings (defined in ancestor's map) that this panel also have defined. * * The main purpose of doing this is to make sure menu/toolbar key bindings will not be intercepted by given component, so panel's key bindings will work when given component is embedded in our * panel. * * @param comp component or <code>null</code> */ public final void removeAncestorKeyBindingsOf(final JComponent comp, final Predicate<KeyStroke> isRemoveKeyStrokePredicate) { // Skip null components (but tolerate that) if (comp == null) { return; } // Get component's ancestors input map (the map which defines which key bindings will work when pressed in a component which is included inside this component). final InputMap compInputMap = comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); // NOTE: don't check and exit if "compInputMap.size() <= 0" because it might be that this map is empty but the key bindings are defined in it's parent map. // Iterate all key bindings for our panel and remove those which are also present in component's ancestor map. final InputMap thisInputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); for (final KeyStroke key : thisInputMap.allKeys())
{ // Check if the component has a key binding defined for our panel key binding. final Object compAction = compInputMap.get(key); if (compAction == null) { continue; } if (isRemoveKeyStrokePredicate != null && !isRemoveKeyStrokePredicate.apply(key)) { continue; } // NOTE: Instead of removing it, it is much more safe to bind it to "none", // to explicitly say to not consume that key event even if is defined in some parent map of this input map. compInputMap.put(key, "none"); if (log.isDebugEnabled()) { log.debug("Removed " + key + "->" + compAction + " which in this component is binded to " + thisInputMap.get(key) + "\n\tThis panel: " + this + "\n\tComponent: " + comp); } } } } // APanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\APanel.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { ensureVariablesInitialized(); checkQueryOk(); return commandContext .getExternalTaskManager() .findExternalTaskCountByQueryCriteria(this); } @Override public List<ExternalTask> executeList(CommandContext commandContext, Page page) { ensureVariablesInitialized(); checkQueryOk(); return commandContext .getExternalTaskManager() .findExternalTasksByQueryCriteria(this); } public List<String> executeIdsList(CommandContext commandContext) { ensureVariablesInitialized(); checkQueryOk(); return commandContext .getExternalTaskManager() .findExternalTaskIdsByQueryCriteria(this); } @Override public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) { checkQueryOk(); return commandContext .getExternalTaskManager() .findDeploymentIdMappingsByQueryCriteria(this); } public String getExternalTaskId() { return externalTaskId; } public String getWorkerId() { return workerId; } public Date getLockExpirationBefore() { return lockExpirationBefore; } public Date getLockExpirationAfter() { return lockExpirationAfter; } public String getTopicName() { return topicName; } public Boolean getLocked() { return locked; } public Boolean getNotLocked() { return notLocked; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String[] getProcessDefinitionKeys() { return processDefinitionKeys; } public String getProcessDefinitionId() { return processDefinitionId; }
public String getProcessDefinitionName() { return processDefinitionName; } public String getProcessDefinitionNameLike() { return processDefinitionNameLike; } public String getActivityId() { return activityId; } public SuspensionState getSuspensionState() { return suspensionState; } public Boolean getRetriesLeft() { return retriesLeft; } public Date getNow() { return ClockUtil.getCurrentTime(); } protected void ensureVariablesInitialized() { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers(); String dbType = processEngineConfiguration.getDatabaseType(); for(QueryVariableValue var : variables) { var.initialize(variableSerializers, dbType); } } public List<QueryVariableValue> getVariables() { return variables; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java
1
请完成以下Java代码
public WindowId getWindowId() { return WINDOW_ID; } @Override public void put(final IView view) { throw new UnsupportedOperationException(); } @Nullable @Override public PaymentsToReconcileView getByIdOrNull(@NonNull final ViewId paymentsToReconcileViewId) { final ViewId bankStatementReconciliationViewId = toBankStatementReconciliationViewId(paymentsToReconcileViewId); final BankStatementReconciliationView bankStatementReconciliationView = banksStatementReconciliationViewFactory.getByIdOrNull(bankStatementReconciliationViewId); return bankStatementReconciliationView != null ? bankStatementReconciliationView.getPaymentsToReconcileView() : null; } private static ViewId toBankStatementReconciliationViewId(@NonNull final ViewId paymentsToReconcileViewId) { return paymentsToReconcileViewId.withWindowId(BankStatementReconciliationViewFactory.WINDOW_ID); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { // nothing }
@Override public Stream<IView> streamAllViews() { return banksStatementReconciliationViewFactory.streamAllViews() .map(BankStatementReconciliationView::cast) .map(BankStatementReconciliationView::getPaymentsToReconcileView); } @Override public void invalidateView(final ViewId paymentsToReconcileViewId) { final PaymentsToReconcileView paymentsToReconcileView = getByIdOrNull(paymentsToReconcileViewId); if (paymentsToReconcileView != null) { paymentsToReconcileView.invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentsToReconcileViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
private MaterialDescriptor createMaterialDescriptorForPPOrder(@NonNull final PPOrder ppOrder) { return MaterialDescriptor.builder() .date(ppOrder.getPpOrderData().getDatePromised()) .productDescriptor(ppOrder.getPpOrderData().getProductDescriptor()) .quantity(ppOrder.getPpOrderData().getQtyOpen()) .warehouseId(ppOrder.getPpOrderData().getWarehouseId()) .build(); } @NonNull private ProductionDetail createProductionDetailForPPOrder( @NonNull final PPOrderCreatedEvent ppOrderEvent) { final PPOrder ppOrder = ppOrderEvent.getPpOrder(); return ProductionDetail.builder() .advised(Flag.FALSE_DONT_UPDATE) .pickDirectlyIfFeasible(Flag.of(ppOrderEvent.isDirectlyPickIfFeasible())) .qty(ppOrder.getPpOrderData().getQtyRequired()) .plantId(ppOrder.getPpOrderData().getPlantId()) .workstationId(ppOrder.getPpOrderData().getWorkstationId()) .productPlanningId(ppOrder.getPpOrderData().getProductPlanningId()) .ppOrderRef(PPOrderRef.ofPPOrderId(ppOrder.getPpOrderId())) .ppOrderDocStatus(ppOrder.getDocStatus()) .build(); } @NonNull private Optional<DemandDetail> retrieveDemandDetail(@NonNull final PPOrderData ppOrderData)
{ if (ppOrderData.getShipmentScheduleId() <= 0) { return Optional.empty(); } final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery. ofShipmentScheduleId(ppOrderData.getShipmentScheduleId()); final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.builder() .productId(ppOrderData.getProductDescriptor().getProductId()) .warehouseId(ppOrderData.getWarehouseId()) .build(); final CandidatesQuery candidatesQuery = CandidatesQuery.builder() .type(CandidateType.DEMAND) .materialDescriptorQuery(materialDescriptorQuery) .demandDetailsQuery(demandDetailsQuery) .build(); return candidateRepositoryRetrieval.retrieveLatestMatch(candidatesQuery) .map(Candidate::getDemandDetail); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\pporder\PPOrderCreatedHandler.java
2
请完成以下Java代码
public OAuth2TokenValidatorResult validate(Jwt token) { if (token.getClaim(this.claimName) == null) { return OAuth2TokenValidatorResult .failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " must have a value", "https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure")); } return OAuth2TokenValidatorResult.success(); } OAuth2TokenValidator<Jwt> isEqualTo(String value) { return and(satisfies((jwt) -> value.equals(jwt.getClaim(this.claimName)))); } OAuth2TokenValidator<Jwt> satisfies(Predicate<Jwt> predicate) { return and((jwt) -> { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " is not valid", "https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure");
if (predicate.test(jwt)) { return OAuth2TokenValidatorResult.success(); } return OAuth2TokenValidatorResult.failure(error); }); } OAuth2TokenValidator<Jwt> and(OAuth2TokenValidator<Jwt> that) { return (jwt) -> { OAuth2TokenValidatorResult result = validate(jwt); return (result.hasErrors()) ? result : that.validate(jwt); }; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtValidators.java
1
请完成以下Java代码
public void consume(final I_AD_UI_Column uiColumn, final I_AD_UI_Section parent) { logger.debug("Generated in memory {} for {}", uiColumn, parent); section2columns.put(parent, uiColumn); } @Override public List<I_AD_UI_Column> getUIColumns(final I_AD_UI_Section uiSection) { return section2columns.get(uiSection); } @Override public void consume(final I_AD_UI_ElementGroup uiElementGroup, final I_AD_UI_Column parent) { logger.debug("Generated in memory {} for {}", uiElementGroup, parent); column2elementGroups.put(parent, uiElementGroup); } @Override public List<I_AD_UI_ElementGroup> getUIElementGroups(final I_AD_UI_Column uiColumn) { return column2elementGroups.get(uiColumn); } @Override public void consume(final I_AD_UI_Element uiElement, final I_AD_UI_ElementGroup parent) { logger.debug("Generated in memory {} for {}", uiElement, parent); elementGroup2elements.put(parent, uiElement); } @Override public List<I_AD_UI_Element> getUIElements(final I_AD_UI_ElementGroup uiElementGroup) { return elementGroup2elements.get(uiElementGroup);
} @Override public List<I_AD_UI_Element> getUIElementsOfType(@NonNull final AdTabId adTabId, @NonNull final LayoutElementType layoutElementType) { return elementGroup2elements.values().stream() .filter(uiElement -> layoutElementType.getCode().equals(uiElement.getAD_UI_ElementType())) .collect(ImmutableList.toImmutableList()); } @Override public void consume(final I_AD_UI_ElementField uiElementField, final I_AD_UI_Element parent) { logger.debug("Generated in memory {} for {}", uiElementField, parent); element2elementFields.put(parent, uiElementField); } @Override public List<I_AD_UI_ElementField> getUIElementFields(final I_AD_UI_Element uiElement) { return element2elementFields.get(uiElement); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\InMemoryUIElementsProvider.java
1
请完成以下Java代码
public class PurchaseOrderItem { @ProductCheckDigit @NotNull @Pattern(regexp = "A-\\d{8}-\\d") private String productId; private String sourceWarehouse; private String destinationCountry; @AvailableChannel private String tenantChannel; private int numberOfIndividuals; private int numberOfPacks; private int itemsPerPack; @org.hibernate.validator.constraints.UUID private String clientUuid; public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getSourceWarehouse() { return sourceWarehouse; } public void setSourceWarehouse(String sourceWarehouse) { this.sourceWarehouse = sourceWarehouse; } public String getDestinationCountry() { return destinationCountry; } public void setDestinationCountry(String destinationCountry) { this.destinationCountry = destinationCountry; } public String getTenantChannel() { return tenantChannel; } public void setTenantChannel(String tenantChannel) { this.tenantChannel = tenantChannel; } public int getNumberOfIndividuals() { return numberOfIndividuals;
} public void setNumberOfIndividuals(int numberOfIndividuals) { this.numberOfIndividuals = numberOfIndividuals; } public int getNumberOfPacks() { return numberOfPacks; } public void setNumberOfPacks(int numberOfPacks) { this.numberOfPacks = numberOfPacks; } public int getItemsPerPack() { return itemsPerPack; } public void setItemsPerPack(int itemsPerPack) { this.itemsPerPack = itemsPerPack; } public String getClientUuid() { return clientUuid; } public void setClientUuid(String clientUuid) { this.clientUuid = clientUuid; } }
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\customstatefulvalidation\model\PurchaseOrderItem.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_DocType_Invoicing_Pool_ID (final int C_DocType_Invoicing_Pool_ID) { if (C_DocType_Invoicing_Pool_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocType_Invoicing_Pool_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_Invoicing_Pool_ID, C_DocType_Invoicing_Pool_ID); } @Override public int getC_DocType_Invoicing_Pool_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_Invoicing_Pool_ID); } @Override public void setIsOnDistinctICTypes (final boolean IsOnDistinctICTypes) { set_Value (COLUMNNAME_IsOnDistinctICTypes, IsOnDistinctICTypes); } @Override public boolean isOnDistinctICTypes() { return get_ValueAsBoolean(COLUMNNAME_IsOnDistinctICTypes); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @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 setNegative_Amt_C_DocType_ID (final int Negative_Amt_C_DocType_ID)
{ if (Negative_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, Negative_Amt_C_DocType_ID); } @Override public int getNegative_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Negative_Amt_C_DocType_ID); } @Override public void setPositive_Amt_C_DocType_ID (final int Positive_Amt_C_DocType_ID) { if (Positive_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, Positive_Amt_C_DocType_ID); } @Override public int getPositive_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Positive_Amt_C_DocType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Invoicing_Pool.java
1
请在Spring Boot框架中完成以下Java代码
public class RepositoryCheckBook { @Id @GeneratedValue private Long id; private String title; public RepositoryCheckBook() { } public RepositoryCheckBook(String title) { this.title = title; } public void setId(Long id) {
this.id = id; } public Long getId() { return id; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\insertableonly\repositorycheck\RepositoryCheckBook.java
2
请完成以下Java代码
protected Templates reloadFormattingTemplates() { final TransformerFactory transformerFactory = this.domXmlDataFormat.getTransformerFactory(); try (final InputStream formattingConfiguration = getFormattingConfiguration()) { if (formattingConfiguration == null) { throw LOG.unableToFindStripSpaceXsl(STRIP_SPACE_XSL); } return transformerFactory.newTemplates(new StreamSource(formattingConfiguration)); } catch (final IOException | TransformerConfigurationException ex) { throw LOG.unableToLoadFormattingTemplates(ex); } } /** * Set the {@link Templates} which used for creating the transformer. * @param formattingTemplates */ protected void setFormattingTemplates(Templates formattingTemplates) { this.formattingTemplates = formattingTemplates; } private InputStream getFormattingConfiguration() { final InputStream importedConfiguration = this.domXmlDataFormat.getFormattingConfiguration(); if (importedConfiguration != null) { return importedConfiguration; } // default strip-spaces.xsl return DomXmlDataFormatWriter.class.getClassLoader().getResourceAsStream(STRIP_SPACE_XSL); } /** * Returns a configured transformer to write XML and apply indentation (pretty-print) to the xml. * * @return the XML configured transformer * @throws SpinXmlElementException if no new transformer can be created */ protected Transformer getFormattingTransformer() { try {
Transformer transformer = formattingTemplates.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } } /** * Returns a configured transformer to write XML as is. * * @return the XML configured transformer * @throws SpinXmlElementException if no new transformer can be created */ protected Transformer getTransformer() { TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory(); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatWriter.java
1
请完成以下Java代码
public double getFree() { return NumberUtil.div(free, (1024 * 1024), 2); } public void setFree(double free) { this.free = free; } public double getUsed() { return NumberUtil.div(total - free, (1024 * 1024), 2); } public double getUsage() { return NumberUtil.mul(NumberUtil.div(total - free, total, 4), 100); } /** * 获取JDK名称 */ public String getName() { return ManagementFactory.getRuntimeMXBean().getVmName(); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; }
public String getHome() { return home; } public void setHome(String home) { this.home = home; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getStartTime() { return DateUtil.formatDateTime(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())); } public void setRunTime(String runTime) { this.runTime = runTime; } public String getRunTime() { long startTime = ManagementFactory.getRuntimeMXBean().getStartTime(); return DateUtil.formatBetween(DateUtil.current(false) - startTime); } }
repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Jvm.java
1
请完成以下Java代码
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; } public DmnTypeDefinition getTypeDefinition() { return typeDefinition; } public void setTypeDefinition(DmnTypeDefinition typeDefinition) { this.typeDefinition = typeDefinition; } public String getExpressionLanguage() { return expressionLanguage; } public void setExpressionLanguage(String expressionLanguage) { this.expressionLanguage = expressionLanguage; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } @Override public String toString() { return "DmnExpressionImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", typeDefinition=" + typeDefinition +
", expressionLanguage='" + expressionLanguage + '\'' + ", expression='" + expression + '\'' + '}'; } public void cacheCompiledScript(CompiledScript compiledScript) { this.cachedCompiledScript = compiledScript; } public CompiledScript getCachedCompiledScript() { return this.cachedCompiledScript; } public ElExpression getCachedExpression() { return this.cachedExpression; } public void setCachedExpression(ElExpression expression) { this.cachedExpression = expression; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnExpressionImpl.java
1
请完成以下Java代码
protected void unsubscribe(TopicSubscriptionImpl subscription) { subscriptions.remove(subscription); } public EngineClient getEngineClient() { return engineClient; } public List<TopicSubscription> getSubscriptions() { return subscriptions; } public boolean isRunning() { return isRunning.get(); } public void setBackoffStrategy(BackoffStrategy backOffStrategy) { this.backoffStrategy = backOffStrategy; } protected void runBackoffStrategy(FetchAndLockResponseDto fetchAndLockResponse) { try { List<ExternalTask> externalTasks = fetchAndLockResponse.getExternalTasks(); if (backoffStrategy instanceof ErrorAwareBackoffStrategy) { ErrorAwareBackoffStrategy errorAwareBackoffStrategy = ((ErrorAwareBackoffStrategy) backoffStrategy); ExternalTaskClientException exception = fetchAndLockResponse.getError(); errorAwareBackoffStrategy.reconfigure(externalTasks, exception); } else { backoffStrategy.reconfigure(externalTasks); } long waitTime = backoffStrategy.calculateBackoffTime(); suspend(waitTime); } catch (Throwable e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } } protected void suspend(long waitTime) { if (waitTime > 0 && isRunning.get()) { ACQUISITION_MONITOR.lock(); try { if (isRunning.get()) { IS_WAITING.await(waitTime, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) {
LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } finally { ACQUISITION_MONITOR.unlock(); } } } protected void resume() { ACQUISITION_MONITOR.lock(); try { IS_WAITING.signal(); } finally { ACQUISITION_MONITOR.unlock(); } } public void disableBackoffStrategy() { this.isBackoffStrategyDisabled.set(true); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionManager.java
1
请完成以下Java代码
private void initComponents() throws InstantiationException, IllegalAccessException { // 获取需要扫描的包名 String pkgName = getPackage(); // 获取包下所有类 List<Class<?>> classes = ClassUtil.getClasses(pkgName); if (CollectionUtils.isEmpty(classes)) { return; } // 遍历类 for (Class clazz : classes) { Field[] fields = clazz.getDeclaredFields(); if (fields==null || fields.length==0) { continue; } // 遍历成员变量 for (Field field : fields) { // 获取Field上的@InjectComponents注解 InjectComponents injectComponents = AnnotationUtil.getAnnotationValueByField(field, InjectComponents.class); if (injectComponents == null) { continue; } // 创建componentList对象 List<BaseComponent> componentList = initComponentList(injectComponents); // 赋值 setValueForField(clazz, field, componentList); } } } /** * 将ComponentList赋给ComponentList * @param clazz ComponentList所在类 * @param field ComponentList成员变量 * @param componentList 组件对象列表 */ private void setValueForField(Class clazz, Field field, List<BaseComponent> componentList) throws IllegalAccessException { // 获取Processor对象 Object processor = applicationContext.getBean(clazz); // 将field设为public field.setAccessible(true); // 赋值
field.set(processor, componentList); System.out.println(processor); System.out.println(componentList); System.out.println("---------------"); } /** * 初始化componentList * @param injectComponents componentList上的注解 */ private List<BaseComponent> initComponentList(InjectComponents injectComponents) throws IllegalAccessException, InstantiationException { List<BaseComponent> componentList = Lists.newArrayList(); // 获取Components Class[] componentClassList = injectComponents.value(); if (componentClassList == null || componentClassList.length <= 0) { return componentList; } // 遍历components for (Class<BaseComponent> componentClass : componentClassList) { // 获取IOC容器中的Component对象 BaseComponent componentInstance = applicationContext.getBean(componentClass); // 加入容器 componentList.add(componentInstance); } return componentList; } /** * 获取需要扫描的包名 */ private String getPackage() { PackageScan packageScan = AnnotationUtil.getAnnotationValueByClass(this.getClass(), PackageScan.class); return packageScan.value(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\init\InitComponentList.java
1
请完成以下Java代码
public String getScheduleConf() { return scheduleConf; } public void setScheduleConf(String scheduleConf) { this.scheduleConf = scheduleConf; } public String getMisfireStrategy() { return misfireStrategy; } public void setMisfireStrategy(String misfireStrategy) { this.misfireStrategy = misfireStrategy; } public String getExecutorRouteStrategy() { return executorRouteStrategy; } public void setExecutorRouteStrategy(String executorRouteStrategy) { this.executorRouteStrategy = executorRouteStrategy; } public String getExecutorHandler() { return executorHandler; } public void setExecutorHandler(String executorHandler) { this.executorHandler = executorHandler; } public String getExecutorParam() { return executorParam; } public void setExecutorParam(String executorParam) { this.executorParam = executorParam; } public String getExecutorBlockStrategy() { return executorBlockStrategy; } public void setExecutorBlockStrategy(String executorBlockStrategy) { this.executorBlockStrategy = executorBlockStrategy; } public int getExecutorTimeout() { return executorTimeout; } public void setExecutorTimeout(int executorTimeout) { this.executorTimeout = executorTimeout; } public int getExecutorFailRetryCount() { return executorFailRetryCount; } public void setExecutorFailRetryCount(int executorFailRetryCount) { this.executorFailRetryCount = executorFailRetryCount; } public String getGlueType() { return glueType; } public void setGlueType(String glueType) { this.glueType = glueType; } public String getGlueSource() { return glueSource; } public void setGlueSource(String glueSource) { this.glueSource = glueSource; } public String getGlueRemark() { return glueRemark; } public void setGlueRemark(String glueRemark) { this.glueRemark = glueRemark; }
public Date getGlueUpdatetime() { return glueUpdatetime; } public void setGlueUpdatetime(Date glueUpdatetime) { this.glueUpdatetime = glueUpdatetime; } public String getChildJobId() { return childJobId; } public void setChildJobId(String childJobId) { this.childJobId = childJobId; } public int getTriggerStatus() { return triggerStatus; } public void setTriggerStatus(int triggerStatus) { this.triggerStatus = triggerStatus; } public long getTriggerLastTime() { return triggerLastTime; } public void setTriggerLastTime(long triggerLastTime) { this.triggerLastTime = triggerLastTime; } public long getTriggerNextTime() { return triggerNextTime; } public void setTriggerNextTime(long triggerNextTime) { this.triggerNextTime = triggerNextTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java
1
请完成以下Java代码
public int getM_ShipmentSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID); } @Override public void setM_ShipmentSchedule_ExportAudit_Item_ID (final int M_ShipmentSchedule_ExportAudit_Item_ID) { if (M_ShipmentSchedule_ExportAudit_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java
1
请在Spring Boot框架中完成以下Java代码
public class X_MobileConfiguration extends org.compiere.model.PO implements I_MobileConfiguration, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1713061336L; /** Standard Constructor */ public X_MobileConfiguration (final Properties ctx, final int MobileConfiguration_ID, @Nullable final String trxName) { super (ctx, MobileConfiguration_ID, trxName); } /** Load Constructor */ public X_MobileConfiguration (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * DefaultAuthenticationMethod AD_Reference_ID=541848 * Reference name: MobileAuthenticationMethod */ public static final int DEFAULTAUTHENTICATIONMETHOD_AD_Reference_ID=541848; /** QR Code = QR_Code */ public static final String DEFAULTAUTHENTICATIONMETHOD_QRCode = "QR_Code"; /** User & Pass = UserPass */ public static final String DEFAULTAUTHENTICATIONMETHOD_UserPass = "UserPass"; @Override public void setDefaultAuthenticationMethod (final java.lang.String DefaultAuthenticationMethod)
{ set_Value (COLUMNNAME_DefaultAuthenticationMethod, DefaultAuthenticationMethod); } @Override public java.lang.String getDefaultAuthenticationMethod() { return get_ValueAsString(COLUMNNAME_DefaultAuthenticationMethod); } @Override public void setMobileConfiguration_ID (final int MobileConfiguration_ID) { if (MobileConfiguration_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileConfiguration_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileConfiguration_ID, MobileConfiguration_ID); } @Override public int getMobileConfiguration_ID() { return get_ValueAsInt(COLUMNNAME_MobileConfiguration_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileConfiguration.java
2
请完成以下Java代码
public final class UserDashboard { @Getter @NonNull private final UserDashboardId id; @NonNull private final ClientId adClientId; private final ImmutableMap<UserDashboardItemId, UserDashboardItem> _targetIndicatorItemsById; private final ImmutableMap<UserDashboardItemId, UserDashboardItem> _kpiItemsById; @Builder private UserDashboard( @NonNull final UserDashboardId id, @NonNull final ClientId adClientId, @NonNull @Singular final ImmutableList<UserDashboardItem> items) { this.id = id; this.adClientId = adClientId; this._targetIndicatorItemsById = items.stream() .filter(item -> item.getWidgetType() == DashboardWidgetType.TargetIndicator) .collect(ImmutableMap.toImmutableMap(UserDashboardItem::getId, item -> item)); this._kpiItemsById = items.stream() .filter(item -> item.getWidgetType() == DashboardWidgetType.KPI) .collect(ImmutableMap.toImmutableMap(UserDashboardItem::getId, item -> item)); } private ImmutableMap<UserDashboardItemId, UserDashboardItem> getItemsById(final DashboardWidgetType widgetType) { if (widgetType == DashboardWidgetType.TargetIndicator) { return _targetIndicatorItemsById; } else if (widgetType == DashboardWidgetType.KPI) { return _kpiItemsById; } else { throw new AdempiereException("Unknown widget type: " + widgetType); }
} public ImmutableSet<UserDashboardItemId> getItemIds(final DashboardWidgetType dashboardWidgetType) { return getItemsById(dashboardWidgetType).keySet(); } public Collection<UserDashboardItem> getItems(final DashboardWidgetType dashboardWidgetType) { return getItemsById(dashboardWidgetType).values(); } public UserDashboardItem getItemById( @NonNull final DashboardWidgetType dashboardWidgetType, @NonNull final UserDashboardItemId itemId) { final UserDashboardItem item = getItemsById(dashboardWidgetType).get(itemId); if (item == null) { throw new EntityNotFoundException("No " + dashboardWidgetType + " item found") .setParameter("itemId", itemId); } return item; } public void assertItemIdExists( @NonNull final DashboardWidgetType dashboardWidgetType, @NonNull final UserDashboardItemId itemId) { getItemById(dashboardWidgetType, itemId); // will fail if itemId does not exist } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboard.java
1
请完成以下Java代码
public void deleteOauth2ClientsByTenantId(TenantId tenantId) { log.trace("Executing deleteOauth2ClientsByTenantId, tenantId [{}]", tenantId); oauth2ClientDao.deleteByTenantId(tenantId.getId()); } @Override public PageData<OAuth2ClientInfo> findOAuth2ClientInfosByTenantId(TenantId tenantId, PageLink pageLink) { log.trace("Executing findOAuth2ClientInfosByTenantId tenantId=[{}]", tenantId); PageData<OAuth2Client> clients = oauth2ClientDao.findByTenantId(tenantId.getId(), pageLink); return clients.mapData(OAuth2ClientInfo::new); } @Override public List<OAuth2ClientInfo> findOAuth2ClientInfosByIds(TenantId tenantId, List<OAuth2ClientId> oAuth2ClientIds) { log.trace("Executing findQueueStatsByIds, tenantId [{}], oAuth2ClientIds [{}]", tenantId, oAuth2ClientIds); return oauth2ClientDao.findByIds(tenantId.getId(), oAuth2ClientIds) .stream() .map(OAuth2ClientInfo::new) .sorted(Comparator.comparing(OAuth2ClientInfo::getTitle)) .collect(Collectors.toList()); } @Override public boolean isPropagateOAuth2ClientToEdge(TenantId tenantId, OAuth2ClientId oAuth2ClientId) { log.trace("Executing isPropagateOAuth2ClientToEdge, tenantId [{}], oAuth2ClientId [{}]", tenantId, oAuth2ClientId); return oauth2ClientDao.isPropagateToEdge(tenantId, oAuth2ClientId.getId()); } @Override public void deleteByTenantId(TenantId tenantId) { deleteOauth2ClientsByTenantId(tenantId); }
@Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findOAuth2ClientById(tenantId, new OAuth2ClientId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(oauth2ClientDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteOAuth2ClientById(tenantId, (OAuth2ClientId) id); } @Override public EntityType getEntityType() { return EntityType.OAUTH2_CLIENT; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\oauth2\OAuth2ClientServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void add(final @NonNull ServiceRepairProjectCostCollector costCollector) { final QuotationLineKey lineKey = QuotationLineAggregator.extractKey(costCollector); final QuotationLineAggregator lineAggregator = lineAggregators.computeIfAbsent(lineKey, this::newLineAggregator); lineAggregator.add(costCollector); } private QuotationLineAggregator newLineAggregator(@NonNull final QuotationLineKey lineKey) { return QuotationLineAggregator.builder() .priceCalculator(priceCalculator) .key(lineKey) .build(); } @Override public void createOrderLines(@NonNull final OrderFactory orderFactory) {
lineAggregators.values() .forEach(lineAggregator -> lineAggregator.createOrderLines(orderFactory)); } @Override public Stream<Map.Entry<ServiceRepairProjectCostCollectorId, OrderAndLineId>> streamQuotationLineIdsIndexedByCostCollectorId() { return lineAggregators.values() .stream() .flatMap(QuotationLineAggregator::streamQuotationLineIdsIndexedByCostCollectorId); } @Override public GroupTemplate getGroupTemplate() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\OtherLinesAggregator.java
2
请完成以下Java代码
public boolean isAllowed(String uri, @Nullable Authentication authentication) { return isAllowed(null, uri, null, authentication); } /** * Determines whether the user represented by the supplied <tt>Authentication</tt> * object is allowed to invoke the supplied URI, with the given . * <p> * Note the default implementation of <tt>FilterInvocationSecurityMetadataSource</tt> * disregards the <code>contextPath</code> when evaluating which secure object * metadata applies to a given request URI, so generally the <code>contextPath</code> * is unimportant unless you are using a custom * <code>FilterInvocationSecurityMetadataSource</code>. * @param uri the URI excluding the context path * @param contextPath the context path (may be null, in which case a default value * will be used). * @param method the HTTP method (or null, for any method) * @param authentication the <tt>Authentication</tt> instance whose authorities should * be used in evaluation whether access should be granted. * @return true if access is allowed, false if denied */ @Override public boolean isAllowed(@Nullable String contextPath, String uri, @Nullable String method, @Nullable Authentication authentication) { Assert.notNull(uri, "uri parameter is required"); FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext); Collection<ConfigAttribute> attributes = this.securityInterceptor.obtainSecurityMetadataSource() .getAttributes(filterInvocation); if (attributes == null) { return (!this.securityInterceptor.isRejectPublicInvocations()); } if (authentication == null) {
return false; } try { this.securityInterceptor.getAccessDecisionManager().decide(authentication, filterInvocation, attributes); return true; } catch (AccessDeniedException ex) { logger.debug(LogMessage.format("%s denied for %s", filterInvocation, authentication), ex); return false; } } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\DefaultWebInvocationPrivilegeEvaluator.java
1
请完成以下Java代码
public class ChatRequest { @Schema(description = "模型ID,目前只支持gpt-3.5-turbo和gpt-3.5-turbo-0301", example = "gpt-3.5-turbo", required = true) private String model; @Schema(description = "要为其生成聊天内容的消息列表", required = true) private List<Message> messages; @Schema(description = "抽样温度,范围为0到2。较高的值(如0.8)会使输出更随机,而较低的值(如0.2)会使其更专注和确定性。") private Double temperature; @Schema(description = "top-p策略的概率阈值,只保留该阈值内的概率之和,范围为0到1。与抽样温度二选一。") private Double topP; @Schema(description = "每个输入消息要生成的聊天完成选择数量。") private Integer n; @Schema(description = "是否使用流式传输,如果设置,则会发送部分消息增量,就像ChatGPT一样。Token将作为仅包含数据的服务器发送事件发送,随着它们可用,流将由data: [DONE]消息终止。") private Boolean stream; @Schema(description = "最多允许生成的答案的最大标记数。默认情况下,模型可以返回的标记数为(4096 -提示标记数)。")
private Integer maxTokens; @Schema(description = "基于它们是否已在到目前为止的文本中出现,对新标记进行惩罚的数字,介于-2.0和2.0之间的数字。正值会增加模型谈论新话题的可能性。") private Double presencePenalty; @Schema(description = "基于它们到目前为止在文本中的现有频率对新标记进行惩罚的数字,介于-2.0和2.0之间的数字。正值会减少模型直接重复相同内容的可能性。") private Double frequencyPenalty; @Schema(description = "修改特定标记出现在完成中的可能性。接受将标记(由其在标记器中的标记ID指定)映射到-100到100的关联偏差值的json对象。在采样之前,数学上将偏差添加到模型生成的标志物中的logit。确切的效果将因模型而异,但值介于-1和1之间应该会减少或增加选择的可能性;值为-100或100应该导致禁止或专有选择相关标记。") private JSONObject logitBias; @Schema(description = "用于表示终端用户的唯一标识符,可帮助OpenAI监视和检测滥用。了解更多。") private String user; @Schema(description = "当达到以下任意一个序列时,API将停止生成进一步的标记。") private JSONArray stop; }
repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\vo\ChatRequest.java
1
请完成以下Java代码
protected MessageCorrelationBatchConfiguration createJobConfiguration(MessageCorrelationBatchConfiguration configuration, List<String> processIdsForJob) { return new MessageCorrelationBatchConfiguration( processIdsForJob, configuration.getMessageName(), configuration.getBatchId()); } @Override protected void postProcessJob(MessageCorrelationBatchConfiguration configuration, JobEntity job, MessageCorrelationBatchConfiguration jobConfiguration) { // if there is only one process instance to adjust, set its ID to the job so exclusive scheduling is possible if (jobConfiguration.getIds() != null && jobConfiguration.getIds().size() == 1) { job.setProcessInstanceId(jobConfiguration.getIds().get(0)); } } @Override public void executeHandler(MessageCorrelationBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { String batchId = batchConfiguration.getBatchId(); MessageCorrelationBuilderImpl correlationBuilder = new MessageCorrelationBuilderImpl(commandContext, batchConfiguration.getMessageName()); correlationBuilder.executionsOnly(); setVariables(batchId, correlationBuilder, commandContext); for (String id : batchConfiguration.getIds()) { correlationBuilder.processInstanceId(id); commandContext.executeWithOperationLogPrevented(new CorrelateAllMessageCmd(correlationBuilder, false, false)); }
} protected void setVariables(String batchId, MessageCorrelationBuilder correlationBuilder, CommandContext commandContext) { Map<String, ?> variables = null; if (batchId != null) { variables = VariableUtil.findBatchVariablesSerialized(batchId, commandContext); if (variables != null) { correlationBuilder.setVariables(new VariableMapImpl(new HashMap<>(variables))); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\message\MessageCorrelationBatchJobHandler.java
1
请完成以下Java代码
public List<CustomProperty> getCustomProperties() { return customProperties; } public void setCustomProperties(List<CustomProperty> customProperties) { this.customProperties = customProperties; } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public UserTask clone() { UserTask clone = new UserTask(); clone.setValues(this); return clone; } public void setValues(UserTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression());
setCandidateGroups(new ArrayList<String>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<String>(otherElement.getCandidateUsers())); setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks); setCustomUserIdentityLinks(otherElement.customUserIdentityLinks); formProperties = new ArrayList<FormProperty>(); if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) { for (FormProperty property : otherElement.getFormProperties()) { formProperties.add(property.clone()); } } taskListeners = new ArrayList<ActivitiListener>(); if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) { for (ActivitiListener listener : otherElement.getTaskListeners()) { taskListeners.add(listener.clone()); } } } @Override public void accept(ReferenceOverrider referenceOverrider) { referenceOverrider.override(this); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\UserTask.java
1
请完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(final String username) { email = username; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final User user = (User) obj; return email.equals(user.email); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\model\User.java
1
请完成以下Java代码
public I_M_HU_PI getM_LU_HU_PI() { return luPI; } @Override public I_M_HU_PI getM_TU_HU_PI() { return null; } @Override public boolean isInfiniteQtyTUsPerLU() { return true; } @Override public BigDecimal getQtyTUsPerLU() { return null; } @Override
public boolean isInfiniteQtyCUsPerTU() { return true; } @Override public BigDecimal getQtyCUsPerTU() { return null; } @Override public I_C_UOM getQtyCUsPerTU_UOM() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\LUPIPackingInfo.java
1
请完成以下Spring Boot application配置
management.endpoints.web.exposure.include=info,health,metrics # JPA and Security is not required for Metrics application spring.autoconfigure.exclude= org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, \ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, \ org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfigu
ration, \ org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration, \ org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration
repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\resources\application-metrics.properties
2
请完成以下Java代码
class DateFilterUtil { private static final AdMessageKey MSG_FILTER_CAPTION = AdMessageKey.of("Date"); public static DocumentFilterDescriptor createFilterDescriptor() { final DocumentFilterParamDescriptor.Builder standaloneParamDescriptor = DocumentFilterParamDescriptor.builder() .fieldName(DateFilterVO.PARAM_Date) .displayName(Services.get(IMsgBL.class).translatable(DateFilterVO.PARAM_Date)) .widgetType(DocumentFieldWidgetType.LocalDate) .operator(Operator.EQUAL) .mandatory(true) .showIncrementDecrementButtons(true); return DocumentFilterDescriptor.builder() .setFrequentUsed(true) .setFilterId(DateFilterVO.FILTER_ID) .setDisplayName(Services.get(IMsgBL.class).getTranslatableMsgText(MSG_FILTER_CAPTION)) .addParameter(standaloneParamDescriptor) .build(); } public static DocumentFilter createFilterToday() { return DocumentFilter.builder() .setFilterId(DateFilterVO.FILTER_ID) .setCaption(Services.get(IMsgBL.class).translatable(DateFilterVO.PARAM_Date)) .addParameter(DocumentFilterParam.ofNameOperatorValue(DateFilterVO.PARAM_Date, Operator.EQUAL, Env.getDate())) .build(); }
public DateFilterVO extractDateFilterVO(final DocumentFilterList filters) { return filters.getFilterById(DateFilterVO.FILTER_ID) .map(filter -> extractDateFilterVO(filter)) .orElse(DateFilterVO.EMPTY); } public DateFilterVO extractDateFilterVO(final DocumentFilter filter) { Check.assume(DateFilterVO.FILTER_ID.equals(filter.getFilterId()), "Filter ID is {} but it was {}", DateFilterVO.FILTER_ID, filter); return DateFilterVO.builder() .date(filter.getParameterValueAsLocalDateOrNull(DateFilterVO.PARAM_Date)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\DateFilterUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class ChangeLogConfigRepository { @NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class); @VisibleForTesting public static ChangeLogConfigRepository newInstanceForUnitTesting() { Adempiere.assertUnitTestMode(); return new ChangeLogConfigRepository(); } @NonNull public ImmutableList<ChangeLogConfig> retrieveChangeLogConfigList() { return queryBL.createQueryBuilder(I_AD_ChangeLog_Config.class) .addOnlyActiveRecordsFilter()
.create() .stream() .map(ChangeLogConfigRepository::fromRecord) .collect(ImmutableList.toImmutableList()); } private static ChangeLogConfig fromRecord(@NonNull final I_AD_ChangeLog_Config changeLogConfig) { return ChangeLogConfig.builder() .tableId(AdTableId.ofRepoId(changeLogConfig.getAD_Table_ID())) .keepChangeLogsDays(changeLogConfig.getKeepChangeLogsDays()) .orgId(OrgId.ofRepoId(changeLogConfig.getAD_Org_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\ChangeLogConfigRepository.java
2
请完成以下Java代码
public String getId() { return id; } /** * The date/time when this task was last updated. * All operations that fire {@link TaskListener#EVENTNAME_UPDATE} count as an update to the task. * Returns null if the task was never updated before (i.e. it was only created). * */ public Date getLastUpdated() { return lastUpdated; } /** Name or title of the task. */ public String getName() { return name; } /** * The {@link User.getId() userId} of the person responsible for this task. */ public String getOwner() { return owner; } /** * indication of how important/urgent this task is with a number between 0 and * 100 where higher values mean a higher priority and lower values mean lower * priority: [0..19] lowest, [20..39] low, [40..59] normal, [60..79] high * [80..100] highest */ public int getPriority() { return priority; } /** * Reference to the process definition or null if it is not related to a * process. */ public String getProcessDefinitionId() { return processDefinitionId; } /** * Reference to the process instance or null if it is not related to a process * instance. */ public String getProcessInstanceId() { return processInstanceId; }
/** * The id of the activity in the process defining this task or null if this is * not related to a process */ public String getTaskDefinitionKey() { return taskDefinitionKey; } /** * Return the id of the tenant this task belongs to. Can be <code>null</code> * if the task belongs to no single tenant. */ public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventName=" + eventName + ", name=" + name + ", createTime=" + createTime + ", lastUpdated=" + lastUpdated + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskDefinitionKey=" + taskDefinitionKey + ", assignee=" + assignee + ", owner=" + owner + ", description=" + description + ", dueDate=" + dueDate + ", followUpDate=" + followUpDate + ", priority=" + priority + ", deleteReason=" + deleteReason + ", caseDefinitionId=" + caseDefinitionId + ", caseExecutionId=" + caseExecutionId + ", caseInstanceId=" + caseInstanceId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\TaskEvent.java
1
请完成以下Java代码
public boolean addAll(Collection<T> values) { this.lock.writeLock().lock(); try { for (T value : values) { if (add(value).isEmpty()) { return false; } } return true; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> remove(T value) { this.lock.writeLock().lock(); try { LinkedListNode<T> linkedListNode = head.search(value); if (!linkedListNode.isEmpty()) { if (linkedListNode == tail) { tail = tail.getPrev(); } if (linkedListNode == head) { head = head.getNext(); } linkedListNode.detach(); size.decrementAndGet(); } return linkedListNode; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> removeTail() { this.lock.writeLock().lock(); try { LinkedListNode<T> oldTail = tail; if (oldTail == head) { tail = head = dummyNode; } else {
tail = tail.getPrev(); oldTail.detach(); } if (!oldTail.isEmpty()) { size.decrementAndGet(); } return oldTail; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> moveToFront(LinkedListNode<T> node) { return node.isEmpty() ? dummyNode : updateAndMoveToFront(node, node.getElement()); } public LinkedListNode<T> updateAndMoveToFront(LinkedListNode<T> node, T newValue) { this.lock.writeLock().lock(); try { if (node.isEmpty() || (this != (node.getListReference()))) { return dummyNode; } detach(node); add(newValue); return head; } finally { this.lock.writeLock().unlock(); } } private void detach(LinkedListNode<T> node) { if (node != tail) { node.detach(); if (node == head) { head = head.getNext(); } size.decrementAndGet(); } else { removeTail(); } } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\DoublyLinkedList.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomMFToExternalSystemMessageSender { private final RabbitTemplate rabbitTemplate; private final Queue queue; public CustomMFToExternalSystemMessageSender( @NonNull final RabbitTemplate rabbitTemplate, @NonNull @Qualifier(QUEUE_NAME_MF_TO_ES_CUSTOM) final Queue queue ) { this.rabbitTemplate = rabbitTemplate; this.queue = queue; } public void send(@NonNull final JsonExternalSystemMessage externalSystemMessage) { final byte[] messageAsBytes; try
{ messageAsBytes = JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsBytes(externalSystemMessage); } catch (final JsonProcessingException e) { throw new AdempiereException("Exception serializing externalSystemRequest", e) .appendParametersToMessage() .setParameter("externalSystemRequest", externalSystemMessage); } final MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentEncoding(StandardCharsets.UTF_8.displayName()); messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON); rabbitTemplate.convertAndSend(queue.getName(), new Message(messageAsBytes, messageProperties)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmq\custom\CustomMFToExternalSystemMessageSender.java
2
请完成以下Java代码
public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Datum. @param ValueDate Datum */ @Override public void setValueDate (java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); } /** Get Datum. @return Datum */ @Override public java.sql.Timestamp getValueDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValueDate); } /** Set Zahlwert. @param ValueNumber
Numeric Value */ @Override public void setValueNumber (java.math.BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } /** Get Zahlwert. @return Numeric Value */ @Override public java.math.BigDecimal getValueNumber () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeInstance.java
1
请在Spring Boot框架中完成以下Java代码
public BpmnInterface getInterface() { return bpmnInterface; } public void setInterface(BpmnInterface bpmnInterface) { this.bpmnInterface = bpmnInterface; } public MessageDefinition getInMessage() { return inMessage; } public void setInMessage(MessageDefinition inMessage) { this.inMessage = inMessage; } public MessageDefinition getOutMessage() {
return outMessage; } public void setOutMessage(MessageDefinition outMessage) { this.outMessage = outMessage; } public OperationImplementation getImplementation() { return implementation; } public void setImplementation(OperationImplementation implementation) { this.implementation = implementation; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\webservice\Operation.java
2
请完成以下Java代码
public Criteria andCouponStatusNotIn(List<Integer> values) { addCriterion("coupon_status not in", values, "couponStatus"); return (Criteria) this; } public Criteria andCouponStatusBetween(Integer value1, Integer value2) { addCriterion("coupon_status between", value1, value2, "couponStatus"); return (Criteria) this; } public Criteria andCouponStatusNotBetween(Integer value1, Integer value2) { addCriterion("coupon_status not between", value1, value2, "couponStatus"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; }
protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsIntegrationConsumeSettingExample.java
1
请完成以下Java代码
public class BatchingApp { static void simpleProcessing() throws Exception { final Path testPath = Paths.get("./testio.txt"); testPath.toFile().createNewFile(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool(100); Set<Future> futures = new HashSet<>(); for (int i = 0; i < 50000; i++) { futures.add(executorService.submit(() -> { try { Files.write(testPath, Collections.singleton(Thread.currentThread().getName()), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } })); } long start = System.currentTimeMillis(); for (Future future : futures) { future.get(); } System.out.println("Time: " + (System.currentTimeMillis() - start)); executorService.shutdown(); } static void batchedProcessing() throws Exception { final Path testPath = Paths.get("./testio.txt"); testPath.toFile().createNewFile();
SmartBatcher batcher = new SmartBatcher(10, strings -> { List<String> content = new ArrayList<>(strings); content.add("-----Batch Operation-----"); try { Files.write(testPath, content, StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } }); for (int i = 0; i < 50000; i++) { batcher.submit(Thread.currentThread().getName() + "-1"); } long start = System.currentTimeMillis(); while (!batcher.finished()) { Thread.sleep(10); } System.out.println("Time: " + (System.currentTimeMillis() - start)); } public static void main(String[] args) throws Exception { // simpleProcessing(); batchedProcessing(); } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\smartbatching\BatchingApp.java
1
请完成以下Java代码
public String getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link String } * */ public void setTp(String value) { this.tp = value; } /** * Gets the value of the dt property. * * @return * possible object is * {@link DateAndDateTimeChoice }
* */ public DateAndDateTimeChoice getDt() { return dt; } /** * Sets the value of the dt property. * * @param value * allowed object is * {@link DateAndDateTimeChoice } * */ public void setDt(DateAndDateTimeChoice value) { this.dt = 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\ProprietaryDate2.java
1
请在Spring Boot框架中完成以下Java代码
public IntegrationContextBuilder integrationContextBuilder( ExtensionsVariablesMappingProvider variablesMappingProvider, ExpressionManager expressionManager ) { return new IntegrationContextBuilder(variablesMappingProvider, expressionManager); } @Bean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME) @ConditionalOnMissingBean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME) public DefaultServiceTaskBehavior defaultServiceTaskBehavior( ApplicationContext applicationContext, IntegrationContextBuilder integrationContextBuilder, VariablesPropagator variablesPropagator ) { return new DefaultServiceTaskBehavior(applicationContext, integrationContextBuilder, variablesPropagator); } @Bean @ConditionalOnMissingBean public ExtensionsVariablesMappingProvider variablesMappingProvider( ProcessExtensionService processExtensionService, ExpressionResolver expressionResolver,
VariableParsingService variableParsingService ) { return new ExtensionsVariablesMappingProvider( processExtensionService, expressionResolver, variableParsingService ); } @Bean @ConditionalOnMissingBean public VariablesPropagator variablesPropagator(VariablesCalculator variablesCalculator) { return new VariablesPropagator(variablesCalculator); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ConnectorsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public java.lang.String getImportErrorMsg() { return get_ValueAsString(COLUMNNAME_ImportErrorMsg); } @Override public void setJSONValue (final @Nullable java.lang.String JSONValue) { set_Value (COLUMNNAME_JSONValue, JSONValue); } @Override public java.lang.String getJSONValue() { return get_ValueAsString(COLUMNNAME_JSONValue); }
@Override public void setS_FailedTimeBooking_ID (final int S_FailedTimeBooking_ID) { if (S_FailedTimeBooking_ID < 1) set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, null); else set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, S_FailedTimeBooking_ID); } @Override public int getS_FailedTimeBooking_ID() { return get_ValueAsInt(COLUMNNAME_S_FailedTimeBooking_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_FailedTimeBooking.java
2
请完成以下Java代码
public static ExternalSystemRabbitMQConfigId ofRepoId(final int repoId) { return new ExternalSystemRabbitMQConfigId(repoId); } @Nullable public static ExternalSystemRabbitMQConfigId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new ExternalSystemRabbitMQConfigId(repoId) : null; } public static ExternalSystemRabbitMQConfigId cast(@NonNull final IExternalSystemChildConfigId id) { return (ExternalSystemRabbitMQConfigId)id; }
@JsonValue public int toJson() { return getRepoId(); } private ExternalSystemRabbitMQConfigId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_Config_RabbitMQ_HTTP_ID"); } @Override public ExternalSystemType getType() { return ExternalSystemType.RabbitMQ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmqhttp\ExternalSystemRabbitMQConfigId.java
1
请完成以下Java代码
public int getM_Replenish_ID() { return get_ValueAsInt(COLUMNNAME_M_Replenish_ID); } @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setOrgValue (java.lang.String OrgValue) { set_Value (COLUMNNAME_OrgValue, OrgValue); } @Override public java.lang.String getOrgValue() { return (java.lang.String)get_Value(COLUMNNAME_OrgValue); } @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() {
return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** * ReplenishType AD_Reference_ID=164 * Reference name: M_Replenish Type */ public static final int REPLENISHTYPE_AD_Reference_ID=164; /** Maximalbestand beibehalten = 2 */ public static final String REPLENISHTYPE_MaximalbestandBeibehalten = "2"; /** Manuell = 0 */ public static final String REPLENISHTYPE_Manuell = "0"; /** Bei Unterschreitung Minimalbestand = 1 */ public static final String REPLENISHTYPE_BeiUnterschreitungMinimalbestand = "1"; /** Custom = 9 */ public static final String REPLENISHTYPE_Custom = "9"; /** Zuk?nftigen Bestand sichern = 7 */ public static final String REPLENISHTYPE_ZukNftigenBestandSichern = "7"; @Override public void setReplenishType (java.lang.String ReplenishType) { set_Value (COLUMNNAME_ReplenishType, ReplenishType); } @Override public java.lang.String getReplenishType() { return (java.lang.String)get_Value(COLUMNNAME_ReplenishType); } @Override public void setTimeToMarket (int TimeToMarket) { set_Value (COLUMNNAME_TimeToMarket, Integer.valueOf(TimeToMarket)); } @Override public int getTimeToMarket() { return get_ValueAsInt(COLUMNNAME_TimeToMarket); } @Override public void setWarehouseValue (java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return (java.lang.String)get_Value(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Replenish.java
1
请完成以下Java代码
public void addFacetCollector(final IFacetCollector<ModelType> facetCollector) { Check.assumeNotNull(facetCollector, "facetCollector not null"); facetCollectors.add(facetCollector); } /** @return true if this composite has at least one collector */ public boolean hasCollectors() { return !facetCollectors.isEmpty(); } @Override public IFacetCollectorResult<ModelType> collect(final FacetCollectorRequestBuilder<ModelType> request) { final FacetCollectorResult.Builder<ModelType> aggregatedResult = FacetCollectorResult.builder(); for (final IFacetCollector<ModelType> facetCollector : facetCollectors) { try { final IFacetCollectorResult<ModelType> result = facetCollector.collect(request); aggregatedResult.addFacetCollectorResult(result); } catch (Exception e) {
final AdempiereException ex = new AdempiereException("Failed to collect facets from collector" + "\n Collector: " + facetCollector + "\n Request: " + request , e); logger.warn("Skip collector because it failed", ex); } } return aggregatedResult.build(); } @Override public List<IFacetCategory> getAllFacetCategories() { // NOTE: teoretically we could cache this list, but i am thinking to Composite in Composite case, on which, caching approach will fail. final ImmutableList.Builder<IFacetCategory> aggregatedFacetCategories = ImmutableList.builder(); for (final IFacetCollector<ModelType> facetCollector : facetCollectors) { final List<IFacetCategory> facetCategories = facetCollector.getAllFacetCategories(); facetCategories.addAll(facetCategories); } return aggregatedFacetCategories.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\CompositeFacetCollector.java
1
请完成以下Java代码
public class X_C_Phonecall_Schema extends org.compiere.model.PO implements I_C_Phonecall_Schema, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -168721881L; /** Standard Constructor */ public X_C_Phonecall_Schema (Properties ctx, int C_Phonecall_Schema_ID, String trxName) { super (ctx, C_Phonecall_Schema_ID, trxName); /** if (C_Phonecall_Schema_ID == 0) { setC_Phonecall_Schema_ID (0); setName (null); } */ } /** Load Constructor */ public X_C_Phonecall_Schema (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Anrufliste. @param C_Phonecall_Schema_ID Anrufliste */ @Override
public void setC_Phonecall_Schema_ID (int C_Phonecall_Schema_ID) { if (C_Phonecall_Schema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Phonecall_Schema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Phonecall_Schema_ID, Integer.valueOf(C_Phonecall_Schema_ID)); } /** Get Anrufliste. @return Anrufliste */ @Override public int getC_Phonecall_Schema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Phonecall_Schema_ID); if (ii == null) return 0; return ii.intValue(); } /** 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_Phonecall_Schema.java
1
请完成以下Java代码
public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTrxAmt (final @Nullable BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * TrxType AD_Reference_ID=215 * Reference name: C_Payment Trx Type */ public static final int TRXTYPE_AD_Reference_ID=215; /** Sales = S */ public static final String TRXTYPE_Sales = "S"; /** DelayedCapture = D */ public static final String TRXTYPE_DelayedCapture = "D"; /** CreditPayment = C */ public static final String TRXTYPE_CreditPayment = "C"; /** VoiceAuthorization = F */ public static final String TRXTYPE_VoiceAuthorization = "F"; /** Authorization = A */ public static final String TRXTYPE_Authorization = "A"; /** Void = V */ public static final String TRXTYPE_Void = "V"; /** Rückzahlung = R */ public static final String TRXTYPE_Rueckzahlung = "R"; @Override public void setTrxType (final @Nullable java.lang.String TrxType)
{ set_Value (COLUMNNAME_TrxType, TrxType); } @Override public java.lang.String getTrxType() { return get_ValueAsString(COLUMNNAME_TrxType); } @Override public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java
1
请完成以下Java代码
public CountryId getCountryId() { return CoalesceUtil.coalesceSuppliersNotNull( // first, try the contract's location from the tine the contract was created () -> { final I_C_Location billLocationValue = getC_Flatrate_Term().getBill_Location_Value(); return billLocationValue != null ? CountryId.ofRepoId(billLocationValue.getC_Country_ID()) : null; }, // second, try the current C_Location of the C_BPartner_Location () -> { final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class); return bPartnerDAO.getCountryId(BPartnerLocationId.ofRepoId(getC_Flatrate_Term().getBill_BPartner_ID(), getC_Flatrate_Term().getBill_Location_ID())); } ); } @Override public I_M_PriceList_Version getM_PriceList_Version() { return _priceListVersion; } @Override public PricingSystemId getPricingSystemId() { PricingSystemId pricingSystemId = _pricingSystemId; if (pricingSystemId == null) { pricingSystemId = _pricingSystemId = PricingSystemId.ofRepoId(getC_Flatrate_Term().getM_PricingSystem_ID()); } return pricingSystemId; } @Override public I_C_Flatrate_Term getC_Flatrate_Term() { if (_flatrateTerm == null)
{ _flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID()); // shouldn't be null because we prevent even material-tracking purchase orders without a flatrate term. Check.errorIf(_flatrateTerm == null, "M_Material_Tracking {} has no flatrate term", materialTracking); } return _flatrateTerm; } @Override public String getInvoiceRule() { if (!_invoiceRuleSet) { // // Try getting the InvoiceRule from Flatrate Term final I_C_Flatrate_Term flatrateTerm = getC_Flatrate_Term(); final String invoiceRule = flatrateTerm .getC_Flatrate_Conditions() .getInvoiceRule(); Check.assumeNotEmpty(invoiceRule, "Unable to retrieve invoiceRule from materialTracking {}", materialTracking); _invoiceRule = invoiceRule; _invoiceRuleSet = true; } return _invoiceRule; } /* package */void setM_PriceList_Version(final I_M_PriceList_Version priceListVersion) { _priceListVersion = priceListVersion; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingAsVendorInvoicingInfo.java
1
请完成以下Java代码
public void setQtyToOrder (java.math.BigDecimal QtyToOrder) { set_Value (COLUMNNAME_QtyToOrder, QtyToOrder); } /** Get Quantity to Order. @return Quantity to Order */ @Override public java.math.BigDecimal getQtyToOrder () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity to Order (TU). @param QtyToOrder_TU Quantity to Order (TU) */ @Override
public void setQtyToOrder_TU (java.math.BigDecimal QtyToOrder_TU) { set_Value (COLUMNNAME_QtyToOrder_TU, QtyToOrder_TU); } /** Get Quantity to Order (TU). @return Quantity to Order (TU) */ @Override public java.math.BigDecimal getQtyToOrder_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder_TU); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate.java
1
请完成以下Java代码
public class UnknownHostExceptionHandling { public static int getResponseCode(String hostname) throws IOException { URL url = null; try { url = new URI(hostname.trim()).toURL(); } catch (URISyntaxException e) { throw new IOException(e); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); int resCode = -1; try { resCode = con.getResponseCode(); } catch (UnknownHostException e){ con.disconnect();
} return resCode; } public static int getResponseCodeUnhandled(String hostname) throws IOException { URL url = null; try { url = new URI(hostname.trim()).toURL(); } catch (URISyntaxException e) { throw new IOException(e); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); int resCode = con.getResponseCode(); return resCode; } }
repos\tutorials-master\core-java-modules\core-java-exceptions\src\main\java\com\baeldung\exceptions\unknownhostexception\UnknownHostExceptionHandling.java
1
请完成以下Java代码
public static OrderAndLineId ofRepoIds(@NonNull final OrderId orderId, final int orderLineRepoId) { return new OrderAndLineId(orderId, OrderLineId.ofRepoId(orderLineRepoId)); } public static OrderAndLineId of(final OrderId orderId, final OrderLineId orderLineId) { return new OrderAndLineId(orderId, orderLineId); } @Nullable public static OrderAndLineId ofNullable(@Nullable final OrderId orderId, @Nullable final OrderLineId orderLineId) { return orderId != null && orderLineId != null ? new OrderAndLineId(orderId, orderLineId) : null; } public static Optional<OrderAndLineId> optionalOfRepoIds(final int orderRepoId, final int orderLineRepoId) { return Optional.ofNullable(ofRepoIdsOrNull(orderRepoId, orderLineRepoId)); } public static int toOrderRepoId(@Nullable final OrderAndLineId orderAndLineId) { return getOrderRepoIdOr(orderAndLineId, -1); } public static int getOrderRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue) { return orderAndLineId != null ? orderAndLineId.getOrderRepoId() : defaultValue; } public static int toOrderLineRepoId(@Nullable final OrderAndLineId orderAndLineId) { return getOrderLineRepoIdOr(orderAndLineId, -1); } public static int getOrderLineRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue) { return orderAndLineId != null ? orderAndLineId.getOrderLineRepoId() : defaultValue; } public static Set<Integer> getOrderLineRepoIds(final Collection<OrderAndLineId> orderAndLineIds) { return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineRepoId).collect(ImmutableSet.toImmutableSet()); } public static Set<OrderId> getOrderIds(final Collection<OrderAndLineId> orderAndLineIds) { return orderAndLineIds.stream().map(OrderAndLineId::getOrderId).collect(ImmutableSet.toImmutableSet()); } public static Set<OrderLineId> getOrderLineIds(final Collection<OrderAndLineId> orderAndLineIds) { return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet()); } OrderId orderId; OrderLineId orderLineId;
private OrderAndLineId(@NonNull final OrderId orderId, @NonNull final OrderLineId orderLineId) { this.orderId = orderId; this.orderLineId = orderLineId; } public int getOrderRepoId() { return orderId.getRepoId(); } public int getOrderLineRepoId() { return orderLineId.getRepoId(); } public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2) { return Objects.equals(o1, o2); } @JsonValue public String toJson() { return orderId.getRepoId() + "_" + orderLineId.getRepoId(); } @JsonCreator public static OrderAndLineId ofJson(@NonNull String json) { try { final int idx = json.indexOf("_"); return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1))); } catch (Exception ex) { throw new AdempiereException("Invalid JSON: " + json, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java
1
请在Spring Boot框架中完成以下Java代码
public IdentityLinkDataManager getIdentityLinkDataManager() { return identityLinkDataManager; } public IdentityLinkServiceConfiguration setIdentityLinkDataManager(IdentityLinkDataManager identityLinkDataManager) { this.identityLinkDataManager = identityLinkDataManager; return this; } public HistoricIdentityLinkDataManager getHistoricIdentityLinkDataManager() { return historicIdentityLinkDataManager; } public IdentityLinkServiceConfiguration setHistoricIdentityLinkDataManager(HistoricIdentityLinkDataManager historicIdentityLinkDataManager) { this.historicIdentityLinkDataManager = historicIdentityLinkDataManager; return this; } public IdentityLinkEntityManager getIdentityLinkEntityManager() { return identityLinkEntityManager; } public IdentityLinkServiceConfiguration setIdentityLinkEntityManager(IdentityLinkEntityManager identityLinkEntityManager) { this.identityLinkEntityManager = identityLinkEntityManager; return this; } public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return historicIdentityLinkEntityManager; } public IdentityLinkServiceConfiguration setHistoricIdentityLinkEntityManager(HistoricIdentityLinkEntityManager historicIdentityLinkEntityManager) { this.historicIdentityLinkEntityManager = historicIdentityLinkEntityManager; return this;
} @Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public IdentityLinkServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public IdentityLinkEventHandler getIdentityLinkEventHandler() { return identityLinkEventHandler; } public IdentityLinkServiceConfiguration setIdentityLinkEventHandler(IdentityLinkEventHandler identityLinkEventHandler) { this.identityLinkEventHandler = identityLinkEventHandler; return this; } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\IdentityLinkServiceConfiguration.java
2
请完成以下Java代码
public void setM_DemandLine_ID (int M_DemandLine_ID) { if (M_DemandLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, Integer.valueOf(M_DemandLine_ID)); } /** Get Demand Line. @return Material Demand Line */ public int getM_DemandLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DemandLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_ForecastLine getM_ForecastLine() throws RuntimeException { return (I_M_ForecastLine)MTable.get(getCtx(), I_M_ForecastLine.Table_Name) .getPO(getM_ForecastLine_ID(), get_TrxName()); } /** Set Forecast Line. @param M_ForecastLine_ID Forecast Line */ public void setM_ForecastLine_ID (int M_ForecastLine_ID) { if (M_ForecastLine_ID < 1) set_Value (COLUMNNAME_M_ForecastLine_ID, null); else set_Value (COLUMNNAME_M_ForecastLine_ID, Integer.valueOf(M_ForecastLine_ID)); } /** Get Forecast Line. @return Forecast Line */ public int getM_ForecastLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ForecastLine_ID);
if (ii == null) return 0; return ii.intValue(); } public I_M_RequisitionLine getM_RequisitionLine() throws RuntimeException { return (I_M_RequisitionLine)MTable.get(getCtx(), I_M_RequisitionLine.Table_Name) .getPO(getM_RequisitionLine_ID(), get_TrxName()); } /** Set Requisition Line. @param M_RequisitionLine_ID Material Requisition Line */ public void setM_RequisitionLine_ID (int M_RequisitionLine_ID) { if (M_RequisitionLine_ID < 1) set_Value (COLUMNNAME_M_RequisitionLine_ID, null); else set_Value (COLUMNNAME_M_RequisitionLine_ID, Integer.valueOf(M_RequisitionLine_ID)); } /** Get Requisition Line. @return Material Requisition Line */ public int getM_RequisitionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DemandDetail.java
1
请在Spring Boot框架中完成以下Java代码
void accept(TreeVisitor visitor) throws Exception { this.acceptMethod.invoke(getInstance(), Proxy.newProxyInstance(getInstance().getClass().getClassLoader(), new Class<?>[] { this.treeVisitorType }, new TreeVisitorInvocationHandler(visitor)), 0); } /** * {@link InvocationHandler} to call the {@link TreeVisitor}. */ private class TreeVisitorInvocationHandler implements InvocationHandler { private TreeVisitor treeVisitor; TreeVisitorInvocationHandler(TreeVisitor treeVisitor) { this.treeVisitor = treeVisitor; } @Override @SuppressWarnings("rawtypes") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("visitClass") && (Integer) args[1] == 0) {
Iterable members = (Iterable) Tree.this.getClassTreeMembers.invoke(args[0]); for (Object member : members) { if (member != null) { Tree.this.acceptMethod.invoke(member, proxy, ((Integer) args[1]) + 1); } } } if (method.getName().equals("visitVariable")) { this.treeVisitor.visitVariable(new VariableTree(args[0])); } return null; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\Tree.java
2
请完成以下Java代码
public @Nullable ThreadPool getThreadPool() { return this.threadPool; } @Override public void setThreadPool(@Nullable ThreadPool threadPool) { this.threadPool = threadPool; } public boolean isUseForwardHeaders() { return this.useForwardHeaders; } @Override public void setUseForwardHeaders(boolean useForwardHeaders) { this.useForwardHeaders = useForwardHeaders; } protected AbstractConnector createConnector(InetSocketAddress address, Server server) { return this.createConnector(address, server, null, null, null); } protected AbstractConnector createConnector(InetSocketAddress address, Server server, @Nullable Executor executor, @Nullable Scheduler scheduler, @Nullable ByteBufferPool pool) { HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSendServerVersion(false); List<ConnectionFactory> connectionFactories = new ArrayList<>(); connectionFactories.add(new HttpConnectionFactory(httpConfiguration)); if (getHttp2() != null && getHttp2().isEnabled()) { connectionFactories.add(new HTTP2CServerConnectionFactory(httpConfiguration)); } ServerConnector connector = new ServerConnector(server, executor, scheduler, pool, this.getAcceptors(), this.getSelectors(), connectionFactories.toArray(new ConnectionFactory[0]));
connector.setHost(address.getHostString()); connector.setPort(address.getPort()); return connector; } protected void customizeSsl(Server server, InetSocketAddress address) { Ssl ssl = getSsl(); Assert.state(ssl != null, "'ssl' must not be null"); Assert.state(ssl.getServerNameBundles().isEmpty(), "Server name SSL bundles are not supported with Jetty"); new SslServerCustomizer(getHttp2(), address, ssl.getClientAuth(), getSslBundle()).customize(server); } protected Handler addHandlerWrappers(Handler handler) { if (getCompression() != null && getCompression().getEnabled()) { handler = applyWrapper(handler, JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); } if (StringUtils.hasText(getServerHeader())) { handler = applyWrapper(handler, JettyHandlerWrappers.createServerHeaderHandlerWrapper(getServerHeader())); } return handler; } protected Handler applyWrapper(Handler handler, Handler.Wrapper wrapper) { wrapper.setHandler(handler); return wrapper; } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\JettyWebServerFactory.java
1
请完成以下Java代码
public void validate(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl targetActivity = instruction.getTargetActivity(); if (isWaitStateGateway(targetActivity)) { validateIncomingSequenceFlows(instruction, instructions, report); validateParentScopeMigrates(instruction, instructions, report); validateSingleInstruction(instruction, instructions, report); } } protected void validateIncomingSequenceFlows(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl sourceActivity = instruction.getSourceActivity(); ActivityImpl targetActivity = instruction.getTargetActivity(); int numSourceIncomingFlows = sourceActivity.getIncomingTransitions().size(); int numTargetIncomingFlows = targetActivity.getIncomingTransitions().size(); if (numSourceIncomingFlows > numTargetIncomingFlows) { report.addFailure("The target gateway must have at least the same number " + "of incoming sequence flows that the source gateway has"); } } protected void validateParentScopeMigrates(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl sourceActivity = instruction.getSourceActivity(); ScopeImpl flowScope = sourceActivity.getFlowScope(); if (flowScope != flowScope.getProcessDefinition()) { if (instructions.getInstructionsBySourceScope(flowScope).isEmpty()) { report.addFailure("The gateway's flow scope '" + flowScope.getId() + "' must be mapped"); }
} } protected void validateSingleInstruction(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl targetActivity = instruction.getTargetActivity(); List<ValidatingMigrationInstruction> instructionsToTargetGateway = instructions.getInstructionsByTargetScope(targetActivity); if (instructionsToTargetGateway.size() > 1) { report.addFailure("Only one gateway can be mapped to gateway '" + targetActivity.getId() + "'"); } } protected boolean isWaitStateGateway(ActivityImpl activity) { ActivityBehavior behavior = activity.getActivityBehavior(); return behavior instanceof ParallelGatewayActivityBehavior || behavior instanceof InclusiveGatewayActivityBehavior; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\GatewayMappingValidator.java
1
请完成以下Java代码
private static Object invokeMethod(Method method, @Nullable Object instance, Object... args) { try { return method.invoke(instance, args); } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) { String message = "Error while invoking method " + method.getClass().getName() + "." + method.getName() + "(" + Arrays.asList(args) + ")"; logger.error(message, ex); throw new RuntimeException(message, ex); } } private static Method getMethod(String className, String methodName, String[] parameterTypeNames) { try { Class<?> c = Class.forName(className); int len = parameterTypeNames.length; Class<?>[] parameterTypes = new Class[len]; for (int i = 0; i < len; i++) { parameterTypes[i] = Class.forName(parameterTypeNames[i]); } return c.getDeclaredMethod(methodName, parameterTypes); } catch (ClassNotFoundException ex) { logger.error("Required class" + className + " not found"); throw new RuntimeException("Required class" + className + " not found", ex); } catch (NoSuchMethodException ex) { logger.error("Required method " + methodName + " with parameter types (" + Arrays.asList(parameterTypeNames) + ") not found on class " + className); throw new RuntimeException("Required class" + className + " not found", ex); } } private static Method getRunAsSubjectMethod() { if (getRunAsSubject == null) { getRunAsSubject = getMethod("com.ibm.websphere.security.auth.WSSubject", "getRunAsSubject", new String[] {}); } return getRunAsSubject; } private static Method getGroupsForUserMethod() { if (getGroupsForUser == null) { getGroupsForUser = getMethod("com.ibm.websphere.security.UserRegistry", "getGroupsForUser", new String[] { "java.lang.String" }); } return getGroupsForUser; } private static Method getSecurityNameMethod() { if (getSecurityName == null) { getSecurityName = getMethod("com.ibm.websphere.security.cred.WSCredential", "getSecurityName", new String[] {});
} return getSecurityName; } private static Method getNarrowMethod() { if (narrow == null) { narrow = getMethod(PORTABLE_REMOTE_OBJECT_CLASSNAME, "narrow", new String[] { Object.class.getName(), Class.class.getName() }); } return narrow; } // SEC-803 private static Class<?> getWSCredentialClass() { if (wsCredentialClass == null) { wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential"); } return wsCredentialClass; } private static Class<?> getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { logger.error("Required class " + className + " not found"); throw new RuntimeException("Required class " + className + " not found", ex); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\websphere\DefaultWASUsernameAndGroupsExtractor.java
1
请完成以下Java代码
private String createSysConfigName(Object key) { return createSysConfigPrefix() + "." + key.toString(); } private String createSysConfigPrefix() { return SYSCONFIG_PREFIX + lookAndFeelId; } public void loadAllFromSysConfigTo(final UIDefaults uiDefaults) { if (!DB.isConnected()) { return; } final String prefix = createSysConfigPrefix() + "."; final boolean removePrefix = true; final Properties ctx = Env.getCtx(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx));
final Map<String, String> map = sysConfigBL.getValuesForPrefix(prefix, removePrefix, clientAndOrgId); for (final Map.Entry<String, String> mapEntry : map.entrySet()) { final String key = mapEntry.getKey(); final String valueStr = mapEntry.getValue(); try { final Object value = serializer.fromString(valueStr); uiDefaults.put(key, value); } catch (Exception ex) { logger.warn("Failed loading " + key + ": " + valueStr + ". Skipped.", ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SysConfigUIDefaultsRepository.java
1
请完成以下Java代码
public Class<Person> getObjectType() { return Person.class; } @Override public Object getObject() throws Exception { return new Person(); } public boolean isSingleton() { return true; } public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getSecondName() { return secondName; } public void setSecondName(String secondName) { this.secondName = secondName; } @Override public String toString() { return "Person [firstName=" + firstName + ", secondName=" + secondName + "]"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-annotations\src\main\java\com\baeldung\multibeaninstantiation\solution3\Person.java
1
请完成以下Java代码
public Comment execute(CommandContext commandContext) { TaskEntity task = null; // Validate task if (taskId != null) { task = commandContext.getTaskEntityManager().findById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class); } if (task.isSuspended()) { throw new ActivitiException(getSuspendedTaskException()); } } ExecutionEntity execution = null; if (processInstanceId != null) { execution = commandContext.getExecutionEntityManager().findById(processInstanceId); if (execution == null) { throw new ActivitiObjectNotFoundException( "execution " + processInstanceId + " doesn't exist", Execution.class ); } if (execution.isSuspended()) { throw new ActivitiException(getSuspendedExceptionMessage()); } } String processDefinitionId = null; if (execution != null) { processDefinitionId = execution.getProcessDefinitionId(); } else if (task != null) { processDefinitionId = task.getProcessDefinitionId(); } return executeInternal(commandContext, processDefinitionId); } protected Comment executeInternal(CommandContext commandContext, String processDefinitionId) { String userId = Authentication.getAuthenticatedUserId(); CommentEntity comment = commandContext.getCommentEntityManager().create(); comment.setUserId(userId); comment.setType((type == null) ? CommentEntity.TYPE_COMMENT : type); comment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime()); comment.setTaskId(taskId); comment.setProcessInstanceId(processInstanceId); comment.setAction(Event.ACTION_ADD_COMMENT);
String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } comment.setMessage(eventMessage); comment.setFullMessage(message); commandContext.getCommentEntityManager().insert(comment); return comment; } protected String getSuspendedTaskException() { return "Cannot add a comment to a suspended task"; } protected String getSuspendedExceptionMessage() { return "Cannot add a comment to a suspended execution"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddCommentCmd.java
1
请完成以下Java代码
public Foo findById(@PathVariable @Min(0) final long id) { return repo.findById(id).orElse(null); } @GetMapping("/foos") public List<Foo> findAll() { return repo.findAll(); } @GetMapping( value="/foos", params = { "page", "size" }) @Validated public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) { return repo.findAll(PageRequest.of(page, size)).getContent(); } // API - write
@PutMapping("/foos/{id}") @ResponseStatus(HttpStatus.OK) public Foo update(@PathVariable("id") final String id, @RequestBody final Foo foo) { return foo; } @PostMapping("/foos") @ResponseStatus(HttpStatus.CREATED) public void create( @RequestBody final Foo foo) { if (null == foo || null == foo.getName()) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST," 'name' is required"); } repo.save(foo); } }
repos\tutorials-master\spring-web-modules\spring-5-mvc\src\main\java\com\baeldung\web\FooController.java
1
请完成以下Java代码
default ProducerFactory<K, V> getProducerFactory() { throw new UnsupportedOperationException("This implementation does not support this operation"); } /** * Receive a single record with the default poll timeout (5 seconds). * @param topic the topic. * @param partition the partition. * @param offset the offset. * @return the record or null. * @since 2.8 * @see #DEFAULT_POLL_TIMEOUT */ @Nullable default ConsumerRecord<K, V> receive(String topic, int partition, long offset) { return receive(topic, partition, offset, DEFAULT_POLL_TIMEOUT); } /** * Receive a single record. * @param topic the topic. * @param partition the partition. * @param offset the offset. * @param pollTimeout the timeout. * @return the record or null. * @since 2.8 */ @Nullable ConsumerRecord<K, V> receive(String topic, int partition, long offset, Duration pollTimeout); /** * Receive a multiple records with the default poll timeout (5 seconds). Only * absolute, positive offsets are supported. * @param requested a collection of record requests (topic/partition/offset). * @return the records * @since 2.8 * @see #DEFAULT_POLL_TIMEOUT */ default ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested) { return receive(requested, DEFAULT_POLL_TIMEOUT); } /** * Receive multiple records. Only absolute, positive offsets are supported. * @param requested a collection of record requests (topic/partition/offset). * @param pollTimeout the timeout.
* @return the record or null. * @since 2.8 */ ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout); /** * A callback for executing arbitrary operations on the {@link Producer}. * @param <K> the key type. * @param <V> the value type. * @param <T> the return type. * @since 1.3 */ interface ProducerCallback<K, V, T> { T doInKafka(Producer<K, V> producer); } /** * A callback for executing arbitrary operations on the {@link KafkaOperations}. * @param <K> the key type. * @param <V> the value type. * @param <T> the return type. * @since 1.3 */ interface OperationsCallback<K, V, T> { @Nullable T doInOperations(KafkaOperations<K, V> operations); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaOperations.java
1
请完成以下Java代码
public void process(@NonNull final I_EDI_Desadv desadv) { enqueueShipmentsForDesadv(queue, desadv); } }) .process(createIterator()); return MSG_OK; } private void enqueueShipmentsForDesadv( final @NonNull IWorkPackageQueue queue, final @NonNull I_EDI_Desadv desadv) { final List<I_M_InOut> shipments = desadvDAO.retrieveShipmentsWithStatus(desadv, ImmutableSet.of(EDIExportStatus.Pending, EDIExportStatus.Error)); final String trxName = InterfaceWrapperHelper.getTrxName(desadv); for (final I_M_InOut shipment : shipments) { queue.newWorkPackage() .setAD_PInstance_ID(getPinstanceId()) .bindToTrxName(trxName) .addElement(shipment) .buildAndEnqueue(); shipment.setEDI_ExportStatus(I_M_InOut.EDI_EXPORTSTATUS_Enqueued); InterfaceWrapperHelper.save(shipment); addLog("Enqueued M_InOut_ID={} for EDI_Desadv_ID={}", shipment.getM_InOut_ID(), desadv.getEDI_Desadv_ID()); } if(shipments.isEmpty()) { addLog("Found no M_InOuts to enqueue for EDI_Desadv_ID={}", desadv.getEDI_Desadv_ID()); } else { desadv.setEDI_ExportStatus(I_M_InOut.EDI_EXPORTSTATUS_Enqueued); InterfaceWrapperHelper.save(desadv); }
} @NonNull private Iterator<I_EDI_Desadv> createIterator() { final IQueryBuilder<I_EDI_Desadv> queryBuilder = queryBL.createQueryBuilder(I_EDI_Desadv.class, getCtx(), get_TrxName()) .addOnlyActiveRecordsFilter() .filter(getProcessInfo().getQueryFilterOrElseFalse()); queryBuilder.orderBy() .addColumn(I_EDI_Desadv.COLUMNNAME_POReference) .addColumn(I_EDI_Desadv.COLUMNNAME_EDI_Desadv_ID); final Iterator<I_EDI_Desadv> iterator = queryBuilder .create() .iterate(I_EDI_Desadv.class); if(!iterator.hasNext()) { addLog("Found no EDI_Desadvs to enqueue within the current selection"); } return iterator; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_InOut_EnqueueForExport.java
1
请完成以下Java代码
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 Builder clientRegistrationEndpoint(String clientRegistrationEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.CLIENT_REGISTRATION_ENDPOINT, clientRegistrationEndpoint); } /** * Sets the OpenID Connect 1.0 Client Registration endpoint. * @param oidcClientRegistrationEndpoint the OpenID Connect 1.0 Client * Registration endpoint * @return the {@link Builder} for further configuration */ public Builder oidcClientRegistrationEndpoint(String oidcClientRegistrationEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_CLIENT_REGISTRATION_ENDPOINT, oidcClientRegistrationEndpoint); } /** * Sets the OpenID Connect 1.0 UserInfo endpoint. * @param oidcUserInfoEndpoint the OpenID Connect 1.0 UserInfo endpoint * @return the {@link Builder} for further configuration */ public Builder oidcUserInfoEndpoint(String oidcUserInfoEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_USER_INFO_ENDPOINT, oidcUserInfoEndpoint); } /** * Sets the OpenID Connect 1.0 Logout endpoint. * @param oidcLogoutEndpoint the OpenID Connect 1.0 Logout endpoint * @return the {@link Builder} for further configuration */ public Builder oidcLogoutEndpoint(String oidcLogoutEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_LOGOUT_ENDPOINT, oidcLogoutEndpoint);
} /** * Builds the {@link AuthorizationServerSettings}. * @return the {@link AuthorizationServerSettings} */ @Override public AuthorizationServerSettings build() { AuthorizationServerSettings authorizationServerSettings = new AuthorizationServerSettings(getSettings()); if (authorizationServerSettings.getIssuer() != null && authorizationServerSettings.isMultipleIssuersAllowed()) { throw new IllegalArgumentException("The issuer identifier (" + authorizationServerSettings.getIssuer() + ") cannot be set when isMultipleIssuersAllowed() is true."); } return authorizationServerSettings; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AuthorizationServerSettings.java
1
请完成以下Java代码
public static class OneToManyMappingConverter extends BaseActivityMigrationMappingConverter<ActivityMigrationMapping.OneToManyMapping> { @Override protected ObjectNode convertMappingInfoToJson(ActivityMigrationMapping.OneToManyMapping mapping, ObjectMapper objectMapper) { ObjectNode mappingNode = objectMapper.createObjectNode(); mappingNode.put(ProcessInstanceMigrationDocumentConstants.FROM_ACTIVITY_ID_JSON_PROPERTY, mapping.getFromActivityId()); JsonNode toActivityIdsNode = objectMapper.valueToTree(mapping.getToActivityIds()); mappingNode.set(ProcessInstanceMigrationDocumentConstants.TO_ACTIVITY_IDS_JSON_PROPERTY, toActivityIdsNode); mappingNode.setAll(convertAdditionalMappingInfoToJson(mapping, objectMapper)); return mappingNode; } @Override public JsonNode convertLocalVariablesToJson(ActivityMigrationMapping.OneToManyMapping mapping, ObjectMapper objectMapper) { Map<String, Map<String, Object>> activitiesLocalVariables = mapping.getActivitiesLocalVariables(); if (activitiesLocalVariables != null && !activitiesLocalVariables.isEmpty()) { return objectMapper.valueToTree(activitiesLocalVariables); } return null; } @Override protected JsonNode convertNewAssigneeToJson(ActivityMigrationMapping.OneToManyMapping mapping, ObjectMapper objectMapper) { return null; } @Override public ActivityMigrationMapping.OneToManyMapping convertFromJson(JsonNode jsonNode, ObjectMapper objectMapper) { String fromActivityId = jsonNode.get(ProcessInstanceMigrationDocumentConstants.FROM_ACTIVITY_ID_JSON_PROPERTY).stringValue(); JsonNode toActivityIdsNode = jsonNode.get(ProcessInstanceMigrationDocumentConstants.TO_ACTIVITY_IDS_JSON_PROPERTY); List<String> toActivityIds = objectMapper.convertValue(toActivityIdsNode, new TypeReference<>() {
}); ActivityMigrationMapping.OneToManyMapping oneToManyMapping = ActivityMigrationMapping.createMappingFor(fromActivityId, toActivityIds); convertAdditionalMappingInfoFromJson(oneToManyMapping, jsonNode); Map<String, Map<String, Object>> localVariables = getLocalVariablesFromJson(jsonNode, objectMapper); if (localVariables != null) { oneToManyMapping.withLocalVariables(localVariables); } return oneToManyMapping; } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceMigrationDocumentConverter.java
1
请完成以下Java代码
private final I_M_HU createNewIncludedHU( @NonNull final I_M_HU_Item item, @NonNull final IAllocationRequest request) { final IHUItemStorage storage = getHUItemStorage(item, request); if (!storage.requestNewHU()) { return null; } final I_M_HU_PI includedHUDef; if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType())) { // if we are to create an HU below an HUAggregate item, then we always create a VHU. includedHUDef = services.getVirtualPI(request.getHuContext().getCtx()); } else { includedHUDef = services.getIncluded_HU_PI(item);
} // we cannot create an instance which has no included handling unit definition Check.errorIf(includedHUDef == null, "Unable to get a M_HU_PI for the given request and item; request={}; item={}", request, item); return AllocationUtils.createHUBuilder(request) .setM_HU_Item_Parent(item) .create(includedHUDef); } private final void destroyIncludedHU(final I_M_HU hu) { services.deleteHU(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\FIFOAllocationStrategy.java
1
请完成以下Java代码
MqttClient getMqttClient(TbContext ctx, MqttClientConfig config) { return MqttClient.create(config, null, ctx.getExternalCallExecutor()); } protected void prepareMqttClientConfig(MqttClientConfig config) { ClientCredentials credentials = mqttNodeConfiguration.getCredentials(); if (credentials.getType() == CredentialsType.BASIC) { BasicCredentials basicCredentials = (BasicCredentials) credentials; config.setUsername(basicCredentials.getUsername()); config.setPassword(basicCredentials.getPassword()); } } private SslContext getSslContext() throws SSLException { return mqttNodeConfiguration.isSsl() ? mqttNodeConfiguration.getCredentials().initSslContext() : null; } private String getData(TbMsg tbMsg, boolean parseToPlainText) { if (parseToPlainText) { return JacksonUtil.toPlainText(tbMsg.getData()); } return tbMsg.getData(); } @Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: String parseToPlainText = "parseToPlainText"; if (!oldConfiguration.has(parseToPlainText)) {
hasChanges = true; ((ObjectNode) oldConfiguration).put(parseToPlainText, false); } case 1: String protocolVersion = "protocolVersion"; if (!oldConfiguration.has(protocolVersion)) { hasChanges = true; ((ObjectNode) oldConfiguration).put(protocolVersion, MqttVersion.MQTT_3_1.name()); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mqtt\TbMqttNode.java
1
请完成以下Java代码
public static Builder builder() { return new Builder(); } /** * Creates a builder to build {@link StartMessageDeploymentDefinitionImpl} and initialize it with the given object. * @param startMessageEventSubscriptionImpl to initialize the builder with * @return created builder */ public static Builder builderFrom(StartMessageDeploymentDefinitionImpl startMessageEventSubscriptionImpl) { return new Builder(startMessageEventSubscriptionImpl); } /** * Builder to build {@link StartMessageDeploymentDefinitionImpl}. */ public static final class Builder { private StartMessageSubscription messageSubscription; private ProcessDefinition processDefinition; public Builder() {} private Builder(StartMessageDeploymentDefinitionImpl startMessageEventSubscriptionImpl) { this.messageSubscription = startMessageEventSubscriptionImpl.messageSubscription; this.processDefinition = startMessageEventSubscriptionImpl.processDefinition; } /** * Builder method for messageEventSubscription parameter. * @param messageEventSubscription field to set
* @return builder */ public Builder withMessageSubscription(StartMessageSubscription messageEventSubscription) { this.messageSubscription = messageEventSubscription; return this; } /** * Builder method for processDefinition parameter. * @param processDefinition field to set * @return builder */ public Builder withProcessDefinition(ProcessDefinition processDefinition) { this.processDefinition = processDefinition; return this; } /** * Builder method of the builder. * @return built class */ public StartMessageDeploymentDefinitionImpl build() { return new StartMessageDeploymentDefinitionImpl(this); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\StartMessageDeploymentDefinitionImpl.java
1
请完成以下Java代码
public int getDLM_Partition_Config_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set DLM Partitionierungskonfigzeile. * * @param DLM_Partition_Config_Line_ID DLM Partitionierungskonfigzeile */ @Override public void setDLM_Partition_Config_Line_ID(final int DLM_Partition_Config_Line_ID) { if (DLM_Partition_Config_Line_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_Line_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_Line_ID, Integer.valueOf(DLM_Partition_Config_Line_ID)); } } /** * Get DLM Partitionierungskonfigzeile. * * @return DLM Partitionierungskonfigzeile */ @Override public int getDLM_Partition_Config_Line_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_Line_ID); if (ii == null) { return 0; } return ii.intValue(); } @Override public org.compiere.model.I_AD_Table getDLM_Referencing_Table() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class); } @Override public void setDLM_Referencing_Table(final org.compiere.model.I_AD_Table DLM_Referencing_Table) { set_ValueFromPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class, DLM_Referencing_Table); } /** * Set Referenzierende Tabelle. * * @param DLM_Referencing_Table_ID Referenzierende Tabelle */ @Override public void setDLM_Referencing_Table_ID(final int DLM_Referencing_Table_ID) { if (DLM_Referencing_Table_ID < 1) { set_Value(COLUMNNAME_DLM_Referencing_Table_ID, null); } else { set_Value(COLUMNNAME_DLM_Referencing_Table_ID, Integer.valueOf(DLM_Referencing_Table_ID));
} } /** * Get Referenzierende Tabelle. * * @return Referenzierende Tabelle */ @Override public int getDLM_Referencing_Table_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Table_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set DLM aktiviert. * * @param IsDLM * Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden */ @Override public void setIsDLM(final boolean IsDLM) { throw new IllegalArgumentException("IsDLM is virtual column"); } /** * Get DLM aktiviert. * * @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden */ @Override public boolean isDLM() { final Object oo = get_Value(COLUMNNAME_IsDLM); 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.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Line.java
1
请完成以下Java代码
public class PrintingDataToPDFWriter implements IAutoCloseable { private final static Logger logger = LogManager.getLogger(PrintingDataToPDFWriter.class); private final PdfCopy pdfCopy; private final Document document; public PrintingDataToPDFWriter(@NonNull final OutputStream out) { document = new Document(); try { pdfCopy = new PdfCopy(document, out); } catch (final DocumentException e) { throw new AdempiereException(e); } document.open(); } public int addArchivePartToPDF(@NonNull final PrintingData data, @NonNull final PrintingSegment segment) { try { return addArchivePartToPDF0(data, segment); } catch (final Exception e) { throw new PrintingQueueAggregationException(data.getPrintingQueueItemId().getRepoId(), e); } } private int addArchivePartToPDF0(@NonNull final PrintingData data, @NonNull final PrintingSegment segment) throws IOException { if (!data.hasData()) { logger.info("PrintingData {} does not contain any data; -> returning", data); return 0; } logger.debug("Adding data={}; segment={}", data, segment); int pagesAdded = 0; for (int i = 0; i < segment.getCopies(); i++) { final PdfReader reader = new PdfReader(data.getData()); final int archivePageNums = reader.getNumberOfPages(); int pageFrom = segment.getPageFrom(); if (pageFrom <= 0) { // First page is 1 - See com.lowagie.text.pdf.PdfWriter.getImportedPage pageFrom = 1; } int pageTo = segment.getPageTo(); if (pageTo > archivePageNums)
{ // shall not happen at this point logger.debug("Page to ({}) is greater then number of pages. Considering number of pages: {}", new Object[] { pageTo, archivePageNums }); pageTo = archivePageNums; } if (pageFrom > pageTo) { // shall not happen at this point logger.warn("Page from ({}) is greater then Page to ({}). Skipping: {}", pageFrom, pageTo, segment); return 0; } logger.debug("PageFrom={}, PageTo={}, NumberOfPages={}", pageFrom, pageTo, archivePageNums); for (int page = pageFrom; page <= pageTo; page++) { try { pdfCopy.addPage(pdfCopy.getImportedPage(reader, page)); } catch (final BadPdfFormatException e) { throw new AdempiereException("@Invalid@ " + segment + " (Page: " + page + ")", e); } pagesAdded++; } pdfCopy.freeReader(reader); reader.close(); } logger.debug("Added {} pages", pagesAdded); return pagesAdded; } @Override public void close() { document.close(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFWriter.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeId() { return scopeId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getSearchKey() { return searchKey; } @Override public void setSearchKey(String searchKey) { this.searchKey = searchKey; } @Override public String getSearchKey2() { return searchKey2; } @Override public void setSearchKey2(String searchKey2) { this.searchKey2 = searchKey2; } @Override public String getBatchSearchKey() { return batchSearchKey; } @Override public void setBatchSearchKey(String batchSearchKey) { this.batchSearchKey = batchSearchKey; } @Override public String getBatchSearchKey2() { return batchSearchKey2; } @Override public void setBatchSearchKey2(String batchSearchKey2) { this.batchSearchKey2 = batchSearchKey2; }
@Override public String getStatus() { return status; } @Override public void setStatus(String status) { this.status = status; } @Override public ByteArrayRef getResultDocRefId() { return resultDocRefId; } public void setResultDocRefId(ByteArrayRef resultDocRefId) { this.resultDocRefId = resultDocRefId; } @Override public String getResultDocumentJson(String engineType) { if (resultDocRefId != null) { byte[] bytes = resultDocRefId.getBytes(engineType); if (bytes != null) { return new String(bytes, StandardCharsets.UTF_8); } } return null; } @Override public void setResultDocumentJson(String resultDocumentJson, String engineType) { this.resultDocRefId = setByteArrayRef(this.resultDocRefId, BATCH_RESULT_LABEL, resultDocumentJson, engineType); } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } private static ByteArrayRef setByteArrayRef(ByteArrayRef byteArrayRef, String name, String value, String engineType) { if (byteArrayRef == null) { byteArrayRef = new ByteArrayRef(); } byte[] bytes = null; if (value != null) { bytes = value.getBytes(StandardCharsets.UTF_8); } byteArrayRef.setValue(name, bytes, engineType); return byteArrayRef; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchPartEntityImpl.java
2
请完成以下Java代码
default boolean inTransaction() { return false; } /** * Return the producer factory used by this template. * @return the factory. * @since 2.5 */ default ProducerFactory<K, V> getProducerFactory() { throw new UnsupportedOperationException("This implementation does not support this operation"); } /** * Receive a single record with the default poll timeout (5 seconds). * @param topic the topic. * @param partition the partition. * @param offset the offset. * @return the record or null. * @since 2.8 * @see #DEFAULT_POLL_TIMEOUT */ @Nullable default ConsumerRecord<K, V> receive(String topic, int partition, long offset) { return receive(topic, partition, offset, DEFAULT_POLL_TIMEOUT); } /** * Receive a single record. * @param topic the topic. * @param partition the partition. * @param offset the offset. * @param pollTimeout the timeout. * @return the record or null. * @since 2.8 */ @Nullable ConsumerRecord<K, V> receive(String topic, int partition, long offset, Duration pollTimeout); /** * Receive a multiple records with the default poll timeout (5 seconds). Only * absolute, positive offsets are supported. * @param requested a collection of record requests (topic/partition/offset). * @return the records * @since 2.8 * @see #DEFAULT_POLL_TIMEOUT */ default ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested) { return receive(requested, DEFAULT_POLL_TIMEOUT); } /** * Receive multiple records. Only absolute, positive offsets are supported. * @param requested a collection of record requests (topic/partition/offset). * @param pollTimeout the timeout. * @return the record or null. * @since 2.8 */
ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout); /** * A callback for executing arbitrary operations on the {@link Producer}. * @param <K> the key type. * @param <V> the value type. * @param <T> the return type. * @since 1.3 */ interface ProducerCallback<K, V, T> { T doInKafka(Producer<K, V> producer); } /** * A callback for executing arbitrary operations on the {@link KafkaOperations}. * @param <K> the key type. * @param <V> the value type. * @param <T> the return type. * @since 1.3 */ interface OperationsCallback<K, V, T> { @Nullable T doInOperations(KafkaOperations<K, V> operations); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaOperations.java
1
请完成以下Java代码
private static class RemindersQueue { private final SortedSet<PurchaseCandidateReminder> reminders = new TreeSet<>(Comparator.comparing(PurchaseCandidateReminder::getNotificationTime)); public List<PurchaseCandidateReminder> toList() { return ImmutableList.copyOf(reminders); } public boolean add(@NonNull final PurchaseCandidateReminder reminder) { return reminders.add(reminder); } public void setReminders(final Collection<PurchaseCandidateReminder> reminders) { this.reminders.clear(); this.reminders.addAll(reminders); } public List<PurchaseCandidateReminder> removeAllUntil(final ZonedDateTime maxNotificationTime) { final List<PurchaseCandidateReminder> result = new ArrayList<>(); for (final Iterator<PurchaseCandidateReminder> it = reminders.iterator(); it.hasNext();) { final PurchaseCandidateReminder reminder = it.next(); final ZonedDateTime notificationTime = reminder.getNotificationTime(); if (notificationTime.compareTo(maxNotificationTime) <= 0) { it.remove(); result.add(reminder); } } return result; } public ZonedDateTime getMinNotificationTime() { if (reminders.isEmpty()) { return null; } return reminders.first().getNotificationTime(); } } @lombok.Value @lombok.Builder private static class NextDispatch { public static NextDispatch schedule(final Runnable task, final ZonedDateTime date, final TaskScheduler taskScheduler) { final ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(task, TimeUtil.asDate(date));
return builder() .task(task) .scheduledFuture(scheduledFuture) .notificationTime(date) .build(); } Runnable task; ScheduledFuture<?> scheduledFuture; ZonedDateTime notificationTime; public void cancel() { final boolean canceled = scheduledFuture.cancel(false); logger.trace("Cancel requested for {} (result was: {})", this, canceled); } public NextDispatch rescheduleIfAfter(final ZonedDateTime date, final TaskScheduler taskScheduler) { if (!notificationTime.isAfter(date) && !scheduledFuture.isDone()) { logger.trace("Skip rescheduling {} because it's not after {}", date); return this; } cancel(); final ScheduledFuture<?> nextScheduledFuture = taskScheduler.schedule(task, TimeUtil.asTimestamp(date)); NextDispatch nextDispatch = NextDispatch.builder() .task(task) .scheduledFuture(nextScheduledFuture) .notificationTime(date) .build(); logger.trace("Rescheduled {} to {}", this, nextDispatch); return nextDispatch; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\purchasecandidate\reminder\PurchaseCandidateReminderScheduler.java
1
请完成以下Java代码
public void init(final IModelValidationEngine engine) { // Register one document interceptor for each table name/handler. { final IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class); final IInvoiceCandidateHandlerDAO invoiceCandidateHandlerDAO = Services.get(IInvoiceCandidateHandlerDAO.class); final IADTableDAO tableDAO = Services.get(IADTableDAO.class); for (final I_C_ILCandHandler handlerDef : invoiceCandidateHandlerDAO.retrieveAll(Env.getCtx())) { final IInvoiceCandidateHandler handler = invoiceCandidateHandlerBL.mkInstance(handlerDef); final String tableName = handler.getSourceTable(); // Skip if the handler is not about an actual existing table name (e.g. like Manual handler) if (!tableDAO.isExistingTable(tableName)) { continue; }
final ILHandlerModelInterceptor modelInterceptor = new ILHandlerModelInterceptor(handler); engine.addModelValidator(modelInterceptor); } } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE } , ifColumnsChanged = { I_C_ILCandHandler.COLUMNNAME_Classname }) public void validateClassname(final I_C_ILCandHandler handlerDef) { final boolean failIfClassNotFound = true; Services.get(IInvoiceCandidateHandlerBL.class).evalClassName(handlerDef, failIfClassNotFound); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_ILCandHandler.java
1
请完成以下Java代码
public V get(String key) { return trie.get(key); } /** * 是否含有键 * * @param key * @return */ public boolean contains(String key) { return get(key) != null; } /** * 词典大小 * * @return */ public int size() {
return trie.size(); } /** * 从一行词典条目创建值 * * @param params 第一个元素为键,请注意跳过 * @return */ protected abstract V createValue(String[] params); /** * 文本词典加载完毕的回调函数 * * @param map */ protected void onLoaded(TreeMap<String, V> map) { } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonDictionary.java
1
请完成以下Java代码
public class Car { private String make; private String model; private int year; private int seats; private String plant1; private String plant1Loc; private String plant2; private String plant2Loc; public Car(String make, String model, int year, int seats) { this.make = make; this.model = model; this.year = year; this.seats = seats; } public String getPlant2() { return plant2; } public void setPlant2(String plant2) { this.plant2 = plant2; } public String getPlant2Loc() { return plant2Loc; } public void setPlant2Loc(String plant2Loc) { this.plant2Loc = plant2Loc; } public String getPlant1Loc() { return plant1Loc; } public void setPlant1Loc(String plant1Loc) { this.plant1Loc = plant1Loc; } public String getPlant1() { return plant1; } public void setPlant1(String plant1) {
this.plant1 = plant1; } public int getSeats() { return seats; } public void setSeats(int seats) { this.seats = seats; } public String getMake() { return make; } public String getModel() { return model; } public int getYear() { return year; } }
repos\tutorials-master\mapstruct-2\src\main\java\com\baeldung\list\entity\Car.java
1
请完成以下Java代码
public GroupQuery orderByGroupId() { return orderBy(GroupQueryProperty.GROUP_ID); } public GroupQuery orderByGroupName() { return orderBy(GroupQueryProperty.NAME); } public GroupQuery orderByGroupType() { return orderBy(GroupQueryProperty.TYPE); } //getters //////////////////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() {
return nameLike; } public String getType() { return type; } public String getUserId() { return userId; } public String getTenantId() { return tenantId; } public String[] getIds() { return ids; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\GroupQueryImpl.java
1
请完成以下Java代码
public void setShipperName (final @Nullable java.lang.String ShipperName) { set_Value (COLUMNNAME_ShipperName, ShipperName); } @Override public java.lang.String getShipperName() { return get_ValueAsString(COLUMNNAME_ShipperName); } @Override public void setShipperRouteCodeName (final @Nullable java.lang.String ShipperRouteCodeName) { set_Value (COLUMNNAME_ShipperRouteCodeName, ShipperRouteCodeName); } @Override public java.lang.String getShipperRouteCodeName() { return get_ValueAsString(COLUMNNAME_ShipperRouteCodeName); } @Override public void setShortDescription (final @Nullable java.lang.String ShortDescription) { set_Value (COLUMNNAME_ShortDescription, ShortDescription); } @Override public java.lang.String getShortDescription() { return get_ValueAsString(COLUMNNAME_ShortDescription); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } @Override public void setTaxID (final @Nullable java.lang.String TaxID) { set_Value (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() {
return get_ValueAsString(COLUMNNAME_Title); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setURL3 (final @Nullable java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } @Override public java.lang.String getURL3() { return get_ValueAsString(COLUMNNAME_URL3); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
1
请完成以下Java代码
public class UnboundIdContainer implements EmbeddedLdapServerContainer, InitializingBean, DisposableBean, Lifecycle, ApplicationContextAware { private InMemoryDirectoryServer directoryServer; private final String defaultPartitionSuffix; private int port = 53389; private boolean isEphemeral; private ConfigurableApplicationContext context; private boolean running; private final String ldif; public UnboundIdContainer(String defaultPartitionSuffix, String ldif) { this.defaultPartitionSuffix = defaultPartitionSuffix; this.ldif = ldif; } @Override public int getPort() { return this.port; } @Override public void setPort(int port) { this.port = port; this.isEphemeral = port == 0; } @Override public void destroy() { stop(); } @Override public void afterPropertiesSet() { start(); } @Override public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { this.context = (ConfigurableApplicationContext) applicationContext; } @Override public void start() { if (isRunning()) { return; } try { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(this.defaultPartitionSuffix); config.addAdditionalBindCredentials("uid=admin,ou=system", "secret"); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", this.port)); config.setEnforceSingleStructuralObjectClass(false); config.setEnforceAttributeSyntaxCompliance(true); DN dn = new DN(this.defaultPartitionSuffix); Entry entry = new Entry(dn); entry.addAttribute("objectClass", "top", "domain", "extensibleObject"); entry.addAttribute("dc", dn.getRDN().getAttributeValues()[0]); InMemoryDirectoryServer directoryServer = new InMemoryDirectoryServer(config); directoryServer.add(entry);
importLdif(directoryServer); directoryServer.startListening(); this.port = directoryServer.getListenPort(); this.directoryServer = directoryServer; this.running = true; } catch (LDAPException ex) { throw new RuntimeException("Server startup failed", ex); } } private void importLdif(InMemoryDirectoryServer directoryServer) { if (StringUtils.hasText(this.ldif)) { try { Resource[] resources = this.context.getResources(this.ldif); if (resources.length > 0) { if (!resources[0].exists()) { throw new IllegalArgumentException("Unable to find LDIF resource " + this.ldif); } try (InputStream inputStream = resources[0].getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } } @Override public void stop() { if (this.isEphemeral && this.context != null && !this.context.isClosed()) { return; } this.directoryServer.shutDown(true); this.running = false; } @Override public boolean isRunning() { return this.running; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\server\UnboundIdContainer.java
1
请完成以下Java代码
private ClassicHttpResponse executeInitializrMetadataRetrieval(String url) { HttpGet request = new HttpGet(url); request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_META_DATA)); return execute(request, URI.create(url), "retrieve metadata"); } private ClassicHttpResponse execute(HttpUriRequest request, URI url, String description) { try { HttpHost host = HttpHost.create(url); request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion()); return getHttp().executeOpen(host, request, null); } catch (IOException ex) { throw new ReportableException( "Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")"); } } private ReportableException createException(String url, ClassicHttpResponse httpResponse) { StatusLine statusLine = new StatusLine(httpResponse); String message = "Initializr service call failed using '" + url + "' - service returned " + statusLine.getReasonPhrase(); String error = extractMessage(httpResponse.getEntity()); if (StringUtils.hasText(error)) { message += ": '" + error + "'"; } else { int statusCode = statusLine.getStatusCode(); message += " (unexpected " + statusCode + " error)"; } throw new ReportableException(message); } private @Nullable String extractMessage(@Nullable HttpEntity entity) { if (entity != null) { try { JSONObject error = getContentAsJson(entity); if (error.has("message")) { return error.getString("message"); } } catch (Exception ex) {
// Ignore } } return null; } private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException { return new JSONObject(getContent(entity)); } private String getContent(HttpEntity entity) throws IOException { ContentType contentType = ContentType.create(entity.getContentType()); Charset charset = contentType.getCharset(); charset = (charset != null) ? charset : StandardCharsets.UTF_8; byte[] content = FileCopyUtils.copyToByteArray(entity.getContent()); return new String(content, charset); } private @Nullable String extractFileName(@Nullable Header header) { if (header != null) { String value = header.getValue(); int start = value.indexOf(FILENAME_HEADER_PREFIX); if (start != -1) { value = value.substring(start + FILENAME_HEADER_PREFIX.length()); int end = value.indexOf('\"'); if (end != -1) { return value.substring(0, end); } } } return null; } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\init\InitializrService.java
1
请完成以下Java代码
private static <T> T singleNonNullValue(@NonNull final String name, @Nullable final T value1, @Nullable final T value2) { if (value1 == null && value2 == null) { throw new IllegalArgumentException("No value for " + name + " found"); } if (value1 != null && value2 != null && !Objects.equals(value2, value1)) { throw new IllegalArgumentException("More than one value for " + name + " found: " + value1 + ", " + value2); } else { return value1 != null ? value1 : value2; } } private static Integer computeQtyTUs(@NonNull final JsonHUType unitType, final List<JsonHU> includedHUs) { if (unitType == JsonHUType.LU) { return includedHUs.stream() .mapToInt(tu -> tu.isAggregatedTU() ? tu.numberOfAggregatedHUs : 1) .sum(); } else { return null; } } public JsonHU withIsDisposalPending(@Nullable final Boolean isDisposalPending) { return Objects.equals(this.isDisposalPending, isDisposalPending) ? this : toBuilder().isDisposalPending(isDisposalPending).build(); } public JsonHU withDisplayedAttributesOnly(@Nullable final List<String> displayedAttributeCodesOnly) { if (displayedAttributeCodesOnly == null || displayedAttributeCodesOnly.isEmpty()) { return this; } final JsonHUAttributes attributes2New = attributes2.retainOnlyAttributesInOrder(displayedAttributeCodesOnly);
if (Objects.equals(attributes2New, this.attributes2)) { return this; } return toBuilder() .attributes2(attributes2New) .attributes(attributes2New.toJsonHUAttributeCodeAndValues()) .build(); } public JsonHU withLayoutSections(@Nullable List<String> layoutSections) { final ImmutableList<String> layoutSectionsNorm = layoutSections == null || layoutSections.isEmpty() ? null : ImmutableList.copyOf(layoutSections); if (Objects.equals(layoutSectionsNorm, this.layoutSections)) { return this; } else { return toBuilder() .layoutSections(layoutSectionsNorm) .build(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonHU.java
1
请完成以下Java代码
public BadUserRequestException exceptionSettingTransientVariablesAsyncNotSupported(String variableName) { return new BadUserRequestException(exceptionMessage( "044", "Setting transient variable '{}' asynchronously is currently not supported.", variableName)); } public void debugNotAllowedToResolveCalledProcess(String calledProcessId, String callingProcessId, String callActivityId, Throwable cause) { logDebug("046", "Resolving a called process definition {} for {} in {} was not possible. Reason: {}", calledProcessId, callActivityId, callingProcessId, cause.getMessage()); } public void warnFilteringDuplicatesEnabledWithNullDeploymentName() { logWarn("047", "Deployment name set to null. Filtering duplicates will not work properly."); } public void warnReservedErrorCode(int initialCode) { logWarn("048", "With error code {} you are using a reserved error code. Falling back to default error code 0. " + "If you want to override built-in error codes, please disable the built-in error code provider.", initialCode); } public void warnResetToBuiltinCode(Integer builtinCode, int initialCode) { logWarn("049", "You are trying to override the built-in code {} with {}. " + "Falling back to built-in code. If you want to override built-in error codes, " + "please disable the built-in error code provider.", builtinCode, initialCode); } public ProcessEngineException exceptionSettingJobRetriesAsyncNoJobsSpecified() { return new ProcessEngineException(exceptionMessage( "050", "You must specify at least one of jobIds or jobQuery.")); } public ProcessEngineException exceptionSettingJobRetriesAsyncNoProcessesSpecified() { return new ProcessEngineException(exceptionMessage(
"051", "You must specify at least one of or one of processInstanceIds, processInstanceQuery, or historicProcessInstanceQuery.")); } public ProcessEngineException exceptionSettingJobRetriesJobsNotSpecifiedCorrectly() { return new ProcessEngineException(exceptionMessage( "052", "You must specify exactly one of jobId, jobIds or jobDefinitionId as parameter. The parameter can not be null.")); } public ProcessEngineException exceptionNoJobFoundForId(String jobId) { return new ProcessEngineException(exceptionMessage( "053", "No job found with id '{}'.'", jobId)); } public ProcessEngineException exceptionJobRetriesMustNotBeNegative(Integer retries) { return new ProcessEngineException(exceptionMessage( "054", "The number of job retries must be a non-negative Integer, but '{}' has been provided.", retries)); } public ProcessEngineException exceptionWhileRetrievingDiagnosticsDataRegistryNull() { return new ProcessEngineException( exceptionMessage("055", "Error while retrieving diagnostics data. Diagnostics registry was not initialized.")); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CommandLogger.java
1
请在Spring Boot框架中完成以下Java代码
public Object size() { return partsMap.size(); } public <T> Stream<T> map(@NonNull final Function<PackingItemPart, T> mapper) { return partsMap .values() .stream() .map(mapper); } public <T> Optional<T> mapReduce(@NonNull final Function<PackingItemPart, T> mapper) { final ImmutableSet<T> result = map(mapper) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (result.isEmpty()) { return Optional.empty(); } else if (result.size() == 1) { final T singleResult = result.iterator().next(); return Optional.of(singleResult); } else { throw new AdempiereException("Got more than one result: " + result); } } public void setFrom(final PackingItemParts from) { partsMap.clear(); partsMap.putAll(from.partsMap); } public Optional<Quantity> getQtySum() { return map(PackingItemPart::getQty) .reduce(Quantity::add); } public List<PackingItemPart> toList() { return ImmutableList.copyOf(partsMap.values()); } public I_C_UOM getCommonUOM() { //validate that all qtys have the same UOM mapReduce(part -> part.getQty().getUomId()) .orElseThrow(()-> new AdempiereException("Missing I_C_UOM!") .appendParametersToMessage() .setParameter("Parts", this));
return toList().get(0).getQty().getUOM(); } @Override public Iterator<PackingItemPart> iterator() { return toList().iterator(); } public void clear() { partsMap.clear(); } public void addQtys(final PackingItemParts partsToAdd) { partsToAdd.toList() .forEach(this::addQty); } private void addQty(final PackingItemPart part) { partsMap.compute(part.getId(), (id, existingPart) -> existingPart != null ? existingPart.addQty(part.getQty()) : part); } public void removePart(final PackingItemPart part) { partsMap.remove(part.getId(), part); } public void updatePart(@NonNull final PackingItemPart part) { partsMap.put(part.getId(), part); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemParts.java
2
请完成以下Java代码
public TargetDataLine getTargetDataLineForRecord() { TargetDataLine line; DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { return null; } try { line = (TargetDataLine) AudioSystem.getLine(info); line.open(format, line.getBufferSize()); } catch (final Exception ex) { return null; } return line; } public AudioInputStream getAudioInputStream() { return audioInputStream; } public AudioFormat getFormat() {
return format; } public void setFormat(AudioFormat format) { this.format = format; } public Thread getThread() { return thread; } public double getDuration() { return duration; } }
repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\example\soundapi\SoundRecorder.java
1
请在Spring Boot框架中完成以下Java代码
public void sortStepsByCreated(I_AD_Migration migration) { if (migration == null || migration.getAD_Migration_ID() <= 0) { return; } final List<I_AD_MigrationStep> steps = Services.get(IMigrationDAO.class).retrieveSteps(migration, true); Collections.sort(steps, new Comparator<I_AD_MigrationStep>() { @Override public int compare(I_AD_MigrationStep s1, I_AD_MigrationStep s2) { return s1.getCreated().compareTo(s2.getCreated()); } }); int seqNo = 10; for (final I_AD_MigrationStep step : steps) { step.setSeqNo(seqNo); InterfaceWrapperHelper.save(step); seqNo += 10; } } @Override public void mergeMigration(final I_AD_Migration to, final I_AD_Migration from) { Services.get(IMigrationDAO.class).mergeMigration(to, from); } @Override public String getSummary(I_AD_Migration migration) { if (migration == null) { return ""; } return "Migration[" + migration.getSeqNo() + "-" + migration.getName() + "-" + migration.getEntityType()
+ ", ID=" + migration.getAD_Migration_ID() + "]"; } @Override public void setSeqNo(final I_AD_Migration migration) { final int maxSeqNo = Services.get(IMigrationDAO.class).getMigrationLastSeqNo(migration); final int nextSeqNo = maxSeqNo + 10; migration.setSeqNo(nextSeqNo); } @Override public String getSummary(final I_AD_MigrationStep step) { if (step == null) { return ""; } final I_AD_Migration parent = step.getAD_Migration(); return "Migration: " + parent.getName() + ", Step: " + step.getSeqNo() + ", Type: " + step.getStepType(); } @Override public void setSeqNo(final I_AD_MigrationStep step) { final int maxSeqNo = Services.get(IMigrationDAO.class).getMigrationStepLastSeqNo(step); final int nextSeqNo = maxSeqNo + 10; step.setSeqNo(nextSeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\service\impl\MigrationBL.java
2
请完成以下Java代码
public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } @CamundaQueryParam("processInstanceId") public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @CamundaQueryParam("executionId") public void setExecutionId(String executionId) { this.executionId = executionId; } @CamundaQueryParam("caseDefinitionId") public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @CamundaQueryParam("caseInstanceId") public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @CamundaQueryParam("caseExecutionId") public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } @CamundaQueryParam("taskId") public void setTaskId(String taskId) { this.taskId = taskId; } @CamundaQueryParam("jobId") public void setJobId(String jobId) { this.jobId = jobId; } @CamundaQueryParam("jobDefinitionId") public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } @CamundaQueryParam("batchId") public void setBatchId(String batchId) { this.batchId = batchId; } @CamundaQueryParam("userId") public void setUserId(String userId) { this.userId = userId; } @CamundaQueryParam("operationId") public void setOperationId(String operationId) { this.operationId = operationId; } @CamundaQueryParam("externalTaskId") public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId; } @CamundaQueryParam("operationType") public void setOperationType(String operationType) { this.operationType = operationType; } @CamundaQueryParam("entityType") public void setEntityType(String entityType) { this.entityType = entityType; } @CamundaQueryParam(value = "entityTypeIn", converter = StringArrayConverter.class) public void setEntityTypeIn(String[] entityTypes) { this.entityTypes = entityTypes; } @CamundaQueryParam("category") public void setcategory(String category) { this.category = category; } @CamundaQueryParam(value = "categoryIn", converter = StringArrayConverter.class) public void setCategoryIn(String[] categories) { this.categories = categories; } @CamundaQueryParam("property") public void setProperty(String property) { this.property = property; } @CamundaQueryParam(value = "afterTimestamp", converter = DateConverter.class) public void setAfterTimestamp(Date after) { this.afterTimestamp = after; } @CamundaQueryParam(value = "beforeTimestamp", converter = DateConverter.class) public void setBeforeTimestamp(Date before) { this.beforeTimestamp = before; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public void init(H http) { super.init(http); initDefaultLoginFilter(http); ExceptionHandlingConfigurer<H> exceptions = http.getConfigurer(ExceptionHandlingConfigurer.class); if (exceptions != null) { AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(); RequestMatcher requestMatcher = getAuthenticationEntryPointMatcher(http); exceptions.defaultDeniedHandlerForMissingAuthority((ep) -> ep.addEntryPointFor(entryPoint, requestMatcher), FactorGrantedAuthority.PASSWORD_AUTHORITY); } } @Override protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) { return getRequestMatcherBuilder().matcher(HttpMethod.POST, loginProcessingUrl); } /** * Gets the HTTP parameter that is used to submit the username. * @return the HTTP parameter that is used to submit the username */ private String getUsernameParameter() { return getAuthenticationFilter().getUsernameParameter(); } /** * Gets the HTTP parameter that is used to submit the password. * @return the HTTP parameter that is used to submit the password */ private String getPasswordParameter() { return getAuthenticationFilter().getPasswordParameter(); } /** * If available, initializes the {@link DefaultLoginPageGeneratingFilter} shared * object.
* @param http the {@link HttpSecurityBuilder} to use */ private void initDefaultLoginFilter(H http) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http .getSharedObject(DefaultLoginPageGeneratingFilter.class); if (loginPageGeneratingFilter != null && !isCustomLoginPage()) { loginPageGeneratingFilter.setFormLoginEnabled(true); loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter()); loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter()); loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl()); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\FormLoginConfigurer.java
2
请完成以下Java代码
public final IHUAttributesDAO getHUAttributesDAO() { Check.assumeNotNull(huAttributesDAO, "huAttributesDAO not null"); return huAttributesDAO; } @Override public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO) { this.huAttributesDAO = huAttributesDAO; for (final IAttributeStorageFactory factory : factories) { factory.setHUAttributesDAO(huAttributesDAO); } } @Override public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO(); } @Override public IHUStorageFactory getHUStorageFactory() { return huStorageFactory; } @Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory; for (final IAttributeStorageFactory factory : factories) { factory.setHUStorageFactory(huStorageFactory); } } @Override public void flush() { for (final IAttributeStorageFactory factory : factories) { factory.flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageFactory.java
1
请完成以下Java代码
private static POSCashJournalLine fromRecord(final I_C_POS_JournalLine record, final CurrencyId currencyId) { return POSCashJournalLine.builder() .type(POSCashJournalLineType.ofCode(record.getType())) .amount(Money.of(record.getAmount(), currencyId)) .cashierId(UserId.ofRepoId(record.getCashier_ID())) .description(record.getDescription()) .posOrderAndPaymentId(POSOrderAndPaymentId.ofRepoIdsOrNull(record.getC_POS_Order_ID(), record.getC_POS_Payment_ID())) .build(); } private static void updateRecord(final I_C_POS_Journal record, final POSCashJournal from) { record.setC_POS_ID(from.getTerminalId().getRepoId()); record.setDateTrx(Timestamp.from(from.getDateTrx())); record.setC_Currency_ID(from.getCurrencyId().getRepoId()); record.setCashBeginningBalance(from.getCashBeginningBalance().toBigDecimal()); record.setCashEndingBalance(from.getCashEndingBalance().toBigDecimal()); record.setOpeningNote(from.getOpeningNote()); record.setClosingNote(from.getClosingNote()); record.setIsClosed(from.isClosed()); } private static void updateRecord(final I_C_POS_JournalLine record, final POSCashJournalLine from) { record.setType(from.getType().getCode()); record.setAmount(from.getAmount().toBigDecimal()); record.setCashier_ID(from.getCashierId().getRepoId()); record.setDescription(from.getDescription()); record.setC_POS_Order_ID(from.getPosOrderAndPaymentId() != null ? from.getPosOrderAndPaymentId().getOrderId().getRepoId() : -1); record.setC_POS_Payment_ID(from.getPosOrderAndPaymentId() != null ? from.getPosOrderAndPaymentId().getPaymentId().getRepoId() : -1); } public POSCashJournal changeJournalById(@NonNull final POSCashJournalId cashJournalId, @NonNull final Consumer<POSCashJournal> updater) { final I_C_POS_Journal record = retrieveRecordById(cashJournalId); final List<I_C_POS_JournalLine> lineRecords = retrieveLineRecordsByJournalId(cashJournalId); final POSCashJournal journal = fromRecord(record, lineRecords); updater.accept(journal); updateRecord(record, journal); InterfaceWrapperHelper.save(record);
final ImmutableList<POSCashJournalLine> lines = journal.getLines(); for (int i = 0; i < lines.size(); i++) { final POSCashJournalLine line = lines.get(i); I_C_POS_JournalLine lineRecord = i < lineRecords.size() ? lineRecords.get(i) : null; if (lineRecord == null) { lineRecord = InterfaceWrapperHelper.newInstance(I_C_POS_JournalLine.class); lineRecord.setC_POS_Journal_ID(record.getC_POS_Journal_ID()); } lineRecord.setAD_Org_ID(record.getAD_Org_ID()); updateRecord(lineRecord, line); InterfaceWrapperHelper.save(lineRecord); } for (int i = lines.size(); i < lineRecords.size(); i++) { InterfaceWrapperHelper.delete(lineRecords.get(i)); } return journal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSCashJournalRepository.java
1
请完成以下Java代码
private static void addContainers(Workspace workspace) { Model model = workspace.getModel(); SoftwareSystem paymentTerminal = model.getSoftwareSystemWithName(PAYMENT_TERMINAL); Container f5 = paymentTerminal.addContainer("Payment Load Balancer", "Payment Load Balancer", "F5"); Container jvm1 = paymentTerminal.addContainer("JVM-1", "JVM-1", "Java Virtual Machine"); Container jvm2 = paymentTerminal.addContainer("JVM-2", "JVM-2", "Java Virtual Machine"); Container jvm3 = paymentTerminal.addContainer("JVM-3", "JVM-3", "Java Virtual Machine"); Container oracle = paymentTerminal.addContainer("oracleDB", "Oracle Database", "RDBMS"); f5.uses(jvm1, "route"); f5.uses(jvm2, "route"); f5.uses(jvm3, "route"); jvm1.uses(oracle, "storage"); jvm2.uses(oracle, "storage"); jvm3.uses(oracle, "storage"); ContainerView view = workspace.getViews().createContainerView(paymentTerminal, CONTAINER_VIEW, "Container View"); view.addAllContainers(); } private static void exportToPlantUml(View view) throws WorkspaceWriterException { StringWriter stringWriter = new StringWriter(); PlantUMLWriter plantUMLWriter = new PlantUMLWriter(); plantUMLWriter.write(view, stringWriter); System.out.println(stringWriter.toString()); } private static Workspace getSoftwareSystem() { Workspace workspace = new Workspace("Payment Gateway", "Payment Gateway"); Model model = workspace.getModel(); Person user = model.addPerson("Merchant", "Merchant"); SoftwareSystem paymentTerminal = model.addSoftwareSystem(PAYMENT_TERMINAL, "Payment Terminal"); user.uses(paymentTerminal, "Makes payment");
SoftwareSystem fraudDetector = model.addSoftwareSystem(FRAUD_DETECTOR, "Fraud Detector"); paymentTerminal.uses(fraudDetector, "Obtains fraud score"); ViewSet viewSet = workspace.getViews(); SystemContextView contextView = viewSet.createSystemContextView(workspace.getModel().getSoftwareSystemWithName(PAYMENT_TERMINAL), SOFTWARE_SYSTEM_VIEW, "Payment Gateway Diagram"); contextView.addAllElements(); return workspace; } private static void addStyles(ViewSet viewSet) { Styles styles = viewSet.getConfiguration().getStyles(); styles.addElementStyle(Tags.ELEMENT).color("#000000"); styles.addElementStyle(Tags.PERSON).background("#ffbf00").shape(Shape.Person); styles.addElementStyle(Tags.CONTAINER).background("#facc2E"); styles.addRelationshipStyle(Tags.RELATIONSHIP).routing(Routing.Orthogonal); styles.addRelationshipStyle(Tags.ASYNCHRONOUS).dashed(true); styles.addRelationshipStyle(Tags.SYNCHRONOUS).dashed(false); } }
repos\tutorials-master\spring-structurizr\src\main\java\com\baeldung\structurizr\StructurizrSimple.java
1
请完成以下Java代码
public class M_ShipmentSchedule_CloseShipmentSchedules extends JavaProcess { @Override protected String doIt() throws Exception { final IShipmentSchedulePA shipmentSchedulePA = Services.get(IShipmentSchedulePA.class); final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); final IQueryFilter<I_M_ShipmentSchedule> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); IQueryBuilder<I_M_ShipmentSchedule> queryBuilderForShipmentScheduleSelection = shipmentSchedulePA.createQueryForShipmentScheduleSelection(getCtx(), userSelectionFilter); // TODO: filter for picking candidates! final Iterator<I_M_ShipmentSchedule> schedulesToUpdateIterator = queryBuilderForShipmentScheduleSelection .addEqualsFilter(I_M_ShipmentSchedule.COLUMNNAME_QtyPickList, BigDecimal.ZERO) .create() .iterate(I_M_ShipmentSchedule.class);
if (!schedulesToUpdateIterator.hasNext()) { throw new AdempiereException("@NoSelection@"); } while (schedulesToUpdateIterator.hasNext()) { final I_M_ShipmentSchedule schedule = schedulesToUpdateIterator.next(); shipmentScheduleBL.closeShipmentSchedule(schedule); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_CloseShipmentSchedules.java
1
请完成以下Java代码
public boolean canTransform(String feelExpression) { return splitExpression(feelExpression).size() > 1; } public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { List<String> juelExpressions = transformExpressions(transform, feelExpression, inputName); return joinExpressions(juelExpressions); } protected List<String> collectExpressions(String feelExpression) { return splitExpression(feelExpression); } private List<String> splitExpression(String feelExpression) { return Arrays.asList(feelExpression.split(COMMA_SEPARATOR_REGEX, -1)); } protected List<String> transformExpressions(FeelToJuelTransform transform, String feelExpression, String inputName) { List<String> expressions = collectExpressions(feelExpression); List<String> juelExpressions = new ArrayList<String>(); for (String expression : expressions) { if (!expression.trim().isEmpty()) { String juelExpression = transform.transformSimplePositiveUnaryTest(expression, inputName); juelExpressions.add(juelExpression); }
else { throw LOG.invalidListExpression(feelExpression); } } return juelExpressions; } protected String joinExpressions(List<String> juelExpressions) { StringBuilder builder = new StringBuilder(); builder.append("(").append(juelExpressions.get(0)).append(")"); for (int i = 1; i < juelExpressions.size(); i++) { builder.append(" || (").append(juelExpressions.get(i)).append(")"); } return builder.toString(); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\transform\ListTransformer.java
1
请完成以下Java代码
public void setM_ReceiptSchedule(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule M_ReceiptSchedule) { set_ValueFromPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class, M_ReceiptSchedule); } @Override public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID); } @Override public int getM_ReceiptSchedule_ID()
{ return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_ExportAudit.java
1
请完成以下Java代码
public I_C_AcctSchema_GL retrieveAcctSchemaGLRecordOrNull(@NonNull final AcctSchemaId acctSchemaId) { return queryBL.createQueryBuilderOutOfTrx(I_C_AcctSchema_GL.class) .addEqualsFilter(I_C_AcctSchema_GL.COLUMN_C_AcctSchema_ID, acctSchemaId) .create() .firstOnly(I_C_AcctSchema_GL.class); } @Override public void changeAcctSchemaAutomaticPeriodId(@NonNull final AcctSchemaId acctSchemaId, final int periodId) { Check.assumeGreaterThanZero(periodId, "periodId"); final I_C_AcctSchema acctSchemaRecord = InterfaceWrapperHelper.loadOutOfTrx(acctSchemaId, I_C_AcctSchema.class); Check.assumeNotNull(acctSchemaRecord, "Accounting schema shall exists for {}", acctSchemaId); acctSchemaRecord.setC_Period_ID(periodId); InterfaceWrapperHelper.saveRecord(acctSchemaRecord); } private ImmutableSet<CostElementId> retrievePostOnlyForCostElementIds(@NonNull final AcctSchemaId acctSchemaId) { return queryBL .createQueryBuilderOutOfTrx(I_C_AcctSchema_CostElement.class) .addEqualsFilter(I_C_AcctSchema_CostElement.COLUMN_C_AcctSchema_ID, acctSchemaId) .addOnlyActiveRecordsFilter() .create() .listDistinct(I_C_AcctSchema_CostElement.COLUMNNAME_M_CostElement_ID, Integer.class) .stream() .map(CostElementId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } @ToString private static class AcctSchemasMap { private final ImmutableMap<AcctSchemaId, AcctSchema> acctSchemas; public AcctSchemasMap(final List<AcctSchema> acctSchemas) { this.acctSchemas = Maps.uniqueIndex(acctSchemas, AcctSchema::getId); } public AcctSchema getById(@NonNull final AcctSchemaId acctSchemaId) { final AcctSchema acctSchema = acctSchemas.get(acctSchemaId); if (acctSchema == null) { throw new AdempiereException("No accounting schema found for " + acctSchemaId); } return acctSchema; } public List<AcctSchema> getByClientId(@NonNull final ClientId clientId, @Nullable final AcctSchemaId primaryAcctSchemaId) { final ImmutableList.Builder<AcctSchema> result = ImmutableList.builder(); // Primary accounting schema shall be returned first if (primaryAcctSchemaId != null)
{ result.add(getById(primaryAcctSchemaId)); } for (final AcctSchema acctSchema : acctSchemas.values()) { if (acctSchema.getId().equals(primaryAcctSchemaId)) { continue; } if (clientId.equals(acctSchema.getClientId())) { result.add(acctSchema); } } return result.build(); } public List<AcctSchema> getByChartOfAccountsId(@NonNull final ChartOfAccountsId chartOfAccountsId) { return acctSchemas.values() .stream() .filter(acctSchema -> ChartOfAccountsId.equals(acctSchema.getChartOfAccountsId(), chartOfAccountsId)) .collect(ImmutableList.toImmutableList()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AcctSchemaDAO.java
1
请完成以下Java代码
public void enableTLSv12UsingSSLParameters() throws UnknownHostException, IOException { SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url.trim(), port); SSLParameters params = new SSLParameters(); params.setProtocols(new String[] { "TLSv1.2" }); sslSocket.setSSLParameters(params); sslSocket.startHandshake(); handleCommunication(sslSocket, "SSLSocketFactory-SSLParameters"); } public void enableTLSv12UsingProtocol() throws IOException { SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url, port); sslSocket.setEnabledProtocols(new String[] { "TLSv1.2" }); sslSocket.startHandshake(); handleCommunication(sslSocket, "SSLSocketFactory-EnabledProtocols"); } public void enableTLSv12UsingHttpConnection() throws IOException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException { URL urls = new URI("https://" + url + ":" + port).toURL(); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, new SecureRandom()); HttpsURLConnection connection = (HttpsURLConnection) urls.openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory()); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String input; while ((input = br.readLine()) != null) { logger.info(input); } } logger.debug("Created TLSv1.2 connection on HttpsURLConnection"); } public void enableTLSv12UsingSSLContext() throws NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, new SecureRandom()); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); SSLSocket socket = (SSLSocket) socketFactory.createSocket(url, port); handleCommunication(socket, "SSLContext"); } }
repos\tutorials-master\core-java-modules\core-java-security-5\src\main\java\com\baeldung\ssl\EnableTLSv12.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentData { ProductId productId; @JsonIgnore boolean empty; Quantity qtyInStockUom; Quantity qtyNominal; Quantity qtyCatch; List<DeliveredQtyItem> deliveredQtyItems; @Builder @JsonCreator private ShipmentData( @JsonProperty("productId") @NonNull ProductId productId, @JsonProperty("qtyInStockUom") @NonNull Quantity qtyInStockUom, @JsonProperty("qtyNominal") @NonNull Quantity qtyNominal, @JsonProperty("qtyCatch") @Nullable Quantity qtyCatch, @JsonProperty("deliveredQtyItems") @Singular List<DeliveredQtyItem> deliveredQtyItems) { this.productId = productId; this.empty = deliveredQtyItems.isEmpty(); this.qtyInStockUom = qtyInStockUom; this.qtyNominal = qtyNominal; this.qtyCatch = qtyCatch; this.deliveredQtyItems = deliveredQtyItems; }
public StockQtyAndUOMQty computeInvoicableQtyDelivered(@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn) { if(empty) { return StockQtyAndUOMQtys.createZero(productId, getQtyNominal().getUomId()); } Quantity deliveredInUom; switch (invoicableQtyBasedOn) { case CatchWeight: deliveredInUom = coalesce(getQtyCatch(), getQtyNominal()); break; case NominalWeight: deliveredInUom = getQtyNominal(); break; default: throw new AdempiereException("Unexpected InvoicableQtyBasedOn=" + invoicableQtyBasedOn); } return StockQtyAndUOMQty.builder() .productId(productId) .stockQty(qtyInStockUom) .uomQty(deliveredInUom).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\ShipmentData.java
2
请在Spring Boot框架中完成以下Java代码
public VirtualThreadTaskExecutor taskExecutor() { return new VirtualThreadTaskExecutor("virtual-thread-executor"); } @Bean public FlatFileItemReader<Coffee> reader() { return new FlatFileItemReaderBuilder<Coffee>().name("coffeeItemReader") .resource(new ClassPathResource(fileInput)) .delimited() .names(new String[] { "brand", "origin", "characteristics" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<Coffee>() {{ setTargetType(Coffee.class); }}) .build(); } @Bean public CoffeeItemProcessor processor() { return new CoffeeItemProcessor(); } @Bean public JdbcBatchItemWriter<Coffee> writer(DataSource dataSource) { return new JdbcBatchItemWriterBuilder<Coffee>().itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()) .sql("INSERT INTO coffee (brand, origin, characteristics) VALUES (:brand, :origin, :characteristics)") .dataSource(dataSource) .build(); } @Bean
public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) { return new JobBuilder("importUserJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .flow(step1) .end() .build(); } @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter<Coffee> writer, VirtualThreadTaskExecutor taskExecutor) { return new StepBuilder("step1", jobRepository) .<Coffee, Coffee> chunk(10, transactionManager) .reader(reader()) .processor(processor()) .writer(writer) .taskExecutor(taskExecutor) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\bootbatch\BatchConfiguration.java
2
请完成以下Java代码
public class PrintDeviceQRCodes extends JavaProcess { private final DeviceAccessorsHubFactory deviceAccessorsHubFactory = SpringContextHolder.instance.getBean(DeviceAccessorsHubFactory.class); private final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class); public static final String PARAM_DeviceId = "DeviceId"; @Param(parameterName = PARAM_DeviceId) private String p_deviceIdStr; @ProcessParamLookupValuesProvider(parameterName = "DeviceId", numericKey = false) public LookupValuesList getDeviceIds() { return deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() .streamAllDeviceAccessors() .map(PrintDeviceQRCodes::toLookupValue) .distinct() .collect(LookupValuesList.collect()); } private static LookupValue toLookupValue(DeviceAccessor deviceAccessor) { return LookupValue.StringLookupValue.of(deviceAccessor.getId().getAsString(), deviceAccessor.getDisplayName()); } @Override protected String doIt() { final ImmutableList<PrintableQRCode> qrCodes = streamSelectedDevices() .map(PrintDeviceQRCodes::toDeviceQRCode) .map(DeviceQRCode::toPrintableQRCode) .collect(ImmutableList.toImmutableList()); final QRCodePDFResource pdf = globalQRCodeService.createPDF(qrCodes); getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType()); return MSG_OK; } private Stream<DeviceAccessor> streamSelectedDevices() { final DeviceId onlyDeviceId = StringUtils.trimBlankToOptional(p_deviceIdStr) .map(DeviceId::ofString) .orElse(null); if (onlyDeviceId != null)
{ final DeviceAccessor deviceAccessor = deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() .getDeviceAccessorById(onlyDeviceId) .orElseThrow(() -> new AdempiereException("No device found for id: " + onlyDeviceId)); return Stream.of(deviceAccessor); } else { return deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() .streamAllDeviceAccessors(); } } private static DeviceQRCode toDeviceQRCode(final DeviceAccessor deviceAccessor) { return DeviceQRCode.builder() .deviceId(deviceAccessor.getId()) .caption(deviceAccessor.getDisplayName().getDefaultValue()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\devices\webui\process\PrintDeviceQRCodes.java
1
请完成以下Java代码
public class DocumentDeliveryLocationAdapter implements IDocumentDeliveryLocationAdapter, RecordBasedLocationAdapter<DocumentDeliveryLocationAdapter> { private final I_M_InOut delegate; DocumentDeliveryLocationAdapter(@NonNull final I_M_InOut delegate) { this.delegate = delegate; } @Override public int getDropShip_BPartner_ID() { return delegate.getDropShip_BPartner_ID(); } @Override public void setDropShip_BPartner_ID(final int DropShip_BPartner_ID) { delegate.setDropShip_BPartner_ID(DropShip_BPartner_ID); } @Override public int getDropShip_Location_ID() { return delegate.getDropShip_Location_ID(); } @Override public void setDropShip_Location_ID(final int DropShip_Location_ID) { delegate.setDropShip_Location_ID(DropShip_Location_ID); } @Override public int getDropShip_Location_Value_ID() { return delegate.getDropShip_Location_Value_ID(); } @Override public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID) { delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID); } @Override public int getDropShip_User_ID() { return delegate.getDropShip_User_ID(); } @Override public void setDropShip_User_ID(final int DropShip_User_ID) { delegate.setDropShip_User_ID(DropShip_User_ID); } @Override public int getM_Warehouse_ID() { return delegate.getM_Warehouse_ID(); }
@Override public boolean isDropShip() { return delegate.isDropShip(); } @Override public String getDeliveryToAddress() { return delegate.getDeliveryToAddress(); } @Override public void setDeliveryToAddress(final String address) { delegate.setDeliveryToAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from); } @Override public I_M_InOut getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentDeliveryLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentDeliveryLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentDeliveryLocationAdapter.java
1
请完成以下Java代码
public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setIsShipToDefault (final boolean IsShipToDefault) { set_Value (COLUMNNAME_IsShipToDefault, IsShipToDefault); } @Override public boolean isShipToDefault() { return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault); } @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 setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); }
@Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java
1