instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private String getAuthenticationType(AuthenticationObservationContext context) { if (context.getAuthenticationRequest() == null) { return "unknown"; } return context.getAuthenticationRequest().getClass().getSimpleName(); } private String getAuthenticationMethod(AuthenticationObservationContext context) { if (context.getAuthenticationManagerClass() == null) { return "unknown"; } return context.getAuthenticationManagerClass().getSimpleName(); } private String getAuthenticationResult(AuthenticationObservationContext context) { if (context.getAuthenticationResult() == null) { return "n/a"; } return context.getAuthenticationResult().getClass().getSimpleName(); }
private String getAuthenticationFailureType(AuthenticationObservationContext context) { if (context.getError() == null) { return "n/a"; } return context.getError().getClass().getSimpleName(); } /** * {@inheritDoc} */ @Override public boolean supportsContext(Observation.Context context) { return context instanceof AuthenticationObservationContext; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AuthenticationObservationConvention.java
1
请完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getPersonNumber() { return personNumber; } public void setPersonNumber(Long personNumber) { this.personNumber = personNumber; } public Boolean getIsActive() { return isActive; } public void setIsActive(Boolean isActive) { this.isActive = isActive; } public String getScode() { return securityNumber; }
public void setScode(String scode) { this.securityNumber = scode; } public String getDcode() { return departmentCode; } public void setDcode(String dcode) { this.departmentCode = dcode; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\uniqueconstraints\Person.java
1
请完成以下Java代码
public int delete() { log.info(""); StringBuffer sql = new StringBuffer ("DELETE FROM AD_Preference WHERE "); sql.append("AD_Client_ID=").append(cbClient.isSelected() ? m_AD_Client_ID : 0); sql.append(" AND AD_Org_ID=").append(cbOrg.isSelected() ? m_AD_Org_ID : 0); if (cbUser.isSelected()) { sql.append(" AND AD_User_ID=").append(m_AD_User_ID); } else { sql.append(" AND AD_User_ID IS NULL"); } if (cbWindow.isSelected()) { sql.append(" AND AD_Window_ID=").append(m_adWindowId.getRepoId()); } else { sql.append(" AND AD_Window_ID IS NULL"); } sql.append(" AND Attribute='").append(m_Attribute).append("'"); // log.debug( sql.toString()); int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), null); if (no > 0) { Env.setContext(m_ctx, getContextKey(), (String)null); } return no; } // delete /** * Get Context Key * @return Context Key */ private String getContextKey() { if (cbWindow.isSelected()) { return "P" + m_adWindowId.getRepoId() + "|" + m_Attribute; } else { return "P|" + m_Attribute; } } // getContextKey /** * Save to Disk */ public void insert() { log.info(""); // --- Delete first int no = delete(); // Handle NULL if (m_Value == null || m_Value.length() == 0) { if (DisplayType.isLookup(m_DisplayType)) { m_Value = "-1"; // -1 may cause problems (BPartner - M_DiscountSchema } else if (DisplayType.isDate(m_DisplayType)) { m_Value = " ";
} else { ADialog.warn(m_WindowNo, this, "ValuePreferenceNotInserted"); return; } } // --- Inserting int Client_ID = cbClient.isSelected() ? m_AD_Client_ID : 0; int Org_ID = cbOrg.isSelected() ? m_AD_Org_ID : 0; int AD_Preference_ID = DB.getNextID(m_ctx, I_AD_Preference.Table_Name); // StringBuffer sql = new StringBuffer ("INSERT INTO AD_Preference (" + "AD_Preference_ID, AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy,Updated,UpdatedBy," + "AD_Window_ID, AD_User_ID, Attribute, Value) VALUES ("); sql.append(AD_Preference_ID).append(",").append(Client_ID).append(",").append(Org_ID) .append(", 'Y',now(),").append(m_AD_User_ID).append(",now(),").append(m_AD_User_ID).append(", "); if (cbWindow.isSelected()) { sql.append(m_adWindowId.getRepoId()).append(","); } else { sql.append("NULL,") ; } if (cbUser.isSelected()) { sql.append(m_AD_User_ID).append(","); } else { sql.append("NULL,"); } // sql.append(DB.TO_STRING(m_Attribute)).append(",").append(DB.TO_STRING(m_Value)).append(")"); // log.debug( sql.toString()); no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), null); if (no == 1) { Env.setContext(m_ctx, getContextKey(), m_Value); ADialog.info(m_WindowNo, this, "ValuePreferenceInserted"); } else { ADialog.warn(m_WindowNo, this, "ValuePreferenceNotInserted"); } } // insert } // ValuePreference
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\ValuePreference.java
1
请在Spring Boot框架中完成以下Java代码
private Object getValue(String variableType, ExpressionTree expression, Object defaultValue) throws Exception { Object literalValue = expression.getLiteralValue(); if (literalValue != null) { return literalValue; } Object factoryValue = expression.getFactoryValue(); if (factoryValue != null) { return getFactoryValue(expression, factoryValue); } List<? extends ExpressionTree> arrayValues = expression.getArrayExpression(); if (arrayValues != null) { Object[] result = new Object[arrayValues.size()]; for (int i = 0; i < arrayValues.size(); i++) { Object value = getValue(variableType, arrayValues.get(i), null); if (value == null) { // One of the elements could not be resolved return defaultValue; } result[i] = value; } return result; } if (expression.getKind().equals("IDENTIFIER")) { return this.staticFinals.get(expression.toString()); } if (expression.getKind().equals("MEMBER_SELECT")) { Object value = WELL_KNOWN_STATIC_FINALS.get(expression.toString()); if (value != null) { return value; } Member selectedMember = expression.getSelectedMember(); // Type matching the expression, assuming an enum if (selectedMember != null && selectedMember.expression().equals(variableType)) { return ConventionUtils.toDashedCase(selectedMember.identifier().toLowerCase(Locale.ENGLISH)); } return null; } return null; }
private Object getFactoryValue(ExpressionTree expression, Object factoryValue) { Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF, DURATION_SUFFIX); if (durationValue != null) { return durationValue; } Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF, DATA_SIZE_SUFFIX); if (dataSizeValue != null) { return dataSizeValue; } Object periodValue = getFactoryValue(expression, factoryValue, PERIOD_OF, PERIOD_SUFFIX); if (periodValue != null) { return periodValue; } return factoryValue; } private Object getFactoryValue(ExpressionTree expression, Object factoryValue, String prefix, Map<String, String> suffixMapping) { Object instance = expression.getInstance(); if (instance != null && instance.toString().startsWith(prefix)) { String type = instance.toString(); type = type.substring(prefix.length(), type.indexOf('(')); String suffix = suffixMapping.get(type); return (suffix != null) ? factoryValue + suffix : null; } return null; } Map<String, Object> getFieldValues() { return this.fieldValues; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\JavaCompilerFieldValuesParser.java
2
请在Spring Boot框架中完成以下Java代码
class Image { @Id @GeneratedValue Long id; String name; String location; @Lob byte[] content; public Image() { } public Image(Long id) { this.id = id; } public Image(String name, String location) { this.name = name; this.location = location; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public long getId() { return id; } public void setId(long id) { this.id = id; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\db\indexing\Image.java
2
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Role name. @param RoleName Role name */ @Override public void setRoleName (java.lang.String RoleName) { set_Value (COLUMNNAME_RoleName, RoleName); } /** Get Role name. @return Role name */ @Override public java.lang.String getRoleName () { return (java.lang.String)get_Value(COLUMNNAME_RoleName);
} /** Set UserValue. @param UserValue UserValue */ @Override public void setUserValue (java.lang.String UserValue) { set_Value (COLUMNNAME_UserValue, UserValue); } /** Get UserValue. @return UserValue */ @Override public java.lang.String getUserValue () { return (java.lang.String)get_Value(COLUMNNAME_UserValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_User.java
1
请在Spring Boot框架中完成以下Java代码
public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public ArticleMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArticleMapping articleMapping = (ArticleMapping) o; return Objects.equals(this._id, articleMapping._id) && Objects.equals(this.customerId, articleMapping.customerId) && Objects.equals(this.updated, articleMapping.updated); } @Override public int hashCode() { return Objects.hash(_id, customerId, updated);
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArticleMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\ArticleMapping.java
2
请在Spring Boot框架中完成以下Java代码
public class Tweet { private String email; private String tweetText; private Date dateCreated; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTweetText() { return tweetText;
} public void setTweetText(String tweetText) { this.tweetText = tweetText; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\repositoryvsdaopattern\Tweet.java
2
请完成以下Java代码
public void setQueues(Map<String, DestinationInfo> queues) { this.queues = queues; } public Map<String, DestinationInfo> getTopics() { return topics; } public void setTopics(Map<String, DestinationInfo> topics) { this.topics = topics; } // DestinationInfo stores the Exchange name and routing key used // by our producers when posting messages static class DestinationInfo { private String exchange; private String routingKey; public String getExchange() {
return exchange; } public void setExchange(String exchange) { this.exchange = exchange; } public String getRoutingKey() { return routingKey; } public void setRoutingKey(String routingKey) { this.routingKey = routingKey; } } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-amqp\src\main\java\com\baeldung\spring\amqp\DestinationsConfig.java
1
请完成以下Java代码
public Optional<WebuiDocumentReferenceId> getDocumentReferenceId() { return referencing != null && !Check.isBlank(referencing.getReferenceId()) ? Optional.of(WebuiDocumentReferenceId.ofString(referencing.getReferenceId())) : Optional.empty(); } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Data public static final class JSONReferencing { @JsonProperty("referenceId") private final String referenceId; @JsonProperty("documentType") private final String documentType; @JsonProperty("documentIds") private final Set<String> documentIds; @JsonProperty("tabId") private final String tabId; @JsonProperty("rowIds") private final Set<String> rowIds; @JsonCreator private JSONReferencing( @JsonProperty("referenceId") final String referenceId, @JsonProperty("documentType") final String documentType, @JsonProperty("documentIds") final Set<String> documentIds, @JsonProperty("documentId") @Deprecated final String documentId, // but still used! @JsonProperty("tabId") final String tabId, @JsonProperty("rowIds") final Set<String> rowIds) { this.referenceId = referenceId; Preconditions.checkNotNull(documentType, "documentType is missing"); this.documentType = documentType; if (documentIds != null) { Preconditions.checkArgument(documentId == null, "deprecated 'documentId' shall be not set if 'documentIds' is set"); Preconditions.checkArgument(!documentIds.isEmpty(), "'documentIds' is empty"); this.documentIds = ImmutableSet.copyOf(documentIds); } else if (documentId != null)
{ this.documentIds = ImmutableSet.of(documentId); } else { throw new IllegalArgumentException("'documentIds' not provided"); } this.tabId = tabId; if (tabId != null) { if (this.documentIds.size() > 1) { throw new IllegalArgumentException("Only one documentId is allowed when tabId is set."); } if (rowIds == null || rowIds.isEmpty()) { throw new IllegalArgumentException("rowIds not provided"); } this.rowIds = ImmutableSet.copyOf(rowIds); } else { this.rowIds = null; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\json\JSONCreateViewRequest.java
1
请在Spring Boot框架中完成以下Java代码
public Quantity getHUCapacity( @NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final I_C_UOM uom) { final I_M_HU hu = handlingUnitsBL.getById(huId); return handlingUnitsBL .getStorageFactory() .getStorage(hu) .getQuantity(productId, uom); } @NonNull public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId) { final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId) .stream() .map(locatorId -> { final String caption = getLocatorName(locatorId); return LocatorInfo.builder() .id(locatorId) .caption(caption) .qrCode(LocatorQRCode.builder() .locatorId(locatorId) .caption(caption) .build()) .build(); }) .collect(ImmutableList.toImmutableList());
return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList); } @NonNull public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId) { return productBL.getCatchUOMId(productId); } @NonNull private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId) { final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId); return handlingUnitsBL.getLocatorIds(huIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java
2
请完成以下Java代码
public EventDefinitionParse sourceResource(String resource) { if (name == null) { name(resource); } setStreamSource(new ResourceStreamSource(resource)); return this; } public EventDefinitionParse sourceString(String string) { if (name == null) { name("string"); } setStreamSource(new StringStreamSource(string)); return this; } protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } /* * ------------------- GETTERS AND SETTERS ------------------- */ public List<EventDefinitionEntity> getEventDefinitions() { return eventDefinitions; }
public EventDeploymentEntity getDeployment() { return deployment; } public void setDeployment(EventDeploymentEntity deployment) { this.deployment = deployment; } public EventModel getEventModel() { return eventModel; } public void setEventModel(EventModel eventModel) { this.eventModel = eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\parser\EventDefinitionParse.java
1
请在Spring Boot框架中完成以下Java代码
public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the datequal property. * * @return * possible object is * {@link String } * */ public String getDATEQUAL() { return datequal; } /** * Sets the value of the datequal property. * * @param value * allowed object is * {@link String } * */ public void setDATEQUAL(String value) { this.datequal = value; } /** * Gets the value of the datefrom property. * * @return * possible object is * {@link String } * */ public String getDATEFROM() { return datefrom; } /** * Sets the value of the datefrom property. * * @param value * allowed object is * {@link String } * */
public void setDATEFROM(String value) { this.datefrom = value; } /** * Gets the value of the dateto property. * * @return * possible object is * {@link String } * */ public String getDATETO() { return dateto; } /** * Sets the value of the dateto property. * * @param value * allowed object is * {@link String } * */ public void setDATETO(String value) { this.dateto = value; } /** * Gets the value of the days property. * * @return * possible object is * {@link String } * */ public String getDAYS() { return days; } /** * Sets the value of the days property. * * @param value * allowed object is * {@link String } * */ public void setDAYS(String value) { this.days = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HDATE1.java
2
请在Spring Boot框架中完成以下Java代码
StandardConfigDataReference getReference() { return this.reference; } /** * Return the underlying Spring {@link Resource} being loaded. * @return the underlying resource * @since 2.4.2 */ public Resource getResource() { return this.resource; } /** * Return the profile or {@code null} if the resource is not profile specific. * @return the profile or {@code null} * @since 2.4.6 */ public @Nullable String getProfile() { return this.reference.getProfile(); } boolean isEmptyDirectory() { return this.emptyDirectory; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } StandardConfigDataResource other = (StandardConfigDataResource) obj; return (this.emptyDirectory == other.emptyDirectory) && isSameUnderlyingResource(this.resource, other.resource); } private boolean isSameUnderlyingResource(Resource ours, Resource other) { return ours.equals(other) || isSameFile(getUnderlyingFile(ours), getUnderlyingFile(other)); } private boolean isSameFile(@Nullable File ours, @Nullable File other) { return (ours != null) && ours.equals(other); } @Override public int hashCode() { File underlyingFile = getUnderlyingFile(this.resource); return (underlyingFile != null) ? underlyingFile.hashCode() : this.resource.hashCode(); } @Override public String toString() { if (this.resource instanceof FileSystemResource || this.resource instanceof FileUrlResource) {
try { return "file [" + this.resource.getFile() + "]"; } catch (IOException ex) { // Ignore } } return this.resource.toString(); } private @Nullable File getUnderlyingFile(Resource resource) { try { if (resource instanceof ClassPathResource || resource instanceof FileSystemResource || resource instanceof FileUrlResource) { return resource.getFile().getAbsoluteFile(); } } catch (IOException ex) { // Ignore } return null; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataResource.java
2
请完成以下Java代码
ApplicationContext getContext(ServletContext servletContext) { return SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(servletContext); } /** * Handles the HttpSessionEvent by publishing a {@link HttpSessionCreatedEvent} to the * application appContext. * @param event HttpSessionEvent passed in by the container */ @Override public void sessionCreated(HttpSessionEvent event) { extracted(event.getSession(), new HttpSessionCreatedEvent(event.getSession())); } /** * Handles the HttpSessionEvent by publishing a {@link HttpSessionDestroyedEvent} to * the application appContext. * @param event The HttpSessionEvent pass in by the container */ @Override public void sessionDestroyed(HttpSessionEvent event) { extracted(event.getSession(), new HttpSessionDestroyedEvent(event.getSession()));
} /** * @inheritDoc */ @Override public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) { extracted(event.getSession(), new HttpSessionIdChangedEvent(event.getSession(), oldSessionId)); } private void extracted(HttpSession session, ApplicationEvent e) { Log log = LogFactory.getLog(LOGGER_NAME); log.debug(LogMessage.format("Publishing event: %s", e)); getContext(session.getServletContext()).publishEvent(e); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\HttpSessionEventPublisher.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); }
@Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderLine_Detail.java
1
请完成以下Java代码
public int getM_Locator_From_ID() { return locatorFromId; } public int getM_Locator_To_ID() { return locatorToId; } public HUPackingMaterialMovementLineBuilder setProductIdSortComparator(final Comparator<Integer> productIdsSortComparator) { packingMaterialsCollector.setProductIdSortComparator(productIdsSortComparator); return this; } public void addHURecursively(final IQueryBuilder<I_M_HU_Assignment> huAssignments) { packingMaterialsCollector.releasePackingMaterialForHURecursively(huAssignments); } public List<HUPackingMaterialDocumentLineCandidate> getAndClearCandidates()
{ return packingMaterialsCollector.getAndClearCandidates(); } /** * Sets a shared "seen list" for added HUs. * * To be used in case you have multiple {@link HUPackingMaterialsCollector}s and you want if an HU is added to one of them then don't add it to the others. * * @param seenM_HU_IDs_ToAdd */ public void setSeenM_HU_IDs_ToAdd(final Set<Integer> seenM_HU_IDs_ToAdd) { packingMaterialsCollector.setSeenM_HU_IDs_ToAdd(seenM_HU_IDs_ToAdd); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\api\impl\HUPackingMaterialMovementLineBuilder.java
1
请完成以下Java代码
protected Void execute(CommandContext commandContext, TaskEntity task) { // Backwards compatibility if (task.getProcessDefinitionId() != null) { if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.submitTaskFormData(taskId, properties, completeTask); return null; } } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ExecutionEntity executionEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getExecutionId()); CommandContextUtil.getHistoryManager(commandContext) .recordFormPropertiesSubmitted(executionEntity, properties, taskId, processEngineConfiguration.getClock().getCurrentTime()); FormHandlerHelper formHandlerHelper = processEngineConfiguration.getFormHandlerHelper(); TaskFormHandler taskFormHandler = formHandlerHelper.getTaskFormHandlder(task);
if (taskFormHandler != null) { taskFormHandler.submitFormProperties(properties, executionEntity); if (completeTask) { TaskHelper.completeTask(task, null, null, null, null, null, commandContext); } } return null; } @Override protected String getSuspendedTaskExceptionPrefix() { return "Cannot submit a form to"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SubmitTaskFormCmd.java
1
请完成以下Java代码
public void setSKU (String SKU) { set_Value (COLUMNNAME_SKU, SKU); } /** Get SKU. @return Stock Keeping Unit */ public String getSKU () { return (String)get_Value(COLUMNNAME_SKU); } /** Set Tax Amount. @param TaxAmt Tax Amount for a document */ public void setTaxAmt (BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Tax Amount. @return Tax Amount for a document */ public BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Tax Indicator. @param TaxIndicator
Short form for Tax to be printed on documents */ public void setTaxIndicator (String TaxIndicator) { set_Value (COLUMNNAME_TaxIndicator, TaxIndicator); } /** Get Tax Indicator. @return Short form for Tax to be printed on documents */ public String getTaxIndicator () { return (String)get_Value(COLUMNNAME_TaxIndicator); } /** Set UPC/EAN. @param UPC Bar Code (Universal Product Code or its superset European Article Number) */ public void setUPC (String UPC) { set_Value (COLUMNNAME_UPC, UPC); } /** Get UPC/EAN. @return Bar Code (Universal Product Code or its superset European Article Number) */ public String getUPC () { return (String)get_Value(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java
1
请完成以下Java代码
public I_M_HU_Attribute getByAttributeIdOrNull(final AttributeId attributeId) { return huAttributes.get(attributeId); } public boolean isEmpty() { return huAttributes.isEmpty(); } @Override public Iterator<I_M_HU_Attribute> iterator() { return huAttributes.values().iterator(); } public List<I_M_HU_Attribute> toList() { return ImmutableList.copyOf(huAttributes.values()); } @Nullable public I_M_HU_Attribute put(final I_M_HU_Attribute huAttribute) {
final AttributeId attributeId = AttributeId.ofRepoId(huAttribute.getM_Attribute_ID()); return huAttributes.put(attributeId, huAttribute); } public void remove(final I_M_HU_Attribute huAttribute) { final AttributeId attributeId = AttributeId.ofRepoId(huAttribute.getM_Attribute_ID()); final I_M_HU_Attribute huAttributeRemoved = huAttributes.remove(attributeId); if (!Util.same(huAttribute, huAttributeRemoved)) { throw new AdempiereException("Given " + huAttribute + " was not found in internal cache or it's different (" + huAttributeRemoved + ")"); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\SaveDecoupledHUAttributesDAO.java
1
请完成以下Java代码
public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Date getRemovalTime() { return removalTime; } public Date getExecutionStartTime() { return executionStartTime; } public void setExecutionStartTime(final Date executionStartTime) { this.executionStartTime = executionStartTime; } public static HistoricBatchDto fromBatch(HistoricBatch historicBatch) { HistoricBatchDto dto = new HistoricBatchDto(); dto.id = historicBatch.getId(); dto.type = historicBatch.getType();
dto.totalJobs = historicBatch.getTotalJobs(); dto.batchJobsPerSeed = historicBatch.getBatchJobsPerSeed(); dto.invocationsPerBatchJob = historicBatch.getInvocationsPerBatchJob(); dto.seedJobDefinitionId = historicBatch.getSeedJobDefinitionId(); dto.monitorJobDefinitionId = historicBatch.getMonitorJobDefinitionId(); dto.batchJobDefinitionId = historicBatch.getBatchJobDefinitionId(); dto.tenantId = historicBatch.getTenantId(); dto.createUserId = historicBatch.getCreateUserId(); dto.startTime = historicBatch.getStartTime(); dto.endTime = historicBatch.getEndTime(); dto.removalTime = historicBatch.getRemovalTime(); dto.executionStartTime = historicBatch.getExecutionStartTime(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchDto.java
1
请完成以下Java代码
private String setDataToLevel() { String info = "-"; if (isClientLevelOnly()) { StringBuilder sql = new StringBuilder("UPDATE ") .append(getTableName()) .append(" SET AD_Org_ID=0 WHERE AD_Org_ID<>0 AND AD_Client_ID=?"); int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), getAD_Client_ID(), get_TrxName()); info = getTableName() + " set to Shared #" + no; log.info(info); } else if (isOrgLevelOnly()) { StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ") .append(getTableName()) .append(" WHERE AD_Org_ID=0 AND AD_Client_ID=?"); int no = DB.getSQLValue(get_TrxName(), sql.toString(), getAD_Client_ID()); info = getTableName() + " Shared records #" + no; log.info(info); } return info; } // setDataToLevel private String listChildRecords() { final StringBuilder info = new StringBuilder(); String sql = "SELECT AD_Table_ID, TableName " + "FROM AD_Table t " + "WHERE AccessLevel='3' AND IsView='N'" + " AND EXISTS (SELECT * FROM AD_Column c " + "WHERE t.AD_Table_ID=c.AD_Table_ID" + " AND c.IsParent='Y'" + " AND c.ColumnName IN (SELECT ColumnName FROM AD_Column cc " + "WHERE cc.IsKey='Y' AND cc.AD_Table_ID=?))"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, getAD_Table_ID()); rs = pstmt.executeQuery(); while (rs.next()) { String TableName = rs.getString(2); if (info.length() != 0) { info.append(", "); }
info.append(TableName); } } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); } return info.toString(); } @Override protected boolean beforeSave(boolean newRecord) { if (getAD_Org_ID() != 0) { setAD_Org_ID(0); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClientShare.java
1
请完成以下Java代码
private SelectedModelsList retrieveSelectedModels(final Class<?> modelClass) { final List<?> models = view.retrieveModelsByIds(getSelectedRowIds(), modelClass); return SelectedModelsList.of(models, modelClass); } @Override public <T> IQueryFilter<T> getQueryFilter(@NonNull final Class<T> recordClass) { final String tableName = InterfaceWrapperHelper.getTableName(recordClass); final SqlViewRowsWhereClause sqlWhereClause = view.getSqlWhereClause(getSelectedRowIds(), SqlOptions.usingTableName(tableName)); return sqlWhereClause.toQueryFilter(); } private static final class SelectedModelsList { private static SelectedModelsList of(final List<?> models, final Class<?> modelClass) { if (models == null || models.isEmpty()) { return EMPTY; } return new SelectedModelsList(models, modelClass); } private static final SelectedModelsList EMPTY = new SelectedModelsList(); private final ImmutableList<?> models; private final Class<?> modelClass; /** * empty constructor */ private SelectedModelsList() { models = ImmutableList.of(); modelClass = null; }
private SelectedModelsList(final List<?> models, final Class<?> modelClass) { super(); this.models = ImmutableList.copyOf(models); this.modelClass = modelClass; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("modelClass", modelClass) .add("models", models) .toString(); } public <T> List<T> getModels(final Class<T> modelClass) { // If loaded models list is empty, we can return an empty list directly if (models.isEmpty()) { return ImmutableList.of(); } // If loaded models have the same model class as the requested one // we can simple cast & return them if (Objects.equals(modelClass, this.modelClass)) { @SuppressWarnings("unchecked") final List<T> modelsCasted = (List<T>)models; return modelsCasted; } // If not the same class, we have to wrap them fist. else { return InterfaceWrapperHelper.wrapToImmutableList(models, modelClass); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ViewAsPreconditionsContext.java
1
请完成以下Java代码
public void setM_Product_ID(final int productId) { final ProductId productRepoId = ProductId.ofRepoIdOrNull(productId); if (productRepoId == null) { this.onlyProductIds = null; } else { this.onlyProductIds = ImmutableSet.of(productRepoId); } } @Override @Nullable public Set<ProductId> getOnlyProductIds() { return onlyProductIds != null && !onlyProductIds.isEmpty() ? onlyProductIds : null; } @Override public void setOnlyProductIds(final Collection<ProductId> productIds) { this.onlyProductIds = productIds != null ? ImmutableSet.copyOf(productIds) : null; } @Override public int getC_BPartner_ID() { return bpartnerId; } @Override public void setC_BPartner_ID(final int bpartnerId) { this.bpartnerId = bpartnerId <= 0 ? -1 : bpartnerId; } @Override public void setPriceListVersionId(final @Nullable PriceListVersionId priceListVersionId) { this.priceListVersionId = priceListVersionId; } @Nullable @Override public PriceListVersionId getPriceListVersionId() { return priceListVersionId; } @Override public void setDate(final ZonedDateTime date) { this.date = date; } @Override public ZonedDateTime getDate() { return date; } @Override public boolean isAllowAnyProduct() { return allowAnyProduct; } @Override public void setAllowAnyProduct(final boolean allowAnyProduct) { this.allowAnyProduct = allowAnyProduct; } @Override public String getHU_UnitType() { return huUnitType; } @Override public void setHU_UnitType(final String huUnitType) { this.huUnitType = huUnitType; } @Override public boolean isAllowVirtualPI() { return allowVirtualPI; } @Override public void setAllowVirtualPI(final boolean allowVirtualPI) { this.allowVirtualPI = allowVirtualPI; } @Override public void setOneConfigurationPerPI(final boolean oneConfigurationPerPI) { this.oneConfigurationPerPI = oneConfigurationPerPI; } @Override public boolean isOneConfigurationPerPI() {
return oneConfigurationPerPI; } @Override public boolean isAllowDifferentCapacities() { return allowDifferentCapacities; } @Override public void setAllowDifferentCapacities(final boolean allowDifferentCapacities) { this.allowDifferentCapacities = allowDifferentCapacities; } @Override public boolean isAllowInfiniteCapacity() { return allowInfiniteCapacity; } @Override public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity) { this.allowInfiniteCapacity = allowInfiniteCapacity; } @Override public boolean isAllowAnyPartner() { return allowAnyPartner; } @Override public void setAllowAnyPartner(final boolean allowAnyPartner) { this.allowAnyPartner = allowAnyPartner; } @Override public int getM_Product_Packaging_ID() { return packagingProductId; } @Override public void setM_Product_Packaging_ID(final int packagingProductId) { this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
1
请完成以下Java代码
public Mono<Authentication> authenticate(Authentication authentication) { return Mono.defer(() -> { OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication; OAuth2AuthorizationResponse authorizationResponse = token.getAuthorizationExchange() .getAuthorizationResponse(); if (authorizationResponse.statusError()) { return Mono.error(new OAuth2AuthorizationException(authorizationResponse.getError())); } OAuth2AuthorizationRequest authorizationRequest = token.getAuthorizationExchange() .getAuthorizationRequest(); if (!authorizationResponse.getState().equals(authorizationRequest.getState())) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE); return Mono.error(new OAuth2AuthorizationException(oauth2Error)); } OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest( token.getClientRegistration(), token.getAuthorizationExchange()); return this.accessTokenResponseClient.getTokenResponse(authzRequest).map(onSuccess(token));
}); } private Function<OAuth2AccessTokenResponse, OAuth2AuthorizationCodeAuthenticationToken> onSuccess( OAuth2AuthorizationCodeAuthenticationToken token) { return (accessTokenResponse) -> { ClientRegistration registration = token.getClientRegistration(); OAuth2AuthorizationExchange exchange = token.getAuthorizationExchange(); OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken(); OAuth2RefreshToken refreshToken = accessTokenResponse.getRefreshToken(); return new OAuth2AuthorizationCodeAuthenticationToken(registration, exchange, accessToken, refreshToken, accessTokenResponse.getAdditionalParameters()); }; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeReactiveAuthenticationManager.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentReservationCaptureId implements RepoIdAware { @JsonCreator public static PaymentReservationCaptureId ofRepoId(final int repoId) { return new PaymentReservationCaptureId(repoId); } public static PaymentReservationCaptureId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PaymentReservationCaptureId(repoId) : null; } public static int toRepoId(final PaymentReservationCaptureId id) { return id != null ? id.getRepoId() : -1;
} int repoId; private PaymentReservationCaptureId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Payment_Reservation_Capture_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationCaptureId.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .addValue(tags) .toString(); } public String getTagsAsString() { return TAGS_STRING_JOINER.join(tags); } /** @return {@code true} if this attachment has a tag with the given name; the label doesn't need to have a value though. */ public boolean hasTag(@NonNull final String tag) { return tags.containsKey(tag); } public boolean hasAllTagsSetToTrue(@NonNull final List<String> tagNames) { for (final String tagName : tagNames) { if (!hasTagSetToTrue(tagName)) { return false; } } return true; } public boolean hasTagSetToTrue(@NonNull final String tagName) { return StringUtils.toBoolean(getTagValueOrNull(tagName), false); } public boolean hasTagSetToString(@NonNull final String tagName, @NonNull final String tagValue) { return Objects.equals(getTagValueOrNull(tagName), tagValue); } public String getTagValue(@NonNull final String tagName) { return Check.assumeNotEmpty( getTagValueOrNull(tagName), "This attachmentEntry needs to have a tag with name={} and a value; this={}", tagName, this); } public String getTagValueOrNull(String tagName) {
return tags.get(tagName); } public boolean hasAllTagsSetToAnyValue(@NonNull final List<String> tagNames) { for (final String tagName : tagNames) { if (getTagValueOrNull(tagName) == null) { return false; } } return true; } public AttachmentTags withTag(@NonNull final String tagName, @NonNull final String tagValue) { if (hasTagSetToString(tagName, tagValue)) { return this; } else { final HashMap<String, String> map = new HashMap<>(this.tags); map.put(tagName, tagValue); return new AttachmentTags(map); } } public AttachmentTags withoutTags(@NonNull final AttachmentTags tagsToRemove) { final HashMap<String, String> tmp = new HashMap<>(this.tags); tmp.keySet().removeAll(tagsToRemove.tags.keySet()); return new AttachmentTags(tmp); } public AttachmentTags withTags(@NonNull final AttachmentTags additionalTags) { final HashMap<String, String> tmp = new HashMap<>(this.tags); tmp.putAll(additionalTags.tags); return new AttachmentTags(tmp); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentTags.java
1
请在Spring Boot框架中完成以下Java代码
public static void exceptionHandlingExample() { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // Simulate a task that might throw an exception if (true) { throw new RuntimeException("Something went wrong!"); } return "Success"; }) .exceptionally(ex -> { System.err.println("Error in task: " + ex.getMessage()); // Can optionally return a default value return "Error occurred"; }); future.thenAccept(result -> System.out.println("Result: " + result)); } public static void timeoutExample() { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(5000);
} catch (InterruptedException e) { System.err.println("Task execution timed out!"); } return "Task completed"; }); CompletableFuture<String> timeoutFuture = future.completeOnTimeout("Timed out!", 2, TimeUnit.SECONDS); String result = timeoutFuture.join(); System.out.println("Result: " + result); } public static void main(String[] args) { timeoutExample(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executorservicevscompletablefuture\CompletableFutureDemo.java
2
请完成以下Java代码
public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } /** * Gets the value of the ccyOfTrf property. * * @return * possible object is
* {@link String } * */ public String getCcyOfTrf() { return ccyOfTrf; } /** * Sets the value of the ccyOfTrf property. * * @param value * allowed object is * {@link String } * */ public void setCcyOfTrf(String value) { this.ccyOfTrf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\EquivalentAmount2.java
1
请完成以下Java代码
public BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return Env.ZERO; return bd; } /** Set Product. @param Product Product */ public void setProduct (String Product) { set_Value (COLUMNNAME_Product, Product); } /** Get Product. @return Product */ public String getProduct () { return (String)get_Value(COLUMNNAME_Product); } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } public I_W_Basket getW_Basket() throws RuntimeException { return (I_W_Basket)MTable.get(getCtx(), I_W_Basket.Table_Name) .getPO(getW_Basket_ID(), get_TrxName()); } /** Set W_Basket_ID.
@param W_Basket_ID Web Basket */ public void setW_Basket_ID (int W_Basket_ID) { if (W_Basket_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Basket_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Basket_ID, Integer.valueOf(W_Basket_ID)); } /** Get W_Basket_ID. @return Web Basket */ public int getW_Basket_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Basket_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Basket Line. @param W_BasketLine_ID Web Basket Line */ public void setW_BasketLine_ID (int W_BasketLine_ID) { if (W_BasketLine_ID < 1) set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, null); else set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, Integer.valueOf(W_BasketLine_ID)); } /** Get Basket Line. @return Web Basket Line */ public int getW_BasketLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_BasketLine_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_W_BasketLine.java
1
请在Spring Boot框架中完成以下Java代码
public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } public static class Validation { /** * Whether to enable LDAP schema validation. */ private boolean enabled = true; /** * Path to the custom schema. */ private @Nullable Resource schema; public boolean isEnabled() { return this.enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable Resource getSchema() { return this.schema; } public void setSchema(@Nullable Resource schema) { this.schema = schema; } } }
repos\spring-boot-main\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
2
请完成以下Java代码
protected void setJobExecutorActivate(ProcessEngineConfigurationImpl configuration, Map<String, String> properties) { // override job executor auto activate: set to true in shared engine scenario // if it is not specified (see #CAM-4817) configuration.setJobExecutorActivate(true); } protected JmxManagedProcessEngineController createProcessEngineControllerInstance(ProcessEngineConfigurationImpl configuration) { return new JmxManagedProcessEngineController(configuration); } /** * <p>Instantiates and applies all {@link ProcessEnginePlugin}s defined in the processEngineXml */ protected void configurePlugins(ProcessEngineConfigurationImpl configuration, ProcessEngineXml processEngineXml, ClassLoader classLoader) { for (ProcessEnginePluginXml pluginXml : processEngineXml.getPlugins()) { // create plugin instance Class<? extends ProcessEnginePlugin> pluginClass = loadClass(pluginXml.getPluginClass(), classLoader, ProcessEnginePlugin.class); ProcessEnginePlugin plugin = ReflectUtil.createInstance(pluginClass); // apply configured properties Map<String, String> properties = pluginXml.getProperties(); PropertyHelper.applyProperties(plugin, properties); // add to configuration configuration.getProcessEnginePlugins().add(plugin); } }
protected JobExecutor getJobExecutorService(final PlatformServiceContainer serviceContainer) { // lookup container managed job executor String jobAcquisitionName = processEngineXml.getJobAcquisitionName(); JobExecutor jobExecutor = serviceContainer.getServiceValue(ServiceTypes.JOB_EXECUTOR, jobAcquisitionName); return jobExecutor; } @SuppressWarnings("unchecked") protected <T> Class<? extends T> loadClass(String className, ClassLoader customClassloader, Class<T> clazz) { try { return ReflectUtil.loadClass(className, customClassloader, clazz); } catch (ClassNotFoundException e) { throw LOG.cannotLoadConfigurationClass(className, e); } catch (ClassCastException e) { throw LOG.configurationClassHasWrongType(className, clazz, e); } } /** * Add additional plugins that are not declared in the process engine xml. */ protected void addAdditionalPlugins(ProcessEngineConfigurationImpl configuration) { // do nothing } protected void additionalConfiguration(ProcessEngineConfigurationImpl configuration) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\StartProcessEngineStep.java
1
请在Spring Boot框架中完成以下Java代码
public ApplicationDeployedEventProducer applicationDeployedEventProducer( RepositoryService repositoryService, APIDeploymentConverter converter, @Autowired(required = false) List<ProcessRuntimeEventListener<ApplicationDeployedEvent>> listeners, ApplicationEventPublisher eventPublisher ) { return new ApplicationDeployedEventProducer( repositoryService, converter, Optional.ofNullable(listeners).orElse(emptyList()), eventPublisher ); } @Bean @ConditionalOnMissingBean
public CandidateStartersDeploymentConfigurer candidateStartersDeploymentConfigurer() { return new CandidateStartersDeploymentConfigurer(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty("spring.activiti.process-definition-cache-name") public DeploymentCache<ProcessDefinitionCacheEntry> springProcessDefinitionCache( ActivitiProperties properties, CacheManager cacheManager ) { var delegate = cacheManager.getCache(properties.getProcessDefinitionCacheName()); return new SpringProcessDefinitionCache(Objects.requireNonNull(delegate)); } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\ProcessEngineAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public SecurityWebFilterChain securityWebFilterChainSecure(ServerHttpSecurity http) { return http .authorizeExchange( (authorizeExchange) -> authorizeExchange.pathMatchers(this.adminServer.path("/assets/**")) .permitAll() .pathMatchers("/actuator/health/**") .permitAll() .pathMatchers(this.adminServer.path("/login")) .permitAll() .anyExchange() .authenticated()) .formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login")) .authenticationSuccessHandler(loginSuccessHandler(this.adminServer.path("/")))) .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")) .logoutSuccessHandler(logoutSuccessHandler(this.adminServer.path("/login?logout")))) .httpBasic(Customizer.withDefaults()) .csrf(ServerHttpSecurity.CsrfSpec::disable) .build(); }
// The following two methods are only required when setting a custom base-path (see // 'basepath' profile in application.yml) private ServerLogoutSuccessHandler logoutSuccessHandler(String uri) { RedirectServerLogoutSuccessHandler successHandler = new RedirectServerLogoutSuccessHandler(); successHandler.setLogoutSuccessUrl(URI.create(uri)); return successHandler; } private ServerAuthenticationSuccessHandler loginSuccessHandler(String uri) { RedirectServerAuthenticationSuccessHandler successHandler = new RedirectServerAuthenticationSuccessHandler(); successHandler.setLocation(URI.create(uri)); return successHandler; } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-eureka\src\main\java\de\codecentric\boot\admin\SpringBootAdminEurekaApplication.java
2
请完成以下Java代码
private UomId extractProductPriceUomId(final I_C_Campaign_Price record) { final UomId productPriceUomId = UomId.ofRepoIdOrNull(record.getC_UOM_ID()); if (productPriceUomId != null) { return productPriceUomId; } final ProductId productId = ProductId.ofRepoId(record.getM_Product_ID()); return productsService.getStockUOMId(productId); } @Value @Builder private static class CampaignPricePageKey { @NonNull ProductId productId; @NonNull YearMonth month; } @Value private static class CampaignPricePage { public static CampaignPricePage of(final List<CampaignPrice> prices) { if (prices.isEmpty()) { return EMPTY; } else { return new CampaignPricePage(prices); } } private static final CampaignPricePage EMPTY = new CampaignPricePage(); private final ImmutableListMultimap<BPartnerId, CampaignPrice> bpartnerPrices; private final ImmutableListMultimap<BPGroupId, CampaignPrice> bpGroupPrices; private final ImmutableListMultimap<PricingSystemId, CampaignPrice> pricingSystemPrices; private CampaignPricePage(final List<CampaignPrice> prices) { bpartnerPrices = prices.stream() .filter(price -> price.getBpartnerId() != null) .sorted(Comparator.comparing(CampaignPrice::getValidFrom)) .collect(GuavaCollectors.toImmutableListMultimap(CampaignPrice::getBpartnerId)); bpGroupPrices = prices.stream() .filter(price -> price.getBpGroupId() != null) .sorted(Comparator.comparing(CampaignPrice::getValidFrom)) .collect(GuavaCollectors.toImmutableListMultimap(CampaignPrice::getBpGroupId)); pricingSystemPrices = prices.stream() .filter(price -> price.getPricingSystemId() != null) .sorted(Comparator.comparing(CampaignPrice::getValidFrom)) .collect(GuavaCollectors.toImmutableListMultimap(CampaignPrice::getPricingSystemId));
} private CampaignPricePage() { bpartnerPrices = ImmutableListMultimap.of(); bpGroupPrices = ImmutableListMultimap.of(); pricingSystemPrices = ImmutableListMultimap.of(); } public Optional<CampaignPrice> findPrice(@NonNull final CampaignPriceQuery query) { Optional<CampaignPrice> result = findPrice(bpartnerPrices.get(query.getBpartnerId()), query); if (result.isPresent()) { return result; } result = findPrice(bpGroupPrices.get(query.getBpGroupId()), query); if (result.isPresent()) { return result; } return findPrice(pricingSystemPrices.get(query.getPricingSystemId()), query); } private static Optional<CampaignPrice> findPrice(@NonNull final Collection<CampaignPrice> prices, @NonNull final CampaignPriceQuery query) { return prices.stream() .filter(query::isMatching) .findFirst(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\CampaignPriceRepository.java
1
请完成以下Java代码
public void setM_Package_ID (final int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, M_Package_ID); } @Override public int getM_Package_ID() { return get_ValueAsInt(COLUMNNAME_M_Package_ID); } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); }
@Override public void setWeightInKg (final BigDecimal WeightInKg) { set_Value (COLUMNNAME_WeightInKg, WeightInKg); } @Override public BigDecimal getWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java
1
请完成以下Java代码
public class SoapHttpConnectorImpl extends AbstractHttpConnector<SoapHttpRequest, SoapHttpResponse> implements SoapHttpConnector { protected static final SoapHttpConnectorLogger LOG = SoapHttpLogger.SOAP_HTTP_CONNECTOR_LOGGER; public SoapHttpConnectorImpl() { super(SoapHttpConnector.ID); } public SoapHttpConnectorImpl(String connectorId) { super(connectorId); } public SoapHttpRequest createRequest() { return new SoapHttpRequestImpl(this); } protected SoapHttpResponse createResponse(ClassicHttpResponse response) { return new SoapHttpResponseImpl(response); } @Override public SoapHttpResponse execute(SoapHttpRequest request) {
// always use the POST method ((AbstractHttpRequest<?, ?>) request).post(); return super.execute(request); } @Override protected <T extends BasicClassicHttpRequest> void applyPayload(T httpRequest, SoapHttpRequest request) { // SOAP requires soap envelop body if (request.getPayload() == null || request.getPayload().trim().isEmpty()) { throw LOG.noPayloadSet(); } super.applyPayload(httpRequest, request); } }
repos\camunda-bpm-platform-master\connect\soap-http-client\src\main\java\org\camunda\connect\httpclient\soap\impl\SoapHttpConnectorImpl.java
1
请完成以下Java代码
private BigDecimal getQtyFromProductionMaterial(final I_C_UOM uom, final IProductionMaterial productionMaterial) { final BigDecimal result; // note: if the average value is 0 we fall back to the actual value. // this makes us more lenient towards the current unit tests. // imho it's also justifyiable because if the avg qty is null it means that the normal qty is also null if (_buildWithAveragedValues && productionMaterial.getQM_QtyDeliveredAvg(uom).signum() != 0) { result = productionMaterial.getQM_QtyDeliveredAvg(uom); } else { result = productionMaterial.getQty(uom); } return result; }
private final IQualityInspectionLineBuilder newQualityInspectionLine() { final IQualityInspectionLineBuilder reportLineBuilder = new QualityInspectionLineBuilder() { @Override protected void afterLineCreated(final IQualityInspectionLine line) { _createdQualityInspectionLines.add(line); } }; return reportLineBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLinesBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class WSOperation implements OperationImplementation { protected String id; protected String name; protected WSService service; public WSOperation(String id, String operationName, WSService service) { this.id = id; this.name = operationName; this.service = service; } /** * {@inheritDoc} */ public String getId() { return this.id; } /** * {@inheritDoc} */ public String getName() { return this.name; } /** * {@inheritDoc} */ public MessageInstance sendFor( MessageInstance message, Operation operation, ConcurrentMap<QName, URL> overridenEndpointAddresses ) throws Exception { Object[] arguments = this.getArguments(message); Object[] results = this.safeSend(arguments, overridenEndpointAddresses); return this.createResponseMessage(results, operation); } private Object[] getArguments(MessageInstance message) { return message.getStructureInstance().toArray(); } private Object[] safeSend(Object[] arguments, ConcurrentMap<QName, URL> overridenEndpointAddresses) throws Exception {
Object[] results = null; results = this.service.getClient().send(this.name, arguments, overridenEndpointAddresses); if (results == null) { results = new Object[] {}; } return results; } private MessageInstance createResponseMessage(Object[] results, Operation operation) { MessageInstance message = null; MessageDefinition outMessage = operation.getOutMessage(); if (outMessage != null) { message = outMessage.createInstance(); message.getStructureInstance().loadFrom(results); } return message; } public WSService getService() { return this.service; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\webservice\WSOperation.java
2
请完成以下Java代码
class UserDsRequestModel { String name; String password; LocalDateTime creationTime; public UserDsRequestModel(String name, String password, LocalDateTime creationTime) { this.name = name; this.password = password; this.creationTime = creationTime; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public LocalDateTime getCreationTime() { return creationTime; } public void setCreationTime(LocalDateTime creationTime) { this.creationTime = creationTime; } }
repos\tutorials-master\patterns-modules\clean-architecture\src\main\java\com\baeldung\pattern\cleanarchitecture\usercreation\UserDsRequestModel.java
1
请完成以下Java代码
public static Range<Instant> closedOpenRange(@Nullable final Instant lowerBound, @Nullable final Instant upperBound) { if (lowerBound == null) { return upperBound == null ? Range.all() : Range.upTo(upperBound, BoundType.OPEN); } else { return upperBound == null ? Range.downTo(lowerBound, BoundType.CLOSED) : Range.closedOpen(lowerBound, upperBound); } } public static boolean isOverlapping(@NonNull final Range<Instant> range1, @NonNull final Range<Instant> range2) { if (!range1.isConnected(range2)) { return false; } return !range1.intersection(range2).isEmpty(); } @Deprecated @Override public String toString() { return getSql(); } @Override public String getSql() { buildSqlIfNeeded(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return getSqlParams();
} public List<Object> getSqlParams() { buildSqlIfNeeded(); return sqlParams; } private void buildSqlIfNeeded() { if (sqlWhereClause != null) { return; } if (isConstantTrue()) { final ConstantQueryFilter<Object> acceptAll = ConstantQueryFilter.of(true); sqlParams = acceptAll.getSqlParams(); sqlWhereClause = acceptAll.getSql(); } else { sqlParams = Arrays.asList(lowerBoundValue, upperBoundValue); sqlWhereClause = "NOT ISEMPTY(" + "TSTZRANGE(" + lowerBoundColumnName.getColumnName() + ", " + upperBoundColumnName.getColumnName() + ", '[)')" + " * " + "TSTZRANGE(?, ?, '[)')" + ")"; } } private boolean isConstantTrue() { return lowerBoundValue == null && upperBoundValue == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateIntervalIntersectionQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public void init(AuthenticationManagerBuilder auth) { auth.apply(new InitializeUserDetailsManagerConfigurer()); } class InitializeUserDetailsManagerConfigurer extends GlobalAuthenticationConfigurerAdapter { private final Log logger = LogFactory.getLog(getClass()); @Override public void configure(AuthenticationManagerBuilder auth) { String[] beanNames = InitializeUserDetailsBeanManagerConfigurer.this.context .getBeanNamesForType(UserDetailsService.class); if (auth.isConfigured()) { if (beanNames.length > 0) { this.logger.warn("Global AuthenticationManager configured with an AuthenticationProvider bean. " + "UserDetailsService beans will not be used by Spring Security for automatically configuring username/password login. " + "Consider removing the AuthenticationProvider bean. " + "Alternatively, consider using the UserDetailsService in a manually instantiated DaoAuthenticationProvider. " + "If the current configuration is intentional, to turn off this warning, " + "increase the logging level of 'org.springframework.security.config.annotation.authentication.configuration.InitializeUserDetailsBeanManagerConfigurer' to ERROR"); } return; } if (beanNames.length == 0) { return; } else if (beanNames.length > 1) { this.logger.warn(LogMessage.format("Found %s UserDetailsService beans, with names %s. " + "Global Authentication Manager will not use a UserDetailsService for username/password login. " + "Consider publishing a single UserDetailsService bean.", beanNames.length, Arrays.toString(beanNames))); return; } UserDetailsService userDetailsService = InitializeUserDetailsBeanManagerConfigurer.this.context
.getBean(beanNames[0], UserDetailsService.class); PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class); UserDetailsPasswordService passwordManager = getBeanOrNull(UserDetailsPasswordService.class); CompromisedPasswordChecker passwordChecker = getBeanOrNull(CompromisedPasswordChecker.class); DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService); if (passwordEncoder != null) { provider.setPasswordEncoder(passwordEncoder); } if (passwordManager != null) { provider.setUserDetailsPasswordService(passwordManager); } if (passwordChecker != null) { provider.setCompromisedPasswordChecker(passwordChecker); } provider.afterPropertiesSet(); auth.authenticationProvider(provider); this.logger.info(LogMessage.format( "Global AuthenticationManager configured with UserDetailsService bean with name %s", beanNames[0])); } /** * @return a bean of the requested class if there's just a single registered * component, null otherwise. */ private <T> T getBeanOrNull(Class<T> type) { return InitializeUserDetailsBeanManagerConfigurer.this.context.getBeanProvider(type).getIfUnique(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configuration\InitializeUserDetailsBeanManagerConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public TaskResult makePaymentTask(PaymentRequest paymentRequest) { TaskResult result = new TaskResult(); Payment payment = PaymentService.createPayment(paymentRequest); Map<String, Object> output = new HashMap<>(); output.put("orderId", payment.getOrderId()); output.put("paymentId", payment.getPaymentId()); output.put("paymentStatus", payment.getStatus().name()); if(payment.getStatus() == Payment.Status.SUCCESSFUL) { result.setStatus(TaskResult.Status.COMPLETED); } else { output.put("error", payment.getErrorMsg()); result.setStatus(TaskResult.Status.FAILED_WITH_TERMINAL_ERROR); } result.setOutputData(output); return result; } @WorkerTask(value = "ship_food", threadCount = 2, pollingInterval = 300) public TaskResult shipFoodTask(ShippingRequest shippingRequest) { TaskResult result = new TaskResult(); Map<String, Object> output = new HashMap<>(); int driverId = ShipmentService.createShipment(shippingRequest); if (driverId != 0) { result.setStatus(TaskResult.Status.COMPLETED); } else { result.setStatus(TaskResult.Status.FAILED); } return result; } @WorkerTask(value = "notify_driver", threadCount = 2, pollingInterval = 300) public Map<String, Object> checkForDriverNotifications(DriverNotificationRequest driverNotificationRequest) {
Map<String, Object> result = new HashMap<>(); return result; } @WorkerTask(value = "notify_customer", threadCount = 2, pollingInterval = 300) public Map<String, Object> checkForCustomerNotifications(Order order) { Map<String, Object> result = new HashMap<>(); return result; } // @WorkerTask(value = "cancel_payment", threadCount = 2, pollingInterval = 300) public Map<String, Object> cancelPaymentTask(CancelRequest cancelRequest) { Map<String, Object> result = new HashMap<>(); PaymentService.cancelPayment(cancelRequest.getOrderId()); return result; } @WorkerTask(value = "cancel_delivery", threadCount = 2, pollingInterval = 300) public Map<String, Object> cancelDeliveryTask(CancelRequest cancelRequest) { Map<String, Object> result = new HashMap<>(); ShipmentService.cancelDelivery(cancelRequest.getOrderId()); return result; } @WorkerTask(value = "cancel_order", threadCount = 2, pollingInterval = 300) public Map<String, Object> cancelOrderTask(CancelRequest cancelRequest) { Map<String, Object> result = new HashMap<>(); Order order = OrderService.getOrder(cancelRequest.getOrderId()); OrderService.cancelOrder(order); return result; } }
repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\workers\ConductorWorkers.java
2
请完成以下Java代码
private final String[] toStringArray(final List<ITrx> trxs) { if (trxs == null || trxs.isEmpty()) { return new String[] {}; } final String[] arr = new String[trxs.size()]; for (int i = 0; i < trxs.size(); i++) { final ITrx trx = trxs.get(0); if (trx == null) { arr[i] = "null"; } else { arr[i] = trx.toString(); } } return arr; } @Override public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName); } final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx)) { // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try
{ rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); } if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine); } /** Set Storno-Zeile. @param ReversalLine_ID Storno-Zeile */ @Override public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Storno-Zeile. @return Storno-Zeile */ @Override public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Abschreiben. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{ set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Abschreiben. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); 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_C_AllocationLine.java
1
请在Spring Boot框架中完成以下Java代码
public class GetInstitutionsRouteContext { @NonNull String orgCode; @NonNull AlbertaConnectionDetails albertaConnectionDetails; @NonNull String albertaResourceId; @NonNull JsonBPartnerRole role; @NonNull DoctorApi doctorApi;
@NonNull HospitalApi hospitalApi; @NonNull NursingHomeApi nursingHomeApi; @NonNull NursingServiceApi nursingServiceApi; @NonNull PayerApi payerApi; @NonNull PharmacyApi pharmacyApi; }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\institutions\GetInstitutionsRouteContext.java
2
请完成以下Java代码
public static void closeQuietly(final Iterator<?> iterator) { try { close(iterator); } catch (Throwable e) { // ignore the exception e.printStackTrace(); } } public static void close(final BlindIterator<?> iterator) { if (iterator == null) { return; } if (iterator instanceof Closeable) { final Closeable closeable = (Closeable)iterator; try { closeable.close(); } catch (IOException e) { throw Throwables.propagate(e); } } else if (iterator instanceof AutoCloseable) { final AutoCloseable closeable = (AutoCloseable)iterator; try { closeable.close(); } catch (Exception e) { throw Throwables.propagate(e); } } else if (iterator instanceof IteratorWrapper) { final IteratorWrapper<?> wrapper = (IteratorWrapper<?>)iterator; final Iterator<?> parentIterator = wrapper.getParentIterator(); close(parentIterator); } // iterator is not closeable, nothing to do }
public static <E> PeekIterator<E> asPeekIterator(final Iterator<E> iterator) { if (iterator instanceof PeekIterator) { final PeekIterator<E> peekIterator = (PeekIterator<E>)iterator; return peekIterator; } else { return new PeekIteratorWrapper<>(iterator); } } public static <IT, OT> Iterator<OT> map(@NonNull final Iterator<IT> iterator, @NonNull final Function<IT, OT> mapper) { return new MappingIteratorWrapper<>(iterator, mapper); } public static <T> Iterator<T> unmodifiableIterator(final Iterator<T> iterator) { return new UnmodifiableIterator<>(iterator); } public static <T> Iterator<T> emptyIterator() { return EmptyIterator.getInstance(); } /** * @param iterator * @return the iterator wrapped to stream */ public static <T> Stream<T> stream(final Iterator<T> iterator) { Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED); final boolean parallel = false; return StreamSupport.stream(spliterator, parallel); } public static <T> Stream<T> stream(final BlindIterator<T> blindIterator) { return stream(asIterator(blindIterator)); } public static <T> PagedIteratorBuilder<T> newPagedIterator() { return PagedIterator.builder(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IteratorUtils.java
1
请完成以下Java代码
public static ValueNamePair retrieveWarning() { final ValueNamePair lastWarning = getLastErrorsInstance().getLastWarningAndReset(); return lastWarning; } // retrieveWarning /** * Reset Saved Messages/Errors/Info */ public static void resetLast() { getLastErrorsInstance().reset(); } private final static LastErrorsInstance getLastErrorsInstance() { final Properties ctx = Env.getCtx(); return Env.get(ctx, LASTERRORINSTANCE_CTXKEY, LastErrorsInstance::new); } /** * Holds last error/exception, warning and info. * * @author tsa */ @ThreadSafe @SuppressWarnings("serial") private static class LastErrorsInstance implements Serializable { private ValueNamePair lastError; private Throwable lastException; private ValueNamePair lastWarning; private LastErrorsInstance() { super(); } @Override public synchronized String toString() { final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append("["); sb.append("lastError=").append(lastError); sb.append(", lastException=").append(lastException); sb.append(", lastWarning=").append(lastWarning); sb.append("]"); return sb.toString(); } public synchronized ValueNamePair getLastErrorAndReset() { final ValueNamePair lastErrorToReturn = lastError; lastError = null; return lastErrorToReturn; } public synchronized void setLastError(final ValueNamePair lastError) { this.lastError = lastError; } public synchronized Throwable getLastExceptionAndReset() {
final Throwable lastExceptionAndClear = lastException; lastException = null; return lastExceptionAndClear; } public synchronized void setLastException(final Throwable lastException) { this.lastException = lastException; } public synchronized ValueNamePair getLastWarningAndReset() { final ValueNamePair lastWarningToReturn = lastWarning; lastWarning = null; return lastWarningToReturn; } public synchronized void setLastWarning(final ValueNamePair lastWarning) { this.lastWarning = lastWarning; } public synchronized void reset() { lastError = null; lastException = null; lastWarning = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshLastError.java
1
请完成以下Java代码
public java.lang.String getInternalName () { return (java.lang.String)get_Value(COLUMNNAME_InternalName); } /** Set IsDestination. @param IsDestination IsDestination */ @Override public void setIsDestination (boolean IsDestination) { set_Value (COLUMNNAME_IsDestination, Boolean.valueOf(IsDestination)); } /** Get IsDestination. @return IsDestination */ @Override public boolean isDestination () { Object oo = get_Value(COLUMNNAME_IsDestination); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Beleg soll per EDI übermittelt werden. @param IsEdiEnabled Beleg soll per EDI übermittelt werden */ @Override public void setIsEdiEnabled (boolean IsEdiEnabled) { set_Value (COLUMNNAME_IsEdiEnabled, Boolean.valueOf(IsEdiEnabled)); } /** Get Beleg soll per EDI übermittelt werden. @return Beleg soll per EDI übermittelt werden */ @Override public boolean isEdiEnabled () { Object oo = get_Value(COLUMNNAME_IsEdiEnabled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name);
} /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_AD_InputDataSource.java
1
请完成以下Java代码
public void destroy() { if (statsPrintScheduler != null) { statsPrintScheduler.shutdownNow(); } if (consumer != null) { consumer.close(); } } @Builder @Data private static class GroupTopicStats { private String topic; private int partition; private long committedOffset; private long endOffset; private long lag;
@Override public String toString() { return "[" + "topic=[" + topic + ']' + ", partition=[" + partition + "]" + ", committedOffset=[" + committedOffset + "]" + ", endOffset=[" + endOffset + "]" + ", lag=[" + lag + "]" + "]"; } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaConsumerStatsService.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Profile. @param ProfileInfo Information to help profiling the system for solving support issues */ public void setProfileInfo (String ProfileInfo) { set_Value (COLUMNNAME_ProfileInfo, ProfileInfo); } /** Get Profile. @return Information to help profiling the system for solving support issues */ public String getProfileInfo () { return (String)get_Value(COLUMNNAME_ProfileInfo); } /** Set Issue Project. @param R_IssueProject_ID Implementation Projects */ public void setR_IssueProject_ID (int R_IssueProject_ID) { if (R_IssueProject_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, Integer.valueOf(R_IssueProject_ID)); } /** Get Issue Project. @return Implementation Projects */ public int getR_IssueProject_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueProject_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Statistics. @param StatisticsInfo Information to help profiling the system for solving support issues */ public void setStatisticsInfo (String StatisticsInfo) { set_Value (COLUMNNAME_StatisticsInfo, StatisticsInfo); } /** Get Statistics. @return Information to help profiling the system for solving support issues */ public String getStatisticsInfo () { return (String)get_Value(COLUMNNAME_StatisticsInfo); } /** SystemStatus AD_Reference_ID=374 */ public static final int SYSTEMSTATUS_AD_Reference_ID=374; /** Evaluation = E */ public static final String SYSTEMSTATUS_Evaluation = "E"; /** Implementation = I */ public static final String SYSTEMSTATUS_Implementation = "I"; /** Production = P */ public static final String SYSTEMSTATUS_Production = "P"; /** Set System Status. @param SystemStatus Status of the system - Support priority depends on system status */ public void setSystemStatus (String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } /** Get System Status. @return Status of the system - Support priority depends on system status */ public String getSystemStatus () { return (String)get_Value(COLUMNNAME_SystemStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueProject.java
1
请完成以下Java代码
private static void applyAuthConfig(Map<String, String> headersMap, String metadataStr, HttpServletRequest currentHttpRequest) { if (oConvertUtils.isEmpty(metadataStr)) { return; } try { JSONObject metadata = JSONObject.parseObject(metadataStr); if (metadata == null) { return; } String authType = metadata.getString("authType"); if (oConvertUtils.isEmpty(authType) || !"token".equalsIgnoreCase(authType)) { return; } // Token授权方式:从metadata中获取token配置并添加到headers String tokenParamName = metadata.getString("tokenParamName"); String tokenParamValue = metadata.getString("tokenParamValue"); // 如果token参数名存在,但token值未设置,尝试从TokenUtils获取当前请求的token if (oConvertUtils.isNotEmpty(tokenParamName) && oConvertUtils.isEmpty(tokenParamValue)) { try { // 注意:TokenUtils需要获取当前线程的request,所以必须在同步调用中使用 String currentToken = TokenUtils.getTokenByRequest(); if(oConvertUtils.isEmpty(currentToken) && currentHttpRequest != null) { currentToken = TokenUtils.getTokenByRequest(currentHttpRequest); } if (oConvertUtils.isNotEmpty(currentToken)) { tokenParamValue = currentToken; log.debug("从TokenUtils获取Token并添加到请求头: {} = {}", tokenParamName, currentToken.length() > 10 ? currentToken.substring(0, 10) + "..." : currentToken);
} else { log.warn("Token授权配置中tokenParamValue为空,且无法从TokenUtils获取当前请求的token"); } } catch (Exception e) { log.warn("从TokenUtils获取token失败: {}", e.getMessage()); } } if (oConvertUtils.isNotEmpty(tokenParamName) && oConvertUtils.isNotEmpty(tokenParamValue)) { // 如果headers中已存在同名header,优先使用metadata中的配置(覆盖) headersMap.put(tokenParamName, tokenParamValue); // 日志中只显示token的前几个字符,避免泄露完整token String tokenPreview = tokenParamValue.length() > 10 ? tokenParamValue.substring(0, 10) + "..." : tokenParamValue; log.debug("添加Token授权到请求头: {} = {}", tokenParamName, tokenPreview); } else { log.warn("Token授权配置不完整: tokenParamName={}, tokenParamValue={}", tokenParamName, tokenParamValue != null ? "***" : null); } } catch (Exception e) { log.warn("解析授权配置失败: {}", metadataStr, e); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\handler\PluginToolBuilder.java
1
请完成以下Java代码
public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public boolean isSameDeployment() { return sameDeployment; } public void setSameDeployment(boolean sameDeployment) { this.sameDeployment = sameDeployment; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; }
public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } @Override public CasePageTask clone() { CasePageTask clone = new CasePageTask(); clone.setValues(this); return clone; } public void setValues(CasePageTask otherElement) { super.setValues(otherElement); setType(otherElement.getType()); setFormKey(otherElement.getFormKey()); setSameDeployment(otherElement.isSameDeployment()); setLabel(otherElement.getLabel()); setIcon(otherElement.getIcon()); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers())); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CasePageTask.java
1
请完成以下Java代码
public String getProcessMsg() { return processMsg; } @Override public int getDoc_User_ID() { return handler.getDoc_User_ID(model); } @Override public int getC_Currency_ID() { return handler.getC_Currency_ID(model); } @Override public BigDecimal getApprovalAmt() { return handler.getApprovalAmt(model); } @Override public int getAD_Client_ID() { return model.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return model.getAD_Org_ID(); } @Override public String getDocAction() { return model.getDocAction(); } @Override public boolean save() { InterfaceWrapperHelper.save(model); return true; } @Override public Properties getCtx() { return InterfaceWrapperHelper.getCtx(model); } @Override public int get_ID() { return InterfaceWrapperHelper.getId(model); } @Override public int get_Table_ID() {
return InterfaceWrapperHelper.getModelTableId(model); } @Override public String get_TrxName() { return InterfaceWrapperHelper.getTrxName(model); } @Override public void set_TrxName(final String trxName) { InterfaceWrapperHelper.setTrxName(model, trxName); } @Override public boolean isActive() { return model.isActive(); } @Override public Object getModel() { return getDocumentModel(); } @Override public Object getDocumentModel() { return model; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java
1
请完成以下Java代码
protected JobDefinitionEntity getJobDefinitionFor(String jobDefinitionId) { if (jobDefinitionId != null) { return Context.getCommandContext() .getJobDefinitionManager() .findById(jobDefinitionId); } else { return null; } } protected Long getActivityPriority(ExecutionEntity execution, JobDeclaration<?, ?> jobDeclaration) { if (jobDeclaration != null) { ParameterValueProvider priorityProvider = jobDeclaration.getJobPriorityProvider(); if (priorityProvider != null) { return evaluateValueProvider(priorityProvider, execution, describeContext(jobDeclaration, execution)); }
} return null; } @Override protected void logNotDeterminingPriority(ExecutionEntity execution, Object value, ProcessEngineException e) { LOG.couldNotDeterminePriority(execution, value, e); } protected String describeContext(JobDeclaration<?, ?> jobDeclaration, ExecutionEntity executionEntity) { return "Job " + jobDeclaration.getActivityId() + "/" + jobDeclaration.getJobHandlerType() + " instantiated " + "in context of " + executionEntity; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\DefaultJobPriorityProvider.java
1
请完成以下Java代码
public java.lang.String getJSONPathEmail() { return get_ValueAsString(COLUMNNAME_JSONPathEmail); } @Override public void setJSONPathMetasfreshID (final @Nullable java.lang.String JSONPathMetasfreshID) { set_Value (COLUMNNAME_JSONPathMetasfreshID, JSONPathMetasfreshID); } @Override public java.lang.String getJSONPathMetasfreshID() { return get_ValueAsString(COLUMNNAME_JSONPathMetasfreshID); } @Override public void setJSONPathSalesRepID (final @Nullable java.lang.String JSONPathSalesRepID) { set_Value (COLUMNNAME_JSONPathSalesRepID, JSONPathSalesRepID); } @Override public java.lang.String getJSONPathSalesRepID() { return get_ValueAsString(COLUMNNAME_JSONPathSalesRepID); } @Override public void setJSONPathShopwareID (final @Nullable java.lang.String JSONPathShopwareID) { set_Value (COLUMNNAME_JSONPathShopwareID, JSONPathShopwareID); } @Override public java.lang.String getJSONPathShopwareID() { return get_ValueAsString(COLUMNNAME_JSONPathShopwareID); } @Override public void setM_FreightCost_NormalVAT_Product_ID (final int M_FreightCost_NormalVAT_Product_ID) { if (M_FreightCost_NormalVAT_Product_ID < 1) set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, null); else set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, M_FreightCost_NormalVAT_Product_ID); } @Override public int getM_FreightCost_NormalVAT_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_FreightCost_NormalVAT_Product_ID); }
@Override public void setM_FreightCost_ReducedVAT_Product_ID (final int M_FreightCost_ReducedVAT_Product_ID) { if (M_FreightCost_ReducedVAT_Product_ID < 1) set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, null); else set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, M_FreightCost_ReducedVAT_Product_ID); } @Override public int getM_FreightCost_ReducedVAT_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); } /** * ProductLookup AD_Reference_ID=541499 * Reference name: _ProductLookup */ public static final int PRODUCTLOOKUP_AD_Reference_ID=541499; /** Product Id = ProductId */ public static final String PRODUCTLOOKUP_ProductId = "ProductId"; /** Product Number = ProductNumber */ public static final String PRODUCTLOOKUP_ProductNumber = "ProductNumber"; @Override public void setProductLookup (final java.lang.String ProductLookup) { set_Value (COLUMNNAME_ProductLookup, ProductLookup); } @Override public java.lang.String getProductLookup() { return get_ValueAsString(COLUMNNAME_ProductLookup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setBill_BPartner_ID (final int Bill_BPartner_ID) { if (Bill_BPartner_ID < 1) set_Value (COLUMNNAME_Bill_BPartner_ID, null); else set_Value (COLUMNNAME_Bill_BPartner_ID, Bill_BPartner_ID); } @Override public int getBill_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Bill_BPartner_ID); } @Override public org.compiere.model.I_C_Invoice getC_Invoice() { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice(final org.compiere.model.I_C_Invoice C_Invoice) { set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice); } @Override public void setC_Invoice_ID (final int C_Invoice_ID) { throw new IllegalArgumentException ("C_Invoice_ID is virtual column"); } @Override public int getC_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_ID); } @Override public void setIsDeliveryStop (final boolean IsDeliveryStop) { set_Value (COLUMNNAME_IsDeliveryStop, IsDeliveryStop); } @Override public boolean isDeliveryStop() { return get_ValueAsBoolean(COLUMNNAME_IsDeliveryStop); }
@Override public void setIsPaid (final boolean IsPaid) { throw new IllegalArgumentException ("IsPaid is virtual column"); } @Override public boolean isPaid() { return get_ValueAsBoolean(COLUMNNAME_IsPaid); } @Override public void setM_Shipment_Constraint_ID (final int M_Shipment_Constraint_ID) { if (M_Shipment_Constraint_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, M_Shipment_Constraint_ID); } @Override public int getM_Shipment_Constraint_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipment_Constraint_ID); } @Override public void setSourceDoc_Record_ID (final int SourceDoc_Record_ID) { if (SourceDoc_Record_ID < 1) set_Value (COLUMNNAME_SourceDoc_Record_ID, null); else set_Value (COLUMNNAME_SourceDoc_Record_ID, SourceDoc_Record_ID); } @Override public int getSourceDoc_Record_ID() { return get_ValueAsInt(COLUMNNAME_SourceDoc_Record_ID); } @Override public void setSourceDoc_Table_ID (final int SourceDoc_Table_ID) { if (SourceDoc_Table_ID < 1) set_Value (COLUMNNAME_SourceDoc_Table_ID, null); else set_Value (COLUMNNAME_SourceDoc_Table_ID, SourceDoc_Table_ID); } @Override public int getSourceDoc_Table_ID() { return get_ValueAsInt(COLUMNNAME_SourceDoc_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Shipment_Constraint.java
1
请完成以下Java代码
public void addFiscalRepresentationLocationId(final I_C_Fiscal_Representation fiscalRep) { fiscalRepresentationBL.updateCountryId(fiscalRep); } @CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_ValidFrom }) public void updateFiscalRepresentationValidFrom(final I_C_Fiscal_Representation fiscalRep) { if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidFromDate(fiscalRep)) { fiscalRepresentationBL.updateValidFrom(fiscalRep); } } @CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Location_ID }) public void updateFiscalRepresentationLocationId(final I_C_Fiscal_Representation fiscalRep) { fiscalRepresentationBL.updateCountryId(fiscalRep); } @CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_ValidTo })
public void updateFiscalRepresentationValidTo(final I_C_Fiscal_Representation fiscalRep) { if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidToDate(fiscalRep)) { fiscalRepresentationBL.updateValidTo(fiscalRep); } } @CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Representative_ID }) public void updateFiscalRepresentationPartner(final I_C_Fiscal_Representation fiscalRep) { fiscalRep.setC_BPartner_Location_ID(-1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\interceptors\C_Fiscal_Representation.java
1
请完成以下Java代码
private void onRecordCopied(@NonNull final PO to, @NonNull final PO from, @NonNull final CopyTemplate template) { if (InterfaceWrapperHelper.isInstanceOf(to, I_C_OrderLine.class) && InterfaceWrapperHelper.isInstanceOf(from, I_C_OrderLine.class)) { final I_C_OrderLine newSalesOrderLine = InterfaceWrapperHelper.create(to, I_C_OrderLine.class); final I_C_OrderLine fromProposalLine = InterfaceWrapperHelper.create(from, I_C_OrderLine.class); newSalesOrderLine.setRef_ProposalLine_ID(fromProposalLine.getC_OrderLine_ID()); final I_C_Order fromProposal = fromProposalLine.getC_Order(); final DocTypeId proposalDocType = DocTypeId.ofRepoId(fromProposal.getC_DocType_ID()); if (isKeepProposalPrices && docTypeBL.isSalesQuotation(proposalDocType)) { newSalesOrderLine.setIsManualPrice(true); newSalesOrderLine.setPriceActual(fromProposalLine.getPriceActual());
} } } private void completeSalesOrderIfNeeded(final I_C_Order newSalesOrder) { if (completeIt) { documentBL.processEx(newSalesOrder, IDocument.ACTION_Complete, IDocument.STATUS_Completed); } else { newSalesOrder.setDocAction(IDocument.ACTION_Prepare); orderDAO.save(newSalesOrder); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\CreateSalesOrderFromProposalCommand.java
1
请完成以下Java代码
public static Optional<Integer> getCpuUsage() { try { return Optional.of((int) (HARDWARE.getProcessor().getSystemCpuLoad(1000) * 100.0)); } catch (Throwable e) { log.debug("Failed to get cpu usage!!!", e); } return Optional.empty(); } public static Optional<Integer> getCpuCount() { try { return Optional.of(HARDWARE.getProcessor().getLogicalProcessorCount()); } catch (Throwable e) { log.debug("Failed to get total cpu count!!!", e); } return Optional.empty(); } public static Optional<Integer> getDiscSpaceUsage() { try { FileStore store = Files.getFileStore(Paths.get("/")); long total = store.getTotalSpace(); long available = store.getUsableSpace();
return Optional.of(toPercent(total - available, total)); } catch (Throwable e) { log.debug("Failed to get free disc space!!!", e); } return Optional.empty(); } public static Optional<Long> getTotalDiscSpace() { try { FileStore store = Files.getFileStore(Paths.get("/")); return Optional.of(store.getTotalSpace()); } catch (Throwable e) { log.debug("Failed to get total disc space!!!", e); } return Optional.empty(); } private static int toPercent(long used, long total) { BigDecimal u = new BigDecimal(used); BigDecimal t = new BigDecimal(total); BigDecimal i = new BigDecimal(100); return u.multiply(i).divide(t, RoundingMode.HALF_UP).intValue(); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\SystemUtil.java
1
请在Spring Boot框架中完成以下Java代码
public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getLicencePic() { return licencePic; } public void setLicencePic(String licencePic) { this.licencePic = licencePic; } public Timestamp getRegisterTime() { return registerTime; } public void setRegisterTime(Timestamp registerTime) { this.registerTime = registerTime; } public UserTypeEnum getUserTypeEnum() { return userTypeEnum; } public void setUserTypeEnum(UserTypeEnum userTypeEnum) { this.userTypeEnum = userTypeEnum; } public UserStateEnum getUserStateEnum() { return userStateEnum;
} public void setUserStateEnum(UserStateEnum userStateEnum) { this.userStateEnum = userStateEnum; } public RoleEntity getRoleEntity() { return roleEntity; } public void setRoleEntity(RoleEntity roleEntity) { this.roleEntity = roleEntity; } @Override public String toString() { return "UserEntity{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", mail='" + mail + '\'' + ", licencePic='" + licencePic + '\'' + ", registerTime=" + registerTime + ", userTypeEnum=" + userTypeEnum + ", userStateEnum=" + userStateEnum + ", roleEntity=" + roleEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\UserEntity.java
2
请在Spring Boot框架中完成以下Java代码
public void configureWebSocketTransport(WebSocketTransportRegistration registry) { // TODO Auto-generated method stub } @Override public void configureClientInboundChannel(ChannelRegistration registration) { // TODO Auto-generated method stub } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { // TODO Auto-generated method stub } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // TODO Auto-generated method stub
} @Override public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { // TODO Auto-generated method stub } @Override public boolean configureMessageConverters(List<MessageConverter> messageConverters) { // TODO Auto-generated method stub return false; } }
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsockets\config\WebSocketMessageBrokerConfig.java
2
请完成以下Java代码
public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() { return toEdge; } @Override public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() { return toEdgeNotifications; } @Override public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() { return toEdgeEvents; } @Override public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() { return toUsageStats; } @Override public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Rule Engine!"); }
@Override public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() { return toHousekeeper; } @Override public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() { return toCalculatedFields; } @Override public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() { return toCalculatedFieldNotifications; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbRuleEngineProducerProvider.java
1
请完成以下Java代码
public class ScriptExecutionException extends ScriptException { /** * */ private static final long serialVersionUID = -1165299685098998072L; private IDatabase database; private IScript script; private IScriptExecutor executor; private List<String> log; public ScriptExecutionException(final String message, final Throwable cause) { super(message, cause); } public ScriptExecutionException(final String message) { super(message); } @Override public ScriptExecutionException addParameter(final String name, final Object value) { super.addParameter(name, value); return this; } public IDatabase getDatabase() { return database; } public ScriptExecutionException setDatabase(final IDatabase database) { addParameter("database", database); this.database = database; return this; } public IScript getScript() { return script; } public ScriptExecutionException setScript(final IScript script) {
addParameter("script", script); this.script = script; return this; } public IScriptExecutor getExecutor() { return executor; } public ScriptExecutionException setExecutor(final IScriptExecutor executor) { addParameter("executor", executor); this.executor = executor; return this; } public ScriptExecutionException setLog(final List<String> log) { addParameter("log", log); this.log = log; return this; } public List<String> getLog() { if (log == null) { return Collections.emptyList(); } return log; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\exception\ScriptExecutionException.java
1
请完成以下Java代码
protected void applySortBy(HistoricIncidentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_INCIDENT_ID)) { query.orderByIncidentId(); } else if (sortBy.equals(SORT_BY_INCIDENT_MESSAGE)) { query.orderByIncidentMessage(); } else if (sortBy.equals(SORT_BY_CREATE_TIME)) { query.orderByCreateTime(); } else if (sortBy.equals(SORT_BY_END_TIME)) { query.orderByEndTime(); } else if (sortBy.equals(SORT_BY_INCIDENT_TYPE)) { query.orderByIncidentType(); } else if (sortBy.equals(SORT_BY_EXECUTION_ID)) { query.orderByExecutionId(); } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { query.orderByActivityId(); } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { query.orderByProcessInstanceId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_CAUSE_INCIDENT_ID)) {
query.orderByCauseIncidentId(); } else if (sortBy.equals(SORT_BY_ROOT_CAUSE_INCIDENT_ID)) { query.orderByRootCauseIncidentId(); } else if (sortBy.equals(SORT_BY_CONFIGURATION)) { query.orderByConfiguration(); } else if (sortBy.equals(SORT_BY_HISTORY_CONFIGURATION)) { query.orderByHistoryConfiguration(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } else if (sortBy.equals(SORT_BY_INCIDENT_STATE)) { query.orderByIncidentState(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentQueryDto.java
1
请完成以下Java代码
public void setDunningGraceIfAutomatic(final I_C_Invoice invoice) { Services.get(IInvoiceSourceBL.class).setDunningGraceIfManaged(invoice); InterfaceWrapperHelper.save(invoice); } /** * This method is triggered when DunningGrace field is changed. * * NOTE: to developer: please keep this method with only ifColumnsChanged=DunningGrace because we want to avoid update cycles between invoice and dunning candidate * * @param invoice */ @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE , ifColumnsChanged = I_C_Invoice.COLUMNNAME_DunningGrace) public void validateCandidatesOnDunningGraceChange(final I_C_Invoice invoice) { final Timestamp dunningGraceDate = invoice.getDunningGrace(); logger.debug("DunningGraceDate: {}", dunningGraceDate); final IDunningDAO dunningDAO = Services.get(IDunningDAO.class); final IDunningBL dunningBL = Services.get(IDunningBL.class); final Properties ctx = InterfaceWrapperHelper.getCtx(invoice); final String trxName = InterfaceWrapperHelper.getTrxName(invoice); final IDunningContext context = dunningBL.createDunningContext(ctx, null, // dunningLevel null, // dunningDate trxName); final I_C_Dunning_Candidate callerCandidate = InterfaceWrapperHelper.getDynAttribute(invoice, C_Dunning_Candidate.POATTR_CallerPO); // // Gets dunning candidates for specific invoice, to check if they are still viable. final List<I_C_Dunning_Candidate> candidates = dunningDAO.retrieveDunningCandidates( context, getTableId(I_C_Invoice.class), invoice.getC_Invoice_ID()); for (final I_C_Dunning_Candidate candidate : candidates) {
if (callerCandidate != null && callerCandidate.getC_Dunning_Candidate_ID() == candidate.getC_Dunning_Candidate_ID()) { // skip the caller candidate to avoid cycles continue; } if (candidate.isProcessed()) { logger.debug("Skip processed candidate: {}", candidate); continue; } if (dunningBL.isExpired(candidate, dunningGraceDate)) { logger.debug("Deleting expired candidate: {}", candidate); InterfaceWrapperHelper.delete(candidate); } else { logger.debug("Updating DunningGrace for candidate: {}", candidate); candidate.setDunningGrace(invoice.getDunningGrace()); InterfaceWrapperHelper.save(candidate); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\model\validator\C_Invoice.java
1
请完成以下Java代码
public String getSeparator() { return this.separator; } /** * Sets the statement separator to use when reading the schema and data scripts. * @param separator statement separator used in the schema and data scripts */ public void setSeparator(String separator) { this.separator = separator; } /** * Returns the encoding to use when reading the schema and data scripts. * @return the script encoding */ public @Nullable Charset getEncoding() { return this.encoding; } /** * Sets the encoding to use when reading the schema and data scripts. * @param encoding encoding to use when reading the schema and data scripts */ public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; }
/** * Gets the mode to use when determining whether database initialization should be * performed. * @return the initialization mode * @since 2.5.1 */ public DatabaseInitializationMode getMode() { return this.mode; } /** * Sets the mode the use when determining whether database initialization should be * performed. * @param mode the initialization mode * @since 2.5.1 */ public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\DatabaseInitializationSettings.java
1
请完成以下Java代码
public class Authentication implements Principal, Serializable { public static final Authentication ANONYMOUS = new Authentication(null, null); private static final long serialVersionUID = 1L; protected final String identityId; protected final String processEngineName; public Authentication(String identityId, String processEngineName) { this.identityId = identityId; this.processEngineName = processEngineName; } /** * java.security.Principal implementation: return the id of the identity * (userId) behind this authentication */ public String getName() { return identityId; } /** * @return the id of the identity * (userId) behind this authentication */ public String getIdentityId() { return identityId; } /** * @return return the name of the process engine for which this authentication * was established. */ public String getProcessEngineName() { return processEngineName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((identityId == null) ? 0 : identityId.hashCode()); result = prime * result + ((processEngineName == null) ? 0 : processEngineName.hashCode()); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Authentication other = (Authentication) obj; if (identityId == null) { if (other.identityId != null) return false; } else if (!identityId.equals(other.identityId)) return false; if (processEngineName == null) { if (other.processEngineName != null) return false; } else if (!processEngineName.equals(other.processEngineName)) return false; return true; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\Authentication.java
1
请完成以下Java代码
public Collection<Decision> getDecisionsMade() { return decisionDecisionMadeRefCollection.getReferenceTargetElements(this); } public Collection<Decision> getDecisionsOwned() { return decisionDecisionOwnedRefCollection.getReferenceTargetElements(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OrganizationUnit.class, DMN_ELEMENT_ORGANIZATION_UNIT) .namespaceUri(LATEST_DMN_NS) .extendsType(BusinessContextElement.class) .instanceProvider(new ModelTypeInstanceProvider<OrganizationUnit>() { public OrganizationUnit newInstance(ModelTypeInstanceContext instanceContext) { return new OrganizationUnitImpl(instanceContext); } });
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); decisionDecisionMadeRefCollection = sequenceBuilder.elementCollection(DecisionMadeReference.class) .uriElementReferenceCollection(Decision.class) .build(); decisionDecisionOwnedRefCollection = sequenceBuilder.elementCollection(DecisionOwnedReference.class) .uriElementReferenceCollection(Decision.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OrganizationUnitImpl.java
1
请完成以下Java代码
public class BaseRootResource extends AbstractCockpitPluginRootResource { @Context protected Providers providers; public BaseRootResource() { super("base"); } @Path("{engine}" + ProcessDefinitionRestService.PATH) public ProcessDefinitionRestService getProcessDefinitionResource(@PathParam("engine") String engineName) { return subResource(new ProcessDefinitionRestService(engineName), engineName); } @Path("{engine}" + ProcessInstanceRestService.PATH) public ProcessInstanceRestService getProcessInstanceRestService(@PathParam("engine") String engineName) { ProcessInstanceRestService subResource = new ProcessInstanceRestService(engineName); subResource.setObjectMapper(getObjectMapper()); return subResource(subResource, engineName); }
@Path("{engine}" + IncidentRestService.PATH) public IncidentRestService getIncidentRestService(@PathParam("engine") String engineName) { return subResource(new IncidentRestService(engineName), engineName); } protected ObjectMapper getObjectMapper() { if(providers != null) { return ProvidersUtil .resolveFromContext(providers, ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE, this.getClass()); } else { return null; } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\BaseRootResource.java
1
请完成以下Java代码
public static int longToIntCast(long number) { return (int) number; } public static int longToIntJavaWithMath(long number) { return Math.toIntExact(number); } public static int longToIntJavaWithLambda(long number) { return convert.apply(number); } public static int longToIntBoxingValues(long number) { return Long.valueOf(number) .intValue();
} public static int longToIntGuava(long number) { return Ints.checkedCast(number); } public static int longToIntGuavaSaturated(long number) { return Ints.saturatedCast(number); } public static int longToIntWithBigDecimal(long number) { return new BigDecimal(number).intValueExact(); } }
repos\tutorials-master\core-java-modules\core-java-numbers-4\src\main\java\com\baeldung\convertLongToInt\ConvertLongToInt.java
1
请完成以下Java代码
public static DocumentKey of( @NonNull final WindowId windowId, @NonNull final DocumentId documentId) { return new DocumentKey(DocumentType.Window, windowId.toDocumentId(), documentId); } private final DocumentType documentType; private final DocumentId documentTypeId; private final DocumentId documentId; private Integer _hashcode = null; private DocumentKey( @NonNull final DocumentType documentType, @NonNull final DocumentId documentTypeId, @NonNull final DocumentId documentId) { this.documentType = documentType; this.documentTypeId = documentTypeId; this.documentId = documentId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("type", documentType) .add("typeId", documentTypeId) .add("documentId", documentId) .toString(); } @Override public int hashCode() { if (_hashcode == null) { _hashcode = Objects.hash(documentType, documentTypeId, documentId); } return _hashcode; } @Override public boolean equals(final Object obj) {
if (this == obj) { return true; } if (!(obj instanceof DocumentKey)) { return false; } final DocumentKey other = (DocumentKey)obj; return Objects.equals(documentType, other.documentType) && Objects.equals(documentTypeId, other.documentTypeId) && Objects.equals(documentId, other.documentId); } public WindowId getWindowId() { Check.assume(documentType == DocumentType.Window, "documentType shall be {} but it was {}", DocumentType.Window, documentType); return WindowId.of(documentTypeId); } public DocumentId getDocumentId() { return documentId; } public DocumentPath getDocumentPath() { return DocumentPath.rootDocumentPath(documentType, documentTypeId, documentId); } } // DocumentKey }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentCollection.java
1
请完成以下Java代码
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, @Nullable Exception ex) { cleanup(); } private void setup(Message<?> message) { Authentication authentication = message.getHeaders().get(this.authenticationHeaderName, Authentication.class); SecurityContext currentContext = this.securityContextHolderStrategy.getContext(); Stack<SecurityContext> contextStack = originalContext.get(); if (contextStack == null) { contextStack = new Stack<>(); originalContext.set(contextStack); } contextStack.push(currentContext); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication); this.securityContextHolderStrategy.setContext(context); } private void cleanup() { Stack<SecurityContext> contextStack = originalContext.get(); if (contextStack == null || contextStack.isEmpty()) { this.securityContextHolderStrategy.clearContext();
originalContext.remove(); return; } SecurityContext context = contextStack.pop(); try { if (this.empty.equals(context)) { this.securityContextHolderStrategy.clearContext(); originalContext.remove(); } else { this.securityContextHolderStrategy.setContext(context); } } catch (Throwable ex) { this.securityContextHolderStrategy.clearContext(); } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextPropagationChannelInterceptor.java
1
请完成以下Java代码
public void setIsAllowInvoicing (final boolean IsAllowInvoicing) { set_Value (COLUMNNAME_IsAllowInvoicing, IsAllowInvoicing); } @Override public boolean isAllowInvoicing() { return get_ValueAsBoolean(COLUMNNAME_IsAllowInvoicing); } @Override public void setIsAllowOnPurchase (final boolean IsAllowOnPurchase) { set_Value (COLUMNNAME_IsAllowOnPurchase, IsAllowOnPurchase); } @Override public boolean isAllowOnPurchase() { return get_ValueAsBoolean(COLUMNNAME_IsAllowOnPurchase); } @Override public void setIsAllowOnSales (final boolean IsAllowOnSales) { set_Value (COLUMNNAME_IsAllowOnSales, IsAllowOnSales); } @Override public boolean isAllowOnSales() { return get_ValueAsBoolean(COLUMNNAME_IsAllowOnSales); } @Override public I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class); } @Override public void setM_CostElement(final I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement); } @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_Value (COLUMNNAME_M_CostElement_ID, null); else set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override
public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cost_Type.java
1
请在Spring Boot框架中完成以下Java代码
private SourceHUsCollection retrieveActiveSourceHusFromWarehouse(@NonNull final ProductId productId) { final List<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveMatchingSourceHuMarkers( SourceHUsService.MatchingSourceHusQuery.builder() .productId(productId) .warehouseIds(getIssueFromWarehouseIds()) .build() ); final List<I_M_HU> hus = handlingUnitsDAO.getByIds(extractHUIdsFromSourceHUs(sourceHUs)); return SourceHUsCollection.builder() .husThatAreFlaggedAsSource(ImmutableList.copyOf(hus)) .sourceHUs(sourceHUs) .build(); } @NonNull private SourceHUsCollection retrieveActiveSourceHusForHus(@NonNull final ProductId productId) { final ImmutableList<I_M_HU> activeHUsMatchingProduct = handlingUnitsDAO.createHUQueryBuilder() .setOnlyActiveHUs(true) .setAllowEmptyStorage() .addOnlyHUIds(getPPOrderSourceHUIds()) .addOnlyWithProductId(productId) .createQuery()
.listImmutable(I_M_HU.class); final ImmutableList<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveSourceHuMarkers(extractHUIdsFromHUs(activeHUsMatchingProduct)); return SourceHUsCollection.builder() .husThatAreFlaggedAsSource(activeHUsMatchingProduct) .sourceHUs(sourceHUs) .build(); } private static ImmutableSet<HuId> extractHUIdsFromSourceHUs(final Collection<I_M_Source_HU> sourceHUs) { return sourceHUs.stream().map(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID())).collect(ImmutableSet.toImmutableSet()); } private static ImmutableSet<HuId> extractHUIdsFromHUs(final Collection<I_M_HU> hus) { return hus.stream().map(I_M_HU::getM_HU_ID).map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\SourceHUsCollectionProvider.java
2
请完成以下Java代码
public class BarURLHandler extends AbstractURLStreamHandlerService { private static final Logger LOGGER = LoggerFactory.getLogger(BarURLHandler.class); private static final String SYNTAX = "bar: bar-xml-uri"; private URL barXmlURL; /** * Open the connection for the given URL. * * @param url * the url from which to open a connection. * @return a connection on the specified URL. * @throws IOException * if an error occurs or if the URL is malformed. */ @Override public URLConnection openConnection(URL url) throws IOException { if (url.getPath() == null || url.getPath().trim().length() == 0) { throw new MalformedURLException("Path can not be null or empty. Syntax: " + SYNTAX); } barXmlURL = new URL(url.getPath()); LOGGER.debug("bar xml URL is: [{}]", barXmlURL); return new Connection(url); } public URL getBarXmlURL() { return barXmlURL; } public class Connection extends URLConnection {
public Connection(URL url) { super(url); } @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { final PipedInputStream pin = new PipedInputStream(); final PipedOutputStream pout = new PipedOutputStream(pin); new Thread() { @Override public void run() { try { BarTransformer.transform(barXmlURL, pout); } catch (Exception e) { LOGGER.warn("Bundle cannot be generated"); } finally { try { pout.close(); } catch (IOException ignore) { // if we get here something is very wrong LOGGER.error("Bundle cannot be generated", ignore); } } } }.start(); return pin; } } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BarURLHandler.java
1
请完成以下Java代码
public <T> List<IHUDocument> createHUDocuments(final Properties ctx, final Class<T> modelClass, final Iterator<T> records) { final String tableName = InterfaceWrapperHelper.getTableName(modelClass); assumeTableName(tableName); final List<IHUDocumentLine> lines = new ArrayList<IHUDocumentLine>(); while (records.hasNext()) { final T record = records.next(); final I_M_ReceiptSchedule schedule = InterfaceWrapperHelper.create(record, I_M_ReceiptSchedule.class); try { final List<IHUDocument> subsequentDocuments = null; // we don't care about subsequent documents final IHUDocumentLine line = createHUDocumentLine(schedule, subsequentDocuments); lines.add(line); } catch (final Exception e) { logger.warn("Error while creating line from " + schedule + ". Skipping.", e); } } final List<IHUDocument> docs = new ArrayList<IHUDocument>(); final IHUDocument doc = createHUDocumentFromLines(lines); docs.add(doc); return docs; } @Override public List<IHUDocument> createHUDocuments(final ProcessInfo pi) { Check.assumeNotNull(pi, "process info not null"); final String tableName = pi.getTableNameOrNull(); assumeTableName(tableName); final Iterator<I_M_ReceiptSchedule> schedules = retrieveReceiptSchedules(pi); return createHUDocuments(pi.getCtx(), I_M_ReceiptSchedule.class, schedules); } private Iterator<I_M_ReceiptSchedule> retrieveReceiptSchedules(final ProcessInfo pi) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_ReceiptSchedule.class, pi.getCtx(), ITrx.TRXNAME_None) // Filter by process info selection .filter(new ProcessInfoSelectionQueryFilter<I_M_ReceiptSchedule>(pi)) // FIXME: we need to fetch also those who where processed because on some of them we fully allocated to HUs and we cannot distinguish right now
// // Just those that are not processed // .filter(new EqualsQueryFilter<I_M_ReceiptSchedule>(I_M_ReceiptSchedule.COLUMNNAME_Processed, false)) .create() // Only active records .setOnlyActiveRecords(true) // Only those on which logged in user has RW access .setRequiredAccess(Access.WRITE) // .iterate(I_M_ReceiptSchedule.class); } @Override public List<IHUDocument> createHUDocumentsFromModel(final Object model) { final I_M_ReceiptSchedule schedule = InterfaceWrapperHelper.create(model, I_M_ReceiptSchedule.class); final List<IHUDocument> subsequentDocuments = null; // we don't care for subsequent documents final IHUDocumentLine line = createHUDocumentLine(schedule, subsequentDocuments); final IHUDocument doc = createHUDocumentFromLines(Collections.singletonList(line)); return Collections.singletonList(doc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUDocumentFactory.java
1
请在Spring Boot框架中完成以下Java代码
static class GenericConfiguration { @Bean ConnectionFactory connectionFactory(R2dbcProperties properties, ObjectProvider<R2dbcConnectionDetails> connectionDetails, ResourceLoader resourceLoader, ObjectProvider<ConnectionFactoryOptionsBuilderCustomizer> customizers, ObjectProvider<ConnectionFactoryDecorator> decorators) { return createConnectionFactory(properties, connectionDetails.getIfAvailable(), resourceLoader.getClassLoader(), customizers.orderedStream().toList(), decorators.orderedStream().toList()); } } /** * {@link Condition} that checks that a {@link ConnectionPool} is requested. The * condition matches if pooling was opt-in through configuration. If any of the * spring.r2dbc.pool.* properties have been configured, an exception is thrown if the * URL also contains pooling-related options or io.r2dbc.pool.ConnectionPool is not on * the class path. */ static class PooledConnectionFactoryCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { BindResult<Pool> pool = Binder.get(context.getEnvironment()) .bind("spring.r2dbc.pool", Bindable.of(Pool.class)); if (hasPoolUrl(context.getEnvironment())) { if (pool.isBound()) { throw new MultipleConnectionPoolConfigurationsException(); } return ConditionOutcome.noMatch("URL-based pooling has been configured"); }
if (pool.isBound() && !ClassUtils.isPresent("io.r2dbc.pool.ConnectionPool", context.getClassLoader())) { throw new MissingR2dbcPoolDependencyException(); } if (pool.orElseGet(Pool::new).isEnabled()) { return ConditionOutcome.match("Property-based pooling is enabled"); } return ConditionOutcome.noMatch("Property-based pooling is disabled"); } private boolean hasPoolUrl(Environment environment) { String url = environment.getProperty("spring.r2dbc.url"); return StringUtils.hasText(url) && url.contains(":pool:"); } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryConfigurations.java
2
请完成以下Java代码
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); } public static Effect getRootAsEffect(ByteBuffer _bb) { return getRootAsEffect(_bb, new Effect()); } public static Effect getRootAsEffect(ByteBuffer _bb, Effect obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public Effect __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } public short damage() { int o = __offset(6); return o != 0 ? bb.getShort(o + bb_pos) : 0; } public boolean mutateDamage(short damage) { int o = __offset(6); if (o != 0) { bb.putShort(o + bb_pos, damage); return true; } else { return false; } } public static int createEffect(FlatBufferBuilder builder, int nameOffset, short damage) { builder.startTable(2); Effect.addName(builder, nameOffset); Effect.addDamage(builder, damage); return Effect.endEffect(builder); }
public static void startEffect(FlatBufferBuilder builder) { builder.startTable(2); } public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(0, nameOffset, 0); } public static void addDamage(FlatBufferBuilder builder, short damage) { builder.addShort(1, damage, 0); } public static int endEffect(FlatBufferBuilder builder) { int o = builder.endTable(); return o; } public static final class Vector extends BaseVector { public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } public Effect get(int j) { return get(new Effect(), j); } public Effect get(Effect obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } } }
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\flatbuffers\MyGame\terrains\Effect.java
1
请在Spring Boot框架中完成以下Java代码
EmbeddedActiveMQ embeddedActiveMq(org.apache.activemq.artemis.core.config.Configuration configuration, JMSConfiguration jmsConfiguration, ObjectProvider<ArtemisConfigurationCustomizer> configurationCustomizers) { for (JMSQueueConfiguration queueConfiguration : jmsConfiguration.getQueueConfigurations()) { String queueName = queueConfiguration.getName(); configuration.addAddressConfiguration(new CoreAddressConfiguration().setName(queueName) .addRoutingType(RoutingType.ANYCAST) .addQueueConfiguration(QueueConfiguration.of(queueName) .setAddress(queueName) .setFilterString(queueConfiguration.getSelector()) .setDurable(queueConfiguration.isDurable()) .setRoutingType(RoutingType.ANYCAST))); } for (TopicConfiguration topicConfiguration : jmsConfiguration.getTopicConfigurations()) { configuration.addAddressConfiguration(new CoreAddressConfiguration().setName(topicConfiguration.getName()) .addRoutingType(RoutingType.MULTICAST)); } configurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration)); EmbeddedActiveMQ embeddedActiveMq = new EmbeddedActiveMQ(); embeddedActiveMq.setConfiguration(configuration); return embeddedActiveMq; } @Bean @ConditionalOnMissingBean JMSConfiguration artemisJmsConfiguration(ObjectProvider<JMSQueueConfiguration> queuesConfiguration, ObjectProvider<TopicConfiguration> topicsConfiguration) { JMSConfiguration configuration = new JMSConfigurationImpl(); configuration.getQueueConfigurations().addAll(queuesConfiguration.orderedStream().toList()); configuration.getTopicConfigurations().addAll(topicsConfiguration.orderedStream().toList()); addQueues(configuration, this.properties.getEmbedded().getQueues()); addTopics(configuration, this.properties.getEmbedded().getTopics()); return configuration; }
private void addQueues(JMSConfiguration configuration, String[] queues) { boolean persistent = this.properties.getEmbedded().isPersistent(); for (String queue : queues) { JMSQueueConfigurationImpl jmsQueueConfiguration = new JMSQueueConfigurationImpl(); jmsQueueConfiguration.setName(queue); jmsQueueConfiguration.setDurable(persistent); jmsQueueConfiguration.setBindings("/queue/" + queue); configuration.getQueueConfigurations().add(jmsQueueConfiguration); } } private void addTopics(JMSConfiguration configuration, String[] topics) { for (String topic : topics) { TopicConfigurationImpl topicConfiguration = new TopicConfigurationImpl(); topicConfiguration.setName(topic); topicConfiguration.setBindings("/topic/" + topic); configuration.getTopicConfigurations().add(topicConfiguration); } } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisEmbeddedServerConfiguration.java
2
请完成以下Java代码
public void setHasStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } @Override public boolean isGraphicalNotationDefined() { return isGraphicalNotationDefined; } @Override public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public boolean getIsGraphicalNotationDefined() { return isGraphicalNotationDefined; } public void setIsGraphicalNotationDefined(boolean isGraphicalNotationDefined) { this.isGraphicalNotationDefined = isGraphicalNotationDefined; } @Override public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) { this.isGraphicalNotationDefined = isGraphicalNotationDefined; } @Override public int getSuspensionState() { return suspensionState; } @Override public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } @Override public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } @Override public String getDerivedFrom() { return derivedFrom; } @Override public void setDerivedFrom(String derivedFrom) { this.derivedFrom = derivedFrom; } @Override public String getDerivedFromRoot() { return derivedFromRoot; } @Override public void setDerivedFromRoot(String derivedFromRoot) { this.derivedFromRoot = derivedFromRoot; } @Override public int getDerivedVersion() {
return derivedVersion; } @Override public void setDerivedVersion(int derivedVersion) { this.derivedVersion = derivedVersion; } @Override public String getEngineVersion() { return engineVersion; } @Override public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public IOSpecification getIoSpecification() { return ioSpecification; } public void setIoSpecification(IOSpecification ioSpecification) { this.ioSpecification = ioSpecification; } @Override public String toString() { return "ProcessDefinitionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java
1
请完成以下Java代码
public int create(String name, Integer age) { return jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age); } @Override public List<User> getByName(String name) { List<User> users = jdbcTemplate.query("select NAME, AGE from USER where NAME = ?", (resultSet, i) -> { User user = new User(); user.setName(resultSet.getString("NAME")); user.setAge(resultSet.getInt("AGE")); return user; }, name); return users; }
@Override public int deleteByName(String name) { return jdbcTemplate.update("delete from USER where NAME = ?", name); } @Override public int getAllUsers() { return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class); } @Override public int deleteAllUsers() { return jdbcTemplate.update("delete from USER"); } }
repos\SpringBoot-Learning-master\2.x\chapter3-1\src\main\java\com\didispace\chapter31\UserServiceImpl.java
1
请完成以下Java代码
public Advice getAdvice() { return this; } @Override public boolean isPerInstance() { return true; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) { this.securityContextHolderStrategy = () -> strategy; } /** * Filter a {@code returnedObject} using the {@link PostFilter} annotation that the * {@link MethodInvocation} specifies. * @param mi the {@link MethodInvocation} to check check * @return filtered {@code returnedObject} */ @Override public @Nullable Object invoke(MethodInvocation mi) throws Throwable { Object returnedObject = mi.proceed(); ExpressionAttribute attribute = this.registry.getAttribute(mi); if (attribute == null) { return returnedObject;
} MethodSecurityExpressionHandler expressionHandler = this.registry.getExpressionHandler(); EvaluationContext ctx = expressionHandler.createEvaluationContext(this::getAuthentication, mi); return expressionHandler.filter(returnedObject, attribute.getExpression(), ctx); } private Authentication getAuthentication() { Authentication authentication = this.securityContextHolderStrategy.get().getContext().getAuthentication(); if (authentication == null) { throw new AuthenticationCredentialsNotFoundException( "An Authentication object was not found in the SecurityContext"); } return authentication; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationMethodInterceptor.java
1
请完成以下Java代码
public OrgId getOrgId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return OrgId.ofRepoId(shipmentSchedule.getAD_Org_ID()); } public BPartnerId getBPartnerId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return scheduleEffectiveBL.getBPartnerId(shipmentSchedule); } public Optional<AsyncBatchId> getAsyncBatchId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return Optional.ofNullable(AsyncBatchId.ofRepoIdOrNull(shipmentSchedule.getC_Async_Batch_ID())); } @Nullable public ShipperId getShipperId(@Nullable final String shipperInternalName) { if (Check.isBlank(shipperInternalName)) { return null; } final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper); return shipper != null ? ShipperId.ofRepoId(shipper.getM_Shipper_ID()) : null; } @Nullable public String getTrackingURL(@NonNull final String shipperInternalName) { final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null ? shipper.getTrackingURL() : null; } @Nullable private I_M_Shipper loadShipper(@NonNull final String shipperInternalName) { return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName); } public ProductId getProductId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()); } public ProductId getProductId(@NonNull final String productSearchKey, @NonNull final OrgId orgId) { final ProductQuery query = ProductQuery.builder() .value(productSearchKey) .orgId(orgId) .includeAnyOrg(true) // include articles with org=* .build(); return productIdsByQuery.computeIfAbsent(query, this::retrieveProductIdByQuery); } private ProductId retrieveProductIdByQuery(@NonNull final ProductQuery query) { final ProductId productId = productDAO.retrieveProductIdBy(query); if (productId == null) { throw new AdempiereException("No product found for " + query); } return productId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShippingInfoCache.java
1
请完成以下Java代码
public void setQtyLU(@NonNull final BigDecimal qtyLU) { orderLine.setQtyLU(qtyLU); } public BigDecimal getQtyLU() { return orderLine.getQtyLU(); } @Override public void setLuId(@Nullable final HuPackingInstructionsId luId) { orderLine.setM_LU_HU_PI_ID(HuPackingInstructionsId.toRepoId(luId)); } @Override public HuPackingInstructionsId getLuId() { return HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID()); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); }
@Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public String toString() { return String .format("OrderLineHUPackingAware [orderLine=%s, getM_Product_ID()=%s, getM_Product()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, qtyLU()=%s, luId()=%s, isInDispute()=%s]", orderLine, getM_Product_ID(), getM_Product_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQtyTU(), getC_BPartner_ID(), getM_HU_PI_Item_Product_ID(), getQtyLU(), getLuId(), isInDispute()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(fulfillments, total, warnings); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ShippingFulfillmentPagedCollection {\n"); sb.append(" fulfillments: ").append(toIndentedString(fulfillments)).append("\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n"); sb.append(" warnings: ").append(toIndentedString(warnings)).append("\n"); sb.append("}"); return sb.toString(); }
/** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\ShippingFulfillmentPagedCollection.java
2
请完成以下Java代码
public static boolean isEventBusPostAsync(@NonNull final Topic topic) { if (alwaysConsiderAsyncTopics.contains(topic)) { return true; } // NOTE: in case of unit tests which are checking what notifications were arrived, // allowing the events to be posted async could be a problem because the event might arrive after the check. if (Adempiere.isUnitTestMode()) { return false; } final String nameForAllTopics = "de.metas.event.asyncEventBus"; final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final Map<String, String> valuesForPrefix = sysConfigBL.getValuesForPrefix(nameForAllTopics, ClientAndOrgId.SYSTEM); final String keyForTopic = nameForAllTopics + ".topic_" + topic.getName(); final String valueForTopic = valuesForPrefix.get(keyForTopic);
if (Check.isNotBlank(valueForTopic)) { getLogger(EventBusConfig.class).debug("SysConfig returned value={} for keyForTopic={}", valueForTopic, keyForTopic); return StringUtils.toBoolean(valueForTopic); } final String standardValue = valuesForPrefix.get(nameForAllTopics); getLogger(EventBusConfig.class).debug("SysConfig returned value={} for keyForTopic={}", standardValue, keyForTopic); return StringUtils.toBoolean(standardValue); } public static void alwaysConsiderAsync(@NonNull final Topic topic) { alwaysConsiderAsyncTopics.add(topic); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\EventBusConfig.java
1
请完成以下Java代码
public void markAsRead(final String notificationId) { notificationsRepo.markAsReadById(Integer.parseInt(notificationId)); fireEventOnWebsocket(JSONNotificationEvent.eventRead(notificationId, getUnreadCount())); } public void markAllAsRead() { logger.trace("Marking all notifications as read (if any) for {}...", this); notificationsRepo.markAllAsReadByUserId(getUserId()); fireEventOnWebsocket(JSONNotificationEvent.eventReadAll()); } public int getUnreadCount() { return notificationsRepo.getUnreadCountByUserId(getUserId()); } public void setLanguage(@NonNull final String adLanguage) { this.jsonOptions = jsonOptions.withAdLanguage(adLanguage);
} public void delete(final String notificationId) { notificationsRepo.deleteById(Integer.parseInt(notificationId)); fireEventOnWebsocket(JSONNotificationEvent.eventDeleted(notificationId, getUnreadCount())); } public void deleteAll() { notificationsRepo.deleteAllByUserId(getUserId()); fireEventOnWebsocket(JSONNotificationEvent.eventDeletedAll()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsQueue.java
1
请完成以下Java代码
public class ScriptBindingsFactory { protected ProcessEngineConfigurationImpl processEngineConfiguration; protected List<ResolverFactory> resolverFactories; public ScriptBindingsFactory( ProcessEngineConfigurationImpl processEngineConfiguration, List<ResolverFactory> resolverFactories ) { this.processEngineConfiguration = processEngineConfiguration; this.resolverFactories = resolverFactories; } public Bindings createBindings(VariableScope variableScope) { return new ScriptBindings(createResolvers(variableScope), variableScope); } public Bindings createBindings(VariableScope variableScope, boolean storeScriptVariables) { return new ScriptBindings(createResolvers(variableScope), variableScope, storeScriptVariables); } protected List<Resolver> createResolvers(VariableScope variableScope) { List<Resolver> scriptResolvers = new ArrayList<Resolver>(); for (ResolverFactory scriptResolverFactory : resolverFactories) { Resolver resolver = scriptResolverFactory.createResolver(processEngineConfiguration, variableScope);
if (resolver != null) { scriptResolvers.add(resolver); } } return scriptResolvers; } public List<ResolverFactory> getResolverFactories() { return resolverFactories; } public void setResolverFactories(List<ResolverFactory> resolverFactories) { this.resolverFactories = resolverFactories; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindingsFactory.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_C_ReferenceNo[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Reference No. @param C_ReferenceNo_ID Reference No */ @Override public void setC_ReferenceNo_ID (int C_ReferenceNo_ID) { if (C_ReferenceNo_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID)); } /** Get Reference No. @return Reference No */ @Override public int getC_ReferenceNo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.document.refid.model.I_C_ReferenceNo_Type getC_ReferenceNo_Type() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_Type_ID, de.metas.document.refid.model.I_C_ReferenceNo_Type.class); } @Override public void setC_ReferenceNo_Type(de.metas.document.refid.model.I_C_ReferenceNo_Type C_ReferenceNo_Type) { set_ValueFromPO(COLUMNNAME_C_ReferenceNo_Type_ID, de.metas.document.refid.model.I_C_ReferenceNo_Type.class, C_ReferenceNo_Type); } /** Set Reference No Type. @param C_ReferenceNo_Type_ID Reference No Type */ @Override public void setC_ReferenceNo_Type_ID (int C_ReferenceNo_Type_ID) { if (C_ReferenceNo_Type_ID < 1) set_Value (COLUMNNAME_C_ReferenceNo_Type_ID, null); else set_Value (COLUMNNAME_C_ReferenceNo_Type_ID, Integer.valueOf(C_ReferenceNo_Type_ID)); } /** Get Reference No Type. @return Reference No Type */ @Override public int getC_ReferenceNo_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Manuell. @param IsManual Dies ist ein manueller Vorgang */
@Override public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return Dies ist ein manueller Vorgang */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenznummer. @param ReferenceNo Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public void setReferenceNo (java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } /** Get Referenznummer. @return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public java.lang.String getReferenceNo () { return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo.java
1
请完成以下Java代码
public final void setPoolable(final boolean poolable) throws SQLException { getStatementImpl().setPoolable(poolable); } @Override public final boolean isPoolable() throws SQLException { return getStatementImpl().isPoolable(); } @Override public final void closeOnCompletion() throws SQLException { getStatementImpl().closeOnCompletion(); } @Override public final boolean isCloseOnCompletion() throws SQLException { return getStatementImpl().isCloseOnCompletion(); } @Override public final String getSql() { return this.vo.getSql(); } protected final String convertSqlAndSet(final String sql) { final String sqlConverted = DB.getDatabase().convertStatement(sql); vo.setSql(sqlConverted); MigrationScriptFileLoggerHolder.logMigrationScript(sql); return sqlConverted; } @Override public final void commit() throws SQLException { if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit()) { this.ownedConnection.commit(); } }
@Nullable private static Trx getTrx(@NonNull final CStatementVO vo) { final ITrxManager trxManager = Services.get(ITrxManager.class); final String trxName = vo.getTrxName(); if (trxManager.isNull(trxName)) { return (Trx)ITrx.TRX_None; } else { final ITrx trx = trxManager.get(trxName, false); // createNew=false // NOTE: we assume trx if of type Trx because we need to invoke getConnection() return (Trx)trx; } } @Override public String toString() { return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id private int id; private String login; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLogin() {
return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\java\com\baeldung\h2\exceptions\models\User.java
2
请完成以下Java代码
private MLocator findOldestLocatorWithSameWarehouse(final int M_Locator_ID) { final String trxName = null; MLocator retValue = null; final String sql = "SELECT * FROM M_Locator l " + "WHERE IsActive = 'Y' AND IsDefault='Y'" + " AND EXISTS (SELECT * FROM M_Locator lx " + "WHERE l.M_Warehouse_ID=lx.M_Warehouse_ID AND lx.M_Locator_ID=?) " + "ORDER BY Created"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trxName); pstmt.setInt(1, M_Locator_ID); rs = pstmt.executeQuery(); while (rs.next()) { retValue = new MLocator(getCtx(), rs, trxName); } } catch (SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return retValue; } // getDefault /** * Get Storage Sources * * @param M_Product_ID product * @param M_Locator_ID locator * @return sources */ private MStorage[] getSources(final int M_Product_ID, final int M_Locator_ID) { ArrayList<MStorage> list = new ArrayList<>();
String sql = "SELECT * " + "FROM M_Storage s " + "WHERE QtyOnHand > 0" + " AND M_Product_ID=?" // Empty ASI + " AND (M_AttributeSetInstance_ID=0" + " OR EXISTS (SELECT * FROM M_AttributeSetInstance asi " + "WHERE s.M_AttributeSetInstance_ID=asi.M_AttributeSetInstance_ID" + " AND asi.Description IS NULL) )" // Stock in same Warehouse + " AND EXISTS (SELECT * FROM M_Locator sl, M_Locator x " + "WHERE s.M_Locator_ID=sl.M_Locator_ID" + " AND x.M_Locator_ID=?" + " AND sl.M_Warehouse_ID=x.M_Warehouse_ID) " + "ORDER BY M_AttributeSetInstance_ID"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, M_Product_ID); pstmt.setInt(2, M_Locator_ID); rs = pstmt.executeQuery(); while (rs.next()) { list.add(new MStorage(getCtx(), rs, get_TrxName())); } } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } final MStorage[] retValue = new MStorage[list.size()]; list.toArray(retValue); return retValue; } // getSources } // StorageCleanup
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\StorageCleanup.java
1
请完成以下Java代码
protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered { @Override public void suspend() { } @Override public void resume() { } @Override public void flush() { } @Override public void beforeCommit(boolean readOnly) { } @Override public void beforeCompletion() { } @Override
public void afterCommit() { } @Override public void afterCompletion(int status) { } @Override public int getOrder() { return transactionSynchronizationAdapterOrder; } } }
repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\SpringTransactionContext.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } final PaySelectionId paySelectionId = PaySelectionId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (paySelectionId == null) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } if (context.getSelectedIncludedRecords().isEmpty()) { return ProcessPreconditionsResolution.rejectWithInternalReason("No lines selected"); } final DocStatus docStatus = getDocStatus(paySelectionId); if (!docStatus.isDraftedOrInProgress()) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } private DocStatus getDocStatus(@Nullable final PaySelectionId paySelectionId) { if (paySelectionId == null) { return DocStatus.Unknown; } return paySelectionBL.getById(paySelectionId) .map(paySelection -> DocStatus.ofCode(paySelection.getDocStatus())) .orElse(DocStatus.Unknown); } @Override protected String doIt() { assertDraftPaySelection(); final BPartnerId bpartnerId = getBPartnerIdFromSelectedLines(); openViewForBPartner(bpartnerId); return MSG_OK; } private void assertDraftPaySelection() { final PaySelectionId paySelectionId = getPaySelectionId(); final DocStatus docStatus = getDocStatus(paySelectionId); if (!docStatus.isDraftedOrInProgress()) { throw new AdempiereException("Invalid doc status"); } }
@NonNull private PaySelectionId getPaySelectionId() { return PaySelectionId.ofRepoId(getRecord_ID()); } private BPartnerId getBPartnerIdFromSelectedLines() { final PaySelectionId paySelectionId = getPaySelectionId(); final ImmutableSet<PaySelectionLineId> paySelectionLineIds = getSelectedIncludedRecordIds(I_C_PaySelectionLine.class, repoId -> PaySelectionLineId.ofRepoId(paySelectionId, repoId)); final ImmutableSet<BPartnerId> bpartnerIds = paySelectionBL.getBPartnerIdsFromPaySelectionLineIds(paySelectionLineIds); if (bpartnerIds.isEmpty()) { throw new AdempiereException("No BPartners"); } else if (bpartnerIds.size() != 1) { throw new AdempiereException("More than one BPartner selected"); } else { return bpartnerIds.iterator().next(); } } private void openViewForBPartner(final BPartnerId bpartnerId) { final ViewId viewId = viewsFactory.createView( CreateViewRequest.builder(PaymentsViewFactory.WINDOW_ID) .setParameter(PaymentsViewFactory.PARAMETER_TYPE_BPARTNER_ID, bpartnerId) .build()) .getViewId(); getResult().setWebuiViewToOpen(WebuiViewToOpen.modalOverlay(viewId.getViewId())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentView_Launcher_From_PaySelection.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { ensureNotNull(NotValidException.class, "jobDefinitionId", jobDefinitionId); JobDefinitionEntity jobDefinition = commandContext.getJobDefinitionManager().findById(jobDefinitionId); ensureNotNull(NotFoundException.class, "Job definition with id '" + jobDefinitionId + "' does not exist", "jobDefinition", jobDefinition); checkUpdateProcess(commandContext, jobDefinition); Long currentPriority = jobDefinition.getOverridingJobPriority(); jobDefinition.setJobPriority(priority); UserOperationLogContext opLogContext = new UserOperationLogContext(); createJobDefinitionOperationLogEntry(opLogContext, currentPriority, jobDefinition); if (cascade && priority != null) { commandContext.getJobManager().updateJobPriorityByDefinitionId(jobDefinitionId, priority); createCascadeJobsOperationLogEntry(opLogContext, jobDefinition); } commandContext.getOperationLogManager().logUserOperations(opLogContext); return null; } protected void checkUpdateProcess(CommandContext commandContext, JobDefinitionEntity jobDefinition) { String processDefinitionId = jobDefinition.getProcessDefinitionId(); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessDefinitionById(processDefinitionId); if (cascade) { checker.checkUpdateProcessInstanceByProcessDefinitionId(processDefinitionId); } } } protected void createJobDefinitionOperationLogEntry(UserOperationLogContext opLogContext, Long previousPriority, JobDefinitionEntity jobDefinition) { PropertyChange propertyChange = new PropertyChange(
JOB_DEFINITION_OVERRIDING_PRIORITY, previousPriority, jobDefinition.getOverridingJobPriority()); UserOperationLogContextEntry entry = UserOperationLogContextEntryBuilder .entry(UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY, EntityTypes.JOB_DEFINITION) .inContextOf(jobDefinition) .propertyChanges(propertyChange) .category(UserOperationLogEntry.CATEGORY_OPERATOR) .create(); opLogContext.addEntry(entry); } protected void createCascadeJobsOperationLogEntry(UserOperationLogContext opLogContext, JobDefinitionEntity jobDefinition) { // old value is unknown PropertyChange propertyChange = new PropertyChange( SetJobPriorityCmd.JOB_PRIORITY_PROPERTY, null, jobDefinition.getOverridingJobPriority()); UserOperationLogContextEntry entry = UserOperationLogContextEntryBuilder .entry(UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY, EntityTypes.JOB) .inContextOf(jobDefinition) .propertyChanges(propertyChange) .category(UserOperationLogEntry.CATEGORY_OPERATOR) .create(); opLogContext.addEntry(entry); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetJobDefinitionPriorityCmd.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getAge() { return age; } /** * 设置age属性的值。 * * @param value * allowed object is * {@link Integer } * */ public void setAge(Integer value) { this.age = value; } /** * 获取id属性的值。 * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * 设置id属性的值。 * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * 获取name属性的值。 * * @return * possible object is
* {@link String } * */ public String getName() { return name; } /** * 设置name属性的值。 * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\User.java
2
请在Spring Boot框架中完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (projectId == null) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } final ImmutableSet<ServiceRepairProjectTaskId> taskIds = getSelectedTaskIds(context); final ImmutableSet<ServiceRepairProjectTaskId> taskIdsOfTypeSpareParts = projectService.retainIdsOfTypeSpareParts(taskIds); if (taskIdsOfTypeSpareParts.size() != 1) { return ProcessPreconditionsResolution.rejectWithInternalReason("one and only one task shall be selected"); } return checkIsServiceOrRepairProject(projectId); } @Override protected String doIt() { final ServiceRepairProjectTaskId taskId = getSingleSelectedTaskId(); if (!projectService.isSparePartsTask(taskId))
{ throw new AdempiereException("Not a spare parts task"); } final ServiceRepairProjectTask task = projectService.getTaskById(taskId); final IView view = viewsRepository.createView( husToIssueViewFactory.createViewRequest(HUsToIssueViewContext.builder() .taskId(taskId) .productId(task.getProductId()) .build())); getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder() .viewId(view.getViewId().toJson()) .target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\C_Project_OpenHUsToIssue.java
2
请在Spring Boot框架中完成以下Java代码
private List<ConfigDataResolutionResult> resolve(ConfigDataLocationResolver<?> resolver, ConfigDataLocationResolverContext context, ConfigDataLocation location, @Nullable Profiles profiles) { List<ConfigDataResolutionResult> resolved = resolve(location, false, () -> resolver.resolve(context, location)); if (profiles == null) { return resolved; } List<ConfigDataResolutionResult> profileSpecific = resolve(location, true, () -> resolver.resolveProfileSpecific(context, location, profiles)); return merge(resolved, profileSpecific); } private List<ConfigDataResolutionResult> resolve(ConfigDataLocation location, boolean profileSpecific, Supplier<List<? extends ConfigDataResource>> resolveAction) { List<ConfigDataResource> resources = nonNullList(resolveAction.get()); List<ConfigDataResolutionResult> resolved = new ArrayList<>(resources.size()); for (ConfigDataResource resource : resources) { resolved.add(new ConfigDataResolutionResult(location, resource, profileSpecific)); } return resolved; } @SuppressWarnings("unchecked")
private <T> List<T> nonNullList(@Nullable List<? extends T> list) { return (list != null) ? (List<T>) list : Collections.emptyList(); } private <T> List<T> merge(List<T> list1, List<T> list2) { List<T> merged = new ArrayList<>(list1.size() + list2.size()); merged.addAll(list1); merged.addAll(list2); return merged; } /** * Return the resolvers managed by this object. * @return the resolvers */ List<ConfigDataLocationResolver<?>> getResolvers() { return this.resolvers; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationResolvers.java
2
请完成以下Java代码
public ImmutableCredentialRecordBuilder uvInitialized(boolean uvInitialized) { this.uvInitialized = uvInitialized; return this; } public ImmutableCredentialRecordBuilder transports(Set<AuthenticatorTransport> transports) { this.transports = transports; return this; } public ImmutableCredentialRecordBuilder backupEligible(boolean backupEligible) { this.backupEligible = backupEligible; return this; } public ImmutableCredentialRecordBuilder backupState(boolean backupState) { this.backupState = backupState; return this; } public ImmutableCredentialRecordBuilder attestationObject(@Nullable Bytes attestationObject) { this.attestationObject = attestationObject; return this; } public ImmutableCredentialRecordBuilder attestationClientDataJSON(@Nullable Bytes attestationClientDataJSON) { this.attestationClientDataJSON = attestationClientDataJSON;
return this; } public ImmutableCredentialRecordBuilder created(Instant created) { this.created = created; return this; } public ImmutableCredentialRecordBuilder lastUsed(Instant lastUsed) { this.lastUsed = lastUsed; return this; } public ImmutableCredentialRecordBuilder label(String label) { this.label = label; return this; } public ImmutableCredentialRecord build() { return new ImmutableCredentialRecord(this.credentialType, this.credentialId, this.userEntityUserId, this.publicKey, this.signatureCount, this.uvInitialized, this.transports, this.backupEligible, this.backupState, this.attestationObject, this.attestationClientDataJSON, this.created, this.lastUsed, this.label); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutableCredentialRecord.java
1