instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class ESRReceiptLineMatcherUtil { public final static AdMessageKey ERR_WRONG_CTRL_AMT = AdMessageKey.of("ESR_Wrong_Ctrl_Amt"); public final static AdMessageKey ERR_WRONG_CTRL_QTY = AdMessageKey.of("ESR_Wrong_Ctrl_Qty"); public final static AdMessageKey ERR_WRONG_TRX_TYPE = AdMessageKey.of("ESR_Wrong_Trx_Type"); public boolean isReceiptLine(@NonNull final String v11LineStr) { final String trxType = ESRTransactionLineMatcherUtil.extractEsrTrxType(v11LineStr); return ESRConstants.ESRTRXTYPE_Receipt.equals(trxType); } /** * * @param v11LineStr * @return {@code true} if the given string is a V11 receipt (control) line, but does not have the correct length of 87. */ public boolean isReceiptLineWithWrongLength(@NonNull final String v11LineStr) { if (!isReceiptLine(v11LineStr)) { return false; } return v11LineStr.length() != 87; } /** * If there is a problem extracting the amount, it logs an error message to {@link Loggables#get()}. * * @param esrImportLineText * @return */ public BigDecimal extractCtrlAmount(@NonNull final String esrImportLineText) { // set the control amount (from the control line) final String ctrlAmtStr = esrImportLineText.substring(39, 51); try { final BigDecimal controlAmount = new BigDecimal(ctrlAmtStr).divide(Env.ONEHUNDRED, 2, RoundingMode.UNNECESSARY); return controlAmount; } catch (NumberFormatException e) { Loggables.addLog(Services.get(IMsgBL.class).getMsg(Env.getCtx(), ERR_WRONG_CTRL_AMT, new Object[] { ctrlAmtStr })); return null;
} } /** * If there is a problem extracting the qty, it logs an error message to {@link Loggables#get()}. * * @param esrImportLineText * @return */ public BigDecimal extractCtrlQty(@NonNull final String esrImportLineText) { final String trxQtysStr = esrImportLineText.substring(51, 63); try { final BigDecimal controlTrxQty = new BigDecimal(trxQtysStr); return controlTrxQty; } catch (NumberFormatException e) { Loggables.addLog(Services.get(IMsgBL.class).getMsg(Env.getCtx(), ERR_WRONG_CTRL_QTY, new Object[] { trxQtysStr })); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\impl\v11\ESRReceiptLineMatcherUtil.java
1
请完成以下Java代码
public String getIdAsString() { return String.valueOf(id); } public String getMessage(final String adLanguage) { return adLanguage2message.computeIfAbsent(adLanguage, this::buildMessage); } private String buildMessage(final String adLanguage) { // // Build detail message final StringBuilder detailBuf = new StringBuilder(); if(!severity.isNotice()) { final String notificationSeverity = getSeverity().getNameTrl().translate(adLanguage); detailBuf.append(notificationSeverity).append(":"); } // Add plain detail if any if (!Check.isEmpty(detailPlain, true)) { detailBuf.append(detailPlain.trim()); } // Translate, parse and add detail (AD_Message). if (!Check.isEmpty(detailADMessage, true)) { final String detailTrl = Services.get(IMsgBL.class) .getTranslatableMsgText(detailADMessage) .translate(adLanguage); final String detailTrlParsed = UserNotificationDetailMessageFormat.newInstance() .setLeftBrace("{").setRightBrace("}") .setThrowExceptionIfKeyWasNotFound(false) .setArguments(detailADMessageParams) .format(detailTrl); if (!Check.isEmpty(detailTrlParsed, true)) { if (detailBuf.length() > 0) { detailBuf.append("\n"); } detailBuf.append(detailTrlParsed); } } return detailBuf.toString(); } public synchronized boolean isRead() { return read;
} public boolean isNotRead() { return !isRead(); } public synchronized boolean setRead(final boolean read) { final boolean readOld = this.read; this.read = read; return readOld; } @Nullable public String getTargetWindowIdAsString() { return targetWindowId != null ? String.valueOf(targetWindowId.getRepoId()) : null; } @Nullable public String getTargetDocumentId() { return targetRecord != null ? String.valueOf(targetRecord.getRecord_ID()) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotification.java
1
请完成以下Java代码
public static class BigArray { int[] data; @Setup(Level.Iteration) public void prepare() { data = new int[ARRAY_SIZE]; for(int j = 0; j< ARRAY_SIZE; j++) { data[j] = 1; } } @TearDown(Level.Iteration) public void destroy() { data = null; }
} @Benchmark public void largeArrayLoopSum(BigArray bigArray, Blackhole blackhole) { for (int i = 0; i < ARRAY_SIZE - 1; i++) { bigArray.data[i + 1] += bigArray.data[i]; } blackhole.consume(bigArray.data); } @Benchmark public void largeArrayParallelPrefixSum(BigArray bigArray, Blackhole blackhole) { Arrays.parallelPrefix(bigArray.data, (left, right) -> left + right); blackhole.consume(bigArray.data); } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\arrays\ParallelPrefixBenchmark.java
1
请完成以下Java代码
public void setM_Product_Category_Parent_ID (int M_Product_Category_Parent_ID) { if (M_Product_Category_Parent_ID < 1) set_Value (COLUMNNAME_M_Product_Category_Parent_ID, null); else set_Value (COLUMNNAME_M_Product_Category_Parent_ID, Integer.valueOf(M_Product_Category_Parent_ID)); } /** Get Parent Product Category. @return Parent Product Category */ @Override public int getM_Product_Category_Parent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** * MRP_Exclude AD_Reference_ID=319 * Reference name: _YesNo */ public static final int MRP_EXCLUDE_AD_Reference_ID=319; /** Yes = Y */ public static final String MRP_EXCLUDE_Yes = "Y"; /** No = N */ public static final String MRP_EXCLUDE_No = "N"; /** Set MRP ausschliessen. @param MRP_Exclude MRP ausschliessen */ @Override public void setMRP_Exclude (java.lang.String MRP_Exclude) { set_Value (COLUMNNAME_MRP_Exclude, MRP_Exclude); } /** Get MRP ausschliessen. @return MRP ausschliessen */ @Override public java.lang.String getMRP_Exclude () { return (java.lang.String)get_Value(COLUMNNAME_MRP_Exclude); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set DB1 %. @param PlannedMargin Project's planned margin as a percentage */ @Override public void setPlannedMargin (java.math.BigDecimal PlannedMargin) { set_Value (COLUMNNAME_PlannedMargin, PlannedMargin); } /** Get DB1 %. @return Project's planned margin as a percentage */ @Override public java.math.BigDecimal getPlannedMargin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PlannedMargin); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Category.java
1
请在Spring Boot框架中完成以下Java代码
public class PackagingDetailsType { @XmlElement(name = "NumberOfPackages") protected BigDecimal numberOfPackages; @XmlElement(name = "CustomersPackagingNumber") protected String customersPackagingNumber; @XmlElement(name = "SuppliersPackagingNumber") protected String suppliersPackagingNumber; @XmlElement(name = "PackagingCapacity") protected BigDecimal packagingCapacity; /** * Gets the value of the numberOfPackages property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getNumberOfPackages() { return numberOfPackages; } /** * Sets the value of the numberOfPackages property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setNumberOfPackages(BigDecimal value) { this.numberOfPackages = value; } /** * Gets the value of the customersPackagingNumber property. * * @return * possible object is * {@link String } * */ public String getCustomersPackagingNumber() { return customersPackagingNumber; } /** * Sets the value of the customersPackagingNumber property. * * @param value * allowed object is * {@link String } * */ public void setCustomersPackagingNumber(String value) { this.customersPackagingNumber = value; } /** * Gets the value of the suppliersPackagingNumber property. * * @return * possible object is * {@link String } * */ public String getSuppliersPackagingNumber() {
return suppliersPackagingNumber; } /** * Sets the value of the suppliersPackagingNumber property. * * @param value * allowed object is * {@link String } * */ public void setSuppliersPackagingNumber(String value) { this.suppliersPackagingNumber = value; } /** * Gets the value of the packagingCapacity property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getPackagingCapacity() { return packagingCapacity; } /** * Sets the value of the packagingCapacity property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setPackagingCapacity(BigDecimal value) { this.packagingCapacity = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PackagingDetailsType.java
2
请完成以下Java代码
public HistoricVariableInstanceQuery orderByVariableName() { wrappedHistoricVariableInstanceQuery.orderByVariableName(); return this; } @Override public HistoricVariableInstanceQuery asc() { wrappedHistoricVariableInstanceQuery.asc(); return this; } @Override public HistoricVariableInstanceQuery desc() { wrappedHistoricVariableInstanceQuery.desc(); return this; } @Override public HistoricVariableInstanceQuery orderBy(QueryProperty property) { wrappedHistoricVariableInstanceQuery.orderBy(property); return this; } @Override public HistoricVariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { wrappedHistoricVariableInstanceQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return wrappedHistoricVariableInstanceQuery.count(); } @Override
public HistoricVariableInstance singleResult() { return wrappedHistoricVariableInstanceQuery.singleResult(); } @Override public List<HistoricVariableInstance> list() { return wrappedHistoricVariableInstanceQuery.list(); } @Override public List<HistoricVariableInstance> listPage(int firstResult, int maxResults) { return wrappedHistoricVariableInstanceQuery.listPage(firstResult, maxResults); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\CmmnHistoricVariableInstanceQueryImpl.java
1
请完成以下Java代码
public TenantProfile get(TenantId tenantId) { TenantProfileId profileId = tenantsMap.get(tenantId); if (profileId == null) { Tenant tenant = tenantService.findTenantById(tenantId); if (tenant != null) { profileId = tenant.getTenantProfileId(); tenantsMap.put(tenantId, profileId); } else { return null; } } return get(profileId); } @Override public void put(TenantProfile profile) { if (profile.getId() != null) { tenantProfilesMap.put(profile.getId(), profile); notifyTenantListeners(profile); } } @Override public void evict(TenantProfileId profileId) { tenantProfilesMap.remove(profileId); notifyTenantListeners(get(profileId)); } public void notifyTenantListeners(TenantProfile tenantProfile) { if (tenantProfile != null) { tenantsMap.forEach(((tenantId, tenantProfileId) -> { if (tenantProfileId.equals(tenantProfile.getId())) { ConcurrentMap<EntityId, Consumer<TenantProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(tenantProfile)); } } })); } }
@Override public void evict(TenantId tenantId) { tenantsMap.remove(tenantId); TenantProfile tenantProfile = get(tenantId); if (tenantProfile != null) { ConcurrentMap<EntityId, Consumer<TenantProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(tenantProfile)); } } } @Override public void addListener(TenantId tenantId, EntityId listenerId, Consumer<TenantProfile> profileListener) { //Force cache of the tenant id. get(tenantId); if (profileListener != null) { profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener); } } @Override public void removeListener(TenantId tenantId, EntityId listenerId) { ConcurrentMap<EntityId, Consumer<TenantProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.remove(listenerId); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\DefaultTbTenantProfileCache.java
1
请完成以下Java代码
public L getLeft() { return left; } /** * @return the right element */ public R getRight() { return right; } /** * Create a pair of elements. * * @param left * the left element * @param right * the right element */ public ImmutablePair(L left, R right) { this.left = left; this.right = right; } @Override public final L getKey() { return this.getLeft(); } @Override public R getValue() { return this.getRight(); } /** * This is not allowed since the pair itself is immutable. * * @return never * @throws UnsupportedOperationException */ @Override public R setValue(R value) { throw new UnsupportedOperationException("setValue not allowed for an ImmutablePair"); } /** * Compares the pair based on the left element followed by the right element. * The types must be {@code Comparable}. * * @param other * the other pair, not null * @return negative if this is less, zero if equal, positive if greater */ @Override @SuppressWarnings("unchecked") public int compareTo(ImmutablePair<L, R> o) { if (o == null) { throw new IllegalArgumentException("Pair to compare to must not be null"); } try { int leftComparison = compare((Comparable<L>) getLeft(), (Comparable<L>) o.getLeft()); return leftComparison == 0 ? compare((Comparable<R>) getRight(), (Comparable<R>) o.getRight()) : leftComparison; } catch (ClassCastException cce) { throw new IllegalArgumentException("Please provide comparable elements", cce); } } @SuppressWarnings({ "unchecked", "rawtypes" })
protected int compare(Comparable original, Comparable other) { if (original == other) { return 0; } if (original == null) { return -1; } if (other == null) { return 1; } return original.compareTo(other); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Entry)) { return false; } else { Entry<?, ?> other = (Entry<?, ?>) obj; return Objects.equals(this.getKey(), other.getKey()) && Objects.equals(this.getValue(), other.getValue()); } } @Override public int hashCode() { return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^ (this.getValue() == null ? 0 : this.getValue().hashCode()); } @Override public String toString() { return "(" + this.getLeft() + ',' + this.getRight() + ')'; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ImmutablePair.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutProcessInstanceId() { return withoutProcessInstanceId; } public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) { this.withoutProcessInstanceId = withoutProcessInstanceId; } public String getTaskCandidateGroup() { return taskCandidateGroup; } public void setTaskCandidateGroup(String taskCandidateGroup) { this.taskCandidateGroup = taskCandidateGroup; } public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; } public String getPlanItemInstanceId() { return planItemInstanceId; } public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java
2
请完成以下Java代码
public static boolean isEntityTypeDisplayedInUIOrTrueIfNull( @NonNull final IUserRolePermissions role, @NonNull final String entityType) { final UIDisplayedEntityTypes constraint = role .getConstraint(UIDisplayedEntityTypes.class) .orElse(null); // If no constraint => return default (true) if (constraint == null) { return true; } // Ask the constraint return constraint.isDisplayedInUI(entityType); } private final boolean showAllEntityTypes; private UIDisplayedEntityTypes(final boolean showAllEntityTypes) { super(); this.showAllEntityTypes = showAllEntityTypes; } @Override public boolean isInheritable() { return false; }
/** * @return true if UI elements for given entity type shall be displayed */ public boolean isDisplayedInUI(final String entityType) { if (showAllEntityTypes) { return EntityTypesCache.instance.isActive(entityType); } else { return EntityTypesCache.instance.isDisplayedInUI(entityType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\UIDisplayedEntityTypes.java
1
请完成以下Java代码
public void setC_CountryArea_Assign_ID (int C_CountryArea_Assign_ID) { if (C_CountryArea_Assign_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CountryArea_Assign_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CountryArea_Assign_ID, Integer.valueOf(C_CountryArea_Assign_ID)); } /** Get Country area assign. @return Country area assign */ @Override public int getC_CountryArea_Assign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_Assign_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_CountryArea getC_CountryArea() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_CountryArea_ID, org.compiere.model.I_C_CountryArea.class); } @Override public void setC_CountryArea(org.compiere.model.I_C_CountryArea C_CountryArea) { set_ValueFromPO(COLUMNNAME_C_CountryArea_ID, org.compiere.model.I_C_CountryArea.class, C_CountryArea); } /** Set Country Area. @param C_CountryArea_ID Country Area */ @Override public void setC_CountryArea_ID (int C_CountryArea_ID) { if (C_CountryArea_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, Integer.valueOf(C_CountryArea_ID)); } /** Get Country Area. @return Country Area */ @Override public int getC_CountryArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CountryArea_Assign.java
1
请完成以下Java代码
public class HandleExternalTaskFailureCmd extends HandleExternalTaskCmd { protected String errorMessage; protected String errorDetails; protected long retryDuration; protected int retries; protected Map<String, Object> variables; protected Map<String, Object> localVariables; /** * Overloaded constructor to support short and full error messages * * @param externalTaskId * @param workerId * @param errorMessage * @param errorDetails * @param retries * @param retryDuration */ public HandleExternalTaskFailureCmd(String externalTaskId, String workerId, String errorMessage, String errorDetails, int retries, long retryDuration, Map<String, Object> variables, Map<String, Object> localVariables) { super(externalTaskId, workerId); this.errorMessage = errorMessage; this.errorDetails = errorDetails; this.retries = retries; this.retryDuration = retryDuration; this.variables = variables; this.localVariables = localVariables; } @Override public void execute(ExternalTaskEntity externalTask) {
externalTask.failed(errorMessage, errorDetails, retries, retryDuration, variables, localVariables); } @Override protected void validateInput() { super.validateInput(); EnsureUtil.ensureGreaterThanOrEqual("retries", retries, 0); EnsureUtil.ensureGreaterThanOrEqual("retryDuration", retryDuration, 0); } @Override public String getErrorMessageOnWrongWorkerAccess() { return "Failure of External Task " + externalTaskId + " cannot be reported by worker '" + workerId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\HandleExternalTaskFailureCmd.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 Org Column. @param OrgColumn Fully qualified Organization column (AD_Org_ID) */ public void setOrgColumn (String OrgColumn) { set_Value (COLUMNNAME_OrgColumn, OrgColumn); } /** Get Org Column. @return Fully qualified Organization column (AD_Org_ID) */ public String getOrgColumn () { return (String)get_Value(COLUMNNAME_OrgColumn); } /** Set Measure Calculation. @param PA_MeasureCalc_ID Calculation method for measuring performance */ public void setPA_MeasureCalc_ID (int PA_MeasureCalc_ID) { if (PA_MeasureCalc_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, Integer.valueOf(PA_MeasureCalc_ID)); } /** Get Measure Calculation. @return Calculation method for measuring performance */ public int getPA_MeasureCalc_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_MeasureCalc_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Product Column. @param ProductColumn Fully qualified Product column (M_Product_ID)
*/ public void setProductColumn (String ProductColumn) { set_Value (COLUMNNAME_ProductColumn, ProductColumn); } /** Get Product Column. @return Fully qualified Product column (M_Product_ID) */ public String getProductColumn () { return (String)get_Value(COLUMNNAME_ProductColumn); } /** Set Sql SELECT. @param SelectClause SQL SELECT clause */ public void setSelectClause (String SelectClause) { set_Value (COLUMNNAME_SelectClause, SelectClause); } /** Get Sql SELECT. @return SQL SELECT clause */ public String getSelectClause () { return (String)get_Value(COLUMNNAME_SelectClause); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_MeasureCalc.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isOpen() { return this.resource.isOpen(); } @Override public URL getURL() throws IOException { return this.resource.getURL(); } @Override public URI getURI() throws IOException { return this.resource.getURI(); } @Override public File getFile() throws IOException { return this.resource.getFile(); } @NonNull @Override public InputStream getInputStream() throws IOException { return this.resource.getInputStream(); } @Override public long contentLength() throws IOException { return this.resource.contentLength(); } @Override public long lastModified() throws IOException { return this.resource.lastModified(); } @Override public net.shibboleth.shared.resource.Resource createRelativeResource(String relativePath) throws IOException { return new SpringResource(this.resource.createRelative(relativePath)); } @Override
public String getFilename() { return this.resource.getFilename(); } @Override public String getDescription() { return this.resource.getDescription(); } } } private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter { CriteriaSetResolverWrapper(MetadataResolver metadataResolver) { super(metadataResolver); } @Override EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception { return super.metadataResolver.resolveSingle(new CriteriaSet(entityId)); } @Override Iterable<EntityDescriptor> resolve(EntityRoleCriterion role) throws Exception { return super.metadataResolver.resolve(new CriteriaSet(role)); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\registration\OpenSaml5AssertingPartyMetadataRepository.java
2
请完成以下Java代码
public class KafkaOutboundChannelModel extends OutboundChannelModel { protected String topic; protected RecordKey recordKey; protected KafkaPartition partition; public KafkaOutboundChannelModel() { super(); setType("kafka"); } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public RecordKey getRecordKey() { return recordKey; } public void setRecordKey(RecordKey recordKey) { this.recordKey = recordKey; } public KafkaPartition getPartition() { return partition; } public void setPartition(KafkaPartition partition) { this.partition = partition; } @JsonInclude(Include.NON_NULL) public static class KafkaPartition { protected String eventField; protected String roundRobin; protected String delegateExpression; public String getEventField() { return eventField; } public void setEventField(String eventField) { this.eventField = eventField; } public String getRoundRobin() { return roundRobin; } public void setRoundRobin(String roundRobin) { this.roundRobin = roundRobin; }
public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } } @JsonInclude(Include.NON_NULL) public static class RecordKey { protected String fixedValue; protected String eventField; protected String delegateExpression; public String getFixedValue() { return fixedValue; } public void setFixedValue(String fixedValue) { this.fixedValue = fixedValue; } public String getEventField() { return eventField; } public void setEventField(String eventField) { this.eventField = eventField; } public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } // backward compatibility @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static RecordKey fromFixedValue(String fixedValue) { RecordKey recordKey = new RecordKey(); recordKey.setFixedValue(fixedValue); return recordKey; } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaOutboundChannelModel.java
1
请完成以下Java代码
private static Object convertToPOValue(final String value, final PO po, final String columnName) { final int displayType = po.getPOInfo().getColumnDisplayType(po.get_ColumnIndex(columnName)); return DisplayType.convertToDisplayType(value, columnName, displayType); } private static String resolveAppendSuffix(final ValueToCopyResolveContext context, @Nullable final String suffixToAppend) { if (suffixToAppend == null || suffixToAppend.isEmpty()) { String valueUnique = TranslatableStrings.builder() .append(StringUtils.nullToEmpty(context.getFromValueAsString())) .append("(") .appendADMessage(MSG_CopiedOn, TranslatableStrings.date(context.getTimestamp(), DisplayType.DateTime)) .append(" ") .append(context.getLoggedUserName().orElse("-")) .append(")") .build() .translate(Env.getADLanguageOrBaseLanguage());
final int fieldLength = context.getToFieldLength(); if (fieldLength > 0 && valueUnique.length() > fieldLength) { valueUnique = valueUnique.substring(0, fieldLength); } return valueUnique; } else { final String oldValue = String.valueOf(context.getFromValue()); return oldValue.concat(suffixToAppend); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\copy\ValueToCopy.java
1
请在Spring Boot框架中完成以下Java代码
public void setStrictness(@Nullable Strictness strictness) { this.strictness = strictness; } public void setLenient(@Nullable Boolean lenient) { setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT); } public @Nullable Boolean getDisableHtmlEscaping() { return this.disableHtmlEscaping; } public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) { this.disableHtmlEscaping = disableHtmlEscaping; } public @Nullable String getDateFormat() { return this.dateFormat; } public void setDateFormat(@Nullable String dateFormat) { this.dateFormat = dateFormat; } /** * Enumeration of levels of strictness. Values are the same as those on * {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize * backwards compatibility, the Gson enum is not used directly. */ public enum Strictness { /** * Lenient compliance.
*/ LENIENT, /** * Strict compliance with some small deviations for legacy reasons. */ LEGACY_STRICT, /** * Strict compliance. */ STRICT } }
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java
2
请完成以下Java代码
private AllocableHU toAllocableHU(@NonNull final PickFromHU pickFromHU, @NonNull final ProductId productId) { final HUsLoadingCache husCache = pickFromHUsSupplier.getHusCache(); final HuId topLevelHUId = pickFromHU.getTopLevelHUId(); // // Make sure our top level HU is not already reserved to somebody else // TODO in future we shall check/accept if the VHU was already reserved for one of our DD_OrderLine(s) final ImmutableSet<HuId> vhuIds = husCache.getVHUIds(topLevelHUId); if (huReservationService.isAnyOfVHUIdsReserved(vhuIds)) { return null; } final I_M_HU topLevelHU = husCache.getHUById(topLevelHUId); return new AllocableHU(storageFactory, topLevelHU, productId); } // // // @Value @Builder private static class AllocationGroupingKey { @NonNull ProductId productId; @NonNull LocatorId pickFromLocatorId; } private static class AllocableHU { private final IHUStorageFactory storageFactory; @Getter private final I_M_HU topLevelHU; private final ProductId productId; private Quantity _storageQty; private Quantity qtyAllocated; public AllocableHU( final IHUStorageFactory storageFactory, final I_M_HU topLevelHU, final ProductId productId) { this.storageFactory = storageFactory; this.topLevelHU = topLevelHU; this.productId = productId; } public Quantity getQtyAvailableToAllocate() { final Quantity qtyStorage = getStorageQty(); return qtyAllocated != null ? qtyStorage.subtract(qtyAllocated)
: qtyStorage; } private Quantity getStorageQty() { Quantity storageQty = this._storageQty; if (storageQty == null) { storageQty = this._storageQty = storageFactory.getStorage(topLevelHU).getProductStorage(productId).getQty(); } return storageQty; } public void addQtyAllocated(@NonNull final Quantity qtyAllocatedToAdd) { final Quantity newQtyAllocated = this.qtyAllocated != null ? this.qtyAllocated.add(qtyAllocatedToAdd) : qtyAllocatedToAdd; final Quantity storageQty = getStorageQty(); if (newQtyAllocated.isGreaterThan(storageQty)) { throw new AdempiereException("Over-allocating is not allowed") .appendParametersToMessage() .setParameter("this.qtyAllocated", this.qtyAllocated) .setParameter("newQtyAllocated", newQtyAllocated) .setParameter("storageQty", storageQty); } this.qtyAllocated = newQtyAllocated; } } private static class AllocableHUsList implements Iterable<AllocableHU> { private final ImmutableList<AllocableHU> hus; private AllocableHUsList(@NonNull final ImmutableList<AllocableHU> hus) {this.hus = hus;} @Override public @NonNull Iterator<AllocableHU> iterator() {return hus.iterator();} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\plan\DDOrderMovePlanCreateCommand.java
1
请完成以下Java代码
public int getQM_SpecificationLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_QM_SpecificationLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (String ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public String getValidFrom () {
return (String)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_QM_SpecificationLine.java
1
请完成以下Java代码
public Flux<Instance> findAll() { return this.eventStore.findAll() .groupBy(InstanceEvent::getInstance) .flatMap((f) -> f.reduce(Instance.create(f.key()), Instance::apply)); } @Override public Mono<Instance> find(InstanceId id) { return this.eventStore.find(id) .collectList() .filter((e) -> !e.isEmpty()) .map((e) -> Instance.create(id).apply(e)); } @Override public Flux<Instance> findByName(String name) { return findAll().filter((a) -> a.isRegistered() && name.equals(a.getRegistration().getName())); } @Override public Mono<Instance> compute(InstanceId id, BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) { return this.find(id)
.flatMap((application) -> remappingFunction.apply(id, application)) .switchIfEmpty(Mono.defer(() -> remappingFunction.apply(id, null))) .flatMap(this::save) .retryWhen(this.retryOptimisticLockException); } @Override public Mono<Instance> computeIfPresent(InstanceId id, BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) { return this.find(id) .flatMap((application) -> remappingFunction.apply(id, application)) .flatMap(this::save) .retryWhen(this.retryOptimisticLockException); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\EventsourcingInstanceRepository.java
1
请完成以下Java代码
default V evaluate(final Evaluatee ctx, final boolean ignoreUnparsable) { // backward compatibility final OnVariableNotFound onVariableNotFound = ignoreUnparsable ? OnVariableNotFound.Empty : OnVariableNotFound.ReturnNoResult; return evaluate(ctx, onVariableNotFound); } /** * Evaluates expression in given context. * * @return evaluation result * @throws ExpressionEvaluationException if evaluation fails and we were advised to throw exception */ V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException; /** * @return true if the given <code>result</code> shall be considered as "NO RESULT"
*/ default boolean isNoResult(final Object result) { return result == null; } /** * @return true if this expression is constant and always evaluated "NO RESULT" * @see #isNoResult(Object) */ default boolean isNullExpression() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IExpression.java
1
请完成以下Java代码
public boolean isLiteralText() { return false; } public Class<?> getType(Bindings bindings, ELContext context) { return null; } public boolean isReadOnly(Bindings bindings, ELContext context) { return true; } public void setValue(Bindings bindings, ELContext context, Object value) { throw new ELException(LocalMessages.get("error.value.set.rvalue", getStructuralId(bindings))); } public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return null; } public boolean isLeftValue() { return false; } public boolean isMethodInvocation() { return true; } public final ValueReference getValueReference(Bindings bindings, ELContext context) { return null; } @Override public void appendStructure(StringBuilder builder, Bindings bindings) { property.appendStructure(builder, bindings); params.appendStructure(builder, bindings); } protected Object eval(Bindings bindings, ELContext context, boolean answerNullIfBaseIsNull) { Object base = property.getPrefix().eval(bindings, context); if (base == null) { if (answerNullIfBaseIsNull) { return null; } throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", property.getPrefix())); } Object method = property.getProperty(bindings, context); if (method == null) { throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base)); } String name = bindings.convert(method, String.class); context.setPropertyResolved(false); Object result = context.getELResolver().invoke(context, base, name, null, params.eval(bindings, context)); if (!context.isPropertyResolved()) {
throw new MethodNotFoundException( LocalMessages.get("error.property.method.notfound", name, base.getClass()) ); } return result; } @Override public Object eval(Bindings bindings, ELContext context) { return eval(bindings, context, true); } public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues ) { return eval(bindings, context, false); } public int getCardinality() { return 2; } public Node getChild(int i) { return i == 0 ? property : i == 1 ? params : null; } @Override public String toString() { return "<method>"; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstMethod.java
1
请完成以下Java代码
public String getErrorMessageAsStringOrNull() { return getErrorMessageAsStringOrNull(-1); } public String getErrorMessageAsStringOrNull(final int maxLength) { final int maxLengthEffective = maxLength > 0 ? maxLength : Integer.MAX_VALUE; final StringBuilder result = new StringBuilder(); if (parseError != null) { result.append(parseError.getMessage()); } if (cells != null) { for (final ImpDataCell cell : cells) { if (!cell.isCellError()) { continue; } final String cellErrorMessage = cell.getCellErrorMessage().getMessage(); if (result.length() > 0) { result.append("; "); } result.append(cellErrorMessage); if (result.length() >= maxLengthEffective) { break; } } } return result.length() > 0 ? StringUtils.trunc(result.toString(), maxLengthEffective) : null; } public List<Object> getJdbcValues(@NonNull final List<ImpFormatColumn> columns) { final int columnsCount = columns.size(); if (parseError != null) { final ArrayList<Object> nulls = new ArrayList<>(columnsCount); for (int i = 0; i < columnsCount; i++) { nulls.add(null);
} return nulls; } else { final ArrayList<Object> values = new ArrayList<>(columnsCount); final int cellsCount = cells.size(); for (int i = 0; i < columnsCount; i++) { if (i < cellsCount) { values.add(cells.get(i).getJdbcValue()); } else { values.add(null); } } return values; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\ImpDataLine.java
1
请完成以下Java代码
public void execute(InterpretableExecution execution) { ActivityImpl activity = (ActivityImpl) execution.getActivity(); ActivityBehavior activityBehavior = activity.getActivityBehavior(); if (activityBehavior == null) { throw new PvmException("no behavior specified in " + activity); } LOGGER.debug("{} executes {}: {}", execution, activity, activityBehavior.getClass().getName()); try { if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_STARTED, execution.getActivity().getId(), (String) execution.getActivity().getProperty("name"), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(),
(String) activity.getProperties().get("type"), activity.getActivityBehavior().getClass().getCanonicalName()), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } activityBehavior.execute(execution); } catch (ActivitiException e) { throw e; } catch (Throwable t) { LogMDC.putMDCExecution(execution); throw new ActivitiActivityExecutionException("couldn't execute activity <" + activity.getProperty("type") + " id=\"" + activity.getId() + "\" ...>: " + t.getMessage(), t); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationActivityExecute.java
1
请完成以下Java代码
public void setAD_Error_ID (int AD_Error_ID) { if (AD_Error_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Error_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Error_ID, Integer.valueOf(AD_Error_ID)); } /** Get Error. @return Error */ public int getAD_Error_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Error_ID); if (ii == null) return 0; return ii.intValue(); } /** AD_Language AD_Reference_ID=106 */ public static final int AD_LANGUAGE_AD_Reference_ID=106; /** Set Language. @param AD_Language Language for this entity */ public void setAD_Language (String AD_Language) { set_Value (COLUMNNAME_AD_Language, AD_Language); } /** Get Language. @return Language for this entity */ public String getAD_Language () { return (String)get_Value(COLUMNNAME_AD_Language); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code.
@return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Error.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeService { @PersistenceContext private EntityManager entityManager; public List<Employee> getAllEmployeesUsingJPQL() { String jpqlQuery = "SELECT e FROM Employee e"; Query query = entityManager.createQuery(jpqlQuery, Employee.class); return query.getResultList(); } public List<Employee> getAllEmployeesByDepartmentUsingJPQL() { String jpqlQuery = "SELECT e FROM Employee e WHERE e.department = 'Engineering' ORDER BY e.lastName ASC"; Query query = entityManager.createQuery(jpqlQuery, Employee.class); return query.getResultList(); } public List<Employee> getAllEmployeesUsingNamedQuery() { Query query = entityManager.createNamedQuery("findAllEmployees", Employee.class); return query.getResultList(); } public List<Employee> getAllEmployeesByDepartmentUsingNamedQuery(String department) { Query query = entityManager.createNamedQuery("findEmployeesByDepartment", Employee.class); query.setParameter("department", department); return query.getResultList(); } public List<Employee> getAllEmployeesUsingCriteriaAPI() { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class); Root<Employee> employeeRoot = criteriaQuery.from(Employee.class);
criteriaQuery.select(employeeRoot); Query query = entityManager.createQuery(criteriaQuery); return query.getResultList(); } public List<Employee> getAllEmployeesByDepartmentUsingCriteriaAPI(String department) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class); Root<Employee> employeeRoot = criteriaQuery.from(Employee.class); Predicate departmentPredicate = criteriaBuilder.equal(employeeRoot.get("department"), department); Path<Object> sortByPath = employeeRoot.get("lastName"); criteriaQuery.orderBy(criteriaBuilder.asc(sortByPath)); criteriaQuery.select(employeeRoot) .where(departmentPredicate); Query query = entityManager.createQuery(criteriaQuery); return query.getResultList(); } public List<Employee> getAllEmployeesByDepartmentUsingOneToManyAnnotations(String departmentName) { try { // Retrieve the department by its name Department department = entityManager.createQuery("SELECT d FROM Department d WHERE d.name = :name", Department.class) .setParameter("name", departmentName) .getSingleResult(); // Return the list of employees associated with the department return department.getEmployees(); } catch (NoResultException e) { return Collections.emptyList(); } } }
repos\tutorials-master\persistence-modules\hibernate-queries-2\src\main\java\com\baeldung\hibernate\listentity\service\EmployeeService.java
2
请完成以下Java代码
public class FlowableServices { private ProcessEngine processEngine; public void setProcessEngine(ProcessEngine processEngine) { this.processEngine = processEngine; } @Produces @Named @ApplicationScoped public ProcessEngine processEngine() { return processEngine; } @Produces @Named @ApplicationScoped public RuntimeService runtimeService() { return processEngine().getRuntimeService(); } @Produces @Named @ApplicationScoped public TaskService taskService() { return processEngine().getTaskService(); } @Produces @Named @ApplicationScoped public RepositoryService repositoryService() { return processEngine().getRepositoryService(); } @Produces @Named @ApplicationScoped public FormService formService() { return processEngine().getFormService(); } @Produces @Named
@ApplicationScoped public HistoryService historyService() { return processEngine().getHistoryService(); } @Produces @Named @ApplicationScoped public IdentityService identityService() { return processEngine().getIdentityService(); } @Produces @Named @ApplicationScoped public ManagementService managementService() { return processEngine().getManagementService(); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\util\FlowableServices.java
1
请完成以下Java代码
public static int toIntegerOrZero(final String str) { if (str == null || str.isEmpty()) { return 0; } try { return Integer.valueOf(str); } catch (NumberFormatException e) { return 0; } } /** * Casts a string to BigDecimal. Returns BigDecimal.ZERO if the operation fails. * * @param str * @return */ public static BigDecimal toBigDecimalOrZero(final String str) { if (str == null || str.isEmpty()) { return BigDecimal.ZERO; } try { return new BigDecimal(str); } catch (NumberFormatException e) { return BigDecimal.ZERO; } } public static String formatMessage(final String message, Object... params) { String messageFormated; if (params != null && params.length > 0) { try { messageFormated = MessageFormat.format(message, params); } catch (Exception e) { // In case message formating failed, we have a fallback format to use messageFormated = new StringBuilder() .append(message) .append(" (").append(params).append(")") .toString(); } } else { messageFormated = message; } return messageFormated; } /** * String diacritics from given string *
* @param s original string * @return string without diacritics */ // note: we just moved the method here, and left it unchanges. as of now idk why all this code is commented out public static String stripDiacritics(String s) { /* JAVA5 behaviour */ return s; /* * JAVA6 behaviour * if (s == null) { return s; } String normStr = java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD); * * StringBuffer sb = new StringBuffer(); for (int i = 0; i < normStr.length(); i++) { char ch = normStr.charAt(i); if (ch < 255) sb.append(ch); } return sb.toString(); /* */ } /** * Check if given string contains digits only. * * @param stringToVerify * @return {@link code true} if the given string consists only of digits (i.e. contains no letter, whitespace decimal point etc). */ public static final boolean isNumber(final String stringToVerify) { // Null or empty strings are not numbers if (stringToVerify == null || stringToVerify.isEmpty()) { return false; } final int length = stringToVerify.length(); for (int i = 0; i < length; i++) { if (!Character.isDigit(stringToVerify.charAt(i))) { return false; } } return true; } public static final String toString(final Collection<?> collection, final String separator) { if (collection == null) { return "null"; } if (collection.isEmpty()) { return ""; } final StringBuilder sb = new StringBuilder(); for (final Object item : collection) { if (sb.length() > 0) { sb.append(separator); } sb.append(String.valueOf(item)); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\util\StringUtils.java
1
请完成以下Java代码
public static int genRandomNum(int length) { int num = 1; double random = Math.random(); if (random < 0.1) { random = random + 0.1; } for (int i = 0; i < length; i++) { num = num * 10; } return (int) ((random * num)); } /** * 生成订单流水号 * * @return */ public static String genOrderNo() {
StringBuffer buffer = new StringBuffer(String.valueOf(System.currentTimeMillis())); int num = genRandomNum(4); buffer.append(num); return buffer.toString(); } public static String formatMoney2Str(Double money) { java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); return df.format(money); } public static String formatMoney2Str(float money) { java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); return df.format(money); } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\utils\NumberUtil.java
1
请完成以下Java代码
public class TbMsgPackCallback implements TbMsgCallback { private final UUID id; private final TenantId tenantId; private final TbMsgPackProcessingContext ctx; private final long startMsgProcessing; private final Timer successfulMsgTimer; private final Timer failedMsgTimer; public TbMsgPackCallback(UUID id, TenantId tenantId, TbMsgPackProcessingContext ctx) { this(id, tenantId, ctx, null, null); } public TbMsgPackCallback(UUID id, TenantId tenantId, TbMsgPackProcessingContext ctx, Timer successfulMsgTimer, Timer failedMsgTimer) { this.id = id; this.tenantId = tenantId; this.ctx = ctx; this.successfulMsgTimer = successfulMsgTimer; this.failedMsgTimer = failedMsgTimer; startMsgProcessing = System.currentTimeMillis(); } @Override public void onSuccess() { log.trace("[{}] ON SUCCESS", id); if (successfulMsgTimer != null) { successfulMsgTimer.record(System.currentTimeMillis() - startMsgProcessing, TimeUnit.MILLISECONDS); } ctx.onSuccess(id); } @Override public void onRateLimit(RuleEngineException e) { log.debug("[{}] ON RATE LIMIT", id, e); //TODO notify tenant on rate limit if (failedMsgTimer != null) { failedMsgTimer.record(System.currentTimeMillis() - startMsgProcessing, TimeUnit.MILLISECONDS); } ctx.onSuccess(id); }
@Override public void onFailure(RuleEngineException e) { if (ExceptionUtil.lookupExceptionInCause(e, AbstractRateLimitException.class) != null) { onRateLimit(e); return; } log.trace("[{}] ON FAILURE", id, e); if (failedMsgTimer != null) { failedMsgTimer.record(System.currentTimeMillis() - startMsgProcessing, TimeUnit.MILLISECONDS); } ctx.onFailure(tenantId, id, e); } @Override public boolean isMsgValid() { return !ctx.isCanceled(); } @Override public void onProcessingStart(RuleNodeInfo ruleNodeInfo) { log.trace("[{}] ON PROCESSING START: {}", id, ruleNodeInfo); ctx.onProcessingStart(id, ruleNodeInfo); } @Override public void onProcessingEnd(RuleNodeId ruleNodeId) { log.trace("[{}] ON PROCESSING END: {}", id, ruleNodeId); ctx.onProcessingEnd(id, ruleNodeId); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbMsgPackCallback.java
1
请完成以下Java代码
private IQueryBuilder<I_M_HU> retrieveActiveSourceHusQuery(@NonNull final MatchingSourceHusQuery query) { if (query.getProductIds().isEmpty()) { return null; } final ICompositeQueryFilter<I_M_HU> huFilters = createHuFilter(query); return Services.get(IQueryBL.class).createQueryBuilder(I_M_Source_HU.class) .addOnlyActiveRecordsFilter() .andCollect(I_M_Source_HU.COLUMN_M_HU_ID) .filter(huFilters); } @Override public List<I_M_Source_HU> retrieveActiveSourceHuMarkers(@NonNull final MatchingSourceHusQuery query) { if (query.getProductIds().isEmpty()) { return ImmutableList.of(); } final IQueryBL queryBL = Services.get(IQueryBL.class); final IQuery<I_M_HU> huQuery = queryBL.createQueryBuilder(I_M_HU.class) .addOnlyActiveRecordsFilter() .filter(createHuFilter(query)) .create(); return queryBL.createQueryBuilder(I_M_Source_HU.class) .addOnlyActiveRecordsFilter() .addInSubQueryFilter(I_M_Source_HU.COLUMN_M_HU_ID, I_M_HU.COLUMN_M_HU_ID, huQuery) .create() .list(); } @VisibleForTesting static ICompositeQueryFilter<I_M_HU> createHuFilter(@NonNull final MatchingSourceHusQuery query) { final IQueryBL queryBL = Services.get(IQueryBL.class);
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final ICompositeQueryFilter<I_M_HU> huFilters = queryBL.createCompositeQueryFilter(I_M_HU.class) .setJoinOr(); final IHUQueryBuilder huQueryBuilder = handlingUnitsDAO.createHUQueryBuilder() .setOnlyActiveHUs(true) .setAllowEmptyStorage() .addOnlyWithProductIds(query.getProductIds()); final ImmutableSet<WarehouseId> warehouseIds = query.getWarehouseIds(); if (warehouseIds != null && !warehouseIds.isEmpty()) { huQueryBuilder.addOnlyInWarehouseIds(warehouseIds); } final IQueryFilter<I_M_HU> huFilter = huQueryBuilder.createQueryFilter(); huFilters.addFilter(huFilter); return huFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\impl\SourceHuDAO.java
1
请完成以下Java代码
private boolean isBoolean(Object value) { if (value == null) { return false; } return Boolean.class.isAssignableFrom(value.getClass()) || boolean.class.isAssignableFrom(value.getClass()); } protected void ensureVariablesInitialized() { if (!getQueryVariableValues().isEmpty()) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers(); String dbType = processEngineConfiguration.getDatabaseType(); for(QueryVariableValue queryVariableValue : getQueryVariableValues()) { queryVariableValue.initialize(variableSerializers, dbType); }
} } public List<QueryVariableValue> getQueryVariableValues() { return queryVariableValues; } public Boolean isVariableNamesIgnoreCase() { return variableNamesIgnoreCase; } public Boolean isVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractVariableQueryImpl.java
1
请完成以下Java代码
private I_C_BPartner updateExistingBPartner(@NonNull final I_I_Pharma_BPartner importRecord) { final I_C_BPartner bpartner; bpartner = InterfaceWrapperHelper.create(importRecord.getC_BPartner(), I_C_BPartner.class); if (!Check.isEmpty(importRecord.getb00name1(), true)) { bpartner.setIsCompany(true); bpartner.setCompanyName(importRecord.getb00name1()); bpartner.setName(importRecord.getb00name1()); } if (!Check.isEmpty(importRecord.getb00name2())) { bpartner.setName2(importRecord.getb00name2()); } if (!Check.isEmpty(importRecord.getb00name3())) { bpartner.setName3(importRecord.getb00name3());
} if (!Check.isEmpty(importRecord.getb00adrnr())) { bpartner.setIFA_Manufacturer(importRecord.getb00adrnr()); bpartner.setDescription("IFA " + importRecord.getb00adrnr()); } bpartner.setIsManufacturer(true); if (!Check.isEmpty(importRecord.getb00homepag())) { bpartner.setURL(importRecord.getb00homepag()); } return bpartner; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerImportHelper.java
1
请完成以下Java代码
public POSOrder changeStatusTo( @NonNull final POSTerminalId posTerminalId, @NonNull final POSOrderExternalId externalId, @NonNull final POSOrderStatus nextStatus, @NonNull final UserId userId) { return ordersService.changeStatusTo(posTerminalId, externalId, nextStatus, userId); } public POSOrder updateOrderFromRemote( @NonNull final RemotePOSOrder remoteOrder, @NonNull final UserId userId) { return ordersService.updateOrderFromRemote(remoteOrder, userId); } public POSOrder checkoutPayment(@NonNull POSPaymentCheckoutRequest request) { return ordersService.checkoutPayment(request);
} public POSOrder refundPayment( @NonNull final POSTerminalId posTerminalId, @NonNull final POSOrderExternalId posOrderExternalId, @NonNull final POSPaymentExternalId posPaymentExternalId, @NonNull final UserId userId) { return ordersService.refundPayment(posTerminalId, posOrderExternalId, posPaymentExternalId, userId); } public Optional<Resource> getReceiptPdf(@NonNull final POSOrderExternalId externalId) { return ordersService.getReceiptPdf(externalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSService.java
1
请在Spring Boot框架中完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) {
this.password = password; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) { if (username == null && password == null) { return; } headerParams.put("Authorization", Credentials.basic( username == null ? "" : username, password == null ? "" : password)); } }
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\invoker\auth\HttpBasicAuth.java
2
请在Spring Boot框架中完成以下Java代码
public LwM2MServerSecurityConfigDefault getServerSecurityInfo(boolean bootstrapServer) { LwM2MSecureServerConfig bsServerConfig = bootstrapServer ? bootstrapConfig.orElse(null) : serverConfig; if (bsServerConfig!= null) { LwM2MServerSecurityConfigDefault result = getServerSecurityConfig(bsServerConfig); result.setBootstrapServerIs(bootstrapServer); return result; } else { return null; } } private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig) { LwM2MServerSecurityConfigDefault bsServ = new LwM2MServerSecurityConfigDefault(); bsServ.setShortServerId(bsServerConfig.getId()); bsServ.setHost(bsServerConfig.getHost()); bsServ.setPort(bsServerConfig.getPort()); bsServ.setSecurityHost(bsServerConfig.getSecureHost()); bsServ.setSecurityPort(bsServerConfig.getSecurePort()); byte[] publicKeyBase64 = getPublicKey(bsServerConfig); if (publicKeyBase64 == null) { bsServ.setServerPublicKey(""); } else { bsServ.setServerPublicKey(Base64.encodeBase64String(publicKeyBase64)); } byte[] certificateBase64 = getCertificate(bsServerConfig); if (certificateBase64 == null) { bsServ.setServerCertificate(""); } else { bsServ.setServerCertificate(Base64.encodeBase64String(certificateBase64)); } return bsServ; }
private byte[] getPublicKey(LwM2MSecureServerConfig config) { try { SslCredentials sslCredentials = config.getSslCredentials(); if (sslCredentials != null) { return sslCredentials.getPublicKey().getEncoded(); } } catch (Exception e) { log.trace("Failed to fetch public key from key store!", e); } return null; } private byte[] getCertificate(LwM2MSecureServerConfig config) { try { SslCredentials sslCredentials = config.getSslCredentials(); if (sslCredentials != null) { return sslCredentials.getCertificateChain()[0].getEncoded(); } } catch (Exception e) { log.trace("Failed to fetch certificate from key store!", e); } return null; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\lwm2m\LwM2MServiceImpl.java
2
请完成以下Java代码
public java.lang.String getUserLevel () { return (java.lang.String)get_Value(COLUMNNAME_UserLevel); } /** Set Is webui role. @param WEBUI_Role Is webui role */ @Override public void setWEBUI_Role (boolean WEBUI_Role) { set_Value (COLUMNNAME_WEBUI_Role, Boolean.valueOf(WEBUI_Role)); } /** Get Is webui role. @return Is webui role */ @Override public boolean isWEBUI_Role () { Object oo = get_Value(COLUMNNAME_WEBUI_Role); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public void setIsAllowPasswordChangeForOthers (final boolean IsAllowPasswordChangeForOthers) { set_Value (COLUMNNAME_IsAllowPasswordChangeForOthers, IsAllowPasswordChangeForOthers); } @Override public boolean isAllowPasswordChangeForOthers() { return get_ValueAsBoolean(COLUMNNAME_IsAllowPasswordChangeForOthers); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role.java
1
请完成以下Spring Boot application配置
logging: level: org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter: error server: port: 8040 turbine: stream: port: 8041 eureka: instance: hostname: registry prefer-ip-address: true metadata-map: user.name: ${security.user.name} user.password: ${security.user.password} client: service-url: defaultZone: http://user:${REGISTRY_SERVER_PASSWORD:password}@registry:8761/eureka/ spring: rabbitmq: host: rabbitmq boot: admin: routes: endpoints: env,metrics,trace,dump,jolokia,info,configprops,trace,
logfile,refresh,flyway,liquibase,heapdump,loggers,auditevents,hystrix.stream turbine: clusters: default location: http://monitor:${turbine.stream.port} security: user: name: admin password: ${MONITOR_SERVER_PASSWORD:admin}
repos\spring-boot-cloud-master\monitor\src\main\resources\application.yml
2
请完成以下Java代码
private Optional<HUTraceForReturnedQtyRequest> buildRequest(@NonNull final I_M_HU_Trx_Line trxLine) { final I_M_HU returnedVHU = trxLine.getM_HU(); final I_M_InOutLine returnLine = trxBL.getReferencedObjectOrNull(trxLine, I_M_InOutLine.class); final I_M_InOut returnHeader = returnLine.getM_InOut(); final InOutLineId shipmentLineId = InOutLineId.ofRepoId(returnLine.getReturn_Origin_InOutLine_ID()); final Map<InOutLineId, List<I_M_HU>> shippedHUs = huInOutDAO.retrieveShippedHUsByShipmentLineId(ImmutableSet.of(shipmentLineId)); if (Check.isEmpty(shippedHUs.get(shipmentLineId))) { return Optional.empty(); } final Set<HuId> shippedTopLevelHuIds = shippedHUs.get(shipmentLineId) .stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(Collectors.toSet()); final Set<HuId> shippedVHUIds = handlingUnitsBL.getVHUIds(shippedTopLevelHuIds); final ProductId productId = ProductId.ofRepoId(trxLine.getM_Product_ID());
final HuId topLevelReturnedHUId = HuId.ofRepoId(handlingUnitsBL.getTopLevelParent(returnedVHU).getM_HU_ID()); final UomId uomIdToUse = UomId.ofRepoId(CoalesceUtil.firstGreaterThanZero(trxLine.getC_UOM_ID(), returnLine.getC_UOM_ID())); final HUTraceForReturnedQtyRequest addTraceRequest = HUTraceForReturnedQtyRequest.builder() .returnedVirtualHU(returnedVHU) .topLevelReturnedHUId(topLevelReturnedHUId) .sourceShippedVHUIds(shippedVHUIds) .customerReturnId(InOutId.ofRepoId(returnHeader.getM_InOut_ID())) .docStatus(returnHeader.getDocStatus()) .eventTime(Instant.now()) .orgId(OrgId.ofRepoId(returnLine.getAD_Org_ID())) .productId(productId) .qty(Quantitys.of(trxLine.getQty(), uomIdToUse)) .build(); return Optional.of(addTraceRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CreateReturnedHUsTrxListener.java
1
请完成以下Java代码
public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(@RequestBody @NonNull final JsonGetNextEligibleLineRequest request) { assertApplicationAccess(); return pickingMobileApplication.getNextEligibleLineToPack(request, getLoggedUserId()); } @PostMapping("/job/{wfProcessId}/pickAll") public WFProcess pickAllAndComplete(@PathVariable("wfProcessId") final String wfProcessIdStr) { assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); return pickingMobileApplication.pickAll(wfProcessId, getLoggedUserId()); } @GetMapping("/job/{wfProcessId}/qtyAvailable")
public JsonPickingJobQtyAvailable getQtyAvailable(@PathVariable("wfProcessId") final String wfProcessIdStr) { assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); final PickingJobQtyAvailable qtyAvailable = pickingMobileApplication.getQtyAvailable(wfProcessId, getLoggedUserId()); return JsonPickingJobQtyAvailable.of(qtyAvailable); } @PostMapping("/job/{wfProcessId}/complete") public WFProcess complete(@PathVariable("wfProcessId") final String wfProcessIdStr) { assertApplicationAccess(); return pickingMobileApplication.complete(WFProcessId.ofString(wfProcessIdStr), getLoggedUserId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\rest_api\PickingRestController.java
1
请完成以下Java代码
private static Duration extractSkipTimeout(final I_C_Async_Batch_Type asyncBatchType) { final int skipTimeoutMillis = asyncBatchType.getSkipTimeoutMillis(); return skipTimeoutMillis > 0 ? Duration.ofMillis(skipTimeoutMillis) : Duration.ZERO; } private void updateProcessedFlag(@NonNull final I_C_Async_Batch asyncBatch) { final List<I_C_Queue_WorkPackage> workPackages = asyncBatchDAO.retrieveWorkPackages(asyncBatch, null); if (Check.isEmpty(workPackages)) { return; } final int workPackagesProcessedCount = (int)workPackages.stream() .filter(I_C_Queue_WorkPackage::isProcessed) .count(); final int workPackagesWithErrorCount = (int)workPackages.stream() .filter(I_C_Queue_WorkPackage::isError) .count(); final int workPackagesFinalized = workPackagesProcessedCount + workPackagesWithErrorCount; final boolean allWorkPackagesAreDone = workPackagesFinalized >= workPackages.size(); final boolean isProcessed = asyncBatch.getCountExpected() > 0 ? allWorkPackagesAreDone && workPackagesFinalized >= asyncBatch.getCountExpected() : allWorkPackagesAreDone; asyncBatch.setProcessed(isProcessed); asyncBatch.setIsProcessing(!allWorkPackagesAreDone); } private int getProcessedTimeOffsetMillis() { return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_PROCESSED_OFFSET_MILLIS, 1); } private void save(final I_C_Async_Batch asyncBatch) { Services.get(IQueueDAO.class).save(asyncBatch); } private int setAsyncBatchCountEnqueued(@NonNull final I_C_Queue_WorkPackage workPackage, final int offset) { final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(workPackage.getC_Async_Batch_ID()); if (asyncBatchId == null) {
return 0; } lock.lock(); try { final I_C_Async_Batch asyncBatch = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(asyncBatchId); final Timestamp enqueued = SystemTime.asTimestamp(); if (asyncBatch.getFirstEnqueued() == null) { asyncBatch.setFirstEnqueued(enqueued); } asyncBatch.setLastEnqueued(enqueued); final int countEnqueued = asyncBatch.getCountEnqueued() + offset; asyncBatch.setCountEnqueued(countEnqueued); // we just enqueued something, so we are clearly not done yet asyncBatch.setIsProcessing(true); asyncBatch.setProcessed(false); save(asyncBatch); return countEnqueued; } finally { lock.unlock(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBL.java
1
请在Spring Boot框架中完成以下Java代码
public int maxScale() { return obtain(OtlpMetricsProperties::getMaxScale, OtlpConfig.super::maxScale); } @Override public int maxBucketCount() { return obtain(OtlpMetricsProperties::getMaxBucketCount, OtlpConfig.super::maxBucketCount); } @Override public TimeUnit baseTimeUnit() { return obtain(OtlpMetricsProperties::getBaseTimeUnit, OtlpConfig.super::baseTimeUnit); } private <V> Getter<OtlpMetricsProperties, Map<String, V>> perMeter(Getter<Meter, V> getter) { return (properties) -> { if (CollectionUtils.isEmpty(properties.getMeter())) {
return null; } Map<String, V> perMeter = new LinkedHashMap<>(); properties.getMeter().forEach((key, meterProperties) -> { V value = getter.get(meterProperties); if (value != null) { perMeter.put(key, value); } }); return (!perMeter.isEmpty()) ? perMeter : null; }; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsPropertiesConfigAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public ToAPIProcessCandidateStarterGroupAddedEventConverter processCandidateStarterGroupAddedEventConverter( APIProcessCandidateStarterGroupConverter processCandidateStarterGroupConverter ) { return new ToAPIProcessCandidateStarterGroupAddedEventConverter(processCandidateStarterGroupConverter); } @Bean @ConditionalOnMissingBean public APIProcessCandidateStarterGroupConverter apiProcessCandidateStarterGroupConverter() { return new APIProcessCandidateStarterGroupConverter(); } @Bean @ConditionalOnMissingBean(name = "registerProcessCandidateStarterUserRemovedListenerDelegate") public InitializingBean registerProcessCandidateStarterUserRemovedListenerDelegate( RuntimeService runtimeService, @Autowired(required = false) List< ProcessRuntimeEventListener<ProcessCandidateStarterUserRemovedEvent> > listeners, ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter ) { return () -> runtimeService.addEventListener( new ProcessCandidateStarterUserRemovedListenerDelegate( getInitializedListeners(listeners), processCandidateStarterUserRemovedEventConverter ), ActivitiEventType.ENTITY_DELETED ); } @Bean @ConditionalOnMissingBean public ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter( APIProcessCandidateStarterUserConverter processCandidateStarterUserConverter ) { return new ToAPIProcessCandidateStarterUserRemovedEventConverter(processCandidateStarterUserConverter); } @Bean @ConditionalOnMissingBean(name = "registerProcessCandidateStarterGroupRemovedListenerDelegate") public InitializingBean registerProcessCandidateStarterGroupRemovedListenerDelegate( RuntimeService runtimeService, @Autowired(required = false) List< ProcessRuntimeEventListener<ProcessCandidateStarterGroupRemovedEvent> > listeners,
ToAPIProcessCandidateStarterGroupRemovedEventConverter processCandidateStarterGroupRemovedEventConverter ) { return () -> runtimeService.addEventListener( new ProcessCandidateStarterGroupRemovedListenerDelegate( getInitializedListeners(listeners), processCandidateStarterGroupRemovedEventConverter ), ActivitiEventType.ENTITY_DELETED ); } @Bean @ConditionalOnMissingBean public ToAPIProcessCandidateStarterGroupRemovedEventConverter processCandidateStarterGroupRemovedEventConverter( APIProcessCandidateStarterGroupConverter processCandidateStarterGroupConverter ) { return new ToAPIProcessCandidateStarterGroupRemovedEventConverter(processCandidateStarterGroupConverter); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ProcessRuntimeAutoConfiguration.java
2
请完成以下Java代码
public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; }
@Override public Import clone() { Import clone = new Import(); clone.setValues(this); return clone; } public void setValues(Import otherElement) { super.setValues(otherElement); setImportType(otherElement.getImportType()); setLocation(otherElement.getLocation()); setNamespace(otherElement.getNamespace()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\Import.java
1
请完成以下Java代码
public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getRePassword() { return rePassword; } public void setRePassword(String rePassword) { this.rePassword = rePassword; } public String getHistoryPassword() { return historyPassword; } public void setHistoryPassword(String historyPassword) { this.historyPassword = historyPassword; }
public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @Override public String toString() { return "User{" + "id=" + id + ", cnname=" + cnname + ", username=" + username + ", password=" + password + ", email=" + email + ", telephone=" + telephone + ", mobilePhone=" + mobilePhone + '}'; } }
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\User.java
1
请完成以下Java代码
public class CreditCardEditor extends PropertyEditorSupport { @Override public String getAsText() { CreditCard creditCard = (CreditCard) getValue(); return creditCard == null ? "" : creditCard.getRawCardNumber(); } @Override public void setAsText(String text) throws IllegalArgumentException { if (!StringUtils.hasLength(text)) { setValue(null); } else { CreditCard creditCard = new CreditCard(); creditCard.setRawCardNumber(text);
String cardNo = text.replaceAll("-", ""); if (cardNo.length() != 16) throw new IllegalArgumentException("Credit card format should be xxxx-xxxx-xxxx-xxxx"); try { creditCard.setBankIdNo( Integer.valueOf(cardNo.substring(0, 6)) ); creditCard.setAccountNo( Integer.valueOf(cardNo.substring(6, cardNo.length() - 1)) ); creditCard.setCheckCode( Integer.valueOf(cardNo.substring(cardNo.length() - 1)) ); } catch (NumberFormatException nfe) { throw new IllegalArgumentException(nfe); } setValue(creditCard); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-3\src\main\java\com\baeldung\propertyeditor\creditcard\CreditCardEditor.java
1
请在Spring Boot框架中完成以下Java代码
public class AttachmentType { @XmlElement(name = "Name", required = true) protected String name; @XmlElement(name = "Description") protected String description; @XmlElement(name = "MimeType", required = true) protected String mimeType; @XmlElement(name = "AttachmentData", required = true) protected byte[] attachmentData; /** * Name of the attachment. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Free text description of the attachment. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * The MIME type of the attachment. E.g., 'application/pdf' for PDF attachments. * * @return * possible object is * {@link String } * */ public String getMimeType() {
return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } /** * The actual attachment data as base64-encoded String. * * @return * possible object is * byte[] */ public byte[] getAttachmentData() { return attachmentData; } /** * Sets the value of the attachmentData property. * * @param value * allowed object is * byte[] */ public void setAttachmentData(byte[] value) { this.attachmentData = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\AttachmentType.java
2
请完成以下Java代码
public ImmutableList<InOutCost> getByIds(@NonNull final Set<InOutCostId> inoutCostIds) { if (inoutCostIds.isEmpty()) { return ImmutableList.of(); } return queryBL.createQueryBuilder(I_M_InOut_Cost.class) .addInArrayFilter(I_M_InOut_Cost.COLUMNNAME_M_InOut_Cost_ID, inoutCostIds) .orderBy(I_M_InOut_Cost.COLUMNNAME_M_InOut_Cost_ID) .stream() .map(InOutCostRepository::fromRecord) .collect(ImmutableList.toImmutableList()); } public ImmutableList<InOutCost> getByInOutId(@NonNull final InOutId inoutId) { return queryBL.createQueryBuilder(I_M_InOut_Cost.class) .addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_M_InOut_ID, inoutId) .orderBy(I_M_InOut_Cost.COLUMNNAME_M_InOut_Cost_ID) .stream() .map(InOutCostRepository::fromRecord) .collect(ImmutableList.toImmutableList()); } public Stream<InOutCost> stream(@NonNull final InOutCostQuery query) { return toSqlQuery(query).stream().map(InOutCostRepository::fromRecord); } private IQuery<I_M_InOut_Cost> toSqlQuery(@NonNull final InOutCostQuery query) { final IQueryBuilder<I_M_InOut_Cost> queryBuilder = queryBL.createQueryBuilder(I_M_InOut_Cost.class) .setLimit(query.getLimit()) .addOnlyActiveRecordsFilter(); if (query.getBpartnerId() != null) { queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_C_BPartner_ID, query.getBpartnerId()); } if (query.getSoTrx() != null) { queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_IsSOTrx, query.getSoTrx().toBoolean()); } if (query.getOrderId() != null) { queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_C_Order_ID, query.getOrderId()); } if (query.getCostTypeId() != null) {
queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_C_Cost_Type_ID, query.getCostTypeId()); } if (!query.isIncludeReversed()) { queryBuilder.addIsNull(I_M_InOut_Cost.COLUMNNAME_Reversal_ID); } if (query.isOnlyWithOpenAmountToInvoice()) { queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_IsInvoiced, false); } return queryBuilder.create(); } public void deleteAll(@NonNull final ImmutableList<InOutCost> inoutCosts) { if (inoutCosts.isEmpty()) { return; } final ImmutableSet<InOutCostId> inoutCostIds = inoutCosts.stream().map(InOutCost::getId).collect(ImmutableSet.toImmutableSet()); if (inoutCostIds.isEmpty()) { return; } queryBL.createQueryBuilder(I_M_InOut_Cost.class) .addInArrayFilter(I_M_InOut_Cost.COLUMNNAME_M_InOut_Cost_ID, inoutCostIds) .create() .delete(); } public void updateInOutCostById(final InOutCostId inoutCostId, final Consumer<InOutCost> consumer) { final I_M_InOut_Cost record = InterfaceWrapperHelper.load(inoutCostId, I_M_InOut_Cost.class); final InOutCost inoutCost = fromRecord(record); consumer.accept(inoutCost); updateRecord(record, inoutCost); InterfaceWrapperHelper.save(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCostRepository.java
1
请在Spring Boot框架中完成以下Java代码
private static boolean isAssignable(String target, Class<?> type, ClassLoader classLoader) { try { return ClassUtils.resolveClassName(target, classLoader).isAssignableFrom(type); } catch (Throwable ex) { return false; } } protected void await() { // has been waited, return immediately if (awaited.get()) { return; } if (!executorService.isShutdown()) { executorService.execute(() -> executeMutually(() -> { while (!awaited.get()) { if (logger.isInfoEnabled()) { logger.info(" [Dubbo] Current Spring Boot Application is await..."); } try { condition.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } })); } } protected void release() { executeMutually(() -> { while (awaited.compareAndSet(false, true)) { if (logger.isInfoEnabled()) { logger.info(" [Dubbo] Current Spring Boot Application is about to shutdown..."); } condition.signalAll(); // @since 2.7.8 method shutdown() is combined into the method release() shutdown(); } });
} private void shutdown() { if (!executorService.isShutdown()) { // Shutdown executorService executorService.shutdown(); } } private void executeMutually(Runnable runnable) { try { lock.lock(); runnable.run(); } finally { lock.unlock(); } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\context\event\AwaitingNonWebApplicationListener.java
2
请在Spring Boot框架中完成以下Java代码
class ReactiveMethodSecuritySelector implements ImportSelector { private static final boolean isDataPresent = ClassUtils .isPresent("org.springframework.security.data.aot.hint.AuthorizeReturnObjectDataHintsRegistrar", null); private static final boolean isObservabilityPresent = ClassUtils .isPresent("io.micrometer.observation.ObservationRegistry", null); private final ImportSelector autoProxy = new AutoProxyRegistrarSelector(); @Override public String[] selectImports(AnnotationMetadata importMetadata) { if (!importMetadata.hasAnnotation(EnableReactiveMethodSecurity.class.getName())) { return new String[0]; } EnableReactiveMethodSecurity annotation = importMetadata.getAnnotations() .get(EnableReactiveMethodSecurity.class) .synthesize(); List<String> imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata))); if (annotation.useAuthorizationManager()) { imports.add(ReactiveAuthorizationManagerMethodSecurityConfiguration.class.getName()); } else { imports.add(ReactiveMethodSecurityConfiguration.class.getName()); } if (isDataPresent) { imports.add(AuthorizationProxyDataConfiguration.class.getName()); } if (isObservabilityPresent) { imports.add(ReactiveMethodObservationConfiguration.class.getName());
} imports.add(AuthorizationProxyConfiguration.class.getName()); return imports.toArray(new String[0]); } private static final class AutoProxyRegistrarSelector extends AdviceModeImportSelector<EnableReactiveMethodSecurity> { private static final String[] IMPORTS = new String[] { AutoProxyRegistrar.class.getName(), MethodSecurityAdvisorRegistrar.class.getName() }; @Override protected String[] selectImports(@NonNull AdviceMode adviceMode) { if (adviceMode == AdviceMode.PROXY) { return IMPORTS; } throw new IllegalStateException("AdviceMode " + adviceMode + " is not supported"); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\ReactiveMethodSecuritySelector.java
2
请完成以下Java代码
static class Attribute { final static Attribute NULL = new Attribute("未知", 10000.0f); /** * 依存关系 */ public String[] dependencyRelation; /** * 概率 */ public float[] p; public Attribute(int size) { dependencyRelation = new String[size]; p = new float[size]; } Attribute(String dr, float p) { dependencyRelation = new String[]{dr}; this.p = new float[]{p}; } /** * 加权 * @param boost */ public void setBoost(float boost) { for (int i = 0; i < p.length; ++i)
{ p[i] *= boost; } } @Override public String toString() { final StringBuilder sb = new StringBuilder(dependencyRelation.length * 10); for (int i = 0; i < dependencyRelation.length; ++i) { sb.append(dependencyRelation[i]).append(' ').append(p[i]).append(' '); } return sb.toString(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\WordNatureDependencyModel.java
1
请完成以下Java代码
private void exportDunning(@NonNull final DunningToExport dunningToExport) { final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); final List<DunningExportClient> exportClients = dunningExportServiceRegistry.createExportClients(dunningToExport); if (exportClients.isEmpty()) { loggable.addLog("DunningExportService - Found no DunningExportClient implementors for dunningDocId={}; dunningToExport={}", dunningToExport.getId(), dunningToExport); return; // nothing more to do } final List<AttachmentEntryCreateRequest> attachmentEntryCreateRequests = new ArrayList<>(); for (final DunningExportClient exportClient : exportClients) { final List<DunningExportResult> exportResults = exportClient.export(dunningToExport); for (final DunningExportResult exportResult : exportResults) { attachmentEntryCreateRequests.add(createAttachmentRequest(exportResult)); } } for (final AttachmentEntryCreateRequest attachmentEntryCreateRequest : attachmentEntryCreateRequests) { attachmentEntryService.createNewAttachment( TableRecordReference.of(I_C_DunningDoc.Table_Name, dunningToExport.getId()), attachmentEntryCreateRequest); loggable.addLog("DunningExportService - Attached export data to dunningDocId={}; attachment={}", dunningToExport.getId(), attachmentEntryCreateRequest); } } private AttachmentEntryCreateRequest createAttachmentRequest(@NonNull final DunningExportResult exportResult) { byte[] byteArrayData; try {
byteArrayData = ByteStreams.toByteArray(exportResult.getData()); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } final AttachmentTags attachmentTags = AttachmentTags.builder() .tag(AttachmentTags.TAGNAME_IS_DOCUMENT, StringUtils.ofBoolean(true)) // other than the "input" xml with was more or less just a template, this is a document .tag(AttachmentTags.TAGNAME_BPARTNER_RECIPIENT_ID, Integer.toString(exportResult.getRecipientId().getRepoId())) .tag(DunningExportClientFactory.ATTATCHMENT_TAGNAME_EXPORT_PROVIDER, exportResult.getDunningExportProviderId()) .build(); final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest .builderFromByteArray( exportResult.getFileName(), byteArrayData) .tags(attachmentTags) .build(); return attachmentEntryCreateRequest; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\export\DunningExportService.java
1
请在Spring Boot框架中完成以下Java代码
public class SignalResource { @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected RuntimeService runtimeService; @Autowired(required=false) protected BpmnRestApiInterceptor restApiInterceptor; @ApiOperation(value = "Signal event received", tags = { "Runtime" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicated signal has been processed and no errors occurred."), @ApiResponse(code = 202, message = "Indicated signal processing is queued as a job, ready to be executed."), @ApiResponse(code = 400, message = "Signal not processed. The signal name is missing or variables are used together with async, which is not allowed. Response body contains additional information about the error.") }) @PostMapping(value = "/runtime/signals") public void signalEventReceived(@RequestBody SignalEventReceivedRequest signalRequest, HttpServletResponse response) { if (signalRequest.getSignalName() == null) { throw new FlowableIllegalArgumentException("signalName is required"); } if (restApiInterceptor != null) { restApiInterceptor.sendSignal(signalRequest); } Map<String, Object> signalVariables = null; if (signalRequest.getVariables() != null) { signalVariables = new HashMap<>(); for (RestVariable variable : signalRequest.getVariables()) { if (variable.getName() == null) { throw new FlowableIllegalArgumentException("Variable name is required."); } signalVariables.put(variable.getName(), restResponseFactory.getVariableValue(variable)); } } if (signalRequest.isAsync()) { if (signalVariables != null) {
throw new FlowableIllegalArgumentException("Async signals cannot take variables as payload"); } if (signalRequest.isCustomTenantSet()) { runtimeService.signalEventReceivedAsyncWithTenantId(signalRequest.getSignalName(), signalRequest.getTenantId()); } else { runtimeService.signalEventReceivedAsync(signalRequest.getSignalName()); } response.setStatus(HttpStatus.ACCEPTED.value()); } else { if (signalRequest.isCustomTenantSet()) { runtimeService.signalEventReceivedWithTenantId(signalRequest.getSignalName(), signalVariables, signalRequest.getTenantId()); } else { runtimeService.signalEventReceived(signalRequest.getSignalName(), signalVariables); } response.setStatus(HttpStatus.NO_CONTENT.value()); } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\SignalResource.java
2
请完成以下Java代码
public PurchaseOrderItem copy(final PurchaseCandidate newPurchaseCandidate) { return new PurchaseOrderItem(this, newPurchaseCandidate); } @Override public PurchaseCandidateId getPurchaseCandidateId() { return getPurchaseCandidate().getId(); } public ProductId getProductId() { return getPurchaseCandidate().getProductId(); } public int getUomId() { final Quantity purchasedQty = getPurchasedQty(); if (purchasedQty != null) { return purchasedQty.getUOMId(); } return getQtyToPurchase().getUOMId(); } public OrgId getOrgId() { return getPurchaseCandidate().getOrgId(); } public WarehouseId getWarehouseId() { return getPurchaseCandidate().getWarehouseId(); } public BPartnerId getVendorId() { return getPurchaseCandidate().getVendorId(); } public ZonedDateTime getPurchaseDatePromised() { return getPurchaseCandidate().getPurchaseDatePromised(); } public OrderId getSalesOrderId() { final OrderAndLineId salesOrderAndLineId = getPurchaseCandidate().getSalesOrderAndLineIdOrNull(); return salesOrderAndLineId != null ? salesOrderAndLineId.getOrderId() : null; } @Nullable public ForecastLineId getForecastLineId() { return getPurchaseCandidate().getForecastLineId(); } private Quantity getQtyToPurchase() { return getPurchaseCandidate().getQtyToPurchase(); } public boolean purchaseMatchesRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) == 0; } private boolean purchaseMatchesOrExceedsRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0;
} public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId) { this.purchaseOrderAndLineId = purchaseOrderAndLineId; } public void markPurchasedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.markProcessed(); } } public void markReqCreatedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.setReqCreated(true); } } @Nullable public BigDecimal getPrice() { return purchaseCandidate.getPriceEnteredEff(); } @Nullable public UomId getPriceUomId() { return purchaseCandidate.getPriceUomId(); } @Nullable public Percent getDiscount() { return purchaseCandidate.getDiscountEff(); } @Nullable public String getExternalPurchaseOrderUrl() { return purchaseCandidate.getExternalPurchaseOrderUrl(); } @Nullable public ExternalId getExternalHeaderId() { return purchaseCandidate.getExternalHeaderId(); } @Nullable public ExternalSystemId getExternalSystemId() { return purchaseCandidate.getExternalSystemId(); } @Nullable public ExternalId getExternalLineId() { return purchaseCandidate.getExternalLineId(); } @Nullable public String getPOReference() { return purchaseCandidate.getPOReference(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java
1
请在Spring Boot框架中完成以下Java代码
public String prefix() { return "management.prometheus.metrics.export"; } @Override public @Nullable String get(String key) { return null; } @Override public boolean descriptions() { return obtain(PrometheusProperties::isDescriptions, PrometheusConfig.super::descriptions); } @Override public Duration step() { return obtain(PrometheusProperties::getStep, PrometheusConfig.super::step); } @Override
public @Nullable Properties prometheusProperties() { return get(this::fromPropertiesMap, PrometheusConfig.super::prometheusProperties); } private @Nullable Properties fromPropertiesMap(PrometheusProperties prometheusProperties) { Map<String, String> additionalProperties = prometheusProperties.getProperties(); if (additionalProperties.isEmpty()) { return null; } Properties properties = PrometheusConfig.super.prometheusProperties(); if (properties == null) { properties = new Properties(); } properties.putAll(additionalProperties); return properties; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusPropertiesConfigAdapter.java
2
请完成以下Java代码
private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) { return (lastPasswordReset != null && created.before(lastPasswordReset)); } public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, Const.SECRET ) .compact(); } public Boolean canTokenBeRefreshed(String token) { return !isTokenExpired(token); } public String refreshToken(String token) { String refreshedToken; try { final Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = generateToken(claims); } catch (Exception e) {
refreshedToken = null; } return refreshedToken; } public Boolean validateToken(String token, UserDetails userDetails) { User user = (User) userDetails; final String username = getUsernameFromToken(token); return ( username.equals(user.getUsername()) && !isTokenExpired(token) ); } }
repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\util\JwtTokenUtil.java
1
请在Spring Boot框架中完成以下Java代码
private void signatureCheckPointCut() { } /** * 开始验签 */ @Before("signatureCheckPointCut()") public void doSignatureValidation(JoinPoint point) throws Exception { // 获取方法上的注解 MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); SignatureCheck signatureCheck = method.getAnnotation(SignatureCheck.class); log.info("AOP签名验证: {}.{}", method.getDeclaringClass().getSimpleName(), method.getName()); // 如果注解被禁用,直接返回 if (!signatureCheck.enabled()) { log.info("签名验证已禁用,跳过"); return; } ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes == null) { log.error("无法获取请求上下文"); throw new IllegalArgumentException("无法获取请求上下文"); } HttpServletRequest request = attributes.getRequest(); log.info("X-SIGN: {}, X-TIMESTAMP: {}", request.getHeader("X-SIGN"), request.getHeader("X-TIMESTAMP"));
try { // 直接调用SignAuthInterceptor的验证逻辑 signAuthInterceptor.validateSignature(request); log.info("AOP签名验证通过"); } catch (IllegalArgumentException e) { // 使用注解中配置的错误消息,或者保留原始错误消息 String errorMessage = signatureCheck.errorMessage(); log.error("AOP签名验证失败: {}", e.getMessage()); if ("Sign签名校验失败!".equals(errorMessage)) { // 如果是默认错误消息,使用原始的详细错误信息 throw e; } else { // 如果是自定义错误消息,使用自定义消息 throw new IllegalArgumentException(errorMessage, e); } } catch (Exception e) { // 包装其他异常 String errorMessage = signatureCheck.errorMessage(); log.error("AOP签名验证异常: {}", e.getMessage()); throw new IllegalArgumentException(errorMessage, e); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\aspect\SignatureCheckAspect.java
2
请完成以下Java代码
public Optional<BankId> getBankIdBySwiftCode(final String swiftCode) { return bankIdsBySwiftCode.getOrLoad(swiftCode, this::retrieveBankIdBySwiftCode); } @NonNull private Optional<BankId> retrieveBankIdBySwiftCode(final String swiftCode) { final int bankRepoId = queryBL.createQueryBuilderOutOfTrx(I_C_Bank.class) .addEqualsFilter(I_C_Bank.COLUMNNAME_SwiftCode, swiftCode) .addOnlyActiveRecordsFilter() .orderBy(I_C_Bank.COLUMNNAME_C_Bank_ID) .create() .firstId(); return BankId.optionalOfRepoId(bankRepoId); } public boolean isCashBank(@NonNull final BankId bankId) { return getById(bankId).isCashBank(); } public Bank createBank(@NonNull final BankCreateRequest request) { final I_C_Bank record = newInstance(I_C_Bank.class); record.setName(request.getBankName()); record.setSwiftCode(request.getSwiftCode()); record.setRoutingNo(request.getRoutingNo()); record.setIsCashBank(request.isCashBank()); record.setC_Location_ID(LocationId.toRepoId(request.getLocationId())); // ESR: record.setESR_PostBank(request.isEsrPostBank()); record.setC_DataImport_ID(DataImportConfigId.toRepoId(request.getDataImportConfigId())); saveRecord(record); return toBank(record);
} @NonNull public DataImportConfigId retrieveDataImportConfigIdForBank(@Nullable final BankId bankId) { if (bankId == null) { return retrieveDefaultBankDataImportConfigId(); } final Bank bank = getById(bankId); return CoalesceUtil.coalesceSuppliersNotNull( bank::getDataImportConfigId, this::retrieveDefaultBankDataImportConfigId); } public boolean isImportAsSingleSummaryLine(@NonNull final BankId bankId) { return getById(bankId).isImportAsSingleSummaryLine(); } @NonNull public Set<BankId> retrieveBankIdsByName(@NonNull final String bankName) { return queryBL.createQueryBuilder(I_C_Bank.class) .addOnlyActiveRecordsFilter() .addStringLikeFilter(I_C_Bank.COLUMNNAME_Name, bankName, true) .create() .idsAsSet(BankId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\api\BankRepository.java
1
请完成以下Java代码
public final class SeqNo implements Comparable<SeqNo> { private static final ImmutableMap<Integer, SeqNo> cache = createCache(300); private static final int STEP = 10; private final int value; private SeqNo(final int value) { this.value = value; } @SuppressWarnings("SameParameterValue") private static ImmutableMap<Integer, SeqNo> createCache(final int lastSeqNoValue) { final ImmutableMap.Builder<Integer, SeqNo> builder = ImmutableMap.builder(); for (int i = 0; i <= lastSeqNoValue; i += STEP) { builder.put(i, new SeqNo(i)); } return builder.build(); } @JsonCreator public static SeqNo ofInt(final int value) { final SeqNo seqNo = cache.get(value); return seqNo != null ? seqNo : new SeqNo(value); } @Deprecated @Override public String toString() { return String.valueOf(value); }
@JsonValue public int toInt() { return value; } public SeqNo next() { return ofInt(value / STEP * STEP + STEP); } @Override public int compareTo(@NonNull final SeqNo other) { return this.value - other.value; } public static boolean equals(@Nullable final SeqNo seqNo1, @Nullable final SeqNo seqNo2) { return Objects.equals(seqNo1, seqNo2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\SeqNo.java
1
请在Spring Boot框架中完成以下Java代码
public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } @Bean public BeanNameViewResolver beanNameViewResolver(){ BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver(); beanNameViewResolver.setOrder(1); return beanNameViewResolver; }
@Bean public View sample() { return new JstlView("/WEB-INF/view/sample.jsp"); } @Bean public View sample2() { return new JstlView("/WEB-INF/view2/sample2.jsp"); } @Bean public View sample3(){ return new JstlView("/WEB-INF/view3/sample3.jsp"); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\config\WebConfig.java
2
请完成以下Java代码
public class FormView extends HorizontalLayout { public FormView() { addBeanValidationExample(); addCustomValidationExample(); } private void addBeanValidationExample() { var nameField = new TextField("Name"); var emailField = new TextField("Email"); var phoneField = new TextField("Phone"); var saveButton = new Button("Save"); var binder = new BeanValidationBinder<>(Contact.class); binder.forField(nameField).bind(Contact::getName, Contact::setName); binder.forField(emailField).bind(Contact::getEmail, Contact::setEmail); binder.forField(phoneField).bind(Contact::getPhone, Contact::setPhone); var contact = new Contact("John Doe", "john@doe.com", "123-456-7890"); binder.setBean(contact); saveButton.addClickListener(e -> { if (binder.validate().isOk()) { Notification.show("Saved " + contact); } }); add(new VerticalLayout( new H2("Bean Validation Example"), nameField, emailField, phoneField, saveButton )); } private void addCustomValidationExample() { var nameField = new TextField("Name"); var emailField = new TextField("Email"); var phoneField = new TextField("Phone"); var saveButton = new Button("Save"); var binder = new Binder<>(Contact.class); binder.forField(nameField) .asRequired()
.bind(Contact::getName, Contact::setName); binder.forField(emailField) .withValidator(email -> email.contains("@"), "Not a valid email address") .bind(Contact::getEmail, Contact::setEmail); binder.forField(phoneField) .withValidator(phone -> phone.matches("\\d{3}-\\d{3}-\\d{4}"), "Not a valid phone number") .bind(Contact::getPhone, Contact::setPhone); var contact = new Contact("John Doe", "john@doe.com", "123-456-7890"); binder.setBean(contact); saveButton.addClickListener(e -> { if (binder.validate().isOk()) { Notification.show("Saved " + contact); } }); add(new VerticalLayout( new H2("Custom Validation Example"), nameField, emailField, phoneField, saveButton )); } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\introduction\FormView.java
1
请完成以下Java代码
public class JSONBoardCard implements JSONViewRowBase { public static JSONBoardCard of(final BoardCard card, final String adLanguage) { final JSONBoardCardBuilder jsonCard = JSONBoardCard.builder() .cardId(card.getCardId()) .laneId(card.getLaneId()) // .caption(card.getCaption().translate(adLanguage)) .description(card.getDescription().translate(adLanguage)) .documentPath(JSONDocumentPath.ofWindowDocumentPath(card.getDocumentPath())); // Users card.getUsers() .stream() .map(JSONBoardCardUser::of) .forEach(jsonCard::user);
return jsonCard.build(); } private final int cardId; private final int laneId; private final String caption; private final String description; private final JSONDocumentPath documentPath; @Singular @JsonInclude(JsonInclude.Include.NON_EMPTY) private ImmutableList<JSONBoardCardUser> users; }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\json\JSONBoardCard.java
1
请完成以下Java代码
public class BytePrimitiveLookup extends Lookup { private byte[] elements; private final byte pivot = 2; @Setup @Override public void prepare() { byte common = 1; elements = new byte[s]; for (int i = 0; i < s - 1; i++) { elements[i] = common; } elements[s - 1] = pivot; } @TearDown @Override public void clean() { elements = null; } @Benchmark @BenchmarkMode(Mode.AverageTime) public int findPosition() {
int index = 0; while (pivot != elements[index]) { index++; } return index; } @Override public String getSimpleClassName() { return BytePrimitiveLookup.class.getSimpleName(); } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\BytePrimitiveLookup.java
1
请完成以下Java代码
public Class<ExternalTaskClient> getObjectType() { return ExternalTaskClient.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { } public ClientConfiguration getClientConfiguration() { return clientConfiguration; } public void setClientConfiguration(ClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } public List<ClientRequestInterceptor> getRequestInterceptors() { return requestInterceptors; } protected void close() { if (client != null) { client.stop(); } } @Autowired(required = false)
protected void setPropertyConfigurer(PropertySourcesPlaceholderConfigurer configurer) { PropertySources appliedPropertySources = configurer.getAppliedPropertySources(); propertyResolver = new PropertySourcesPropertyResolver(appliedPropertySources); } protected String resolve(String property) { if (propertyResolver == null) { return property; } if (property != null) { return propertyResolver.resolvePlaceholders(property); } else { return null; } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientFactory.java
1
请在Spring Boot框架中完成以下Java代码
PersonService personService(PersonRepository personRepository) { return new PersonService(personRepository); } @Provides PersonRepository personRepository(DataSource dataSource) { return new PersonRepository(dataSource); } @Provides DataSource dataSource() { return new DataSource() { @Override public Connection getConnection() throws SQLException { return null; } @Override public Connection getConnection(String username, String password) throws SQLException { return null; } @Override public PrintWriter getLogWriter() throws SQLException { return null; } @Override public void setLogWriter(PrintWriter out) throws SQLException { } @Override public void setLoginTimeout(int seconds) throws SQLException { } @Override public int getLoginTimeout() throws SQLException { return 0; }
@Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }; } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\activej\config\PersonModule.java
2
请完成以下Java代码
public static <R> CompletableFuture<R> newFailedFuture(Throwable ex) { CompletableFuture<R> future = new CompletableFuture<>(); future.completeExceptionally(ex); return future; } public static <R> CompletableFuture<List<R>> sequenceFuture(List<CompletableFuture<R>> futures) { return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .thenApply(v -> futures.stream() .map(AsyncUtils::getValue) .filter(Objects::nonNull) .collect(Collectors.toList()) ); } public static <R> CompletableFuture<List<R>> sequenceSuccessFuture(List<CompletableFuture<R>> futures) { return CompletableFuture.supplyAsync(() -> futures.parallelStream() .map(AsyncUtils::getValue) .filter(Objects::nonNull) .collect(Collectors.toList())
); } public static <T> T getValue(CompletableFuture<T> future) { try { return future.get(10, TimeUnit.SECONDS); } catch (Exception ex) { LOG.error("getValue for async result failed", ex); } return null; } public static boolean isSuccessFuture(CompletableFuture future) { return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled(); } private AsyncUtils() {} }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\util\AsyncUtils.java
1
请完成以下Java代码
private void setInvoiceCandsInDispute(final List<QuarantineInOutLine> lines) { final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); lines.stream() .map(QuarantineInOutLine::getInOutLine) .forEach(invoiceCandBL::markInvoiceCandInDisputeForReceiptLine); } private LotNumberQuarantine getQuarantineLotNoOrNull(final I_M_InOutLine inOutLine) { final ProductId productId = ProductId.ofRepoId(inOutLine.getM_Product_ID()); final I_M_AttributeSetInstance receiptLineASI = inOutLine.getM_AttributeSetInstance(); if (receiptLineASI == null) { // if it has no attributes set it means it has no lot number set either. return null; } final String lotNumberAttributeValue = lotNoBL.getLotNumberAttributeValueOrNull(receiptLineASI); if (Check.isEmpty(lotNumberAttributeValue)) { // if the attribute is not present or set it automatically means the lotno is not to quarantine, either return null; } return lotNumberQuarantineRepository.getByProductIdAndLot(productId, lotNumberAttributeValue); } private boolean isCreateDDOrder(@NonNull final I_M_InOutLine inOutLine) {
final List<I_M_ReceiptSchedule> rsForInOutLine = receiptScheduleDAO.retrieveRsForInOutLine(inOutLine); for (final I_M_ReceiptSchedule resceiptSchedule : rsForInOutLine) { final boolean createDistributionOrder = X_M_ReceiptSchedule.ONMATERIALRECEIPTWITHDESTWAREHOUSE_CreateDistributionOrder .equals(resceiptSchedule.getOnMaterialReceiptWithDestWarehouse()); if (createDistributionOrder) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\DistributeAndMoveReceiptCreator.java
1
请完成以下Java代码
protected void validateUnknownServiceTaskType(Process process, ServiceTask serviceTask, List<ValidationError> errors) { addError(errors, Problems.SERVICE_TASK_INVALID_TYPE, process, serviceTask, "Invalid or unsupported service task type"); } protected void verifyResultVariableName(Process process, ServiceTask serviceTask, List<ValidationError> errors) { if (StringUtils.isNotEmpty(serviceTask.getResultVariableName()) && (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(serviceTask.getImplementationType()) || ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType()))) { addError(errors, Problems.SERVICE_TASK_RESULT_VAR_NAME_WITH_DELEGATE, process, serviceTask, "'resultVariableName' not supported for service tasks using 'class' or 'delegateExpression"); } if (serviceTask.isUseLocalScopeForResultVariable() && StringUtils.isEmpty(serviceTask.getResultVariableName())) { addWarning(errors, Problems.SERVICE_TASK_USE_LOCAL_SCOPE_FOR_RESULT_VAR_WITHOUT_RESULT_VARIABLE_NAME, process, serviceTask, "'useLocalScopeForResultVariable' is set, but no 'resultVariableName' is set. The property would not be used"); } } protected void verifyWebservice(BpmnModel bpmnModel, Process process, ServiceTask serviceTask, List<ValidationError> errors) { if (ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(serviceTask.getImplementationType()) && StringUtils.isNotEmpty(serviceTask.getOperationRef())) { boolean operationFound = false; if (bpmnModel.getInterfaces() != null && !bpmnModel.getInterfaces().isEmpty()) { for (Interface bpmnInterface : bpmnModel.getInterfaces()) { if (bpmnInterface.getOperations() != null && !bpmnInterface.getOperations().isEmpty()) { for (Operation operation : bpmnInterface.getOperations()) {
if (operation.getId() != null && operation.getId().equals(serviceTask.getOperationRef())) { operationFound = true; break; } } } } } if (!operationFound) { addError(errors, Problems.SERVICE_TASK_WEBSERVICE_INVALID_OPERATION_REF, process, serviceTask, "Invalid operation reference"); } } } }
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\ServiceTaskValidator.java
1
请在Spring Boot框架中完成以下Java代码
private void customizeConnectionTimeout(NettyReactiveWebServerFactory factory, Duration connectionTimeout) { factory.addServerCustomizers((httpServer) -> httpServer.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectionTimeout.toMillis())); } private void customizeRequestDecoder(NettyReactiveWebServerFactory factory, PropertyMapper propertyMapper) { factory.addServerCustomizers((httpServer) -> httpServer.httpRequestDecoder((httpRequestDecoderSpec) -> { propertyMapper.from(this.serverProperties.getMaxHttpRequestHeaderSize()) .to((maxHttpRequestHeader) -> httpRequestDecoderSpec .maxHeaderSize((int) maxHttpRequestHeader.toBytes())); propertyMapper.from(this.nettyProperties.getMaxInitialLineLength()) .to((maxInitialLineLength) -> httpRequestDecoderSpec .maxInitialLineLength((int) maxInitialLineLength.toBytes())); propertyMapper.from(this.nettyProperties.getH2cMaxContentLength()) .to((h2cMaxContentLength) -> httpRequestDecoderSpec .h2cMaxContentLength((int) h2cMaxContentLength.toBytes())); propertyMapper.from(this.nettyProperties.getInitialBufferSize()) .to((initialBufferSize) -> httpRequestDecoderSpec.initialBufferSize((int) initialBufferSize.toBytes())); propertyMapper.from(this.nettyProperties.isValidateHeaders()).to(httpRequestDecoderSpec::validateHeaders); return httpRequestDecoderSpec; }));
} private void customizeIdleTimeout(NettyReactiveWebServerFactory factory, Duration idleTimeout) { factory.addServerCustomizers((httpServer) -> httpServer.idleTimeout(idleTimeout)); } private void customizeMaxKeepAliveRequests(NettyReactiveWebServerFactory factory, int maxKeepAliveRequests) { factory.addServerCustomizers((httpServer) -> httpServer.maxKeepAliveRequests(maxKeepAliveRequests)); } private void customizeHttp2MaxHeaderSize(NettyReactiveWebServerFactory factory, long size) { factory.addServerCustomizers( ((httpServer) -> httpServer.http2Settings((settings) -> settings.maxHeaderListSize(size)))); } }
repos\spring-boot-4.0.1\module\spring-boot-reactor-netty\src\main\java\org\springframework\boot\reactor\netty\autoconfigure\NettyReactiveWebServerFactoryCustomizer.java
2
请完成以下Java代码
public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } public String getField3() { return field3;
} public void setField3(String field3) { this.field3 = field3; } @Override public String toString() { return "TestData{" + "id=" + id + ", field1='" + field1 + '\'' + ", field2='" + field2 + '\'' + ", field3='" + field3 + '\'' + '}'; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\entity\TestData.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PoolConnectionEndpoint)) { return false; } PoolConnectionEndpoint that = (PoolConnectionEndpoint) obj; return super.equals(that) && this.getPool().equals(that.getPool()); } /** * @inheritDoc */ @Override public int hashCode() { int hashValue = super.hashCode(); hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPool()); return hashValue; } /** * @inheritDoc */
@Override public String toString() { return String.format("ConnectionEndpoint [%1$s] from Pool [%2$s]", super.toString(), getPool().map(Pool::getName).orElse("")); } } @SuppressWarnings("unused") protected static class SocketCreationException extends RuntimeException { protected SocketCreationException() { } protected SocketCreationException(String message) { super(message); } protected SocketCreationException(Throwable cause) { super(cause); } protected SocketCreationException(String message, Throwable cause) { super(message, cause); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAwareConfiguration.java
2
请完成以下Java代码
public void setCU_TU_PLU (final String CU_TU_PLU) { set_Value (COLUMNNAME_CU_TU_PLU, CU_TU_PLU); } @Override public String getCU_TU_PLU() { return get_ValueAsString(COLUMNNAME_CU_TU_PLU); } @Override public void setExternalSystem_Config_LeichMehl_ProductMapping_ID (final int ExternalSystem_Config_LeichMehl_ProductMapping_ID) { if (ExternalSystem_Config_LeichMehl_ProductMapping_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public int getExternalSystem_Config_LeichMehl_ProductMapping_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public I_LeichMehl_PluFile_ConfigGroup getLeichMehl_PluFile_ConfigGroup() { return get_ValueAsPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class); } @Override public void setLeichMehl_PluFile_ConfigGroup(final I_LeichMehl_PluFile_ConfigGroup LeichMehl_PluFile_ConfigGroup) { set_ValueFromPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class, LeichMehl_PluFile_ConfigGroup); } @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1)
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); } @Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPLU_File (final String PLU_File) { set_Value (COLUMNNAME_PLU_File, PLU_File); } @Override public String getPLU_File() { return get_ValueAsString(COLUMNNAME_PLU_File); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
1
请完成以下Java代码
public class AnnouncementSendModel implements Serializable { private static final long serialVersionUID = 1L; /**id*/ @TableId(type = IdType.ASSIGN_ID) private java.lang.String id; /**通告id*/ private java.lang.String anntId; /**用户id*/ private java.lang.String userId; /**标题*/ private java.lang.String titile; /**内容*/ private java.lang.String msgContent; /**发布人*/ private java.lang.String sender; /**优先级(L低,M中,H高)*/ private java.lang.String priority; /**阅读状态*/ private java.lang.Integer readFlag; /**发布时间*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private java.util.Date sendTime; /**页数*/ private java.lang.Integer pageNo; /**大小*/ private java.lang.Integer pageSize; /** * 消息类型1:通知公告2:系统消息 */ private java.lang.String msgCategory; /** * 业务id */ private java.lang.String busId; /** * 业务类型 */ private java.lang.String busType; /** * 打开方式 组件:component 路由:url */ private java.lang.String openType; /** * 组件/路由 地址 */ private java.lang.String openPage; /** * 业务类型查询(0.非bpm业务) */ private java.lang.String bizSource; /** * 摘要 */ private java.lang.String msgAbstract;
/** * 发布开始日期 */ private java.lang.String sendTimeBegin; /** * 发布结束日期 */ private java.lang.String sendTimeEnd; /** * 附件 */ private java.lang.String files; /** * 访问量 */ private java.lang.Integer visitsNum; /** * 是否置顶(0否 1是) */ private java.lang.Integer izTop; /** * 通知类型(plan:日程计划 | flow:流程消息 | meeting:会议 | file:知识库 | collab:协同通知 | supe:督办通知 | attendance:考勤) */ private java.lang.String noticeType; /** * 通告类型数组 */ private List<String> noticeTypeList; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\AnnouncementSendModel.java
1
请在Spring Boot框架中完成以下Java代码
private void checkIfTheEffortCanBeBooked(@NonNull final ImportTimeBookingInfo importTimeBookingInfo, @NonNull final IssueEntity targetIssue) { if (!targetIssue.isProcessed() || targetIssue.getProcessedTimestamp() == null) { return;//nothing else to check ( issues that are not processed yet are used for booking effort ) } final LocalDate effortBookedDate = TimeUtil.asLocalDate(importTimeBookingInfo.getBookedDate()); final LocalDate processedIssueDate = TimeUtil.asLocalDate(targetIssue.getProcessedTimestamp()); final boolean effortWasBookedOnAProcessedIssue = effortBookedDate.isAfter(processedIssueDate); if (effortWasBookedOnAProcessedIssue) { final I_AD_User performingUser = userDAO.getById(importTimeBookingInfo.getPerformingUserId()); throw new AdempiereException("Time bookings cannot be added for already processed issues!") .appendParametersToMessage() .setParameter("ImportTimeBookingInfo", importTimeBookingInfo) .setParameter("Performing user", performingUser.getName()) .setParameter("Note", "This FailedTimeBooking record will not be automatically deleted!"); } } private void storeFailed(
@NonNull final OrgId orgId, @NonNull final ImportTimeBookingInfo importTimeBookingInfo, @NonNull final String errorMsg) { final FailedTimeBooking failedTimeBooking = FailedTimeBooking.builder() .orgId(orgId) .externalId(importTimeBookingInfo.getExternalTimeBookingId().getId()) .externalSystem(importTimeBookingInfo.getExternalTimeBookingId().getExternalSystem()) .errorMsg(errorMsg) .build(); failedTimeBookingRepository.save(failedTimeBooking); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\importer\TimeBookingsImporterService.java
2
请完成以下Java代码
public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isForEnabled() { return forEnabled; } public void setForEnabled(boolean forEnabled) { this.forEnabled = forEnabled; } public boolean isHostEnabled() { return hostEnabled; } public void setHostEnabled(boolean hostEnabled) { this.hostEnabled = hostEnabled; } public boolean isPortEnabled() { return portEnabled; } public void setPortEnabled(boolean portEnabled) { this.portEnabled = portEnabled; } public boolean isProtoEnabled() { return protoEnabled; } public void setProtoEnabled(boolean protoEnabled) { this.protoEnabled = protoEnabled; } public boolean isPrefixEnabled() {
return prefixEnabled; } public void setPrefixEnabled(boolean prefixEnabled) { this.prefixEnabled = prefixEnabled; } public boolean isForAppend() { return forAppend; } public void setForAppend(boolean forAppend) { this.forAppend = forAppend; } public boolean isHostAppend() { return hostAppend; } public void setHostAppend(boolean hostAppend) { this.hostAppend = hostAppend; } public boolean isPortAppend() { return portAppend; } public void setPortAppend(boolean portAppend) { this.portAppend = portAppend; } public boolean isProtoAppend() { return protoAppend; } public void setProtoAppend(boolean protoAppend) { this.protoAppend = protoAppend; } public boolean isPrefixAppend() { return prefixAppend; } public void setPrefixAppend(boolean prefixAppend) { this.prefixAppend = prefixAppend; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\XForwardedRequestHeadersFilterProperties.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getCBPartnerLocationID() { return cbPartnerLocationID; } /** * Sets the value of the cbPartnerLocationID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setCBPartnerLocationID(BigInteger value) { this.cbPartnerLocationID = value; } /** * Gets the value of the ediCctop000VID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getEDICctop000VID() { return ediCctop000VID; } /** * Sets the value of the ediCctop000VID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setEDICctop000VID(BigInteger value) { this.ediCctop000VID = value; } /** * Gets the value of the gln property. *
* @return * possible object is * {@link String } * */ public String getGLN() { return gln; } /** * Sets the value of the gln property. * * @param value * allowed object is * {@link String } * */ public void setGLN(String value) { this.gln = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop000VType.java
2
请在Spring Boot框架中完成以下Java代码
public class OrchestratorWorkersWorkflow { private final OpsOrchestratorClient opsOrchestratorClient; private final OpsClient opsClient; public OrchestratorWorkersWorkflow(OpsOrchestratorClient opsOrchestratorClient, OpsClient opsClient) { this.opsOrchestratorClient = opsOrchestratorClient; this.opsClient = opsClient; } public String remoteTestingExecution(String userInput) { System.out.printf("User input: [%s]\n", userInput); String orchestratorRequest = REMOTE_TESTING_ORCHESTRATION_PROMPT + userInput; System.out.println("The prompt to orchestrator: " + orchestratorRequest); ChatClient.ChatClientRequestSpec orchestratorRequestSpec = opsOrchestratorClient.prompt(orchestratorRequest); ChatClient.CallResponseSpec orchestratorResponseSpec = orchestratorRequestSpec.call(); String[] orchestratorResponse = orchestratorResponseSpec.entity(String[].class); String prLink = orchestratorResponse[0]; StringBuilder response = new StringBuilder(); // for each environment that we need to test on for (int i = 1; i < orchestratorResponse.length; i++) {
// execute the chain steps for 1) deployment and 2) test execution String testExecutionChainInput = prLink + " on " + orchestratorResponse[i]; for (String prompt : OpsClientPrompts.EXECUTE_TEST_ON_DEPLOYED_ENV_STEPS) { // Compose the request for the next step String testExecutionChainRequest = String.format("%s\n PR: [%s] environment", prompt, testExecutionChainInput); System.out.printf("PROMPT: %s:\n", testExecutionChainRequest); // Call the ops client with the new request and set the result as the next step input. ChatClient.ChatClientRequestSpec requestSpec = opsClient.prompt(testExecutionChainRequest); ChatClient.CallResponseSpec responseSpec = requestSpec.call(); testExecutionChainInput = responseSpec.content(); System.out.printf("OUTCOME: %s\n", testExecutionChainInput); } response.append(testExecutionChainInput).append("\n"); } return response.toString(); } }
repos\tutorials-master\spring-ai-modules\spring-ai-agentic-patterns\src\main\java\com\baeldung\springai\agenticpatterns\workflows\orchestrator\OrchestratorWorkersWorkflow.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isWithoutProcessDefinitionId() { return withoutProcessDefinitionId; } public String getSubScopeId() { return subScopeId; } public String getScopeId() { return scopeId; } public boolean isWithoutScopeId() { return withoutScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public boolean isWithoutScopeDefinitionId() { return withoutScopeDefinitionId; } public String getScopeDefinitionKey() { return scopeDefinitionKey; } public String getScopeType() { return scopeType; } public Date getCreatedBefore() { return createdBefore; } public Date getCreatedAfter() { return createdAfter; }
public String getTenantId() { return tenantId; } public Collection<String> getTenantIds() { return tenantIds; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getConfiguration() { return configuration; } public Collection<String> getConfigurations() { return configurations; } public boolean isWithoutConfiguration() { return withoutConfiguration; } public List<EventSubscriptionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public EventSubscriptionQueryImpl getCurrentOrQueryObject() { return currentOrQueryObject; } public boolean isInOrStatement() { return inOrStatement; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
private Set<EndpointExposureOutcomeContributor> getExposureOutcomeContributors(ConditionContext context) { Environment environment = context.getEnvironment(); Set<EndpointExposureOutcomeContributor> contributors = exposureOutcomeContributorsCache.get(environment); if (contributors == null) { contributors = new LinkedHashSet<>(); contributors.add(new StandardExposureOutcomeContributor(environment, EndpointExposure.WEB)); if (environment.getProperty(JMX_ENABLED_KEY, Boolean.class, false)) { contributors.add(new StandardExposureOutcomeContributor(environment, EndpointExposure.JMX)); } contributors.addAll(loadExposureOutcomeContributors(context.getClassLoader(), environment)); exposureOutcomeContributorsCache.put(environment, contributors); } return contributors; } private List<EndpointExposureOutcomeContributor> loadExposureOutcomeContributors(@Nullable ClassLoader classLoader, Environment environment) { ArgumentResolver argumentResolver = ArgumentResolver.of(Environment.class, environment); return SpringFactoriesLoader.forDefaultResourceLocation(classLoader) .load(EndpointExposureOutcomeContributor.class, argumentResolver); } /** * Standard {@link EndpointExposureOutcomeContributor}. */ private static class StandardExposureOutcomeContributor implements EndpointExposureOutcomeContributor { private final EndpointExposure exposure; private final String property; private final IncludeExcludeEndpointFilter<?> filter; StandardExposureOutcomeContributor(Environment environment, EndpointExposure exposure) {
this.exposure = exposure; String name = exposure.name().toLowerCase(Locale.ROOT).replace('_', '-'); this.property = "management.endpoints." + name + ".exposure"; this.filter = new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, environment, this.property, exposure.getDefaultIncludes()); } @Override public @Nullable ConditionOutcome getExposureOutcome(EndpointId endpointId, Set<EndpointExposure> exposures, ConditionMessage.Builder message) { if (exposures.contains(this.exposure) && this.filter.match(endpointId)) { return ConditionOutcome .match(message.because("marked as exposed by a '" + this.property + "' property")); } return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\condition\OnAvailableEndpointCondition.java
2
请完成以下Java代码
protected void fireEntityInsertedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_CREATED, entity), engineType); eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_INITIALIZED, entity), engineType); } } @Override public EntityImpl update(EntityImpl entity) { return update(entity, true); } @Override public EntityImpl update(EntityImpl entity, boolean fireUpdateEvent) { EntityImpl updatedEntity = getDataManager().update(entity); if (fireUpdateEvent) { fireEntityUpdatedEvent(entity); } return updatedEntity; } protected void fireEntityUpdatedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { getEventDispatcher().dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, entity), engineType); } } @Override public void delete(String id) { EntityImpl entity = findById(id); delete(entity); } @Override public void delete(EntityImpl entity) { delete(entity, true); }
@Override public void delete(EntityImpl entity, boolean fireDeleteEvent) { getDataManager().delete(entity); FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (fireDeleteEvent && eventDispatcher != null && eventDispatcher.isEnabled()) { fireEntityDeletedEvent(entity); } } protected void fireEntityDeletedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, entity), engineType); } } protected FlowableEntityEvent createEntityEvent(FlowableEngineEventType eventType, Entity entity) { return new FlowableEntityEventImpl(entity, eventType); } protected DM getDataManager() { return dataManager; } protected void setDataManager(DM dataManager) { this.dataManager = dataManager; } protected abstract FlowableEventDispatcher getEventDispatcher(); }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntityManager.java
1
请在Spring Boot框架中完成以下Java代码
public class BigIntegerType implements VariableType { public static final String TYPE_NAME = "biginteger"; @Override public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return true; } @Override public Object getValue(ValueFields valueFields) { BigInteger bigInteger = null; String textValue = valueFields.getTextValue(); if (textValue != null && !textValue.isEmpty()) { bigInteger = new BigInteger(textValue); } return bigInteger; }
@Override public void setValue(Object value, ValueFields valueFields) { if (value != null) { valueFields.setTextValue(value.toString()); } else { valueFields.setTextValue(null); } } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return BigInteger.class.isAssignableFrom(value.getClass()); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\BigIntegerType.java
2
请完成以下Java代码
private Optional<String> extractAsString(final ScannedCode scannedCode) { int startIndex = startPosition - 1; int endIndex = endPosition - 1 + 1; if (endIndex > scannedCode.length()) { return Optional.empty(); } return Optional.of(scannedCode.substring(startIndex, endIndex)); } private BigDecimal toBigDecimal(final String valueStr) { BigDecimal valueBD = new BigDecimal(valueStr); if (decimalPointPosition > 0) { valueBD = valueBD.scaleByPowerOfTen(-decimalPointPosition); } return valueBD; }
private LocalDate toLocalDate(final String valueStr) { final PatternedDateTimeFormatter dateFormat = coalesceNotNull(this.dateFormat, DEFAULT_DATE_FORMAT); return dateFormat.parseLocalDate(valueStr); } private static String trimLeadingZeros(final String valueStr) { int index = 0; while (index < valueStr.length() && valueStr.charAt(index) == '0') { index++; } return index == 0 ? valueStr : valueStr.substring(index); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\ScannableCodeFormatPart.java
1
请完成以下Java代码
public Builder setCustomAttribute(final String attributeName, final Object value) { setAttribute(attributeName, value); return this; } } } public interface SourceDocument { String NAME = "__SourceDocument"; default int getWindowNo() { return Env.WINDOW_None; } boolean hasFieldValue(String fieldName); Object getFieldValue(String fieldName); default int getFieldValueAsInt(final String fieldName, final int defaultValue) { final Object value = getFieldValue(fieldName); return value != null ? (int)value : defaultValue; } @Nullable default <T extends RepoIdAware> T getFieldValueAsRepoId(final String fieldName, final Function<Integer, T> idMapper) { final int id = getFieldValueAsInt(fieldName, -1); if (id > 0) { return idMapper.apply(id); } else { return null; } } static SourceDocument toSourceDocumentOrNull(final Object obj) { if (obj == null) { return null; } if (obj instanceof SourceDocument) { return (SourceDocument)obj; } final PO po = getPO(obj); return new POSourceDocument(po); } } @AllArgsConstructor private static final class POSourceDocument implements SourceDocument
{ @NonNull private final PO po; @Override public boolean hasFieldValue(final String fieldName) { return po.get_ColumnIndex(fieldName) >= 0; } @Override public Object getFieldValue(final String fieldName) { return po.get_Value(fieldName); } } @AllArgsConstructor private static final class GridTabSourceDocument implements SourceDocument { @NonNull private final GridTab gridTab; @Override public boolean hasFieldValue(final String fieldName) { return gridTab.getField(fieldName) != null; } @Override public Object getFieldValue(final String fieldName) { return gridTab.getValue(fieldName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java
1
请在Spring Boot框架中完成以下Java代码
public ConsumerFactory<Integer, String> consumerFactory() { return new DefaultKafkaConsumerFactory<>(consumerProps()); } private Map<String, Object> consumerProps() { Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "group"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // ... return props; } @Bean public Sender sender(KafkaTemplate<Integer, String> template) { return new Sender(template); } @Bean public Listener listener() { return new Listener();
} @Bean public ProducerFactory<Integer, String> producerFactory() { return new DefaultKafkaProducerFactory<>(senderProps()); } private Map<String, Object> senderProps() { Map<String, Object> props = new HashMap<>(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.LINGER_MS_CONFIG, 10); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); //... return props; } @Bean public KafkaTemplate<Integer, String> kafkaTemplate(ProducerFactory<Integer, String> producerFactory) { return new KafkaTemplate<>(producerFactory); } } // end::startedNoBootConfig[]
repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\started\noboot\Config.java
2
请完成以下Java代码
public class DmnDecisionImpl implements DmnDecision { protected String key; protected String name; protected DmnDecisionLogic decisionLogic; protected Collection<DmnDecision> requiredDecision = new ArrayList<DmnDecision>(); public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setDecisionLogic(DmnDecisionLogic decisionLogic) { this.decisionLogic = decisionLogic; }
public DmnDecisionLogic getDecisionLogic() { return decisionLogic; } public void setRequiredDecision(List<DmnDecision> requiredDecision) { this.requiredDecision = requiredDecision; } @Override public Collection<DmnDecision> getRequiredDecisions() { return requiredDecision; } @Override public boolean isDecisionTable() { return decisionLogic != null && decisionLogic instanceof DmnDecisionTableImpl; } @Override public String toString() { return "DmnDecisionTableImpl{" + " key= "+ key + ", name= "+ name + ", requiredDecision=" + requiredDecision + ", decisionLogic=" + decisionLogic + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionImpl.java
1
请完成以下Java代码
private List<MonitorInfo> lockedMonitorsForDepth(MonitorInfo[] lockedMonitors, int depth) { return Stream.of(lockedMonitors).filter((candidate) -> candidate.getLockedStackDepth() == depth).toList(); } private void writeStackTraceElement(PrintWriter writer, StackTraceElement element, ThreadInfo info, List<MonitorInfo> lockedMonitors, boolean firstElement) { writer.printf("\tat %s%n", element.toString()); LockInfo lockInfo = info.getLockInfo(); if (firstElement && lockInfo != null) { if (element.getClassName().equals(Object.class.getName()) && element.getMethodName().equals("wait")) { writer.printf("\t- waiting on %s%n", format(lockInfo)); } else { String lockOwner = info.getLockOwnerName(); if (lockOwner != null) { writer.printf("\t- waiting to lock %s owned by \"%s\" t@%d%n", format(lockInfo), lockOwner, info.getLockOwnerId()); } else { writer.printf("\t- parking to wait for %s%n", format(lockInfo)); } } } writeMonitors(writer, lockedMonitors); }
private String format(LockInfo lockInfo) { return String.format("<%x> (a %s)", lockInfo.getIdentityHashCode(), lockInfo.getClassName()); } private void writeMonitors(PrintWriter writer, List<MonitorInfo> lockedMonitorsAtCurrentDepth) { for (MonitorInfo lockedMonitor : lockedMonitorsAtCurrentDepth) { writer.printf("\t- locked %s%n", format(lockedMonitor)); } } private void writeLockedOwnableSynchronizers(PrintWriter writer, ThreadInfo info) { writer.println(" Locked ownable synchronizers:"); LockInfo[] lockedSynchronizers = info.getLockedSynchronizers(); if (lockedSynchronizers == null || lockedSynchronizers.length == 0) { writer.println("\t- None"); } else { for (LockInfo lockedSynchronizer : lockedSynchronizers) { writer.printf("\t- Locked %s%n", format(lockedSynchronizer)); } } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\PlainTextThreadDumpFormatter.java
1
请在Spring Boot框架中完成以下Java代码
public File fileDown(Date billDate, String dir) throws IOException { // 时间格式转换 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); bill_date = sdf.format(billDate); HttpResponse response = null; try { // 生成xml文件 String xml = this.generateXml(); LOG.info(xml); response = HttpClientUtil.httpsRequest(url, "POST", xml); // String dir = "/home/roncoo/app/accountcheck/billfile/weixin"; File file = new File(dir, bill_date + "_" + bill_type.toLowerCase() + ".txt"); int index = 1; // 判断文件是否已经存在 while (file.exists()) { file = new File(dir, bill_date + "_" + bill_type.toLowerCase() + index + ".txt"); index++; } return FileUtils.saveFile(response, file); } catch (IOException e) { throw new IOException("下载微信账单失败", e); } finally { try { if (response != null) { response.close(); } } catch (IOException e) { LOG.error("关闭下载账单的流/连接失败", e); } } }
/** * 根据微信接口要求,生成xml文件 * * @param appId * 必填 * @param mchId * 必填 * @param billDate * 必填, 下载对账单的日期(最小单位天) * @param billType * 下载单类型 * @param appSecret * 必填, 供签名使用 * @return */ public String generateXml() { HashMap<String, String> params = new HashMap<String, String>(); params.put("appid", appid); params.put("mch_id", mch_id); params.put("bill_date", bill_date); params.put("bill_type", bill_type); // 随机字符串,不长于32,调用随机数函数生成,将得到的值转换为字符串 params.put("nonce_str", WeiXinBaseUtils.createNoncestr()); // 过滤空值 for (Iterator<Entry<String, String>> it = params.entrySet().iterator(); it.hasNext();) { Entry<String, String> entry = it.next(); if (StringUtils.isEmpty(entry.getValue())) { it.remove(); } } String sign = SignHelper.getSign(params, appSecret); params.put("sign", sign.toUpperCase()); return WeiXinBaseUtils.arrayToXml(params); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\fileDown\impl\WinXinFileDown.java
2
请完成以下Java代码
public String getUserEmailAttribute() { return userEmailAttribute; } public void setUserEmailAttribute(String userEmailAttribute) { this.userEmailAttribute = userEmailAttribute; } public String getUserPasswordAttribute() { return userPasswordAttribute; } public void setUserPasswordAttribute(String userPasswordAttribute) { this.userPasswordAttribute = userPasswordAttribute; } public boolean isSortControlSupported() { return sortControlSupported; } public void setSortControlSupported(boolean sortControlSupported) { this.sortControlSupported = sortControlSupported; } public String getGroupIdAttribute() { return groupIdAttribute; } public void setGroupIdAttribute(String groupIdAttribute) { this.groupIdAttribute = groupIdAttribute; } public String getGroupMemberAttribute() { return groupMemberAttribute; } public void setGroupMemberAttribute(String groupMemberAttribute) { this.groupMemberAttribute = groupMemberAttribute; } public boolean isUseSsl() { return useSsl; } public void setUseSsl(boolean useSsl) { this.useSsl = useSsl; } public boolean isUsePosixGroups() { return usePosixGroups; } public void setUsePosixGroups(boolean usePosixGroups) { this.usePosixGroups = usePosixGroups; } public SearchControls getSearchControls() { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setTimeLimit(30000); return searchControls; }
public String getGroupTypeAttribute() { return groupTypeAttribute; } public void setGroupTypeAttribute(String groupTypeAttribute) { this.groupTypeAttribute = groupTypeAttribute; } public boolean isAllowAnonymousLogin() { return allowAnonymousLogin; } public void setAllowAnonymousLogin(boolean allowAnonymousLogin) { this.allowAnonymousLogin = allowAnonymousLogin; } public boolean isAuthorizationCheckEnabled() { return authorizationCheckEnabled; } public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) { this.authorizationCheckEnabled = authorizationCheckEnabled; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public boolean isPasswordCheckCatchAuthenticationException() { return passwordCheckCatchAuthenticationException; } public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) { this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java
1
请完成以下Java代码
public class RuntimeContainerJobExecutor extends JobExecutor { protected void startExecutingJobs() { final RuntimeContainerDelegate runtimeContainerDelegate = getRuntimeContainerDelegate(); // schedule job acquisition if(!runtimeContainerDelegate.getExecutorService().schedule(acquireJobsRunnable, true)) { throw new ProcessEngineException("Could not schedule AcquireJobsRunnable for execution."); } } protected void stopExecutingJobs() { // nothing to do } public void executeJobs(List<String> jobIds, ProcessEngineImpl processEngine) { final RuntimeContainerDelegate runtimeContainerDelegate = getRuntimeContainerDelegate(); final ExecutorService executorService = runtimeContainerDelegate.getExecutorService(); Runnable executeJobsRunnable = getExecuteJobsRunnable(jobIds, processEngine); // delegate job execution to runtime container if(!executorService.schedule(executeJobsRunnable, false)) { logRejectedExecution(processEngine, jobIds.size()); rejectedJobsHandler.jobsRejected(jobIds, processEngine, this); } if (executorService instanceof JmxManagedThreadPool) { int totalQueueCapacity = calculateTotalQueueCapacity(((JmxManagedThreadPool) executorService).getQueueCount(), ((JmxManagedThreadPool) executorService).getQueueAddlCapacity()); logJobExecutionInfo(processEngine, ((JmxManagedThreadPool) executorService).getQueueCount(), totalQueueCapacity, ((JmxManagedThreadPool) executorService).getMaximumPoolSize(),
((JmxManagedThreadPool) executorService).getActiveCount()); } } protected RuntimeContainerDelegate getRuntimeContainerDelegate() { return RuntimeContainerDelegate.INSTANCE.get(); } @Override public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { final RuntimeContainerDelegate runtimeContainerDelegate = getRuntimeContainerDelegate(); final ExecutorService executorService = runtimeContainerDelegate.getExecutorService(); return executorService.getExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\RuntimeContainerJobExecutor.java
1
请完成以下Java代码
public TranslatableStringBuilder appendDateTime(@NonNull final ZonedDateTime value) { return append(DateTimeTranslatableString.ofDateTime(value)); } public TranslatableStringBuilder appendTimeZone( @NonNull final ZoneId zoneId, @NonNull final TextStyle textStyle) { return append(TimeZoneTranslatableString.ofZoneId(zoneId, textStyle)); } public TranslatableStringBuilder append(final Boolean value) { if (value == null) { return append("?"); } else { return append(msgBL.getTranslatableMsgText(value)); } } public TranslatableStringBuilder appendADMessage( final AdMessageKey adMessage, final Object... msgParameters) { final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters); return append(value); } @Deprecated public TranslatableStringBuilder appendADMessage( @NonNull final String adMessage, final Object... msgParameters) { return appendADMessage(AdMessageKey.of(adMessage), msgParameters);
} public TranslatableStringBuilder insertFirstADMessage( final AdMessageKey adMessage, final Object... msgParameters) { final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters); return insertFirst(value); } @Deprecated public TranslatableStringBuilder insertFirstADMessage( final String adMessage, final Object... msgParameters) { return insertFirstADMessage(AdMessageKey.of(adMessage), msgParameters); } public TranslatableStringBuilder appendADElement(final String columnName) { final ITranslatableString value = msgBL.translatable(columnName); return append(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableStringBuilder.java
1
请完成以下Java代码
public CaseInstanceBuilder setVariables(Map<String, Object> variables) { if (variables != null) { if (this.variables == null) { this.variables = Variables.fromMap(variables); } else { this.variables.putAll(variables); } } return this; } public CaseInstance create() { if (isTenantIdSet && caseDefinitionId != null) { throw LOG.exceptionCreateCaseInstanceByIdAndTenantId(); } try { CreateCaseInstanceCmd command = new CreateCaseInstanceCmd(this); if(commandExecutor != null) { return commandExecutor.execute(command); } else { return command.execute(commandContext); } } catch (CaseDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (CaseIllegalStateTransitionException e) { throw new NotAllowedException(e.getMessage(), e); } } // getters //////////////////////////////////// public String getCaseDefinitionKey() {
return caseDefinitionKey; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getBusinessKey() { return businessKey; } public VariableMap getVariables() { return variables; } public String getCaseDefinitionTenantId() { return caseDefinitionTenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseInstanceBuilderImpl.java
1
请完成以下Java代码
public void onC_DocType_ID(final I_GL_Journal glJournal) { final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(getDocType(glJournal).orElse(null)) .setOldDocumentNo(glJournal.getDocumentNo()) .setDocumentModel(glJournal) .buildOrNull(); if (documentNoInfo != null && documentNoInfo.isDocNoControlled()) { glJournal.setDocumentNo(documentNoInfo.getDocumentNo()); } } private Optional<I_C_DocType> getDocType(final I_GL_Journal glJournal) { return DocTypeId.optionalOfRepoId(glJournal.getC_DocType_ID()) .map(docTypeBL::getById); } @CalloutMethod(columnNames = I_GL_Journal.COLUMNNAME_DateDoc) public void onDateDoc(final I_GL_Journal glJournal) { final Timestamp dateDoc = glJournal.getDateDoc(); if (dateDoc == null) { return; } glJournal.setDateAcct(dateDoc); } @CalloutMethod(columnNames = { I_GL_Journal.COLUMNNAME_DateAcct, I_GL_Journal.COLUMNNAME_C_Currency_ID, I_GL_Journal.COLUMNNAME_C_ConversionType_ID }) public void updateCurrencyRate(final I_GL_Journal glJournal) { // // Extract data from source Journal final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID()); if (currencyId == null) { // not set yet return; } final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID()); final Instant dateAcct = glJournal.getDateAcct() != null ? glJournal.getDateAcct().toInstant() : SystemTime.asInstant();
final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID()); final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID()); final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(glJournal.getC_AcctSchema_ID()); final AcctSchema acctSchema = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId); // // Calculate currency rate final BigDecimal currencyRate; if (acctSchema != null) { currencyRate = Services.get(ICurrencyBL.class).getCurrencyRateIfExists( currencyId, acctSchema.getCurrencyId(), dateAcct, conversionTypeId, adClientId, adOrgId) .map(CurrencyRate::getConversionRate) .orElse(BigDecimal.ZERO); } else { currencyRate = BigDecimal.ONE; } // glJournal.setCurrencyRate(currencyRate); } // Old/missing callouts // "GL_Journal";"C_Period_ID";"org.compiere.model.CalloutGLJournal.period" // "GL_Journal";"DateAcct";"org.compiere.model.CalloutGLJournal.period" }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_Journal.java
1
请完成以下Java代码
protected void applySortBy(HistoricExternalTaskLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_TIMESTAMP)) { query.orderByTimestamp(); } else if (sortBy.equals(SORT_BY_EXTERNAL_TASK_ID)) { query.orderByExternalTaskId(); } else if (sortBy.equals(SORT_BY_RETRIES)) { query.orderByRetries(); } else if (sortBy.equals(SORT_BY_PRIORITY)) { query.orderByPriority(); } else if (sortBy.equals(SORT_BY_TOPIC_NAME)) { query.orderByTopicName(); } else if (sortBy.equals(SORT_BY_WORKER_ID)) { query.orderByWorkerId(); } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { query.orderByActivityId();
}else if (sortBy.equals(SORT_BY_ACTIVITY_INSTANCE_ID)) { query.orderByActivityInstanceId(); } else if (sortBy.equals(SORT_BY_EXECUTION_ID)) { query.orderByExecutionId(); } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { query.orderByProcessInstanceId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogQueryDto.java
1
请完成以下Java代码
public int getHR_ListVersion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Max Value. @param MaxValue Max Value */ public void setMaxValue (BigDecimal MaxValue) { set_Value (COLUMNNAME_MaxValue, MaxValue); } /** Get Max Value. @return Max Value */ public BigDecimal getMaxValue () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxValue); if (bd == null) return Env.ZERO; return bd; } /** Set Min Value. @param MinValue Min Value */ public void setMinValue (BigDecimal MinValue) { set_Value (COLUMNNAME_MinValue, MinValue); } /** Get Min Value. @return Min Value */ public BigDecimal getMinValue () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinValue); if (bd == null) return Env.ZERO; return bd; } /** Set Name.
@param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListLine.java
1
请完成以下Java代码
default Optional<ClassLoader> getClassLoader() { return Optional.ofNullable(ClassUtils.getDefaultClassLoader()); } /** * Tries to resolve a {@link Resource} handle from the given, {@literal non-null} {@link String location} * (e.g. {@link String filesystem path}). * * @param location {@link String location} identifying the {@link Resource} to resolve; * must not be {@literal null}. * @return an {@link Optional} {@link Resource} handle for the given {@link String location}. * @see org.springframework.core.io.Resource * @see java.util.Optional */ Optional<Resource> resolve(@NonNull String location); /** * Returns a {@literal non-null}, {@literal existing} {@link Resource} handle resolved from the given, * {@literal non-null} {@link String location} (e.g. {@link String filesystem path}). *
* @param location {@link String location} identifying the {@link Resource} to resolve; * must not be {@literal null}. * @return a {@literal non-null}, {@literal existing} {@link Resource} handle for * the resolved {@link String location}. * @throws ResourceNotFoundException if a {@link Resource} cannot be resolved from the given {@link String location}. * A {@link Resource} is unresolvable if the given {@link String location} does not exist (physically); * see {@link Resource#exists()}. * @see org.springframework.core.io.Resource * @see #resolve(String) */ default @NonNull Resource require(@NonNull String location) { return resolve(location) .filter(Resource::exists) .orElseThrow(() -> new ResourceNotFoundException(String.format("Resource [%s] does not exist", location))); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\ResourceResolver.java
1
请在Spring Boot框架中完成以下Java代码
public DefaultDmnEngineConfiguration build() { List<DmnDecisionEvaluationListener> decisionEvaluationListeners = createCustomPostDecisionEvaluationListeners(); dmnEngineConfiguration.setCustomPostDecisionEvaluationListeners(decisionEvaluationListeners); // override the decision table handler DmnTransformer dmnTransformer = dmnEngineConfiguration.getTransformer(); dmnTransformer.getElementTransformHandlerRegistry().addHandler(Definitions.class, new DecisionRequirementsDefinitionTransformHandler()); dmnTransformer.getElementTransformHandlerRegistry().addHandler(Decision.class, new DecisionDefinitionHandler()); // do not override the script engine resolver if set if (dmnEngineConfiguration.getScriptEngineResolver() == null) { ensureNotNull("scriptEngineResolver", scriptEngineResolver); dmnEngineConfiguration.setScriptEngineResolver(scriptEngineResolver); } // do not override the el provider if set if (dmnEngineConfiguration.getElProvider() == null) { ensureNotNull("elProvider", elProvider); dmnEngineConfiguration.setElProvider(elProvider); } if (dmnEngineConfiguration.getFeelCustomFunctionProviders() == null) { dmnEngineConfiguration.setFeelCustomFunctionProviders(feelCustomFunctionProviders); } return dmnEngineConfiguration; }
protected List<DmnDecisionEvaluationListener> createCustomPostDecisionEvaluationListeners() { ensureNotNull("dmnHistoryEventProducer", dmnHistoryEventProducer); // note that the history level may be null - see CAM-5165 HistoryDecisionEvaluationListener historyDecisionEvaluationListener = new HistoryDecisionEvaluationListener(dmnHistoryEventProducer); List<DmnDecisionEvaluationListener> customPostDecisionEvaluationListeners = dmnEngineConfiguration .getCustomPostDecisionEvaluationListeners(); customPostDecisionEvaluationListeners.add(new MetricsDecisionEvaluationListener()); customPostDecisionEvaluationListeners.add(historyDecisionEvaluationListener); return customPostDecisionEvaluationListeners; } public DmnEngineConfigurationBuilder enableFeelLegacyBehavior(boolean dmnFeelEnableLegacyBehavior) { dmnEngineConfiguration .enableFeelLegacyBehavior(dmnFeelEnableLegacyBehavior); return this; } public DmnEngineConfigurationBuilder returnBlankTableOutputAsNull(boolean dmnReturnBlankTableOutputAsNull) { dmnEngineConfiguration.setReturnBlankTableOutputAsNull(dmnReturnBlankTableOutputAsNull); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\configuration\DmnEngineConfigurationBuilder.java
2
请完成以下Java代码
public void execute(final ActivityExecution execution) throws Exception { ensureConnectorInitialized(); executeWithErrorPropagation(execution, new Callable<Void>() { @Override public Void call() throws Exception { ConnectorRequest<?> request = connectorInstance.createRequest(); applyInputParameters(execution, request); // execute the request and obtain a response: ConnectorResponse response = request.execute(); applyOutputParameters(execution, response); leave(execution); return null; } }); } protected void applyInputParameters(ActivityExecution execution, ConnectorRequest<?> request) { if(ioMapping != null) { // create variable scope for input parameters ConnectorVariableScope connectorInputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution); // execute the connector input parameters ioMapping.executeInputParameters(connectorInputVariableScope); // write the local variables to the request. connectorInputVariableScope.writeToRequest(request); } } protected void applyOutputParameters(ActivityExecution execution, ConnectorResponse response) { if(ioMapping != null) { // create variable scope for output parameters ConnectorVariableScope connectorOutputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution); // read parameters from response connectorOutputVariableScope.readFromResponse(response);
// map variables to parent scope. ioMapping.executeOutputParameters(connectorOutputVariableScope); } } protected void ensureConnectorInitialized() { if(connectorInstance == null) { synchronized (this) { if(connectorInstance == null) { connectorInstance = Connectors.getConnector(connectorId); if (connectorInstance == null) { throw new ConnectorException("No connector found for connector id '" + connectorId + "'"); } } } } } }
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ServiceTaskConnectorActivityBehavior.java
1
请完成以下Java代码
public static ProductType ofNullableCode(@Nullable final String code) { return code != null ? ofCode(code) : null; } public static ProductType ofCode(@NonNull final String code) { ProductType type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + ProductType.class + " found for code: " + code); } return type; } public static String toCodeOrNull(@Nullable final ProductType type) { return type != null ? type.getCode() : null; } private static final ImmutableMap<String, ProductType> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), ProductType::getCode);
public boolean isItem() { return this == Item; } /** @return {@code true} <b>for every</b> non-item, not just {@link #Service}. */ public boolean isService() { return this != Item; } public boolean isFreightCost() { return this == FreightCost; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\ProductType.java
1
请完成以下Java代码
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { parseActivity(transactionElement, activity); } protected boolean isAsync(ActivityImpl activity) { return activity.isAsyncBefore() || activity.isAsyncAfter(); } protected void parseActivity(Element element, ActivityImpl activity) { if (isMultiInstance(activity)) { // in case of multi-instance, the extension elements is set according to the async attributes // the extension for multi-instance body is set on the element of the activity ActivityImpl miBody = activity.getParentFlowScopeActivity(); if (isAsync(miBody)) { setFailedJobRetryTimeCycleValue(element, miBody); } // the extension for inner activity is set on the multiInstanceLoopCharacteristics element if (isAsync(activity)) { Element multiInstanceLoopCharacteristics = element.element(MULTI_INSTANCE_LOOP_CHARACTERISTICS); setFailedJobRetryTimeCycleValue(multiInstanceLoopCharacteristics, activity); } } else if (isAsync(activity)) { setFailedJobRetryTimeCycleValue(element, activity); } } protected void setFailedJobRetryTimeCycleValue(Element element, ActivityImpl activity) { String failedJobRetryTimeCycleConfiguration = null; Element extensionElements = element.element(EXTENSION_ELEMENTS); if (extensionElements != null) { Element failedJobRetryTimeCycleElement = extensionElements.elementNS(FOX_ENGINE_NS, FAILED_JOB_RETRY_TIME_CYCLE); if (failedJobRetryTimeCycleElement == null) { // try to get it from the activiti namespace
failedJobRetryTimeCycleElement = extensionElements.elementNS(BpmnParse.CAMUNDA_BPMN_EXTENSIONS_NS, FAILED_JOB_RETRY_TIME_CYCLE); } if (failedJobRetryTimeCycleElement != null) { failedJobRetryTimeCycleConfiguration = failedJobRetryTimeCycleElement.getText(); } } if (failedJobRetryTimeCycleConfiguration == null || failedJobRetryTimeCycleConfiguration.isEmpty()) { failedJobRetryTimeCycleConfiguration = Context.getProcessEngineConfiguration().getFailedJobRetryTimeCycle(); } if (failedJobRetryTimeCycleConfiguration != null) { FailedJobRetryConfiguration configuration = ParseUtil.parseRetryIntervals(failedJobRetryTimeCycleConfiguration); activity.getProperties().set(FAILED_JOB_CONFIGURATION, configuration); } } protected boolean isMultiInstance(ActivityImpl activity) { // #isMultiInstance() don't work since the property is not set yet ActivityImpl parent = activity.getParentFlowScopeActivity(); return parent != null && parent.getActivityBehavior() instanceof MultiInstanceActivityBehavior; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\DefaultFailedJobParseListener.java
1
请完成以下Java代码
public void onItemError(final Throwable e, final Object item) { Loggables.withLogger(logger, Level.DEBUG).addLog("Error while trying to process item={}; exception={}", item, e); } @Override public void onCompleteChunkError(final Throwable e) { Loggables.withLogger(logger, Level.DEBUG).addLog("Error while completing current chunk; exception={}", e); } @Override public void afterCompleteChunkError(final Throwable e) { // nothing to do.
// error was already logged by onCompleteChunkError } @Override public void onCommitChunkError(final Throwable e) { Loggables.withLogger(logger, Level.DEBUG).addLog("Processor failed to commit current chunk => rollback transaction; exception={}", e); } @Override public void onCancelChunkError(final Throwable e) { Loggables.withLogger(logger, Level.DEBUG).addLog("Error while cancelling current chunk. Ignored; exception={}", e); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\LoggableTrxItemExceptionHandler.java
1