instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class ProjectLine { @NonNull private final ProjectAndLineId id; @NonNull private final ProductId productId; @NonNull private final Quantity plannedQty; @NonNull private Quantity committedQty; @Nullable
private final String description; @Nullable private final OrderAndLineId salesOrderLineId; public Quantity getPlannedQtyButNotCommitted() { return getPlannedQty().subtract(getCommittedQty()); } public void addCommittedQty(@NonNull final Quantity committedQtyToAdd) { this.committedQty = this.committedQty.add(committedQtyToAdd); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectLine.java
1
请完成以下Java代码
public List<DmnDecision> executeList(CommandContext commandContext) { return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getParentDeploymentId() { return parentDeploymentId; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getDecisionId() { return decisionId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public Integer getVersion() { return version; } public Integer getVersionGt() { return versionGt; } public Integer getVersionGte() { return versionGte; }
public Integer getVersionLt() { return versionLt; } public Integer getVersionLte() { return versionLte; } public boolean isLatest() { return latest; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getDecisionType() { return decisionType; } public String getDecisionTypeLike() { return decisionTypeLike; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DecisionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class NonConventionalWeekDaysHolder { @Value("${monday}") private NonConventionalWeekDays monday; @Value("${tuesday}") private NonConventionalWeekDays tuesday; @Value("${wednesday}") private NonConventionalWeekDays wednesday; @Value("${thursday}") private NonConventionalWeekDays thursday; @Value("${friday}") private NonConventionalWeekDays friday; @Value("${saturday}") private NonConventionalWeekDays saturday; @Value("${sunday}") private NonConventionalWeekDays sunday; public NonConventionalWeekDays getMonday() { return monday; } public void setMonday(final NonConventionalWeekDays monday) { this.monday = monday; } public NonConventionalWeekDays getTuesday() { return tuesday; } public void setTuesday(final NonConventionalWeekDays tuesday) { this.tuesday = tuesday; } public NonConventionalWeekDays getWednesday() { return wednesday; } public void setWednesday(final NonConventionalWeekDays wednesday) { this.wednesday = wednesday; } public NonConventionalWeekDays getThursday() { return thursday; } public void setThursday(final NonConventionalWeekDays thursday) { this.thursday = thursday; }
public NonConventionalWeekDays getFriday() { return friday; } public void setFriday(final NonConventionalWeekDays friday) { this.friday = friday; } public NonConventionalWeekDays getSaturday() { return saturday; } public void setSaturday(final NonConventionalWeekDays saturday) { this.saturday = saturday; } public NonConventionalWeekDays getSunday() { return sunday; } public void setSunday(final NonConventionalWeekDays sunday) { this.sunday = sunday; } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties-4\src\main\java\com\baeldung\caseinsensitiveenum\nonconventionalweek\NonConventionalWeekDaysHolder.java
2
请在Spring Boot框架中完成以下Java代码
private void prepareContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); if (request == null) { throw new RuntimeCamelException("Missing exchange body! No JsonExternalSystemRequest found!"); } final String orgCode = request.getOrgCode(); final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH); final String apiKey = request.getParameters().get(ExternalSystemConstants.PARAM_API_KEY); final String tenant = request.getParameters().get(ExternalSystemConstants.PARAM_TENANT); final String albertaResourceId = request.getParameters().get(ExternalSystemConstants.PARAM_ALBERTA_ID); final String role = request.getParameters().get(ExternalSystemConstants.PARAM_ALBERTA_ROLE); final AlbertaConnectionDetails albertaConnectionDetails = AlbertaConnectionDetails.builder() .apiKey(apiKey) .basePath(basePath) .tenant(tenant) .build(); final ApiClient apiClient = new ApiClient().setBasePath(basePath); final GetInstitutionsRouteContext context = GetInstitutionsRouteContext.builder() .orgCode(orgCode) .albertaConnectionDetails(albertaConnectionDetails) .albertaResourceId(albertaResourceId) .role(JsonBPartnerRole.valueOf(role)) .doctorApi(new DoctorApi(apiClient))
.hospitalApi(new HospitalApi(apiClient)) .nursingHomeApi(new NursingHomeApi(apiClient)) .nursingServiceApi(new NursingServiceApi(apiClient)) .payerApi(new PayerApi(apiClient)) .pharmacyApi(new PharmacyApi(apiClient)) .build(); exchange.setProperty(GetInstitutionsRouteConstants.ROUTE_PROPERTY_GET_INSTITUTIONS_CONTEXT, context); if (request.getAdPInstanceId() != null) { exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue()); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\institutions\GetAlbertaInstitutionsRoute.java
2
请完成以下Java代码
public class X_AD_User_SaveCustomInfo extends org.compiere.model.PO implements I_AD_User_SaveCustomInfo, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 138964010L; /** Standard Constructor */ public X_AD_User_SaveCustomInfo (Properties ctx, int AD_User_SaveCustomInfo_ID, String trxName) { super (ctx, AD_User_SaveCustomInfo_ID, trxName); /** if (AD_User_SaveCustomInfo_ID == 0) { setAD_User_SaveCustomInfo_ID (0); } */ } /** Load Constructor */ public X_AD_User_SaveCustomInfo (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set User Save Custom Info. @param AD_User_SaveCustomInfo_ID User Save Custom Info */ @Override public void setAD_User_SaveCustomInfo_ID (int AD_User_SaveCustomInfo_ID) { if (AD_User_SaveCustomInfo_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_SaveCustomInfo_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_SaveCustomInfo_ID, Integer.valueOf(AD_User_SaveCustomInfo_ID)); } /** Get User Save Custom Info. @return User Save Custom Info */ @Override public int getAD_User_SaveCustomInfo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SaveCustomInfo_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Country getC_Country() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class); } @Override
public void setC_Country(org.compiere.model.I_C_Country C_Country) { set_ValueFromPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class, C_Country); } /** Set Land. @param C_Country_ID Land */ @Override public void setC_Country_ID (int C_Country_ID) { if (C_Country_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Country_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID)); } /** Get Land. @return Land */ @Override public int getC_Country_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Capture Sequence. @param CaptureSequence Capture Sequence */ @Override public void setCaptureSequence (java.lang.String CaptureSequence) { set_Value (COLUMNNAME_CaptureSequence, CaptureSequence); } /** Get Capture Sequence. @return Capture Sequence */ @Override public java.lang.String getCaptureSequence () { return (java.lang.String)get_Value(COLUMNNAME_CaptureSequence); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SaveCustomInfo.java
1
请完成以下Java代码
public static IHostIdentifier of(final String hostOrAddress) throws UnknownHostException { Check.assumeNotEmpty(hostOrAddress, "hostOrAddress not empty"); final InetAddress inetAddress = InetAddress.getByName(hostOrAddress); return of(inetAddress); } public static IHostIdentifier of(@NonNull final InetAddress inetAddress) { final String hostAddress = inetAddress.getHostAddress(); final String hostName = inetAddress.getHostName(); return new HostIdentifier(hostName, hostAddress); } @Immutable private static final class HostIdentifier implements IHostIdentifier { private final String hostName; private final String hostAddress; private transient String _toString; private transient Integer _hashcode; private HostIdentifier(final String hostName, final String hostAddress) { this.hostAddress = hostAddress; this.hostName = hostName; } @Override public String toString() { if (_toString == null) { _toString = (hostName != null ? hostName : "") + "/" + hostAddress; } return _toString; } @Override public int hashCode() { if (_hashcode == null) { _hashcode = Objects.hash(hostName, hostAddress); }
return _hashcode; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof HostIdentifier) { final HostIdentifier other = (HostIdentifier)obj; return Objects.equals(hostName, other.hostName) && Objects.equals(hostAddress, other.hostAddress); } else { return false; } } @Override public String getIP() { return hostAddress; } @Override public String getHostName() { return hostName; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\net\NetUtils.java
1
请完成以下Java代码
public List<I_C_ILCandHandler> retrieveForTable(final Properties ctx, final String tableName) { final List<I_C_ILCandHandler> result = new ArrayList<>(); for (final I_C_ILCandHandler handlerDef : retrieveAll(ctx)) { if (tableName.equals(handlerDef.getTableName())) { result.add(handlerDef); } } return result; } @Override public I_C_ILCandHandler retrieveForClassOneOnly(final Properties ctx, @NonNull final Class<? extends IInvoiceCandidateHandler> handlerClass) { final List<I_C_ILCandHandler> result = retrieveForClass(ctx, handlerClass); // // Retain only active handlers for (final Iterator<I_C_ILCandHandler> it = result.iterator(); it.hasNext();) { final I_C_ILCandHandler handlerDef = it.next(); if (!handlerDef.isActive()) { it.remove(); } } if (result.isEmpty()) { throw new AdempiereException("@NotFound@ @C_ILCandHandler@ (@Classname@:" + handlerClass + ")"); } else if (result.size() != 1) { throw new AdempiereException("@QueryMoreThanOneRecordsFound@ @C_ILCandHandler@ (@Classname@:" + handlerClass + "): " + result); }
return result.get(0); } @Override public List<I_C_ILCandHandler> retrieveForClass( final Properties ctx, @NonNull final Class<? extends IInvoiceCandidateHandler> clazz) { final String classname = clazz.getName(); final List<I_C_ILCandHandler> result = new ArrayList<>(); for (final I_C_ILCandHandler handlerDef : retrieveAll(ctx)) { if (classname.equals(handlerDef.getClassname())) { result.add(handlerDef); } } return result; } @Override public I_C_ILCandHandler retrieveFor(final I_C_Invoice_Candidate ic) { final Properties ctx = InterfaceWrapperHelper.getCtx(ic); for (final I_C_ILCandHandler handlerDef : retrieveAll(ctx)) { if (ic.getC_ILCandHandler_ID() == handlerDef.getC_ILCandHandler_ID()) { return handlerDef; } } throw new AdempiereException("Missing C_ILCandHandler return for C_ILCandHandler_ID=" + ic.getC_ILCandHandler_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateHandlerDAO.java
1
请完成以下Java代码
public static void retrieveAllDocumentsUsingFindWithObjectId() { Document document = collection.find() .first(); System.out.println(document); FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, document.get(OBJECT_ID_FIELD))); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void retrieveFirstDocumentWithObjectId() { Document document = collection.find() .first(); System.out.println(document); FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, document.get(OBJECT_ID_FIELD))); Document queriedDocument = documents.first(); System.out.println(queriedDocument); }
public static void retrieveDocumentWithRandomObjectId() { FindIterable<Document> documents = collection.find(eq(OBJECT_ID_FIELD, new ObjectId())); Document queriedDocument = documents.first(); if (queriedDocument != null) { System.out.println(queriedDocument); } else { System.out.println("No documents found"); } } public static void main(String args[]) { setUp(); retrieveAllDocumentsUsingFindWithObjectId(); retrieveFirstDocumentWithObjectId(); retrieveDocumentWithRandomObjectId(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\find\FindWithObjectId.java
1
请完成以下Java代码
public abstract class AbstractEdiDocExtensionExport<T extends I_EDI_Document_Extension> extends AbstractExport<I_EDI_Document_Extension> { public AbstractEdiDocExtensionExport(I_EDI_Document_Extension document, String tableIdentifier, ClientId expClientId) { super(document, tableIdentifier, expClientId); } protected void assertEligible(final T document) { if (!document.isEdiEnabled()) { throw new AdempiereException("@" + I_EDI_Document_Extension.COLUMNNAME_IsEdiEnabled + "@=@N@"); } // Assume document is completed/closed final String docStatus = document.getDocStatus(); if (!I_EDI_Document_Extension.DOCSTATUS_Completed.equals(docStatus) && !I_EDI_Document_Extension.DOCSTATUS_Closed.equals(docStatus)) { throw new AdempiereException("@Invalid@ @DocStatus@"); }
// Assume EDI Status is "Ready for processing" if (!I_EDI_Document_Extension.EDI_EXPORTSTATUS_Pending.equals(document.getEDI_ExportStatus()) && !I_EDI_Document_Extension.EDI_EXPORTSTATUS_Enqueued.equals(document.getEDI_ExportStatus()) // if enqueued, assume pending; we're just flagging it to avoid collisions in async && !I_EDI_Document_Extension.EDI_EXPORTSTATUS_Error.equals(document.getEDI_ExportStatus())) { throw new AdempiereException("@Invalid@ @" + I_EDI_Document_Extension.COLUMNNAME_EDI_ExportStatus + "@"); } } @SuppressWarnings("unchecked") @Override public T getDocument() { return (T)super.getDocument(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\impl\AbstractEdiDocExtensionExport.java
1
请完成以下Java代码
final class AuthorizationMethodPointcuts { static Pointcut forAllAnnotations() { return forAnnotations(PreFilter.class, PreAuthorize.class, PostFilter.class, PostAuthorize.class); } @SafeVarargs static Pointcut forAnnotations(Class<? extends Annotation>... annotations) { ComposablePointcut pointcut = null; for (Class<? extends Annotation> annotation : annotations) { if (pointcut == null) { pointcut = new ComposablePointcut(classOrMethod(annotation)); } else { pointcut.union(classOrMethod(annotation)); } } if (pointcut == null) { throw new IllegalStateException(
"Unable to find a pointcut for annotations " + Arrays.toString(annotations)); } return pointcut; } private static Pointcut classOrMethod(Class<? extends Annotation> annotation) { return Pointcuts.union(new AnnotationMatchingPointcut(null, annotation, true), new AnnotationMatchingPointcut(annotation, true)); } private AuthorizationMethodPointcuts() { } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\AuthorizationMethodPointcuts.java
1
请完成以下Java代码
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 IssueCountersByCategory { public static IssueCountersByCategory of(final Map<IssueCategory, Integer> map) { return !map.isEmpty() ? new IssueCountersByCategory(map) : EMPTY; } private static final IssueCountersByCategory EMPTY = new IssueCountersByCategory(); private final ImmutableMap<IssueCategory, Integer> map; private IssueCountersByCategory(@NonNull final Map<IssueCategory, Integer> map) { this.map = ImmutableMap.copyOf(map); }
private IssueCountersByCategory() { map = ImmutableMap.of(); } public ImmutableSet<IssueCategory> getCategories() { return map.keySet(); } public int getCountOrZero(@NonNull final IssueCategory category) { final Integer count = map.get(category); return count != null ? count : 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\IssueCountersByCategory.java
1
请完成以下Java代码
public final class Message { /** * Separator between Msg and optional Tip */ private static final String SEPARATOR = Env.NL + Env.NL; /** * Empty message */ public static final Message EMPTY = new Message(); private static final AdMessageKey EMPTY_AD_Message = AdMessageKey.of("$EMPTY$"); /** * @return instance for given message text and tip */ public static Message ofTextTipAndErrorCode( @NonNull final AdMessageId adMessageId, @NonNull final AdMessageKey adMessage, @NonNull final ImmutableTranslatableString msgText, @NonNull final ImmutableTranslatableString msgTip, @Nullable final String errorCode) { return new Message(adMessageId, adMessage, msgText, msgTip, false, errorCode); } public static Message ofMissingADMessage(@Nullable final String text) { final String textNorm = StringUtils.trimBlankToNull(text); if (textNorm == null) { return EMPTY; } return new Message( null, AdMessageKey.of(textNorm), ImmutableTranslatableString.ofDefaultValue(text), null, true, null); } @Nullable @Getter private final AdMessageId adMessageId; @NonNull @Getter private final AdMessageKey adMessage; @NonNull private final ITranslatableString msgText; @Nullable private final ITranslatableString msgTip; @NonNull private final ITranslatableString msgTextAndTip; @Getter private final boolean missing; @Getter @Nullable private String errorCode; private Message( @Nullable final AdMessageId adMessageId, @NonNull final AdMessageKey adMessage, @NonNull final ImmutableTranslatableString msgText, @Nullable final ImmutableTranslatableString msgTip, final boolean missing, @Nullable final String errorCode) { this.adMessageId = adMessageId; this.adMessage = adMessage; this.msgText = msgText; this.msgTip = msgTip; if (!TranslatableStrings.isBlank(this.msgTip)) // messageTip on next line, if exists { this.msgTextAndTip = TranslatableStrings.builder() .append(this.msgText) .append(SEPARATOR) .append(this.msgTip)
.build(); } else { this.msgTextAndTip = msgText; } this.missing = missing; this.errorCode = errorCode; } private Message() { this.adMessageId = null; this.adMessage = EMPTY_AD_Message; this.msgText = TranslatableStrings.empty(); this.msgTip = null; this.msgTextAndTip = this.msgText; this.missing = true; } public String getMsgText(@NonNull final String adLanguage) { return msgText.translate(adLanguage); } public String getMsgTip(@NonNull final String adLanguage) { return msgTip != null ? msgTip.translate(adLanguage) : ""; } public String getMsgTextAndTip(@NonNull final String adLanguage) { return msgTextAndTip.translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\Message.java
1
请完成以下Java代码
public de.metas.document.refid.model.I_C_ReferenceNo getC_ReferenceNo() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class); } @Override public void setC_ReferenceNo(de.metas.document.refid.model.I_C_ReferenceNo C_ReferenceNo) { set_ValueFromPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class, C_ReferenceNo); } /** Set Reference No. @param C_ReferenceNo_ID Reference No */ @Override public void setC_ReferenceNo_ID (int C_ReferenceNo_ID) { if (C_ReferenceNo_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID)); } /** Get Reference No. @return Reference No */ @Override public int getC_ReferenceNo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override
public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Doc.java
1
请完成以下Java代码
public class ShortTermBankAccountIndex { private final BPartnerComposite bpartnerComposite; private final HashMap<BPartnerBankAccountId, BPartnerBankAccount> bankAccountsById = new HashMap<>(); private final HashMap<String, BPartnerBankAccount> bankAccountsByIBAN = new HashMap<>(); public ShortTermBankAccountIndex(@NonNull final BPartnerComposite bpartnerComposite) { this.bpartnerComposite = bpartnerComposite; for (final BPartnerBankAccount bankAccount : bpartnerComposite.getBankAccounts()) { bankAccountsById.put(bankAccount.getId(), bankAccount); bankAccountsByIBAN.put(bankAccount.getIban(), bankAccount); } } public Collection<BPartnerBankAccount> getRemainingBankAccounts() { return bankAccountsById.values(); } public void remove(@NonNull final BPartnerBankAccountId bpartnerBankAccountId) { bankAccountsById.remove(bpartnerBankAccountId); } public BPartnerBankAccount extract(final String iban) { return bankAccountsByIBAN.get(iban);
} public BPartnerBankAccount newBankAccount(@NonNull final String iban, @NonNull final CurrencyId currencyId) { final BPartnerBankAccount bankAccount = BPartnerBankAccount.builder() .iban(iban) .currencyId(currencyId) .build(); // bankAccountsById.put(?, bankAccount); bankAccountsByIBAN.put(bankAccount.getIban(), bankAccount); bpartnerComposite.addBankAccount(bankAccount); return bankAccount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\jsonpersister\ShortTermBankAccountIndex.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerAlbertaRoleId implements RepoIdAware { @JsonCreator public static BPartnerAlbertaRoleId ofRepoId(final int repoId) { return new BPartnerAlbertaRoleId(repoId); } @Nullable public static BPartnerAlbertaRoleId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new BPartnerAlbertaRoleId(repoId) : null; } public static int toRepoId(@Nullable final BPartnerAlbertaRoleId bPartnerAlbertaRoleId) {
return bPartnerAlbertaRoleId != null ? bPartnerAlbertaRoleId.getRepoId() : -1; } int repoId; private BPartnerAlbertaRoleId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_BPartner_AlbertaRole_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\role\BPartnerAlbertaRoleId.java
2
请完成以下Java代码
public void putContextInfo( @NonNull final StockAvailabilityQueryItem queryItem, @NonNull final MSV3ArtikelContextInfo contextInfo) { contextInfosByQueryItem.put(queryItem, contextInfo); } public void putContextInfo( @NonNull final StockAvailabilityResponseItem responseItem, @NonNull final MSV3ArtikelContextInfo contextInfo) { contextInfosByResponse.put(responseItem, contextInfo); } public I_MSV3_Verfuegbarkeit_Transaction store() { final I_MSV3_Verfuegbarkeit_Transaction transactionRecord = newInstance(I_MSV3_Verfuegbarkeit_Transaction.class); transactionRecord.setAD_Org_ID(orgId.getRepoId()); final I_MSV3_VerfuegbarkeitsanfrageEinzelne verfuegbarkeitsanfrageEinzelneRecord = // availabilityDataPersister.storeAvailabilityRequest( query, ImmutableMap.copyOf(contextInfosByQueryItem)); transactionRecord.setMSV3_VerfuegbarkeitsanfrageEinzelne(verfuegbarkeitsanfrageEinzelneRecord); if (response != null) { final I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort verfuegbarkeitsanfrageEinzelneAntwortRecord = // availabilityDataPersister.storeAvailabilityResponse( response, ImmutableMap.copyOf(contextInfosByResponse)); transactionRecord.setMSV3_VerfuegbarkeitsanfrageEinzelneAntwort(verfuegbarkeitsanfrageEinzelneAntwortRecord); } if (faultInfo != null) { final I_MSV3_FaultInfo faultInfoRecord = Msv3FaultInfoDataPersister .newInstanceWithOrgId(orgId) .storeMsv3FaultInfoOrNull(faultInfo); transactionRecord.setMSV3_FaultInfo(faultInfoRecord);
} if (otherException != null) { final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(otherException); transactionRecord.setAD_Issue_ID(issueId.getRepoId()); } save(transactionRecord); return transactionRecord; } public RuntimeException getExceptionOrNull() { if (faultInfo == null && otherException == null) { return null; } return Msv3ClientException.builder().msv3FaultInfo(faultInfo) .cause(otherException).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\availability\MSV3AvailabilityTransaction.java
1
请完成以下Java代码
public String getBusinessStatus() { return businessStatus; } public String getProcessInstanceName() { return processInstanceName; } public void setProcessInstanceName(String processInstanceName) { this.processInstanceName = processInstanceName; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public Map<String, Object> getTransientVariables() { return transientVariables; } public void setTransientVariables(Map<String, Object> transientVariables) { this.transientVariables = transientVariables; } public String getInitialActivityId() { return initialActivityId; } public void setInitialActivityId(String initialActivityId) {
this.initialActivityId = initialActivityId; } public FlowElement getInitialFlowElement() { return initialFlowElement; } public void setInitialFlowElement(FlowElement initialFlowElement) { this.initialFlowElement = initialFlowElement; } public Process getProcess() { return process; } public void setProcess(Process process) { this.process = process; } public ProcessDefinition getProcessDefinition() { return processDefinition; } public void setProcessDefinition(ProcessDefinition processDefinition) { this.processDefinition = processDefinition; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\AbstractStartProcessInstanceBeforeContext.java
1
请在Spring Boot框架中完成以下Java代码
public QRCodePDFResource execute() { ImmutableList<ProcessInfoParameter> processParams; final ProcessType processType = adProcessDAO.retrieveProcessType (qrCodeProcessId); if (processType.isJasperJSON()) { processParams = ImmutableList.of( ProcessInfoParameter.of(ReportConstants.REPORT_PARAM_JSON_DATA, toJsonString(qrCodes))); } else { processParams = ImmutableList.of( ProcessInfoParameter.of("AD_PInstance_ID", pInstanceId)); } final PInstanceId processPInstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara( PInstanceRequest.builder() .processId(qrCodeProcessId) .processParams(processParams) .build()); final ProcessInfo reportProcessInfo = ProcessInfo.builder() .setCtx(Env.getCtx()) .setAD_Process_ID(qrCodeProcessId) .setPInstanceId(processPInstanceId) .setJRDesiredOutputType(OutputType.PDF) .build(); final ReportResult report = ReportsClient.get().report(reportProcessInfo); return QRCodePDFResource.builder() .data(report.getReportContent()) .filename(Optional.ofNullable(report.getReportFilename()) .orElse(extractReportFilename(reportProcessInfo))) .pinstanceId(processPInstanceId) .processId(qrCodeProcessId) .build(); } private static String toJsonString(@NonNull final List<PrintableQRCode> qrCodes)
{ try { return JsonObjectMapperHolder .sharedJsonObjectMapper() .writeValueAsString(JsonPrintableQRCodesList.builder() .qrCodes(qrCodes) .build()); } catch (final JsonProcessingException e) { throw new AdempiereException("Failed converting QR codes to JSON: " + qrCodes, e); } } @NonNull private static String extractReportFilename(@NonNull final ProcessInfo pi) { return Optional.ofNullable(pi.getTitle()) .orElseGet(() -> "report_" + PInstanceId.toRepoIdOr(pi.getPinstanceId(), 0)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.services\src\main\java\de\metas\global_qrcodes\service\CreatePDFCommand.java
2
请在Spring Boot框架中完成以下Java代码
public class InstructorDetail { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Long id; @Column(name="youtube_channel") private String youtubeChannel; @Column(name="hobby") private String hobby; public InstructorDetail() { } public InstructorDetail(String youtubeChannel, String hobby) { this.youtubeChannel = youtubeChannel; this.hobby = hobby; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getYoutubeChannel() { return youtubeChannel; }
public void setYoutubeChannel(String youtubeChannel) { this.youtubeChannel = youtubeChannel; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } @Override public String toString() { return "InstructorDetail [id=" + id + ", youtubeChannel=" + youtubeChannel + ", hobby=" + hobby + "]"; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\java\net\alanbinu\springboot\jpa\model\InstructorDetail.java
2
请完成以下Java代码
public class TodoItem { private Long id; private String description; private LocalDate dueDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
public LocalDate getDueDate() { return dueDate; } public void setDueDate(LocalDate dueDate) { this.dueDate = dueDate; } @Override public String toString() { return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]"; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-2\src\main\java\com\baeldung\core\packages\domain\TodoItem.java
1
请完成以下Java代码
private Map<String, String> generate(String task, Map<String, String> previousSuggestions, String evaluation) { String request = CODE_REVIEW_PROMPT + "\n PR: " + task + "\n previous suggestions: " + previousSuggestions + "\n evaluation on previous suggestions: " + evaluation; System.out.println("PR REVIEW PROMPT: " + request); ChatClient.ChatClientRequestSpec requestSpec = codeReviewClient.prompt(request); ChatClient.CallResponseSpec responseSpec = requestSpec.call(); Map<String, String> response = responseSpec.entity(mapClass); System.out.println("PR REVIEW OUTCOME: " + response); return response; }
private Map<String, String> evaluate(Map<String, String> latestSuggestions, String task) { String request = EVALUATE_PROPOSED_IMPROVEMENTS_PROMPT + "\n PR: " + task + "\n proposed suggestions: " + latestSuggestions; System.out.println("EVALUATION PROMPT: " + request); ChatClient.ChatClientRequestSpec requestSpec = codeReviewClient.prompt(request); ChatClient.CallResponseSpec responseSpec = requestSpec.call(); Map<String, String> response = responseSpec.entity(mapClass); System.out.println("EVALUATION OUTCOME: " + response); return response; } }
repos\tutorials-master\spring-ai-modules\spring-ai-agentic-patterns\src\main\java\com\baeldung\springai\agenticpatterns\workflows\evaluator\EvaluatorOptimizerWorkflow.java
1
请在Spring Boot框架中完成以下Java代码
public ReferenceType getRecadvReference() { return recadvReference; } /** * Sets the value of the recadvReference property. * * @param value * allowed object is * {@link ReferenceType } * */ public void setRecadvReference(ReferenceType value) { this.recadvReference = value; } /** * Gets the value of the ordrspReference property. * * @return * possible object is * {@link ReferenceType } * */ public ReferenceType getOrdrspReference() { return ordrspReference; } /** * Sets the value of the ordrspReference property. * * @param value * allowed object is * {@link ReferenceType } * */ public void setOrdrspReference(ReferenceType value) { this.ordrspReference = value; } /** * Gets the value of the contractNumber property. * * @return * possible object is * {@link String } * */ public String getContractNumber() { return contractNumber; } /** * Sets the value of the contractNumber property. * * @param value * allowed object is * {@link String } * */ public void setContractNumber(String value) { this.contractNumber = value; } /** * Gets the value of the agreementNumber property. * * @return * possible object is * {@link String } * */ public String getAgreementNumber() { return agreementNumber; } /** * Sets the value of the agreementNumber property. * * @param value * allowed object is * {@link String } * */ public void setAgreementNumber(String value) { this.agreementNumber = value; } /** * Gets the value of the timeForPayment property. * * @return * possible object is
* {@link BigInteger } * */ public BigInteger getTimeForPayment() { return timeForPayment; } /** * Sets the value of the timeForPayment property. * * @param value * allowed object is * {@link BigInteger } * */ public void setTimeForPayment(BigInteger value) { this.timeForPayment = value; } /** * Consignment reference. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference; } /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */ public void setConsignmentReference(String value) { this.consignmentReference = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\RECADVExtensionType.java
2
请完成以下Java代码
public boolean isOnHotspot(int x, int y) { // TODO: alternativa (ma funge???) //return this.checkBox.contains(x, y); return (this.checkBox.getBounds().contains(x, y)); } /** * Loads an ImageIcon from the file iconFile, searching it in the * classpath.Guarda un po' */ protected static ImageIcon loadIcon(String iconFile) { try { return new ImageIcon(DefaultCheckboxTreeCellRenderer.class.getClassLoader().getResource(iconFile)); } catch (NullPointerException npe) { // did not find the resource return null; } } @Override public void setBackground(Color color) { if (color instanceof ColorUIResource) { color = null; } super.setBackground(color); }
/** * Sets the icon used to represent non-leaf nodes that are expanded. */ public void setOpenIcon(Icon newIcon) { this.label.setOpenIcon(newIcon); } /** * Sets the icon used to represent non-leaf nodes that are not expanded. */ public void setClosedIcon(Icon newIcon) { this.label.setClosedIcon(newIcon); } /** * Sets the icon used to represent leaf nodes. */ public void setLeafIcon(Icon newIcon) { this.label.setLeafIcon(newIcon); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultCheckboxTreeCellRenderer.java
1
请在Spring Boot框架中完成以下Java代码
public void setRecipientID(String value) { this.recipientID = value; } /** * Gets the value of the interchangeRef property. * * @return * possible object is * {@link String } * */ public String getInterchangeRef() { return interchangeRef; } /** * Sets the value of the interchangeRef property. * * @param value * allowed object is * {@link String } * */ public void setInterchangeRef(String value) { this.interchangeRef = value; } /** * Gets the value of the dateTime property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDateTime() { return dateTime; } /** * Sets the value of the dateTime property.
* * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateTime(XMLGregorianCalendar value) { this.dateTime = value; } /** * Gets the value of the testIndicator property. * * @return * possible object is * {@link String } * */ public String getTestIndicator() { return testIndicator; } /** * Sets the value of the testIndicator property. * * @param value * allowed object is * {@link String } * */ public void setTestIndicator(String value) { this.testIndicator = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIMessage.java
2
请完成以下Java代码
public int getPP_Order_Cost_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Cost_ID); } /** * PP_Order_Cost_TrxType AD_Reference_ID=540941 * Reference name: PP_Order_Cost_TrxType */ public static final int PP_ORDER_COST_TRXTYPE_AD_Reference_ID=540941; /** MainProduct = MR */ public static final String PP_ORDER_COST_TRXTYPE_MainProduct = "MR"; /** MaterialIssue = MI */ public static final String PP_ORDER_COST_TRXTYPE_MaterialIssue = "MI"; /** ResourceUtilization = RU */ public static final String PP_ORDER_COST_TRXTYPE_ResourceUtilization = "RU"; /** ByProduct = BY */ public static final String PP_ORDER_COST_TRXTYPE_ByProduct = "BY"; /** CoProduct = CO */ public static final String PP_ORDER_COST_TRXTYPE_CoProduct = "CO"; @Override public void setPP_Order_Cost_TrxType (final java.lang.String PP_Order_Cost_TrxType) { set_Value (COLUMNNAME_PP_Order_Cost_TrxType, PP_Order_Cost_TrxType); } @Override public java.lang.String getPP_Order_Cost_TrxType() { return get_ValueAsString(COLUMNNAME_PP_Order_Cost_TrxType); }
@Override public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Cost.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_M_PriceList getUVP_Price_List() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UVP_Price_List_ID, org.compiere.model.I_M_PriceList.class); } @Override public void setUVP_Price_List(org.compiere.model.I_M_PriceList UVP_Price_List) { set_ValueFromPO(COLUMNNAME_UVP_Price_List_ID, org.compiere.model.I_M_PriceList.class, UVP_Price_List); } /** Set Price List UVP. @param UVP_Price_List_ID Price List UVP */ @Override public void setUVP_Price_List_ID (int UVP_Price_List_ID) { if (UVP_Price_List_ID < 1) set_Value (COLUMNNAME_UVP_Price_List_ID, null); else set_Value (COLUMNNAME_UVP_Price_List_ID, Integer.valueOf(UVP_Price_List_ID)); } /** Get Price List UVP. @return Price List UVP */ @Override public int getUVP_Price_List_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_UVP_Price_List_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_PriceList getZBV_Price_List() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class); } @Override public void setZBV_Price_List(org.compiere.model.I_M_PriceList ZBV_Price_List) { set_ValueFromPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class, ZBV_Price_List); } /** Set Price List ZBV. @param ZBV_Price_List_ID Price List ZBV */ @Override public void setZBV_Price_List_ID (int ZBV_Price_List_ID) { if (ZBV_Price_List_ID < 1) set_Value (COLUMNNAME_ZBV_Price_List_ID, null); else set_Value (COLUMNNAME_ZBV_Price_List_ID, Integer.valueOf(ZBV_Price_List_ID)); } /** Get Price List ZBV. @return Price List ZBV */ @Override public int getZBV_Price_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ZBV_Price_List_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_Product.java
1
请完成以下Java代码
public BigDecimal getWeightInKgOr(final BigDecimal minValue) {return weightInKg != null ? weightInKg.max(minValue) : minValue;} } } @Value @EqualsAndHashCode(exclude = "carrierServices") class DeliveryOrderKey { @NonNull ShipperId shipperId; @NonNull ShipperTransportationId shipperTransportationId; int fromOrgId; int deliverToBPartnerId; int deliverToBPartnerLocationId; @NonNull LocalDate pickupDate; @NonNull LocalTime timeFrom; @NonNull LocalTime timeTo; @Nullable CarrierProductId carrierProductId; @Nullable CarrierGoodsTypeId carrierGoodsTypeId; @Nullable Set<CarrierServiceId> carrierServices; AsyncBatchId asyncBatchId; @Builder public DeliveryOrderKey( @NonNull final ShipperId shipperId, @NonNull final ShipperTransportationId shipperTransportationId, final int fromOrgId, final int deliverToBPartnerId, final int deliverToBPartnerLocationId, @NonNull final LocalDate pickupDate, @NonNull final LocalTime timeFrom, @NonNull final LocalTime timeTo, @Nullable final CarrierProductId carrierProductId, @Nullable final CarrierGoodsTypeId carrierGoodsTypeId, @Nullable final Set<CarrierServiceId> carrierServices, @Nullable final AsyncBatchId asyncBatchId) { Check.assume(fromOrgId > 0, "fromOrgId > 0");
Check.assume(deliverToBPartnerId > 0, "deliverToBPartnerId > 0"); Check.assume(deliverToBPartnerLocationId > 0, "deliverToBPartnerLocationId > 0"); this.shipperId = shipperId; this.shipperTransportationId = shipperTransportationId; this.fromOrgId = fromOrgId; this.deliverToBPartnerId = deliverToBPartnerId; this.deliverToBPartnerLocationId = deliverToBPartnerLocationId; this.pickupDate = pickupDate; this.timeFrom = timeFrom; this.timeTo = timeTo; this.carrierProductId = carrierProductId; this.carrierGoodsTypeId = carrierGoodsTypeId; this.carrierServices = carrierServices; this.asyncBatchId = asyncBatchId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\DraftDeliveryOrderCreator.java
1
请完成以下Java代码
public Optional<Long> getLongValue() { return Optional.ofNullable(null); } @Override public Optional<Boolean> getBooleanValue() { return Optional.ofNullable(null); } @Override public Optional<Double> getDoubleValue() { return Optional.ofNullable(null); } @Override public Optional<String> getJsonValue() { return Optional.ofNullable(null); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BasicKvEntry)) return false;
BasicKvEntry that = (BasicKvEntry) o; return Objects.equals(key, that.key); } @Override public int hashCode() { return Objects.hash(key); } @Override public String toString() { return "BasicKvEntry{" + "key='" + key + '\'' + '}'; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicKvEntry.java
1
请完成以下Java代码
private AvailableForSaleResultGroupBuilder newGroup( @NonNull final AddToResultGroupRequest request, @NonNull final AttributesKey storageAttributesKey) { final AvailableForSaleResultGroupBuilder group = AvailableForSaleResultGroupBuilder.builder() .productId(request.getProductId()) .storageAttributesKey(storageAttributesKey) .warehouseId(request.getWarehouseId()) .build(); groups.add(group); return group; } public void addDefaultEmptyGroupIfPossible() { if (product.isAny()) { return; } final AttributesKey defaultAttributesKey = this.storageAttributesKeyMatcher.toAttributeKeys().orElse(null); if (defaultAttributesKey == null) {
return; } final WarehouseId warehouseId = warehouse.getWarehouseId(); if (warehouseId == null) { return; } final AvailableForSaleResultGroupBuilder group = AvailableForSaleResultGroupBuilder.builder() .productId(ProductId.ofRepoId(product.getProductId())) .storageAttributesKey(defaultAttributesKey) .warehouseId(warehouseId) .build(); groups.add(group); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSaleResultBucket.java
1
请完成以下Java代码
public static Dimension computeScaledDimension(final Dimension size, final Dimension maxSize) { // credits: http://stackoverflow.com/questions/10245220/java-image-resize-maintain-aspect-ratio final int widthOrig = size.width; final int heightOrig = size.height; final int widthMax = maxSize.width; final int heightMax = maxSize.height; int widthNew; int heightNew; // first check if we need to scale width if (widthMax > 0 && widthOrig > widthMax) { // scale width to fit widthNew = widthMax; // scale height to maintain aspect ratio heightNew = widthNew * heightOrig / widthOrig; } else { widthNew = widthOrig; heightNew = heightOrig; } // then check if we need to scale even with the new height if (heightMax > 0 && heightNew > heightMax) { // scale height to fit instead
heightNew = heightMax; // scale width to maintain aspect ratio widthNew = heightNew * widthOrig / heightOrig; } return new Dimension(widthNew, heightNew); } private static String computeImageFormatNameByContentType(@NonNull final String contentType) { final String fileExtension = MimeType.getExtensionByTypeWithoutDot(contentType); if (Check.isEmpty(fileExtension)) { return "png"; } return fileExtension; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\image\AdImage.java
1
请完成以下Java代码
public AuthorRecord value4(Integer value) { setAge(value); return this; } @Override public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached AuthorRecord */ public AuthorRecord() {
super(Author.AUTHOR); } /** * Create a detached, initialised AuthorRecord */ public AuthorRecord(Integer id, String firstName, String lastName, Integer age) { super(Author.AUTHOR); set(0, id); set(1, firstName); set(2, lastName); set(3, age); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java
1
请完成以下Java代码
public String getLastFailureLogId() { return lastFailureLogId; } public void setLastFailureLogId(String lastFailureLogId) { this.lastFailureLogId = lastFailureLogId; } @Override public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } @Override public String toString() { return this.getClass().getSimpleName()
+ "[id=" + id + ", revision=" + revision + ", duedate=" + duedate + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", jobDefinitionId=" + jobDefinitionId + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", failedActivityId=" + failedActivityId + ", deploymentId=" + deploymentId + ", priority=" + priority + ", tenantId=" + tenantId + ", batchId=" + batchId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobEntity.java
1
请完成以下Java代码
public DbOperation addRemovalTimeToIdentityLinkLogByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricIdentityLinkLogEventEntity.class, "updateIdentityLinkLogByProcessInstanceId", parameters); } public void deleteHistoricIdentityLinksLogByProcessDefinitionId(String processDefId) { if (isHistoryEventProduced()) { getDbEntityManager().delete(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinksByProcessDefinitionId", processDefId); } } public void deleteHistoricIdentityLinksLogByTaskId(String taskId) { if (isHistoryEventProduced()) { getDbEntityManager().delete(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinksByTaskId", taskId); } } public void deleteHistoricIdentityLinksLogByTaskProcessInstanceIds(List<String> processInstanceIds) { getDbEntityManager().deletePreserveOrder(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinksByTaskProcessInstanceIds", processInstanceIds); } public void deleteHistoricIdentityLinksLogByTaskCaseInstanceIds(List<String> caseInstanceIds) { getDbEntityManager().deletePreserveOrder(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinksByTaskCaseInstanceIds", caseInstanceIds); } public DbOperation deleteHistoricIdentityLinkLogByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinkLogByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } protected void configureQuery(HistoricIdentityLinkLogQueryImpl query) { getAuthorizationManager().configureHistoricIdentityLinkQuery(query); getTenantManager().configureQuery(query); } protected boolean isHistoryEventProduced() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); return historyLevel.isHistoryEventProduced(HistoryEventTypes.IDENTITY_LINK_ADD, null) || historyLevel.isHistoryEventProduced(HistoryEventTypes.IDENTITY_LINK_DELETE, null); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricIdentityLinkLogManager.java
1
请在Spring Boot框架中完成以下Java代码
public Greeting greetWithPathVariable(@PathVariable("name") String name) { Greeting greeting = new Greeting(); greeting.setId(1); greeting.setMessage("Hello World " + name + "!!!"); return greeting; } @RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Greeting greetWithQueryVariable(@RequestParam("name") String name) { Greeting greeting = new Greeting(); greeting.setId(1); greeting.setMessage("Hello World " + name + "!!!"); return greeting; } @RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json") @ResponseBody public Greeting greetWithPost() {
Greeting greeting = new Greeting(); greeting.setId(1); greeting.setMessage("Hello World!!!"); return greeting; } @RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json") @ResponseBody public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) { Greeting greeting = new Greeting(); greeting.setId(id); greeting.setMessage("Hello World " + name + "!!!"); return greeting; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\web\controller\GreetController.java
2
请完成以下Java代码
public CleanableHistoricCaseInstanceReport tenantIdIn(String... tenantIds) { ensureNotNull(NotValidException.class, "", "tenantIdIn", (Object[]) tenantIds); this.tenantIdIn = tenantIds; isTenantIdSet = true; return this; } @Override public CleanableHistoricCaseInstanceReport withoutTenantId() { this.tenantIdIn = null; isTenantIdSet = true; return this; } @Override public CleanableHistoricCaseInstanceReport compact() { this.isCompact = true; return this; } @Override public CleanableHistoricCaseInstanceReport orderByFinished() { orderBy(CleanableHistoricInstanceReportProperty.FINISHED_AMOUNT); return this; } @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricCaseInstanceManager() .findCleanableHistoricCaseInstancesReportCountByCriteria(this); } @Override public List<CleanableHistoricCaseInstanceReportResult> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricCaseInstanceManager() .findCleanableHistoricCaseInstancesReportByCriteria(this, page); }
public String[] getCaseDefinitionIdIn() { return caseDefinitionIdIn; } public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) { this.caseDefinitionIdIn = caseDefinitionIdIn; } public String[] getCaseDefinitionKeyIn() { return caseDefinitionKeyIn; } public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) { this.caseDefinitionKeyIn = caseDefinitionKeyIn; } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isCompact() { return isCompact; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricCaseInstanceReportImpl.java
1
请完成以下Java代码
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { log.debug("logAround running ....."); if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e;
} } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "execution(* net.alanbinu.springboot2.springboot2jpacrudexample.service.EmployeeService.updateEmployee(..))", throwing = "error") public void logAfterThrowing(JoinPoint joinPoint, Throwable error) { log.debug("logAfterThrowing running ....."); log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), error.getCause() != null ? error.getCause() : "NULL"); } }
repos\Spring-Boot-Advanced-Projects-main\spring-aop-advice-examples\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\aspect\LoggingAspect.java
1
请完成以下Java代码
public class LogoutWebFilter implements WebFilter { private static final Log logger = LogFactory.getLog(LogoutWebFilter.class); private AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken("key", "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); private ServerLogoutHandler logoutHandler = new SecurityContextServerLogoutHandler(); private ServerLogoutSuccessHandler logoutSuccessHandler = new RedirectServerLogoutSuccessHandler(); private ServerWebExchangeMatcher requiresLogout = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/logout"); @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return this.requiresLogout.matches(exchange) .filter((result) -> result.isMatch()) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .map((result) -> exchange) .flatMap(this::flatMapAuthentication) .flatMap((authentication) -> { WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain); return logout(webFilterExchange, authentication); }); } private Mono<Authentication> flatMapAuthentication(ServerWebExchange exchange) { return exchange.getPrincipal().cast(Authentication.class).defaultIfEmpty(this.anonymousAuthenticationToken); } private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) { logger.debug(LogMessage.format("Logging out user '%s' and transferring to logout destination", authentication)); return this.logoutHandler.logout(webFilterExchange, authentication) .then(this.logoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.clearContext()); } /** * Sets the {@link ServerLogoutSuccessHandler}. The default is * {@link RedirectServerLogoutSuccessHandler}. * @param logoutSuccessHandler the handler to use
*/ public void setLogoutSuccessHandler(ServerLogoutSuccessHandler logoutSuccessHandler) { Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null"); this.logoutSuccessHandler = logoutSuccessHandler; } /** * Sets the {@link ServerLogoutHandler}. The default is * {@link SecurityContextServerLogoutHandler}. * @param logoutHandler The handler to use */ public void setLogoutHandler(ServerLogoutHandler logoutHandler) { Assert.notNull(logoutHandler, "logoutHandler must not be null"); this.logoutHandler = logoutHandler; } public void setRequiresLogoutMatcher(ServerWebExchangeMatcher requiresLogoutMatcher) { Assert.notNull(requiresLogoutMatcher, "requiresLogoutMatcher must not be null"); this.requiresLogout = requiresLogoutMatcher; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\logout\LogoutWebFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class Article { @Id private Long id; private String article; private Article() { } @PersistenceConstructor public Article(Long id, String article) { super(); this.id = id; this.article = article; } @Override public String toString() { return "Article [id=" + id + ", article=" + article + "]"; }
public Long getArticleId() { return id; } public void setArticleId(Long id) { this.id = id; } public String getArticle() { return article; } public void setArticle(String article) { this.article = article; } }
repos\tutorials-master\vertx-modules\spring-vertx\src\main\java\com\baeldung\vertxspring\entity\Article.java
2
请完成以下Spring Boot application配置
spring: # Kafka 配置项,对应 KafkaProperties 配置类 kafka: bootstrap-servers: 127.0.0.1:9092 # 指定 Kafka Broker 地址,可以设置多个,以逗号分隔 # Kafka Producer 配置项 producer: acks: 1 # 0-不应答。1-leader 应答。all-所有 leader 和 follower 应答。 retries: 3 # 发送失败时,重试发送的次数 key-serializer: org.apache.kafka.common.serialization.StringSerializer # 消息的 key 的序列化 value-serializer: org.springframework.kafka.support.serializer.JsonSerializer # 消息的 value 的序列化 batch-size: 16384 # 每次批量发送消息的最大数量 buffer-memory: 33554432 # 每次批量发送消息的最大内存 properties: linger: ms: 30000 # 批处理延迟时间上限。这里配置为 30 * 1000 ms 过后,不管是否消息数量是否到达 batch-size 或者消息大小到达 buffer-memory 后,都直接发送一次请求。 # Kafka Consumer 配置项 consumer: auto-offset-reset: earliest # 设置消费者分组最初的消费进度为 earliest 。可参考博客 https://blog.csdn.net/lishuangzhe7047/article/details/74530417 理解 key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer prope
rties: spring: json: trusted: packages: cn.iocoder.springboot.lab03.kafkademo.message # Kafka Consumer Listener 监听器配置 listener: missing-topics-fatal: false # 消费监听接口监听的主题不存在时,默认会报错。所以通过设置为 false ,解决报错 logging: level: org: springframework: kafka: ERROR # spring-kafka INFO 日志太多了,所以我们限制只打印 ERROR 级别 apache: kafka: ERROR # kafka INFO 日志太多了,所以我们限制只打印 ERROR 级别
repos\SpringBoot-Labs-master\lab-03-kafka\lab-03-kafka-demo-batch\src\main\resources\application.yaml
2
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId;
} public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public static AttachmentDto fromAttachment(Attachment attachment) { AttachmentDto dto = new AttachmentDto(); dto.id = attachment.getId(); dto.name = attachment.getName(); dto.type = attachment.getType(); dto.description = attachment.getDescription(); dto.taskId = attachment.getTaskId(); dto.url = attachment.getUrl(); dto.createTime = attachment.getCreateTime(); dto.removalTime = attachment.getRemovalTime(); dto.rootProcessInstanceId = attachment.getRootProcessInstanceId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\AttachmentDto.java
1
请完成以下Java代码
public String rate(final ICalloutField field) { // NOTE: atm this method is used only by UOMConversions. When we will provide an implementation for that, we can get rid of this shit. final Object value = field.getValue(); if (isCalloutActive() || value == null) { return NO_ERROR; } final BigDecimal rate1 = (BigDecimal)value; BigDecimal rate2 = BigDecimal.ZERO; final BigDecimal one = BigDecimal.ONE; if (rate1.signum() != 0) { rate2 = one.divide(rate1, 12, BigDecimal.ROUND_HALF_UP);
} // final String columnName = field.getColumnName(); final Object model = field.getModel(Object.class); if ("MultiplyRate".equals(columnName)) { InterfaceWrapperHelper.setValue(model, "DivideRate", rate2); } else { InterfaceWrapperHelper.setValue(model, "MultiplyRate", rate2); } log.info("columnName={}; value={} => result={}", columnName, rate1, rate2); return NO_ERROR; } // rate } // CalloutEngine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutEngine.java
1
请在Spring Boot框架中完成以下Java代码
public GitIgnore gitIgnore(ObjectProvider<GitIgnoreCustomizer> gitIgnoreCustomizers) { GitIgnore gitIgnore = createGitIgnore(); gitIgnoreCustomizers.orderedStream().forEach((customizer) -> customizer.customize(gitIgnore)); return gitIgnore; } @Bean GitAttributesContributor gitAttributesContributor(GitAttributes gitAttributes) { return new GitAttributesContributor(gitAttributes); } @Bean GitAttributes gitAttributes(ObjectProvider<GitAttributesCustomizer> gitAttributesCustomizers) { GitAttributes gitAttributes = new GitAttributes(); gitAttributesCustomizers.orderedStream().forEach((customizer) -> customizer.customize(gitAttributes)); return gitAttributes; } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public GitIgnoreCustomizer mavenGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add("target/", ".mvn/wrapper/maven-wrapper.jar", "!**/src/main/**/target/", "!**/src/test/**/target/"); gitIgnore.getNetBeans().add("build/", "!**/src/main/**/build/", "!**/src/test/**/build/"); }; } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitIgnoreCustomizer gradleGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add(".gradle", "build/", "!gradle/wrapper/gradle-wrapper.jar", "!**/src/main/**/build/", "!**/src/test/**/build/"); gitIgnore.getIntellijIdea().add("out/", "!**/src/main/**/out/", "!**/src/test/**/out/"); gitIgnore.getSts().add("bin/", "!**/src/main/**/bin/", "!**/src/test/**/bin/"); }; } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public GitAttributesCustomizer mavenGitAttributesCustomizer() { return (gitAttributes) -> { gitAttributes.add("/mvnw", "text", "eol=lf"); gitAttributes.add("*.cmd", "text", "eol=crlf"); };
} @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitAttributesCustomizer gradleGitAttributesCustomizer() { return (gitAttributes) -> { gitAttributes.add("/gradlew", "text", "eol=lf"); gitAttributes.add("*.bat", "text", "eol=crlf"); gitAttributes.add("*.jar", "binary"); }; } private GitIgnore createGitIgnore() { GitIgnore gitIgnore = new GitIgnore(); gitIgnore.getSts() .add(".apt_generated", ".classpath", ".factorypath", ".project", ".settings", ".springBeans", ".sts4-cache"); gitIgnore.getIntellijIdea().add(".idea", "*.iws", "*.iml", "*.ipr"); gitIgnore.getNetBeans().add("/nbproject/private/", "/nbbuild/", "/dist/", "/nbdist/", "/.nb-gradle/"); gitIgnore.getVscode().add(".vscode/"); return gitIgnore; } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitProjectGenerationConfiguration.java
2
请完成以下Java代码
public void generateAndSetUUID(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (grsConfig.getCamelHttpResourceAuthKey() == null) { grsConfig.setCamelHttpResourceAuthKey(UUID.randomUUID().toString()); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW }) public void createExternalSystemInstance(final I_ExternalSystem_Config_GRSSignum grsConfig) { final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(grsConfig.getExternalSystem_Config_ID()); externalServices.initializeServiceInstancesIfRequired(parentConfigId); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsSyncBPartnersToRestEndpoint) public void updateIsAutoFlag(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (!grsConfig.isSyncBPartnersToRestEndpoint()) { grsConfig.setIsAutoSendVendors(false); grsConfig.setIsAutoSendCustomers(false); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = {
I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsCreateBPartnerFolders, I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BasePathForExportDirectories, I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BPartnerExportDirectories }) public void checkIsCreateBPartnerFoldersFlag(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (!grsConfig.isCreateBPartnerFolders()) { return; } if (Check.isBlank(grsConfig.getBPartnerExportDirectories()) || Check.isBlank(grsConfig.getBasePathForExportDirectories())) { throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!") .appendParametersToMessage() .setParameter("ExternalSystem_Config_GRSSignum_ID", grsConfig.getExternalSystem_Config_GRSSignum_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\interceptor\ExternalSystem_Config_GRSSignum.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); }
/** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Disposed.java
1
请完成以下Java代码
public String getKeyword () { return (String)get_Value(COLUMNNAME_Keyword); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getKeyword()); } /** Set Index. @param K_INDEX_ID Text Search Index */ public void setK_INDEX_ID (int K_INDEX_ID) { if (K_INDEX_ID < 1) set_ValueNoCheck (COLUMNNAME_K_INDEX_ID, null); else set_ValueNoCheck (COLUMNNAME_K_INDEX_ID, Integer.valueOf(K_INDEX_ID)); } /** Get Index. @return Text Search Index */ public int getK_INDEX_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_INDEX_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Source Updated. @param SourceUpdated Date the source document was updated */ public void setSourceUpdated (Timestamp SourceUpdated) { set_Value (COLUMNNAME_SourceUpdated, SourceUpdated); } /** Get Source Updated. @return Date the source document was updated */ public Timestamp getSourceUpdated () { return (Timestamp)get_Value(COLUMNNAME_SourceUpdated); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Index.java
1
请完成以下Java代码
public String toString() { return "all public fields"; } @Override public boolean test(final DocumentFieldChange field) { return field.isPublicField(); } }; private static final class FILTER_DocumentFieldView_ByFieldNamesSet implements Predicate<IDocumentFieldView> { private final Set<String> fieldNamesSet; private final Predicate<IDocumentFieldView> parentFilter; private FILTER_DocumentFieldView_ByFieldNamesSet(final Set<String> fieldNamesSet, final Predicate<IDocumentFieldView> parentFilter) { super(); this.fieldNamesSet = fieldNamesSet; this.parentFilter = parentFilter; } @Override public String toString() { return "field name in " + fieldNamesSet + " and " + parentFilter; } @Override public boolean test(final IDocumentFieldView field) { if (!fieldNamesSet.contains(field.getFieldName())) { return false; } return parentFilter.test(field); } } private static final class FILTER_DocumentFieldChange_ByFieldNamesSet implements Predicate<DocumentFieldChange> { private final Set<String> fieldNamesSet;
private final Predicate<DocumentFieldChange> parentFilter; private FILTER_DocumentFieldChange_ByFieldNamesSet(final Set<String> fieldNamesSet, final Predicate<DocumentFieldChange> parentFilter) { super(); this.fieldNamesSet = fieldNamesSet; this.parentFilter = parentFilter; } @Override public String toString() { return "field name in " + fieldNamesSet + " and " + parentFilter; } @Override public boolean test(final DocumentFieldChange field) { if (!fieldNamesSet.contains(field.getFieldName())) { return false; } return parentFilter.test(field); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentOptions.java
1
请在Spring Boot框架中完成以下Java代码
public LocalDate getCopaymentToDate() { return copaymentToDate; } public void setCopaymentToDate(LocalDate copaymentToDate) { this.copaymentToDate = copaymentToDate; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientPayer patientPayer = (PatientPayer) o; return Objects.equals(this.payerId, patientPayer.payerId) && Objects.equals(this.payerType, patientPayer.payerType) && Objects.equals(this.numberOfInsured, patientPayer.numberOfInsured) && Objects.equals(this.copaymentFromDate, patientPayer.copaymentFromDate) && Objects.equals(this.copaymentToDate, patientPayer.copaymentToDate); } @Override public int hashCode() { return Objects.hash(payerId, payerType, numberOfInsured, copaymentFromDate, copaymentToDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientPayer {\n");
sb.append(" payerId: ").append(toIndentedString(payerId)).append("\n"); sb.append(" payerType: ").append(toIndentedString(payerType)).append("\n"); sb.append(" numberOfInsured: ").append(toIndentedString(numberOfInsured)).append("\n"); sb.append(" copaymentFromDate: ").append(toIndentedString(copaymentFromDate)).append("\n"); sb.append(" copaymentToDate: ").append(toIndentedString(copaymentToDate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientPayer.java
2
请完成以下Java代码
private JSONLookupValuesList toJSONLookupValuesList(final LookupValuesList lookupValuesList) { return JSONLookupValuesList.ofLookupValuesList(lookupValuesList, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } private JSONLookupValue toJSONLookupValue(final LookupValue lookupValue) { return JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } @GetMapping("/{asiDocId}/field/{attributeName}/dropdown") public JSONLookupValuesList getAttributeDropdown( @PathVariable("asiDocId") final String asiDocIdStr, @PathVariable("attributeName") final String attributeName) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return forASIDocumentReadonly(asiDocId, asiDoc -> asiDoc.getFieldLookupValues(attributeName)) .transform(this::toJSONLookupValuesList); } @PostMapping(value = "/{asiDocId}/complete") public JSONLookupValue complete( @PathVariable("asiDocId") final String asiDocIdStr, @RequestBody final JSONCompleteASIRequest request)
{ userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return Execution.callInNewExecution("complete", () -> completeInTrx(asiDocId, request)) .transform(this::toJSONLookupValue); } private LookupValue completeInTrx(final DocumentId asiDocId, final JSONCompleteASIRequest request) { return asiRepo.forASIDocumentWritable( asiDocId, NullDocumentChangesCollector.instance, documentsCollection, asiDoc -> { final List<JSONDocumentChangedEvent> events = request.getEvents(); if (events != null && !events.isEmpty()) { asiDoc.processValueChanges(events, REASON_ProcessASIDocumentChanges); } return asiDoc.complete(); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRestController.java
1
请完成以下Java代码
public class ExecutorRouteBusyover extends ExecutorRouter { @Override public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) { StringBuffer idleBeatResultSB = new StringBuffer(); for (String address : addressList) { // beat ReturnT<String> idleBeatResult = null; try { ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(address); idleBeatResult = executorBiz.idleBeat(new IdleBeatParam(triggerParam.getJobId())); } catch (Exception e) { logger.error(e.getMessage(), e); idleBeatResult = new ReturnT<String>(ReturnT.FAIL_CODE, ""+e ); } idleBeatResultSB.append( (idleBeatResultSB.length()>0)?"<br><br>":"") .append(I18nUtil.getString("jobconf_idleBeat") + ":")
.append("<br>address:").append(address) .append("<br>code:").append(idleBeatResult.getCode()) .append("<br>msg:").append(idleBeatResult.getMsg()); // beat success if (idleBeatResult.getCode() == ReturnT.SUCCESS_CODE) { idleBeatResult.setMsg(idleBeatResultSB.toString()); idleBeatResult.setContent(address); return idleBeatResult; } } return new ReturnT<String>(ReturnT.FAIL_CODE, idleBeatResultSB.toString()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\route\strategy\ExecutorRouteBusyover.java
1
请完成以下Java代码
public void setNetDays (int NetDays) { set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays)); } /** Get Net Days. @return Net Days in which payment is due */ public int getNetDays () { Integer ii = (Integer)get_Value(COLUMNNAME_NetDays); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param Qty Quantity */ public void setQty (int Qty)
{ set_Value (COLUMNNAME_Qty, Integer.valueOf(Qty)); } /** Get Quantity. @return Quantity */ public int getQty () { Integer ii = (Integer)get_Value(COLUMNNAME_Qty); if (ii == null) return 0; return ii.intValue(); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Year.java
1
请完成以下Java代码
public class TextCapability extends ServiceCapability<String> { private String content; @JsonCreator TextCapability(@JsonProperty("id") String id) { this(id, null, null); } /** * Creates a new instance. * @param id the id of this capability * @param title the title of this capability * @param description the description of this capability */ public TextCapability(String id, String title, String description) { super(id, ServiceCapabilityType.TEXT, title, description); } @Override public String getContent() {
return this.content; } public void setContent(String content) { this.content = content; } @Override public void merge(String otherContent) { if (otherContent != null) { this.content = otherContent; } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\TextCapability.java
1
请完成以下Java代码
public void setPriceList(final BigDecimal priceList) { this.priceList = priceList; this.priceListSet = true; } public void setPriceStd(final BigDecimal priceStd) { this.priceStd = priceStd; } public void setSeqNo(final Integer seqNo) { this.seqNo = seqNo; this.seqNoSet = true; } public void setTaxCategory(final TaxCategory taxCategory) { this.taxCategory = taxCategory; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setUomCode(final String uomCode) { this.uomCode = uomCode; this.uomCodeSet = true;
} @NonNull public String getOrgCode() { return orgCode; } @NonNull public String getProductIdentifier() { return productIdentifier; } @NonNull public TaxCategory getTaxCategory() { return taxCategory; } @NonNull public BigDecimal getPriceStd() { return priceStd; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonRequestProductPrice.java
1
请在Spring Boot框架中完成以下Java代码
public class ResourceType { @NonNull ResourceTypeId id; @NonNull ITranslatableString caption; @Getter(AccessLevel.PRIVATE) boolean active; @NonNull ProductCategoryId productCategoryId; @NonNull UomId durationUomId; @NonNull TemporalUnit durationUnit; @NonNull @Getter(AccessLevel.NONE) ImmutableSet<DayOfWeek> availableDaysOfWeek; boolean timeSlot; LocalTime timeSlotStart; LocalTime timeSlotEnd; /** * Get how many hours/day a is available. * Minutes, secords and millis are discarded. * * @return available hours */ public int getTimeSlotInHours() { if (isTimeSlot()) { return (int)Duration.between(timeSlotStart, timeSlotEnd).toHours(); } else { return 24; } } public boolean isAvailable() { return isActive() && getAvailableDaysPerWeek() > 0 && getTimeSlotInHours() > 0; } public boolean isDayAvailable(final Instant date) { return isActive() && isDayAvailable(date.atZone(SystemTime.zoneId()).getDayOfWeek()); } public int getAvailableDaysPerWeek() { return availableDaysOfWeek.size(); } public boolean isDayAvailable(@NonNull final DayOfWeek dayOfWeek) { return availableDaysOfWeek.contains(dayOfWeek); } @Deprecated public Timestamp getDayStart(final Timestamp date) { final Instant dayStart = getDayStart(date.toInstant()); return Timestamp.from(dayStart); } public Instant getDayStart(@NonNull final Instant date) { return getDayStart(date.atZone(SystemTime.zoneId())).toInstant(); } public LocalDateTime getDayStart(final LocalDateTime date)
{ return getDayStart(date.atZone(SystemTime.zoneId())).toLocalDateTime(); } public ZonedDateTime getDayStart(final ZonedDateTime date) { if (isTimeSlot()) { return date.toLocalDate().atTime(getTimeSlotStart()).atZone(date.getZone()); } else { return date.toLocalDate().atStartOfDay().atZone(date.getZone()); } } @Deprecated public Timestamp getDayEnd(final Timestamp date) { final LocalDateTime dayEnd = getDayEnd(TimeUtil.asLocalDateTime(date)); return TimeUtil.asTimestamp(dayEnd); } public Instant getDayEnd(final Instant date) { return getDayEnd(date.atZone(SystemTime.zoneId())).toInstant(); } public LocalDateTime getDayEnd(final LocalDateTime date) { return getDayEnd(date.atZone(SystemTime.zoneId())).toLocalDateTime(); } public ZonedDateTime getDayEnd(final ZonedDateTime date) { if (isTimeSlot()) { return date.toLocalDate().atTime(timeSlotEnd).atZone(date.getZone()); } else { return date.toLocalDate().atTime(LocalTime.MAX).atZone(date.getZone()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ResourceType.java
2
请在Spring Boot框架中完成以下Java代码
public City findCityById(Long id) { // 从缓存中获取城市信息 String key = "city_" + id; ValueOperations<String, City> operations = redisTemplate.opsForValue(); // 缓存存在 boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { City city = operations.get(key); LOGGER.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString()); return city; } // 从 DB 中获取城市信息 City city = cityDao.findById(id); // 插入缓存 operations.set(key, city, 10, TimeUnit.SECONDS); LOGGER.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + city.toString()); return city; } @Override public Long saveCity(City city) { return cityDao.saveCity(city); } /** * 更新城市逻辑: * 如果缓存存在,删除 * 如果缓存不存在,不操作 */ @Override public Long updateCity(City city) { Long ret = cityDao.updateCity(city); // 缓存存在,删除缓存 String key = "city_" + city.getId(); boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) { redisTemplate.delete(key); LOGGER.info("CityServiceImpl.updateCity() : 从缓存中删除城市 >> " + city.toString()); } return ret; } @Override public Long deleteCity(Long id) { Long ret = cityDao.deleteCity(id); // 缓存存在,删除缓存 String key = "city_" + id; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); LOGGER.info("CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> " + id); } return ret; } }
repos\springboot-learning-example-master\springboot-mybatis-redis\src\main\java\org\spring\springboot\service\impl\CityServiceImpl.java
2
请完成以下Java代码
public class MWebProject extends X_CM_WebProject { /** * */ private static final long serialVersionUID = -7404800005095450170L; /** * Get MWebProject from Cache * @param ctx context * @param CM_WebProject_ID id * @return MWebProject */ public static MWebProject get (Properties ctx, int CM_WebProject_ID) { Integer key = new Integer (CM_WebProject_ID); MWebProject retValue = (MWebProject)s_cache.get (key); if (retValue != null) return retValue; retValue = new MWebProject (ctx, CM_WebProject_ID, null); if (retValue.get_ID () == CM_WebProject_ID) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MWebProject> s_cache = new CCache<Integer, MWebProject> ("CM_WebProject", 5); /************************************************************************** * Web Project * @param ctx context * @param CM_WebProject_ID id * @param trxName transaction */ public MWebProject (Properties ctx, int CM_WebProject_ID, String trxName) { super (ctx, CM_WebProject_ID, trxName); } // MWebProject /** * Web Project * @param ctx context * @param rs result set * @param trxName transaction */ public MWebProject (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MWebProject /** * Before Save * @param newRecord new
* @return true */ protected boolean beforeSave (boolean newRecord) { // Create Trees if (newRecord) { MTree_Base tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMContainer, MTree_Base.TREETYPE_CMContainer, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMC_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMContainerStage, MTree_Base.TREETYPE_CMContainerStage, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMS_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMTemplate, MTree_Base.TREETYPE_CMTemplate, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMT_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMMedia, MTree_Base.TREETYPE_CMMedia, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMM_ID(tree.getAD_Tree_ID()); } return true; } // beforeSave /** * After Save. * Insert * - create tree * @param newRecord insert * @param success save success * @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (!newRecord) { // Clean Web Project Cache } return success; } // afterSave } // MWebProject
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWebProject.java
1
请完成以下Java代码
public RemittanceAmount1 createRemittanceAmount1() { return new RemittanceAmount1(); } /** * Create an instance of {@link RemittanceInformation5CH } * */ public RemittanceInformation5CH createRemittanceInformation5CH() { return new RemittanceInformation5CH(); } /** * Create an instance of {@link ServiceLevel8Choice } * */ public ServiceLevel8Choice createServiceLevel8Choice() { return new ServiceLevel8Choice(); } /** * Create an instance of {@link StructuredRegulatoryReporting3 } * */ public StructuredRegulatoryReporting3 createStructuredRegulatoryReporting3() { return new StructuredRegulatoryReporting3(); } /** * Create an instance of {@link StructuredRemittanceInformation7 }
* */ public StructuredRemittanceInformation7 createStructuredRemittanceInformation7() { return new StructuredRemittanceInformation7(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "http://www.six-interbank-clearing.com/de/pain.001.001.03.ch.02.xsd", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ObjectFactory.java
1
请完成以下Java代码
public class X_C_PO_OrderLine_Alloc extends org.compiere.model.PO implements I_C_PO_OrderLine_Alloc, org.compiere.model.I_Persistent { private static final long serialVersionUID = -797670499L; /** Standard Constructor */ public X_C_PO_OrderLine_Alloc (final Properties ctx, final int C_PO_OrderLine_Alloc_ID, @Nullable final String trxName) { super (ctx, C_PO_OrderLine_Alloc_ID, trxName); } /** Load Constructor */ public X_C_PO_OrderLine_Alloc (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_PO_OrderLine_Alloc_ID (final int C_PO_OrderLine_Alloc_ID) { if (C_PO_OrderLine_Alloc_ID < 1) set_ValueNoCheck (COLUMNNAME_C_PO_OrderLine_Alloc_ID, null); else set_ValueNoCheck (COLUMNNAME_C_PO_OrderLine_Alloc_ID, C_PO_OrderLine_Alloc_ID); } @Override public int getC_PO_OrderLine_Alloc_ID() { return get_ValueAsInt(COLUMNNAME_C_PO_OrderLine_Alloc_ID); } @Override public org.compiere.model.I_C_OrderLine getC_PO_OrderLine() { return get_ValueAsPO(COLUMNNAME_C_PO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_PO_OrderLine(final org.compiere.model.I_C_OrderLine C_PO_OrderLine) { set_ValueFromPO(COLUMNNAME_C_PO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_PO_OrderLine); }
@Override public void setC_PO_OrderLine_ID (final int C_PO_OrderLine_ID) { if (C_PO_OrderLine_ID < 1) set_Value (COLUMNNAME_C_PO_OrderLine_ID, null); else set_Value (COLUMNNAME_C_PO_OrderLine_ID, C_PO_OrderLine_ID); } @Override public int getC_PO_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_PO_OrderLine_ID); } @Override public org.compiere.model.I_C_OrderLine getC_SO_OrderLine() { return get_ValueAsPO(COLUMNNAME_C_SO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_SO_OrderLine(final org.compiere.model.I_C_OrderLine C_SO_OrderLine) { set_ValueFromPO(COLUMNNAME_C_SO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_SO_OrderLine); } @Override public void setC_SO_OrderLine_ID (final int C_SO_OrderLine_ID) { if (C_SO_OrderLine_ID < 1) set_Value (COLUMNNAME_C_SO_OrderLine_ID, null); else set_Value (COLUMNNAME_C_SO_OrderLine_ID, C_SO_OrderLine_ID); } @Override public int getC_SO_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_SO_OrderLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PO_OrderLine_Alloc.java
1
请在Spring Boot框架中完成以下Java代码
public PayPalConfig getConfig() { return cache.getOrLoad(0, this::retrievePayPalConfig); } private PayPalConfig retrievePayPalConfig() { final I_PayPal_Config record = Services.get(IQueryBL.class).createQueryBuilderOutOfTrx(I_PayPal_Config.class) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_PayPal_Config.class); if (record == null) { throw new AdempiereException("@NotFound@ @PayPal_Config_ID@"); } return toPayPalConfig(record); }
private static PayPalConfig toPayPalConfig(@NonNull final I_PayPal_Config record) { return PayPalConfig.builder() .clientId(record.getPayPal_ClientId()) .clientSecret(record.getPayPal_ClientSecret()) .sandbox(record.isPayPal_Sandbox()) .baseUrl(record.getPayPal_BaseUrl()) .webUrl(record.getPayPal_WebUrl()) // .orderApproveMailTemplateId(MailTemplateId.ofRepoId(record.getPayPal_PayerApprovalRequest_MailTemplate_ID())) .orderApproveCallbackUrl(record.getPayPal_PaymentApprovedCallbackUrl()) // .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\config\PayPalConfigRepository.java
2
请完成以下Java代码
public void fireDunningCandidateEvent( @NonNull final String eventName, @NonNull final I_C_Dunning_Candidate candidate) { synchronized (dunningCandidateListeners) { final List<IDunningCandidateListener> listeners = dunningCandidateListeners.get(eventName); if (listeners == null) { return; } for (final IDunningCandidateListener listener : listeners) { listener.onEvent(eventName, candidate); } } } @Override public boolean registerDunningDocLineSourceListener(final DunningDocLineSourceEvent eventName, final IDunningDocLineSourceListener listener) { Check.assumeNotNull(eventName, "eventName not null"); Check.assumeNotNull(listener, "listener not null"); List<IDunningDocLineSourceListener> eventListeners = dunningDocLineSourceListeners.get(eventName); if (eventListeners == null) { eventListeners = new ArrayList<IDunningDocLineSourceListener>(); dunningDocLineSourceListeners.put(eventName, eventListeners); } if (eventListeners.contains(listener)) { return false; } eventListeners.add(listener); return true;
} @Override public void fireDunningDocLineSourceEvent(final DunningDocLineSourceEvent eventName, final I_C_DunningDoc_Line_Source source) { Check.assumeNotNull(eventName, "eventName not null"); Check.assumeNotNull(source, "source not null"); synchronized (dunningDocLineSourceListeners) { final List<IDunningDocLineSourceListener> listeners = dunningDocLineSourceListeners.get(eventName); if (listeners == null) { return; } for (final IDunningDocLineSourceListener listener : listeners) { listener.onEvent(eventName, source); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningEventDispatcher.java
1
请完成以下Java代码
public ObjectId getId() { return id; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setUserRoles(Set<UserRole> userRoles) { this.userRoles = userRoles; } @Override public Set<UserRole> getAuthorities() { return this.userRoles; } @Override public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; }
@Override public boolean isEnabled() { return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(username, user.username); } @Override public int hashCode() { return Objects.hash(username); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\mongoauth\domain\User.java
1
请完成以下Java代码
public void assertNewDocumentAllowed() { throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName()); } @Override public LogicExpressionResult getAllowCreateNewDocument() { return RESULT_TabReadOnly; } @Override public Document createNewDocument() { throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName()); } @Override public LogicExpressionResult getAllowDeleteDocument() { return RESULT_TabReadOnly; } @Override public void deleteDocuments(final DocumentIdsSelection documentIds) { throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName()); } @Override public DocumentValidStatus checkAndGetValidStatus(final OnValidStatusChanged onValidStatusChanged) { return DocumentValidStatus.documentValid(); } @Override public boolean hasChangesRecursivelly() { return false; }
@Override public void saveIfHasChanges() { } @Override public void markStaleAll() { } @Override public void markStale(final DocumentIdsSelection rowIds) { } @Override public boolean isStale() { return false; } @Override public int getNextLineNo() { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadonlyIncludedDocumentsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult<CartProduct> getCartProduct(@PathVariable Long productId) { CartProduct cartProduct = cartItemService.getCartProduct(productId); return CommonResult.success(cartProduct); } @ApiOperation("修改购物车中商品的规格") @RequestMapping(value = "/update/attr", method = RequestMethod.POST) @ResponseBody public CommonResult updateAttr(@RequestBody OmsCartItem cartItem) { int count = cartItemService.updateAttr(cartItem); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除购物车中的指定商品") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = cartItemService.delete(memberService.getCurrentMember().getId(), ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("清空当前会员的购物车") @RequestMapping(value = "/clear", method = RequestMethod.POST) @ResponseBody public CommonResult clear() { int count = cartItemService.clear(memberService.getCurrentMember().getId()); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\OmsCartItemController.java
2
请完成以下Java代码
public List<CleanableHistoricBatchReportResult> findCleanableHistoricBatchesReportByCriteria(CleanableHistoricBatchReportImpl query, Page page, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); query.getOrderingProperties().add(new QueryOrderingProperty(new QueryPropertyImpl("TYPE_"), Direction.ASCENDING)); if (batchOperationsForHistoryCleanup.isEmpty()) { return getDbEntityManager().selectList("selectOnlyFinishedBatchesReportEntities", query, page); } else { return getDbEntityManager().selectList("selectFinishedBatchesReportEntities", query, page); } } public long findCleanableHistoricBatchesReportCountByCriteria(CleanableHistoricBatchReportImpl query, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); if (batchOperationsForHistoryCleanup.isEmpty()) { return (Long) getDbEntityManager().selectOne("selectOnlyFinishedBatchesReportEntitiesCount", query); } else { return (Long) getDbEntityManager().selectOne("selectFinishedBatchesReportEntitiesCount", query); } } public DbOperation deleteHistoricBatchesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo);
} parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricBatchEntity.class, "deleteHistoricBatchesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } public void addRemovalTimeById(String id, Date removalTime) { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricIncidentManager() .addRemovalTimeToHistoricIncidentsByBatchId(id, removalTime); commandContext.getHistoricJobLogManager() .addRemovalTimeToJobLogByBatchId(id, removalTime); Map<String, Object> parameters = new HashMap<>(); parameters.put("id", id); parameters.put("removalTime", removalTime); getDbEntityManager() .updatePreserveOrder(HistoricBatchEntity.class, "updateHistoricBatchRemovalTimeById", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricBatchManager.java
1
请在Spring Boot框架中完成以下Java代码
private J2eePreAuthenticatedProcessingFilter getFilter(AuthenticationManager authenticationManager, H http) { if (this.j2eePreAuthenticatedProcessingFilter == null) { this.j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter(); this.j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(authenticationManager); this.j2eePreAuthenticatedProcessingFilter .setAuthenticationDetailsSource(createWebAuthenticationDetailsSource()); this.j2eePreAuthenticatedProcessingFilter .setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); this.j2eePreAuthenticatedProcessingFilter = postProcess(this.j2eePreAuthenticatedProcessingFilter); } return this.j2eePreAuthenticatedProcessingFilter; } /** * Gets the {@link AuthenticationUserDetailsService} that was specified or defaults to * {@link PreAuthenticatedGrantedAuthoritiesUserDetailsService}. * @return the {@link AuthenticationUserDetailsService} to use */ private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getUserDetailsService() { return (this.authenticationUserDetailsService != null) ? this.authenticationUserDetailsService : new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
} /** * Creates the {@link J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource} to set * on the {@link J2eePreAuthenticatedProcessingFilter}. It is populated with a * {@link SimpleMappableAttributesRetriever}. * @return the {@link J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource} to use. */ private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource createWebAuthenticationDetailsSource() { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource detailsSource = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); SimpleMappableAttributesRetriever rolesRetriever = new SimpleMappableAttributesRetriever(); rolesRetriever.setMappableAttributes(this.mappableRoles); detailsSource.setMappableRolesRetriever(rolesRetriever); detailsSource = postProcess(detailsSource); return detailsSource; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\JeeConfigurer.java
2
请完成以下Java代码
public String getOutputStatement(String toDisplay) { // We will use out:print function to output statements StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append("out:print(\""); int length = toDisplay.length(); for (int i = 0; i < length; i++) { char c = toDisplay.charAt(i); switch (c) { case '"': stringBuffer.append("\\\""); break; case '\\': stringBuffer.append("\\\\"); break; default: stringBuffer.append(c); break; } } stringBuffer.append("\")"); return stringBuffer.toString(); } public String getParameter(String key) { if (key.equals(ScriptEngine.NAME)) { return getLanguageName(); } else if (key.equals(ScriptEngine.ENGINE)) { return getEngineName(); } else if (key.equals(ScriptEngine.ENGINE_VERSION)) { return getEngineVersion(); } else if (key.equals(ScriptEngine.LANGUAGE)) { return getLanguageName(); } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { return getLanguageVersion(); } else if (key.equals("THREADING")) {
return "MULTITHREADED"; } else { return null; } } public String getProgram(String... statements) { // Each statement is wrapped in '${}' to comply with EL StringBuilder buf = new StringBuilder(); if (statements.length != 0) { for (int i = 0; i < statements.length; i++) { buf.append("${"); buf.append(statements[i]); buf.append("} "); } } return buf.toString(); } public ScriptEngine getScriptEngine() { return new JuelScriptEngine(this); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngineFactory.java
1
请完成以下Java代码
public class ATPProductLookupEnricher { final @Nullable BPartnerId bpartnerId; @NonNull final ZonedDateTime dateOrNull; private final AvailableToPromiseAdapter availableToPromiseAdapter; @Builder public ATPProductLookupEnricher( @Nullable final BPartnerId bpartnerId, @NonNull final ZonedDateTime dateOrNull, @NonNull final AvailableToPromiseAdapter availableToPromiseAdapter) { this.bpartnerId = bpartnerId;
this.dateOrNull = dateOrNull; this.availableToPromiseAdapter = availableToPromiseAdapter; } public List<AvailabilityInfoResultForWebui.Group> getAvailabilityInfoGroups(@NonNull final LookupValuesList productLookupValues) { final AvailableToPromiseQuery query = AvailableToPromiseQuery.builder() .productIds(productLookupValues.getKeysAsInt()) .storageAttributesKeyPatterns(availableToPromiseAdapter.getPredefinedStorageAttributeKeys()) .date(dateOrNull) .bpartner(BPartnerClassifier.specificOrNone(bpartnerId)) .build(); final AvailabilityInfoResultForWebui availableStock = availableToPromiseAdapter.retrieveAvailableStock(query); return availableStock.getGroups(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\productLookup\ATPProductLookupEnricher.java
1
请完成以下Java代码
public JsonWindowsHealthCheckResponse healthCheck( @RequestParam(name = "windowIds", required = false) final String windowIdsCommaSeparated ) { final String adLanguage = Env.getADLanguageOrBaseLanguage(); final ImmutableSet<AdWindowId> skipAdWindowIds = ImmutableSet.of(); final ImmutableSet<AdWindowId> onlyAdWindowIds = RepoIdAwares.ofCommaSeparatedSet(windowIdsCommaSeparated, AdWindowId.class); final ImmutableSet<AdWindowId> allAdWidowIds = adWindowDAO.retrieveAllActiveAdWindowIds(); final ImmutableSet<AdWindowId> adWindowIds = !onlyAdWindowIds.isEmpty() ? onlyAdWindowIds : allAdWidowIds; final ArrayList<JsonWindowsHealthCheckResponse.Entry> skipped = new ArrayList<>(); final ArrayList<JsonWindowsHealthCheckResponse.Entry> errors = new ArrayList<>(); final int countTotal = adWindowIds.size(); int countCurrent = 0; final Stopwatch stopwatch = Stopwatch.createStarted(); for (final AdWindowId adWindowId : adWindowIds) { countCurrent++; final WindowId windowId = WindowId.of(adWindowId); if (skipAdWindowIds.contains(adWindowId)) { skipped.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(windowId) .errorMessage("Programmatically skipped") .build()); continue; } try { if (!allAdWidowIds.contains(adWindowId)) { throw new AdempiereException("Not an existing/active window"); } final ViewLayout viewLayout = viewsRepo.getViewLayout(windowId, JSONViewDataType.grid, null, null); final String viewName = viewLayout.getCaption(adLanguage); logger.info("healthCheck [{}/{}] View `{}` ({}) is OK", countCurrent, countTotal, viewName, windowId);
} catch (Exception ex) { final String viewName = adWindowDAO.retrieveWindowName(adWindowId).translate(adLanguage); logger.info("healthCheck [{}/{}] View `{}` ({}) is NOK: {}", countCurrent, countTotal, viewName, windowId, ex.getLocalizedMessage()); final Throwable cause = DocumentLayoutBuildException.extractCause(ex); errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(windowId) .windowName(viewName) .error(de.metas.rest_api.utils.v2.JsonErrors.ofThrowable(cause, adLanguage)) .build()); } } stopwatch.stop(); return JsonWindowsHealthCheckResponse.builder() .took(stopwatch.toString()) .countTotal(countTotal) .errors(errors) .skipped(skipped) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewHealthRestController.java
1
请在Spring Boot框架中完成以下Java代码
public void runTask(Class c) throws Exception { TableName a = (TableName) c.getAnnotation(TableName.class); String tableName = a.value(); Field[] fields = c.getDeclaredFields(); List<String> fieldNames = new ArrayList<>(); List<String> paramNames = new ArrayList<>(); for (Field f : fields) { fieldNames.add(f.getName()); paramNames.add(":" + f.getName()); } String columnsStr = String.join(",", fieldNames); String paramsStr = String.join(",", paramNames); String csvFileName; if (p.getLocation() == 1) { csvFileName = p.getCsvDir() + tableName + ".csv";
} else { csvFileName = tableName + ".csv"; } JobParameters jobParameters1 = new JobParametersBuilder() .addLong("time", System.currentTimeMillis()) .addString(KEY_JOB_NAME, tableName) .addString(KEY_FILE_NAME, csvFileName) .addString(KEY_VO_NAME, c.getCanonicalName()) .addString(KEY_COLUMNS, String.join(",", fieldNames)) .addString(KEY_SQL, "insert into " + tableName + " (" + columnsStr + ")" + " values(" + paramsStr + ")") .toJobParameters(); jobLauncher.run(commonJob, jobParameters1); } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\service\CsvService.java
2
请完成以下Java代码
public abstract class AbstractBaseInterceptor implements IServiceInterceptor { private final Map<Class<? extends Annotation>, IInterceptorInstance> annotation2Interceptor = new HashMap<Class<? extends Annotation>, IInterceptorInstance>(); private final Map<Class<? extends Annotation>, IInterceptorInstance> annotation2InterceptorRO = Collections.unmodifiableMap(annotation2Interceptor); @Override public Object registerInterceptor(final Class<? extends Annotation> annotationClass, final Object impl) { Check.errorIf(annotation2Interceptor.size() > 0, "our Current implementation can support only one insterceptor!"); final Class<? extends Object> implClass = impl.getClass(); Check.errorIf(!implClass.isAnnotationPresent(annotationClass), "Given interceptor impl {} needs to be annotated with {}", annotationClass); final IInterceptorInstance interceptorInstance = createInterceptorInstance(annotationClass, impl);
return annotation2Interceptor.put(annotationClass, interceptorInstance); } protected abstract IInterceptorInstance createInterceptorInstance(final Class<? extends Annotation> annotationClass, final Object interceptorImpl); /* package */IInterceptorInstance getInterceptor(final Class<? extends Annotation> annotationClass) { return annotation2Interceptor.get(annotationClass); } /* package */Map<Class<? extends Annotation>, IInterceptorInstance> getRegisteredInterceptors() { return annotation2InterceptorRO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\impl\AbstractBaseInterceptor.java
1
请完成以下Java代码
public static Builder newBuilder() { return new Builder(); } static class Builder { private MeterProvider<Counter> attemptCounter; private MeterProvider<DistributionSummary> sentMessageSizeDistribution; private MeterProvider<DistributionSummary> receivedMessageSizeDistribution; private MeterProvider<Timer> clientAttemptDuration; private MeterProvider<Timer> clientCallDuration; private Builder() {} public Builder setAttemptCounter(MeterProvider<Counter> counter) { this.attemptCounter = counter; return this; } public Builder setSentMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) { this.sentMessageSizeDistribution = distribution; return this; } public Builder setReceivedMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) { this.receivedMessageSizeDistribution = distribution;
return this; } public Builder setClientAttemptDuration(MeterProvider<Timer> timer) { this.clientAttemptDuration = timer; return this; } public Builder setClientCallDuration(MeterProvider<Timer> timer) { this.clientCallDuration = timer; return this; } public MetricsClientMeters build() { return new MetricsClientMeters(this); } } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientMeters.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaOrderPackage extends AbstractEntity { @ManyToOne(fetch = FetchType.EAGER) @NotNull @Getter @Setter private JpaOrder order; @Getter @Setter private String documentNo; @Getter @Setter private OrderType orderType; @Getter @Setter /** One of 4 predefined or one free identifier. May deviate from the request identifier and be replaced by one of the 4 predefined identifiers (see specifications). */ private String orderIdentification; @Getter @Setter private int supportId;
@Getter @Setter private String packingMaterialId; @OneToMany(fetch = FetchType.EAGER, mappedBy = "orderPackage", cascade = CascadeType.ALL) @Getter private final List<JpaOrderPackageItem> items = new ArrayList<>(); public void addItems(@NonNull final List<JpaOrderPackageItem> items) { items.forEach(item -> item.setOrderPackage(this)); this.items.addAll(items); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\order\jpa\JpaOrderPackage.java
2
请在Spring Boot框架中完成以下Java代码
public String getBankTrxNo() { return bankTrxNo; } public void setBankTrxNo(String bankTrxNo) { this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim(); } public String getTrxType() { return trxType; } public void setTrxType(String trxType) { this.trxType = trxType == null ? null : trxType.trim(); } public String getTrxTypeDesc() { return TrxTypeEnum.getEnum(this.getTrxType()).getDesc(); } public Integer getRiskDay() { return riskDay; } public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } public String getAmountDesc() { if(this.getFundDirection().equals(AccountFundDirectionEnum.ADD.name())){ return "<span style=\"color: blue;\">+"+this.amount.doubleValue()+"</span>"; }else{ return "<span style=\"color: red;\">-"+this.amount.doubleValue()+"</span>"; } } public String getCreateTimeDesc() { return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss"); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccountHistory.java
2
请在Spring Boot框架中完成以下Java代码
public class DocumentChangeHandler_InOut implements DocumentChangeHandler<I_M_InOut> { private final IInOutDAO shipmentDAO = Services.get(IInOutDAO.class); @NonNull private final CallOrderContractService callOrderContractService; @NonNull private final CallOrderService callOrderService; @NonNull private final CallOrderDetailRepo detailRepo; public DocumentChangeHandler_InOut( final @NonNull CallOrderContractService callOrderContractService, final @NonNull CallOrderService callOrderService, final @NonNull CallOrderDetailRepo detailRepo) { this.callOrderContractService = callOrderContractService; this.callOrderService = callOrderService; this.detailRepo = detailRepo; } @Override public void onComplete(final I_M_InOut shipment) { shipmentDAO.retrieveLines(shipment).forEach(this::syncInOutLine); } @Override public void onReverse(final I_M_InOut shipment) { shipmentDAO.retrieveLines(shipment).forEach(this::syncInOutLine); } @Override
public void onReactivate(final I_M_InOut shipment) { detailRepo.resetDeliveredQtyForShipment(InOutId.ofRepoId(shipment.getM_InOut_ID())); } private void syncInOutLine(@NonNull final I_M_InOutLine inOutLine) { final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoIdOrNull(inOutLine.getC_Flatrate_Term_ID()); if (flatrateTermId == null) { return; } if (!callOrderContractService.isCallOrderContract(flatrateTermId)) { return; } callOrderContractService.validateCallOrderInOutLine(inOutLine, flatrateTermId); final UpsertCallOrderDetailRequest request = UpsertCallOrderDetailRequest.builder() .callOrderContractId(flatrateTermId) .shipmentLine(inOutLine) .build(); callOrderService.handleCallOrderDetailUpsert(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\document\DocumentChangeHandler_InOut.java
2
请完成以下Java代码
public static List<String> getOddIndexedStrings(String[] names) { List<String> oddIndexedNames = IntStream.range(0, names.length) .filter(i -> i % 2 == 1) .mapToObj(i -> names[i]) .collect(Collectors.toList()); return oddIndexedNames; } public static List<String> getOddIndexedStringsVersionTwo(String[] names) { List<String> oddIndexedNames = Stream.of(names) .zipWithIndex() .filter(tuple -> tuple._2 % 2 == 1) .map(tuple -> tuple._1) .toJavaList(); return oddIndexedNames;
} public static List<String> getEvenIndexedStringsUsingAtomicInteger(String[] names) { AtomicInteger index = new AtomicInteger(0); return Arrays.stream(names) .filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList()); } public static List<String> getEvenIndexedStringsAtomicIntegerParallel(String[] names) { AtomicInteger index = new AtomicInteger(0); return Arrays.stream(names) .parallel() .filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\StreamIndices.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsCreateShareForOwnRevenue (final boolean IsCreateShareForOwnRevenue) { set_Value (COLUMNNAME_IsCreateShareForOwnRevenue, IsCreateShareForOwnRevenue); } @Override public boolean isCreateShareForOwnRevenue() { return get_ValueAsBoolean(COLUMNNAME_IsCreateShareForOwnRevenue); } @Override public void setIsSubtractLowerLevelCommissionFromBase (final boolean IsSubtractLowerLevelCommissionFromBase) { set_Value (COLUMNNAME_IsSubtractLowerLevelCommissionFromBase, IsSubtractLowerLevelCommissionFromBase); } @Override public boolean isSubtractLowerLevelCommissionFromBase() { return get_ValueAsBoolean(COLUMNNAME_IsSubtractLowerLevelCommissionFromBase); }
@Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPointsPrecision (final int PointsPrecision) { set_Value (COLUMNNAME_PointsPrecision, PointsPrecision); } @Override public int getPointsPrecision() { return get_ValueAsInt(COLUMNNAME_PointsPrecision); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_HierarchyCommissionSettings.java
1
请完成以下Java代码
public void setRegistry (final @Nullable java.lang.String Registry) { set_Value (COLUMNNAME_Registry, Registry); } @Override public java.lang.String getRegistry() { return get_ValueAsString(COLUMNNAME_Registry); } @Override public void setSecretKey_2FA (final @Nullable java.lang.String SecretKey_2FA) { set_Value (COLUMNNAME_SecretKey_2FA, SecretKey_2FA); } @Override public java.lang.String getSecretKey_2FA() { return get_ValueAsString(COLUMNNAME_SecretKey_2FA); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSupervisor_ID (final int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID); } @Override public int getSupervisor_ID() { return get_ValueAsInt(COLUMNNAME_Supervisor_ID); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { throw new IllegalArgumentException ("Timestamp is virtual column"); }
@Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount) { set_Value (COLUMNNAME_UnlockAccount, UnlockAccount); } @Override public java.lang.String getUnlockAccount() { return get_ValueAsString(COLUMNNAME_UnlockAccount); } @Override public void setUserPIN (final @Nullable java.lang.String UserPIN) { set_Value (COLUMNNAME_UserPIN, UserPIN); } @Override public java.lang.String getUserPIN() { return get_ValueAsString(COLUMNNAME_UserPIN); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java
1
请完成以下Java代码
public boolean isAssigned() { return !assignmentsToRefundCandidates.isEmpty(); } public SplitResult splitQuantity(@NonNull final BigDecimal qtyToSplit) { Check.errorIf(qtyToSplit.compareTo(quantity.toBigDecimal()) >= 0, "The given qtyToSplit={} needs to be less than this instance's quantity; this={}", qtyToSplit, this); final Quantity newQuantity = Quantity.of(qtyToSplit, quantity.getUOM()); final Quantity remainderQuantity = quantity.subtract(qtyToSplit); final BigDecimal newFraction = qtyToSplit .setScale(precision * 2, RoundingMode.HALF_UP) .divide(quantity.toBigDecimal(), RoundingMode.HALF_UP); final BigDecimal newMoneyValue = money .toBigDecimal() .setScale(precision, RoundingMode.HALF_UP) .multiply(newFraction) .setScale(precision, RoundingMode.HALF_UP); final Money newMoney = Money.of(newMoneyValue, money.getCurrencyId()); final Money remainderMoney = money.subtract(newMoney); final AssignableInvoiceCandidate remainderCandidate = toBuilder() .quantity(remainderQuantity) .money(remainderMoney) .build(); final AssignableInvoiceCandidate newCandidate = toBuilder() .id(id)
.quantity(newQuantity) .money(newMoney) .build(); return new SplitResult(remainderCandidate, newCandidate); } @Value public static final class SplitResult { AssignableInvoiceCandidate remainder; AssignableInvoiceCandidate newCandidate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public void setCategory(String category) { this.category = category; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "oneChannel.channel") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName;
} @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneChannel.channel", value = "Contains the actual deployed channel definition JSON.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a channel definition for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\ChannelDefinitionResponse.java
2
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } // Books and authors (JPQL) public List<AuthorNameBookTitle> fetchBooksAndAuthorsJpql() { return bookRepository.findBooksAndAuthorsJpql(); } // Books and authors (SQL) public List<AuthorNameBookTitle> fetchBooksAndAuthorsSql() { return bookRepository.findBooksAndAuthorsSql(); } // Authors and books (JPQL) public List<AuthorNameBookTitle> fetchAuthorsAndBooksJpql() { return authorRepository.findAuthorsAndBooksJpql(); } // Authors and books (SQL) public List<AuthorNameBookTitle> fetchAuthorsAndBooksSql() { return authorRepository.findAuthorsAndBooksSql(); } // Fetch authors and books filtering by author's genre and book's price (JPQL)
public List<AuthorNameBookTitle> findAuthorsAndBooksByGenreAndPriceJpql(String genre, int price) { return authorRepository.findAuthorsAndBooksByGenreAndPriceJpql(genre, price); } // Fetch authors and books filtering by author's genre and book's price (SQL) public List<AuthorNameBookTitle> findAuthorsAndBooksByGenreAndPriceSql(String genre, int price) { return authorRepository.findAuthorsAndBooksByGenreAndPriceSql(genre, price); } // Fetch books and authors filtering by author's genre and book's price (JPQL) public List<AuthorNameBookTitle> findBooksAndAuthorsByGenreAndPriceJpql(String genre, int price) { return bookRepository.findBooksAndAuthorsByGenreAndPriceJpql(genre, price); } // Fetch books and authors filtering by author's genre and book's price (SQL) public List<AuthorNameBookTitle> findBooksAndAuthorsByGenreAndPriceSql(String genre, int price) { return bookRepository.findBooksAndAuthorsByGenreAndPriceSql(genre, price); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaInnerJoins\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public class CommentResponse { private String id; private String author; private String message; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date time; private String taskId; private String taskUrl; private String processInstanceId; private String processInstanceUrl; public void setId(String id) { this.id = id; } public String getId() { return id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getTime() { return time; }
public void setTime(Date time) { this.time = time; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentResponse.java
2
请完成以下Java代码
public void saveAll(@NonNull final ImmutableCollection<ReceiptSchedule> receiptSchedules) { for (final ReceiptSchedule receiptSchedule : receiptSchedules) { save(receiptSchedule); } } private void save(@NonNull final ReceiptSchedule receiptSchedule) { final I_M_ReceiptSchedule record = load(receiptSchedule.getId(), I_M_ReceiptSchedule.class); record.setExportStatus(receiptSchedule.getExportStatus().getCode()); saveRecord(record); } public ImmutableMap<ReceiptScheduleId, ReceiptSchedule> getByIds(@NonNull final ImmutableSet<ReceiptScheduleId> receiptScheduleIds) { final List<I_M_ReceiptSchedule> records = loadByRepoIdAwares(receiptScheduleIds, I_M_ReceiptSchedule.class); final ImmutableMap.Builder<ReceiptScheduleId, ReceiptSchedule> result = ImmutableMap.builder(); for (final I_M_ReceiptSchedule record : records) { result.put(ReceiptScheduleId.ofRepoId(record.getM_ReceiptSchedule_ID()), ofRecord(record)); } return result.build(); } @Value
@Builder public static class ReceiptScheduleQuery { @NonNull @Builder.Default QueryLimit limit = QueryLimit.NO_LIMIT; Instant canBeExportedFrom; APIExportStatus exportStatus; @Builder.Default boolean includeWithQtyToDeliverZero = false; @Builder.Default boolean includeProcessed = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ReceiptScheduleRepository.java
1
请完成以下Java代码
protected void prepare() { // nothing to do } @Override protected String doIt() throws Exception { final ISubscriptionBL subscriptionBL = Services.get(ISubscriptionBL.class); if (getRecord_ID() > 0) { Check.assume(getTable_ID() == MTable.getTable_ID(I_C_OLCand.Table_Name), "Process is called for C_OLCands"); final I_C_OLCand olCand = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_C_OLCand.class, get_TrxName()); subscriptionBL.createTermForOLCand(getCtx(), olCand, getPinstanceId(), true, get_TrxName()); addLog("@C_OLCand_ID@ " + olCand.getC_OLCand_ID() + " @Processed@"); } else { final int counter = subscriptionBL.createMissingTermsForOLCands(getCtx(), true, getPinstanceId(), get_TrxName()); addLog("@Processed@ " + counter + " @C_OLCand_ID@"); } return "@Success@"; } /** * Method returns true if the given gridTab is a {@link I_C_OLCand} with the correct data destination. * * @param gridTab */ @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (!I_C_OLCand.Table_Name.equals(context.getTableName())) { return ProcessPreconditionsResolution.reject(); } if(context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); }
final I_C_OLCand olCand = context.getSelectedModel(I_C_OLCand.class); if(olCand.isError()) { return ProcessPreconditionsResolution.reject("line has errors"); } final IInputDataSourceDAO inputDataSourceDAO = Services.get(IInputDataSourceDAO.class); final I_AD_InputDataSource dest = inputDataSourceDAO.retrieveInputDataSource(Env.getCtx(), Contracts_Constants.DATA_DESTINATION_INTERNAL_NAME, false, get_TrxName()); if (dest == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("no input data source found"); } if (dest.getAD_InputDataSource_ID() != olCand.getAD_DataDestination_ID()) { return ProcessPreconditionsResolution.rejectWithInternalReason("input data source not matching"); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Create_From_OLCand.java
1
请完成以下Java代码
public static CostCollectorType ofNullableCode(@Nullable final String code) { return code != null ? ofCode(code) : null; } public static CostCollectorType ofCode(@NonNull final String code) { final CostCollectorType type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + CostCollectorType.class + " found for code: " + code); } return type; } private static final ImmutableMap<String, CostCollectorType> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), CostCollectorType::getCode); public boolean isMaterial(@Nullable final PPOrderBOMLineId orderBOMLineId) { return isMaterialReceipt() || isAnyComponentIssueOrCoProduct(orderBOMLineId); } public boolean isMaterialReceipt() { return this == MaterialReceipt; } public boolean isMaterialReceiptOrCoProduct() { return isMaterialReceipt() || isCoOrByProductReceipt(); } public boolean isComponentIssue() { return this == ComponentIssue; } public boolean isAnyComponentIssueOrCoProduct(@Nullable final PPOrderBOMLineId orderBOMLineId) { return isAnyComponentIssue(orderBOMLineId) || isCoOrByProductReceipt(); } public boolean isAnyComponentIssue(@Nullable final PPOrderBOMLineId orderBOMLineId) { return isComponentIssue() || isMaterialMethodChangeVariance(orderBOMLineId); } public boolean isActivityControl() { return this == ActivityControl; } public boolean isVariance() { return this == MethodChangeVariance || this == UsageVariance || this == RateVariance || this == MixVariance;
} public boolean isCoOrByProductReceipt() { return this == MixVariance; } public boolean isUsageVariance() { return this == UsageVariance; } public boolean isMaterialUsageVariance(@Nullable final PPOrderBOMLineId orderBOMLineId) { return this == UsageVariance && orderBOMLineId != null; } public boolean isResourceUsageVariance(@Nullable final PPOrderRoutingActivityId activityId) { return this == UsageVariance && activityId != null; } public boolean isRateVariance() { return this == RateVariance; } public boolean isMethodChangeVariance() { return this == MethodChangeVariance; } public boolean isMaterialMethodChangeVariance(@Nullable final PPOrderBOMLineId orderBOMLineId) { return this == MethodChangeVariance && orderBOMLineId != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\CostCollectorType.java
1
请完成以下Java代码
public de.metas.handlingunits.model.I_M_HU_Storage getM_HU_Storage() { return get_ValueAsPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class); } @Override public void setM_HU_Storage(final de.metas.handlingunits.model.I_M_HU_Storage M_HU_Storage) { set_ValueFromPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class, M_HU_Storage); } @Override public void setM_HU_Storage_ID (final int M_HU_Storage_ID) { if (M_HU_Storage_ID < 1) set_Value (COLUMNNAME_M_HU_Storage_ID, null); else set_Value (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID); } @Override public int getM_HU_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID); } @Override public void setM_HU_Storage_Snapshot_ID (final int M_HU_Storage_Snapshot_ID) { if (M_HU_Storage_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Storage_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Storage_Snapshot_ID, M_HU_Storage_Snapshot_ID); } @Override public int getM_HU_Storage_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_Snapshot_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); }
@Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Storage_Snapshot.java
1
请在Spring Boot框架中完成以下Java代码
public class RedeploymentDto { protected String source; protected List<String> resourceIds; protected List<String> resourceNames; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public List<String> getResourceIds() { return resourceIds;
} public void setResourceIds(List<String> resourceIds) { this.resourceIds = resourceIds; } public List<String> getResourceNames() { return resourceNames; } public void setResourceNames(List<String> resourceNames) { this.resourceNames = resourceNames; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\RedeploymentDto.java
2
请完成以下Java代码
public void destroy() { } @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest)request; final AuthResolution authResolution = getAuthResolution(httpRequest); if (authResolution.isDoNotAuthenticate()) { chain.doFilter(request, response); } else { final HttpServletResponse httpResponse = (HttpServletResponse)response; try { userAuthTokenService.run( () -> extractTokenStringIfAvailable(httpRequest), authResolution, () -> { extractAdLanguage(httpRequest).ifPresent(Env::setAD_Language); chain.doFilter(httpRequest, httpResponse); }); } catch (final UserNotAuthorizedException ex) { httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getLocalizedMessage()); } } } private AuthResolution getAuthResolution(@NonNull final HttpServletRequest httpRequest) { // don't check auth for OPTIONS method calls because this causes troubles on chrome preflight checks if ("OPTIONS".equals(httpRequest.getMethod())) { return AuthResolution.DO_NOT_AUTHENTICATE; } return configuration.getAuthResolution(httpRequest).orElse(AuthResolution.AUTHENTICATION_REQUIRED); } @Nullable private static String extractTokenStringIfAvailable(final HttpServletRequest httpRequest) { // // Check Authorization header first { final String authorizationString = StringUtils.trimBlankToNull(httpRequest.getHeader(HEADER_Authorization)); if (authorizationString != null) { if (authorizationString.startsWith("Token ")) { return authorizationString.substring(5).trim(); } else if (authorizationString.startsWith("Basic "))
{ final String userAndTokenString = new String(DatatypeConverter.parseBase64Binary(authorizationString.substring(5).trim())); final int index = userAndTokenString.indexOf(':'); return userAndTokenString.substring(index + 1); } else { return authorizationString; } } } // // Check apiKey query parameter { return StringUtils.trimBlankToNull(httpRequest.getParameter(QUERY_PARAM_API_KEY)); } } @VisibleForTesting Optional<String> extractAdLanguage(@NonNull final HttpServletRequest httpRequest) { final String acceptLanguageHeader = StringUtils.trimBlankToNull(httpRequest.getHeader(HEADER_AcceptLanguage)); final ADLanguageList availableLanguages = languageDAO.retrieveAvailableLanguages(); final String adLanguage = availableLanguages.getAD_LanguageFromHttpAcceptLanguage(acceptLanguageHeader, availableLanguages.getBaseADLanguage()); return Optional.ofNullable(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenFilter.java
1
请完成以下Java代码
protected boolean matchesNonNull(String rawPassword, String encodedPassword) { if (!encodedPassword.contains(DELIMITER)) { return false; } String[] parts = encodedPassword.split(DELIMITER, 2); if (parts.length != 2) { return false; } try { byte[] salt = Base64.getDecoder().decode(parts[0]); String expectedHash = parts[1]; Hash hash = Password.hash(rawPassword).addSalt(salt).with(this.balloonHashingFunction); return expectedHash.equals(hash.getResult());
} catch (IllegalArgumentException ex) { // Invalid Base64 encoding return false; } } @Override protected boolean upgradeEncodingNonNull(String encodedPassword) { // For now, we'll return false to maintain existing behavior // This could be enhanced in the future to check if the encoding parameters // match the current configuration return false; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password4j\BalloonHashingPassword4jPasswordEncoder.java
1
请在Spring Boot框架中完成以下Java代码
class BusinessService { private DataService dataService; //@Autowired @Inject public void setDataService(DataService dataService) { System.out.println("Setter Injection"); this.dataService = dataService; } public DataService getDataService() { return dataService; } } //@Component @Named class DataService { } @Configuration @ComponentScan public class CdiContextLauncherApplication {
public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext (CdiContextLauncherApplication.class)) { Arrays.stream(context.getBeanDefinitionNames()) .forEach(System.out::println); System.out.println(context.getBean(BusinessService.class) .getDataService()); } } }
repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\g1\CdiContextLauncherApplication.java
2
请在Spring Boot框架中完成以下Java代码
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> servletContainerCustomizer() { return tomcatContainerFactory -> tomcatContainerFactory.addConnectorCustomizers(connector -> { final AbstractHttp11Protocol<?> httpProtocol = (AbstractHttp11Protocol<?>)connector.getProtocolHandler(); httpProtocol.setCompression("on"); httpProtocol.setCompressionMinSize(256); final String mimeTypes = httpProtocol.getCompressibleMimeType(); final String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE + ",application/javascript"; httpProtocol.setCompressibleMimeType(mimeTypesWithJson); }); } @Bean(ConfigConstants.BEANNAME_WebuiTaskScheduler) public TaskScheduler webuiTaskScheduler() { final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setThreadNamePrefix("webui-task-scheduler-");
taskScheduler.setDaemon(true); taskScheduler.setPoolSize(10); return taskScheduler; } private static void setDefaultProperties() { if (Check.isEmpty(System.getProperty("PropertyFile"), true)) { System.setProperty("PropertyFile", "./metasfresh.properties"); } if (Check.isBlank(System.getProperty(SYSTEM_PROPERTY_APP_NAME))) { System.setProperty(SYSTEM_PROPERTY_APP_NAME, WebRestApiApplication.class.getSimpleName()); } } }
repos\metasfresh-new_dawn_uat\backend\metasfresh-webui-api\src\main\java\de\metas\ui\web\WebRestApiApplication.java
2
请完成以下Java代码
public class ADValidatorRegistryBL implements IADValidatorRegistryBL { private final Map<Class<?>, IADValidator<?>> validators = new ConcurrentHashMap<>(); public ADValidatorRegistryBL() { registerStandardValidators(); } @Override public <T> void registerValidator(final Class<T> interfaceClass, final IADValidator<T> validator) { if (validators.containsKey(interfaceClass)) { throw new AdempiereException("A validator is already registered for " + interfaceClass); } validators.put(interfaceClass, validator); ApplicationDictionaryGenericModelValidator<T> modelValidator = new ApplicationDictionaryGenericModelValidator<>(interfaceClass, validator); ModelValidationEngine.get().addModelValidator(modelValidator); } @Override public <T> IADValidatorResult validate(final Properties ctx, final Class<T> appDictClass) { final Iterator<T> items = Services.get(IADValidatorDAO.class).retrieveApplicationDictionaryItems(ctx, appDictClass); final IADValidatorResult errorLog = new ADValidatorResult(); while (items.hasNext()) { final T item = items.next(); try { validateItem(appDictClass, item); } catch (Exception e) { final IADValidatorViolation violation = new ADValidatorViolation(item, e); errorLog.addViolation(violation); } } return errorLog; } @Override public List<Class<?>> getRegisteredClasses()
{ return new ArrayList<>(validators.keySet()); } @Override public IADValidator<?> getValidator(final Class<?> registeredClass) { return validators.get(registeredClass); } private <T> void validateItem(final Class<T> appDictClass, final T item) { @SuppressWarnings("unchecked") final IADValidator<T> validator = (IADValidator<T>)validators.get(appDictClass); validator.validate(item); } private void registerStandardValidators() { registerValidator(I_AD_ColumnCallout.class, new ADColumnCalloutADValidator()); registerValidator(I_AD_Form.class, new ADFormADValidator()); registerValidator(I_AD_ModelValidator.class, new ADModelValidatorADValidator()); registerValidator(I_AD_Process.class, new ADProcessADValidator()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\api\impl\ADValidatorRegistryBL.java
1
请完成以下Java代码
public @Nullable String getServerHeader() { return this.serverHeader; } @Override public void setServerHeader(@Nullable String serverHeader) { this.serverHeader = serverHeader; } @Override public void setShutdown(Shutdown shutdown) { this.shutdown = shutdown; } /** * Returns the shutdown configuration that will be applied to the server. * @return the shutdown configuration * @since 2.3.0 */ public Shutdown getShutdown() { return this.shutdown; } /** * Return the {@link SslBundle} that should be used with this server. * @return the SSL bundle */ protected final SslBundle getSslBundle() { return WebServerSslBundle.get(this.ssl, this.sslBundles); }
protected final Map<String, SslBundle> getServerNameSslBundles() { Assert.state(this.ssl != null, "'ssl' must not be null"); return this.ssl.getServerNameBundles() .stream() .collect(Collectors.toMap(ServerNameSslBundle::serverName, (serverNameSslBundle) -> { Assert.state(this.sslBundles != null, "'sslBundles' must not be null"); return this.sslBundles.getBundle(serverNameSslBundle.bundle()); })); } /** * Return the absolute temp dir for given web server. * @param prefix server name * @return the temp dir for given server. */ protected final File createTempDir(String prefix) { try { File tempDir = Files.createTempDirectory(prefix + "." + getPort() + ".").toFile(); tempDir.deleteOnExit(); return tempDir; } catch (IOException ex) { throw new WebServerException( "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\AbstractConfigurableWebServerFactory.java
1
请在Spring Boot框架中完成以下Java代码
public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration cors = new CorsConfiguration(); cors.setAllowedOriginPatterns(List.of("*")); cors.setAllowedMethods(List.of("*")); cors.setAllowedHeaders(List.of("*")); cors.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", cors); return source; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
@Bean public JwtDecoder jwtDecoder(@Value("${security.key.public}") RSAPublicKey rsaPublicKey) { return NimbusJwtDecoder.withPublicKey(rsaPublicKey).build(); } @Bean public JwtEncoder jwtEncoder( @Value("${security.key.public}") RSAPublicKey rsaPublicKey, @Value("${security.key.private}") RSAPrivateKey rsaPrivateKey) { JWK jwk = new RSAKey.Builder(rsaPublicKey).privateKey(rsaPrivateKey).build(); JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk)); return new NimbusJwtEncoder(jwks); } }
repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\config\SecurityConfiguration.java
2
请完成以下Java代码
public abstract class CachableTreeCellRenderer extends DefaultTreeCellRenderer { private boolean virtual; private HashMap cache; private CachableTreeCellRenderer complement; protected abstract void init(Object value); public CachableTreeCellRenderer() { this(false); } public CachableTreeCellRenderer(boolean virtual) { super(); this.virtual = virtual; cache = new HashMap(); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); String name = (String)getFromCache(value); if(name == null) { init(value); name = (String)getFromCache(value); } setName(name); return this; } /* public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if(!isVirtual()) { if(!isInitialized()) { init(value); } return this; } else {
CachableTreeCellRenderer r = null; try { System.out.println(this.getClass()+" class: "+getClass()); r = (CachableTreeCellRenderer)this.getClass().newInstance(); r.setVirtual(false); r.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); complement = (CachableTreeCellRenderer)tree.getCellRenderer(); tree.setCellRenderer(r); } catch(Exception e) { e.printStackTrace(); } return r; } } */ public boolean isInitialized() { return !cache.isEmpty(); } public void addToCache(Object key, Object value) { cache.put(key, value); } public Object getFromCache(Object key) { return cache.get(key); } public boolean isVirtual() { return virtual; } public void setVirtual(boolean on) { this.virtual = on; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\form\tree\CachableTreeCellRenderer.java
1
请完成以下Java代码
public static String getPublicIpAddressAws() { try { String urlString = "http://checkip.amazonaws.com/"; URL url = new URI(urlString).toURL(); try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { return br.readLine(); } } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } } public static String getLocalIpAddress() { try { return Inet4Address.getLocalHost() .getHostAddress(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } public static List<String> getAllLocalIpAddressUsingNetworkInterface() { List<String> ipAddress = new ArrayList<>(); Enumeration<NetworkInterface> networkInterfaceEnumeration = null; try { networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { throw new RuntimeException(e); } for (; networkInterfaceEnumeration.hasMoreElements(); ) { NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); try { if (!networkInterface.isUp() || networkInterface.isLoopback()) {
continue; } } catch (SocketException e) { throw new RuntimeException(e); } Enumeration<InetAddress> address = networkInterface.getInetAddresses(); for (; address.hasMoreElements(); ) { InetAddress addr = address.nextElement(); ipAddress.add(addr.getHostAddress()); } } return ipAddress; } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\iplookup\IPAddressLookup.java
1
请完成以下Java代码
public int getM_Product_ID() { return inoutLine.getM_Product_ID(); } @Override public void setM_Product_ID(final int productId) { inoutLine.setM_Product_ID(productId); } @Override public void setQty(final BigDecimal qty) { inoutLine.setQtyEntered(qty); final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID()); final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID()); final BigDecimal movementQty = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty); inoutLine.setMovementQty(movementQty); } @Override public BigDecimal getQty() { return inoutLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class); final org.compiere.model.I_M_InOut inOut = inoutLine.getM_InOut(); // Applied only to customer return inout lines. final boolean isCustomerReturnInOutLine = huInOutBL.isCustomerReturn(inOut); if (inoutLine.isManualPackingMaterial() || isCustomerReturnInOutLine) { return inoutLine.getM_HU_PI_Item_Product_ID(); } final I_C_OrderLine orderline = InterfaceWrapperHelper.create(inoutLine.getC_OrderLine(), I_C_OrderLine.class); return orderline == null ? -1 : orderline.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return inoutLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { inoutLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return inoutLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId)
{ // we assume inoutLine's UOM is correct if (uomId > 0) { inoutLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return inoutLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { inoutLine.setQtyEnteredTU(qtyPacks); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public boolean isInDispute() { return inoutLine.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { inoutLine.setIsInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InOutLineHUPackingAware.java
1
请完成以下Java代码
public boolean matches(HttpServletRequest request) { return matches(request.getRemoteAddr()); } public boolean matches(String ipAddress) { // Do not match null or blank address if (!StringUtils.hasText(ipAddress)) { return false; } assertNotHostName(ipAddress); InetAddress remoteAddress = parseAddress(ipAddress); if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) { return false; } if (this.nMaskBits < 0) { return remoteAddress.equals(this.requiredAddress); } byte[] remAddr = remoteAddress.getAddress(); byte[] reqAddr = this.requiredAddress.getAddress(); int nMaskFullBytes = this.nMaskBits / 8; for (int i = 0; i < nMaskFullBytes; i++) { if (remAddr[i] != reqAddr[i]) { return false; } } byte finalByte = (byte) (0xFF00 >> (this.nMaskBits & 0x07)); if (finalByte != 0) { return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte); } return true; } private static void assertNotHostName(String ipAddress) { Assert.isTrue(isIpAddress(ipAddress), () -> String.format("ipAddress %s doesn't look like an IP Address. Is it a host name?", ipAddress)); } private static boolean isIpAddress(String ipAddress) { // @formatter:off return IPV4.matcher(ipAddress).matches()
|| ipAddress.charAt(0) == '[' || ipAddress.charAt(0) == ':' || Character.digit(ipAddress.charAt(0), 16) != -1 && ipAddress.indexOf(':') > 0; // @formatter:on } private InetAddress parseAddress(String address) { try { return InetAddress.getByName(address); } catch (UnknownHostException ex) { throw new IllegalArgumentException("Failed to parse address '" + address + "'", ex); } } @Override public String toString() { String hostAddress = this.requiredAddress.getHostAddress(); return (this.nMaskBits < 0) ? "IpAddress [" + hostAddress + "]" : "IpAddress [" + hostAddress + "/" + this.nMaskBits + "]"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\IpAddressMatcher.java
1
请完成以下Java代码
public class CamundaBpmRunProcessEnginePluginHelper { protected static final CamundaBpmRunLogger LOG = CamundaBpmRunLogger.LOG; public static void registerYamlPlugins(List<ProcessEnginePlugin> processEnginePlugins, List<CamundaBpmRunProcessEnginePluginProperty> pluginsInfo) { for (CamundaBpmRunProcessEnginePluginProperty pluginInfo : pluginsInfo) { String className = pluginInfo.getPluginClass(); ProcessEnginePlugin plugin = getOrCreatePluginInstance(processEnginePlugins, className); Map<String, Object> pluginParameters = pluginInfo.getPluginParameters(); populatePluginInstance(plugin, pluginParameters); LOG.processEnginePluginRegistered(className); } } protected static ProcessEnginePlugin getOrCreatePluginInstance( List<ProcessEnginePlugin> processEnginePlugins, String className) { try { // find class on classpath Class<? extends ProcessEnginePlugin> pluginClass = ReflectUtil .loadClass(className, null, ProcessEnginePlugin.class); // check if an instance of the process engine plugin is already present Optional<ProcessEnginePlugin> plugin = processEnginePlugins.stream() .filter(p -> pluginClass.isInstance(p)).findFirst(); // get existing plugin instance or create a new one and add it to the list return plugin.orElseGet(() -> { ProcessEnginePlugin newPlugin = ReflectUtil.createInstance(pluginClass); processEnginePlugins.add(newPlugin);
return newPlugin; }); } catch (ClassNotFoundException | ClassCastException | ProcessEngineException e) { throw LOG.failedProcessEnginePluginInstantiation(className, e); } } protected static void populatePluginInstance(ProcessEnginePlugin plugin, Map<String, Object> properties) { try { SpringBootStarterPropertyHelper.applyProperties(plugin, properties, false); } catch (SpringBootStarterException e) { throw LOG.pluginPropertyNotFound(plugin.getClass().getCanonicalName(), "", e); } } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\utils\CamundaBpmRunProcessEnginePluginHelper.java
1
请完成以下Java代码
public Flux<Payload> requestChannel(Publisher<Payload> payloads) { return Flux.from(payloads).switchOnFirst((signal, innerFlux) -> { Payload firstPayload = signal.get(); Assert.notNull(firstPayload, "payload cannot be null"); return intercept(PayloadExchangeType.REQUEST_CHANNEL, firstPayload) .flatMapMany((context) -> innerFlux.index() .concatMap((tuple) -> justOrIntercept(tuple.getT1(), tuple.getT2())) .transform(this.source::requestChannel) .contextWrite(context)); }); } private Mono<Payload> justOrIntercept(Long index, Payload payload) { return (index == 0) ? Mono.just(payload) : intercept(PayloadExchangeType.PAYLOAD, payload).thenReturn(payload); } @Override public Mono<Void> metadataPush(Payload payload) { return intercept(PayloadExchangeType.METADATA_PUSH, payload) .flatMap((c) -> this.source.metadataPush(payload).contextWrite(c)); } private Mono<Context> intercept(PayloadExchangeType type, Payload payload) { return Mono.defer(() -> {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors); DefaultPayloadExchange exchange = new DefaultPayloadExchange(type, payload, this.metadataMimeType, this.dataMimeType); return chain.next(exchange) .then(Mono.fromCallable(chain::getContext)) .defaultIfEmpty(Context.empty()) .contextWrite(this.context); }); } @Override public String toString() { return getClass().getSimpleName() + "[source=" + this.source + ",interceptors=" + this.interceptors + "]"; } }
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocket.java
1
请完成以下Java代码
public Builder setUserRolePermissions(final IUserRolePermissions userRolePermissions) { this.userRolePermissions = userRolePermissions; return this; } public IUserRolePermissions getUserRolePermissions() { if (userRolePermissions == null) { return Env.getUserRolePermissions(getCtx()); } return userRolePermissions; } public Builder setAD_Tree_ID(final int AD_Tree_ID) { this.AD_Tree_ID = AD_Tree_ID; return this; } public int getAD_Tree_ID() { if (AD_Tree_ID <= 0) { throw new IllegalArgumentException("Param 'AD_Tree_ID' may not be null"); } return AD_Tree_ID; } public Builder setTrxName(@Nullable final String trxName) { this.trxName = trxName; return this; } @Nullable public String getTrxName() { return trxName; } /** * @param editable True, if tree can be modified * - includes inactive and empty summary nodes */ public Builder setEditable(final boolean editable) { this.editable = editable; return this; }
public boolean isEditable() { return editable; } /** * @param clientTree the tree is displayed on the java client (not on web) */ public Builder setClientTree(final boolean clientTree) { this.clientTree = clientTree; return this; } public boolean isClientTree() { return clientTree; } public Builder setAllNodes(final boolean allNodes) { this.allNodes = allNodes; return this; } public boolean isAllNodes() { return allNodes; } public Builder setLanguage(final String adLanguage) { this.adLanguage = adLanguage; return this; } private String getAD_Language() { if (adLanguage == null) { return Env.getADLanguageOrBaseLanguage(getCtx()); } return adLanguage; } } } // MTree
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree.java
1