instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public PersonV1 getFirstVersionOfPersonRequestParameter() { return new PersonV1("Bob Charlie"); } @GetMapping(path = "/person", params = "version=2") public PersonV2 getSecondVersionOfPersonRequestParameter() { return new PersonV2(new Name("Bob", "Charlie")); } @GetMapping(path = "/person/header", headers = "X-API-VERSION=1") public PersonV1 getFirstVersionOfPersonRequestHeader() { return new PersonV1("Bob Charlie"); } @GetMapping(path = "/person/header", headers = "X-API-VERSION=2")
public PersonV2 getSecondVersionOfPersonRequestHeader() { return new PersonV2(new Name("Bob", "Charlie")); } @GetMapping(path = "/person/accept", produces = "application/vnd.company.app-v1+json") public PersonV1 getFirstVersionOfPersonAcceptHeader() { return new PersonV1("Bob Charlie"); } @GetMapping(path = "/person/accept", produces = "application/vnd.company.app-v2+json") public PersonV2 getSecondVersionOfPersonAcceptHeader() { return new PersonV2(new Name("Bob", "Charlie")); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\versioning\VersioningPersonController.java
2
请完成以下Java代码
public Map<Class<?>, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class<?>, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class<?>, String> getBulkDeleteStatements() { return bulkDeleteStatements; } public void setBulkDeleteStatements(Map<Class<?>, String> bulkDeleteStatements) { this.bulkDeleteStatements = bulkDeleteStatements; } public Map<Class<?>, String> getSelectStatements() { return selectStatements; } public void setSelectStatements(Map<Class<?>, String> selectStatements) { this.selectStatements = selectStatements; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseCatalog() { return databaseCatalog;
} public void setDatabaseCatalog(String databaseCatalog) { this.databaseCatalog = databaseCatalog; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) { this.tablePrefixIsSchema = tablePrefixIsSchema; } public boolean isTablePrefixIsSchema() { return tablePrefixIsSchema; } public int getMaxNrOfStatementsInBulkInsert() { return maxNrOfStatementsInBulkInsert; } public void setMaxNrOfStatementsInBulkInsert(int maxNrOfStatementsInBulkInsert) { this.maxNrOfStatementsInBulkInsert = maxNrOfStatementsInBulkInsert; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSessionFactory.java
1
请完成以下Java代码
public static CoNLLSentence compute(List<Term> termList) { return new MaxEntDependencyParser().parse(termList); } /** * 分析句子的依存句法 * * @param sentence 句子 * @return CoNLL格式的依存句法树 */ public static CoNLLSentence compute(String sentence) { return new MaxEntDependencyParser().parse(sentence); } @Override protected Edge makeEdge(Node[] nodeArray, int from, int to) { LinkedList<String> context = new LinkedList<String>(); int index = from; for (int i = index - 2; i < index + 2 + 1; ++i) { Node w = i >= 0 && i < nodeArray.length ? nodeArray[i] : Node.NULL; context.add(w.compiledWord + "i" + (i - index)); // 在尾巴上做个标记,不然特征冲突了 context.add(w.label + "i" + (i - index)); } index = to; for (int i = index - 2; i < index + 2 + 1; ++i) { Node w = i >= 0 && i < nodeArray.length ? nodeArray[i] : Node.NULL; context.add(w.compiledWord + "j" + (i - index)); // 在尾巴上做个标记,不然特征冲突了 context.add(w.label + "j" + (i - index)); } context.add(nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord); context.add(nodeArray[from].label + '→' + nodeArray[to].label); context.add(nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord + (from - to)); context.add(nodeArray[from].label + '→' + nodeArray[to].label + (from - to)); Node wordBeforeI = from - 1 >= 0 ? nodeArray[from - 1] : Node.NULL; Node wordBeforeJ = to - 1 >= 0 ? nodeArray[to - 1] : Node.NULL; context.add(wordBeforeI.compiledWord + '@' + nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord);
context.add(nodeArray[from].compiledWord + '→' + wordBeforeJ.compiledWord + '@' + nodeArray[to].compiledWord); context.add(wordBeforeI.label + '@' + nodeArray[from].label + '→' + nodeArray[to].label); context.add(nodeArray[from].label + '→' + wordBeforeJ.label + '@' + nodeArray[to].label); List<Pair<String, Double>> pairList = model.predict(context.toArray(new String[0])); Pair<String, Double> maxPair = new Pair<String, Double>("null", -1.0); // System.out.println(context); // System.out.println(pairList); for (Pair<String, Double> pair : pairList) { if (pair.getValue() > maxPair.getValue() && !"null".equals(pair.getKey())) { maxPair = pair; } } // System.out.println(nodeArray[from].word + "→" + nodeArray[to].word + " : " + maxPair); return new Edge(from, to, maxPair.getKey(), (float) - Math.log(maxPair.getValue())); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\MaxEntDependencyParser.java
1
请完成以下Java代码
default LocalDate getPreviousBusinessDay(@NonNull final LocalDate date) { final int targetWorkingDays = 0; return getPreviousBusinessDay(date, targetWorkingDays); } default LocalDateTime getPreviousBusinessDay(@NonNull final LocalDateTime dateTime, final int targetWorkingDays) { final LocalDate previousDate = getPreviousBusinessDay(dateTime.toLocalDate(), targetWorkingDays); return LocalDateTime.of(previousDate, dateTime.toLocalTime()); } default ZonedDateTime getPreviousBusinessDay(@NonNull final ZonedDateTime dateTime, final int targetWorkingDays) { final LocalDate previousDate = getPreviousBusinessDay(dateTime.toLocalDate(), targetWorkingDays); return ZonedDateTime.of(previousDate, dateTime.toLocalTime(), dateTime.getZone()); } default LocalDate getPreviousBusinessDay(@NonNull final LocalDate date, final int targetWorkingDays) { Check.assumeGreaterOrEqualToZero(targetWorkingDays, "targetWorkingDays"); LocalDate currentDate = date; // Skip until we find the first business day while (!isBusinessDay(currentDate)) { currentDate = currentDate.minusDays(1); } if (targetWorkingDays == 0) { return currentDate; } int workingDays = 0;
while (true) { currentDate = currentDate.minusDays(1); final boolean isBusinessDay = isBusinessDay(currentDate); if (isBusinessDay) { workingDays++; } if (workingDays >= targetWorkingDays && isBusinessDay) { return currentDate; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\calendar\IBusinessDayMatcher.java
1
请完成以下Java代码
final class JWKS { private JWKS() { } static OctetSequenceKey.Builder signing(SecretKey key) throws JOSEException { Date issued = new Date(); return new OctetSequenceKey.Builder(key).keyOperations(Set.of(KeyOperation.SIGN)) .keyUse(KeyUse.SIGNATURE) .algorithm(JWSAlgorithm.HS256) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } static ECKey.Builder signingWithEc(ECPublicKey pub, ECPrivateKey key) throws JOSEException { Date issued = new Date(); Curve curve = Curve.forECParameterSpec(pub.getParams()); JWSAlgorithm algorithm = computeAlgorithm(curve); return new ECKey.Builder(curve, pub).privateKey(key) .keyOperations(Set.of(KeyOperation.SIGN)) .keyUse(KeyUse.SIGNATURE) .algorithm(algorithm) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } private static JWSAlgorithm computeAlgorithm(Curve curve) { try { return ECDSA.resolveAlgorithm(curve); } catch (JOSEException ex) { throw new IllegalArgumentException(ex);
} } static RSAKey.Builder signingWithRsa(RSAPublicKey pub, RSAPrivateKey key) throws JOSEException { Date issued = new Date(); return new RSAKey.Builder(pub).privateKey(key) .keyUse(KeyUse.SIGNATURE) .keyOperations(Set.of(KeyOperation.SIGN)) .algorithm(JWSAlgorithm.RS256) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JWKS.java
1
请完成以下Java代码
static <RES, REQ> DataResponse<RES> paginateList(PaginateRequest paginateRequest, Query<?, REQ> query, String defaultSort, Map<String, QueryProperty> properties, ListProcessor<REQ, RES> listProcessor) { // Use defaults for paging, if not set in the PaginationRequest, nor in the URL Integer start = paginateRequest.getStart(); if (start == null || start < 0) { start = 0; } Integer size = paginateRequest.getSize(); if (size == null || size < 0) { size = 10; } String sort = paginateRequest.getSort(); if (sort == null) { sort = defaultSort; } String order = paginateRequest.getOrder(); if (order == null) { order = "asc"; } // Sort order if (sort != null && properties != null && !properties.isEmpty()) { QueryProperty queryProperty = properties.get(sort); if (queryProperty == null) { throw new FlowableIllegalArgumentException("Value for param 'sort' is not valid, '" + sort + "' is not a valid property"); } query.orderBy(queryProperty); if ("asc".equals(order)) {
query.asc(); } else if ("desc".equals(order)) { query.desc(); } else { throw new FlowableIllegalArgumentException("Value for param 'order' is not valid : '" + order + "', must be 'asc' or 'desc'"); } } DataResponse<RES> response = new DataResponse<>(); response.setStart(start); response.setSort(sort); response.setOrder(order); // Get result and set pagination parameters List<RES> list = listProcessor.processList(query.listPage(start, size)); if (start == 0 && list.size() < size) { response.setTotal(list.size()); } else { response.setTotal(query.count()); } response.setSize(list.size()); response.setData(list); return response; } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\PaginateListUtil.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_users?cachePrepStmts=true&useServerPrepStmts=true&rewriteBatchedStatements=true&createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect
=org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.format-sql=true spring.jpa.properties.hibernate.generate_statistics=true
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertsViaSession\src\main\resources\application.properties
2
请完成以下Java代码
public DocumentPath getDocumentPath() { // TODO i think we shall make this method not mandatory in interface return null; } @Override public boolean isProcessed() { return !editable; } @Override public ImmutableSet<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public Map<String, DocumentFieldWidgetType> getWidgetTypesByFieldName() { return values.getWidgetTypesByFieldName(); } @Override public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return values.getViewEditorRenderModeByFieldName(); } @Override public List<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); } final void assertEditable() { if (!editable) { throw new AdempiereException("Row is not editable"); } } public PricingConditionsRow copyAndChangeToEditable() { if (editable) { return this;
} return toBuilder().editable(true).build(); } public LookupValuesPage getFieldTypeahead(final String fieldName, final String query) { return lookups.getFieldTypeahead(fieldName, query); } public LookupValuesList getFieldDropdown(final String fieldName) { return lookups.getFieldDropdown(fieldName); } public BPartnerId getBpartnerId() { return BPartnerId.ofRepoId(bpartner.getIdAsInt()); } public String getBpartnerDisplayName() { return bpartner.getDisplayName(); } public boolean isVendor() { return !isCustomer(); } public CurrencyId getCurrencyId() { return CurrencyId.ofRepoId(currency.getIdAsInt()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRow.java
1
请完成以下Java代码
private boolean atLeastOneMetadata(TbMsg msg) { if (!metadataNamesList.isEmpty()) { Map<String, String> metadataMap = metadataToMap(msg); return processAtLeastOne(metadataNamesList, metadataMap); } return false; } private boolean processAllKeys(List<String> data, Map<String, String> map) { for (String field : data) { if (!map.containsKey(field)) { return false; } } return true; } private boolean processAtLeastOne(List<String> data, Map<String, String> map) { for (String field : data) { if (map.containsKey(field)) {
return true; } } return false; } private Map<String, String> metadataToMap(TbMsg msg) { return msg.getMetaData().getData(); } @SuppressWarnings("unchecked") private Map<String, String> dataToMap(TbMsg msg) { return (Map<String, String>) gson.fromJson(msg.getData(), Map.class); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\filter\TbCheckMessageNode.java
1
请完成以下Java代码
public class InOutLineBPartnerAware implements IBPartnerAware { public static final IBPartnerAwareFactory factory = new IBPartnerAwareFactory() { @Override public IBPartnerAware createBPartnerAware(Object model) { final I_M_InOutLine inoutLine = InterfaceWrapperHelper.create(model, I_M_InOutLine.class); final IBPartnerAware partnerAware = new InOutLineBPartnerAware(inoutLine); return partnerAware; } }; private final I_M_InOutLine inoutLine; private InOutLineBPartnerAware(@NonNull final I_M_InOutLine inoutLine) { this.inoutLine = inoutLine; } @Override public int getAD_Client_ID() { return inoutLine.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return inoutLine.getAD_Org_ID(); } @Override public boolean isSOTrx()
{ final I_M_InOut inout = getM_InOut(); return inout.isSOTrx(); } @Override public I_C_BPartner getC_BPartner() { final I_M_InOut inout = getM_InOut(); final I_C_BPartner partner = InterfaceWrapperHelper.load(inout.getC_BPartner_ID(), I_C_BPartner.class); if (partner == null) { return null; } return partner; } private I_M_InOut getM_InOut() { final I_M_InOut inout = inoutLine.getM_InOut(); if (inout == null) { throw new AdempiereException("M_InOut_ID was not set in " + inoutLine); } return inout; } @Override public String toString() { return String.format("InOutLineBPartnerAware [inoutLine=%s, isSOTrx()=%s, getC_BPartner()=%s, getM_InOut()=%s]", inoutLine, isSOTrx(), getC_BPartner(), getM_InOut()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\InOutLineBPartnerAware.java
1
请完成以下Java代码
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyRejectedToPick (final BigDecimal QtyRejectedToPick) { set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick); } @Override public BigDecimal getQtyRejectedToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override
public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } @Override public void setSinglePackage (final boolean SinglePackage) { set_Value (COLUMNNAME_SinglePackage, SinglePackage); } @Override public boolean isSinglePackage() { return get_ValueAsBoolean(COLUMNNAME_SinglePackage); } @Override public void setWorkplaceIndicator_ID (final int WorkplaceIndicator_ID) { throw new IllegalArgumentException ("WorkplaceIndicator_ID is virtual column"); } @Override public int getWorkplaceIndicator_ID() { return get_ValueAsInt(COLUMNNAME_WorkplaceIndicator_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step.java
1
请完成以下Java代码
public class MedExpirationBatchRunner { @Autowired private Job medExpirationJob; @Autowired private JobLauncher jobLauncher; @Value("${batch.medicine.alert_type}") private String alertType; @Value("${batch.medicine.expiration.default.days}") private long defaultExpiration; @Value("${batch.medicine.start.sale.default.days}") private long saleStartDays; @Value("${batch.medicine.sale}") private double medicineSale; @Scheduled(cron = "${batch.medicine.cron}", zone = "GMT") public void runJob() { ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); launchJob(now); }
public void launchJob(ZonedDateTime triggerZonedDateTime) { try { JobParameters jobParameters = new JobParametersBuilder().addString(BatchConstants.TRIGGERED_DATE_TIME, triggerZonedDateTime.toString()) .addString(BatchConstants.ALERT_TYPE, alertType) .addLong(BatchConstants.DEFAULT_EXPIRATION, defaultExpiration) .addLong(BatchConstants.SALE_STARTS_DAYS, saleStartDays) .addDouble(BatchConstants.MEDICINE_SALE, medicineSale) .addString(BatchConstants.TRACE_ID, UUID.randomUUID() .toString()) .toJobParameters(); jobLauncher.run(medExpirationJob, jobParameters); } catch (Exception e) { log.error("Failed to run", e); } } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchreaderproperties\MedExpirationBatchRunner.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_ProductDownload[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Download URL. @param DownloadURL URL of the Download files */ public void setDownloadURL (String DownloadURL) { set_Value (COLUMNNAME_DownloadURL, DownloadURL); } /** Get Download URL. @return URL of the Download files */ public String getDownloadURL () { return (String)get_Value(COLUMNNAME_DownloadURL); } /** Set Product Download. @param M_ProductDownload_ID Product downloads */ public void setM_ProductDownload_ID (int M_ProductDownload_ID) { if (M_ProductDownload_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, Integer.valueOf(M_ProductDownload_ID)); } /** Get Product Download. @return Product downloads */ public int getM_ProductDownload_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductDownload_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item
*/ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductDownload.java
1
请完成以下Java代码
public @Nullable static InstantAndOrgId ofTimestampOrNull(@Nullable final java.sql.Timestamp timestamp, @NonNull final OrgId orgId) { if(timestamp == null) { return null; } return ofTimestamp(timestamp, orgId); } public @NonNull static InstantAndOrgId ofTimestamp(@NonNull final java.sql.Timestamp timestamp, @NonNull final OrgId orgId) { return new InstantAndOrgId(timestamp.toInstant(), orgId); } public @NonNull static InstantAndOrgId ofTimestamp(@NonNull final java.sql.Timestamp timestamp, final int orgRepoId) { return new InstantAndOrgId(timestamp.toInstant(), OrgId.ofRepoId(orgRepoId)); } public @NonNull OrgId getOrgId() {return orgId;}
public Instant toInstant() {return instant;} public @NonNull ZonedDateTime toZonedDateTime(@NonNull final ZoneId zoneId) {return instant.atZone(zoneId);} public @NonNull ZonedDateTime toZonedDateTime(@NonNull final Function<OrgId, ZoneId> orgMapper) {return instant.atZone(orgMapper.apply(orgId));} public @NonNull java.sql.Timestamp toTimestamp() {return java.sql.Timestamp.from(instant);} public LocalDate toLocalDate(@NonNull final Function<OrgId, ZoneId> orgMapper) {return toZonedDateTime(orgMapper).toLocalDate();} public LocalDateAndOrgId toLocalDateAndOrgId(@NonNull final Function<OrgId, ZoneId> orgMapper) {return LocalDateAndOrgId.ofLocalDate(toLocalDate(orgMapper), orgId);} @Override public int compareTo(@NonNull final InstantAndOrgId other) {return this.instant.compareTo(other.instant);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\InstantAndOrgId.java
1
请完成以下Java代码
public void disable() { enabled.set(false); logger.info("Disabled FactAcctRelatedDocumentsProvider"); } @Override public List<RelatedDocumentsCandidateGroup> retrieveRelatedDocumentsCandidates( @NonNull final IZoomSource fromDocument, @Nullable final AdWindowId targetWindowId) { // Return empty if not enabled if (!enabled.get()) { return ImmutableList.of(); } if (!fromDocument.isSingleKeyRecord()) { return ImmutableList.of(); } // // Get the Fact_Acct AD_Window_ID final AdWindowId factAcctWindowId = CoalesceUtil.coalesceSuppliers( () -> RecordWindowFinder.findAdWindowId(TABLENAME_Fact_Acct_Transactions_View).orElse(null), () -> RecordWindowFinder.findAdWindowId(I_Fact_Acct.Table_Name).orElse(null) ); if (factAcctWindowId == null) { return ImmutableList.of(); } // If not our target window ID, return nothing if (targetWindowId != null && !AdWindowId.equals(targetWindowId, factAcctWindowId)) { return ImmutableList.of(); } // Return nothing if source is not Posted if (fromDocument.hasField(COLUMNNAME_Posted)) { final boolean posted = fromDocument.getFieldValueAsBoolean(COLUMNNAME_Posted);
if (!posted) { return ImmutableList.of(); } } // // Build query and check count if needed final MQuery query = new MQuery(I_Fact_Acct.Table_Name); query.addRestriction(I_Fact_Acct.COLUMNNAME_AD_Table_ID, Operator.EQUAL, fromDocument.getAD_Table_ID()); query.addRestriction(I_Fact_Acct.COLUMNNAME_Record_ID, Operator.EQUAL, fromDocument.getRecord_ID()); final ITranslatableString windowCaption = adWindowDAO.retrieveWindowName(factAcctWindowId); final RelatedDocumentsCountSupplier recordsCountSupplier = new FactAcctRelatedDocumentsCountSupplier(fromDocument.getAD_Table_ID(), fromDocument.getRecord_ID()); return ImmutableList.of( RelatedDocumentsCandidateGroup.of( RelatedDocumentsCandidate.builder() .id(RelatedDocumentsId.ofString(I_Fact_Acct.Table_Name)) .internalName(I_Fact_Acct.Table_Name) .targetWindow(RelatedDocumentsTargetWindow.ofAdWindowId(factAcctWindowId)) .priority(relatedDocumentsPriority) .querySupplier(RelatedDocumentsQuerySuppliers.ofQuery(query)) .windowCaption(windowCaption) .documentsCountSupplier(recordsCountSupplier) .build())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\fact_acct\FactAcctRelatedDocumentsProvider.java
1
请完成以下Java代码
public LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength) { return findEntities(ctx, null, 0, pageLength); } @Override public LookupValue findById(final Object idObj) { final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey()); if (idNormalized == null) { return null; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getById(idNormalized); } @Override public @NonNull LookupValuesList findByIdsOrdered(@NonNull final Collection<?> ids) { final ImmutableList<Object> idsNormalized = LookupValue.normalizeIds(ids, fetcher.isNumericKey()); if (idsNormalized.isEmpty()) { return LookupValuesList.EMPTY; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getByIdsInOrder(idsNormalized); } @Override public DocumentZoomIntoInfo getDocumentZoomInto(final int id) { final String tableName = fetcher.getLookupTableName() .orElseThrow(() -> new IllegalStateException("Failed converting id=" + id + " to " + DocumentZoomIntoInfo.class + " because the fetcher returned null TableName: " + fetcher)); return DocumentZoomIntoInfo.of(tableName, id); }
@Override public Optional<WindowId> getZoomIntoWindowId() { return fetcher.getZoomIntoWindowId(); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(cacheByPartition.stats()); } @Override public void cacheInvalidate() { cacheByPartition.reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\FullyCachedLookupDataSource.java
1
请完成以下Java代码
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) { ExecutionEntity executionEntity = deleteSignalEventSubscription(execution); leaveIntermediateCatchEvent(executionEntity); } @Override public void eventCancelledByEventGateway(DelegateExecution execution) { deleteSignalEventSubscription(execution); Context.getCommandContext() .getExecutionEntityManager() .deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL); } protected ExecutionEntity deleteSignalEventSubscription(DelegateExecution execution) { ExecutionEntity executionEntity = (ExecutionEntity) execution; String eventName = null; if (signal != null) { eventName = signal.getName(); } else { eventName = signalEventDefinition.getSignalRef(); }
EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager(); List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if ( eventSubscription instanceof SignalEventSubscriptionEntity && eventSubscription.getEventName().equals(eventName) ) { eventSubscriptionEntityManager.delete(eventSubscription); } } return executionEntity; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateCatchSignalEventActivityBehavior.java
1
请完成以下Java代码
public int getPMM_PurchaseCandidate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PMM_PurchaseCandidate_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Purchase order candidate - order line. @param PMM_PurchaseCandidate_OrderLine_ID Purchase order candidate - order line */ @Override public void setPMM_PurchaseCandidate_OrderLine_ID (int PMM_PurchaseCandidate_OrderLine_ID) { if (PMM_PurchaseCandidate_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PMM_PurchaseCandidate_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PMM_PurchaseCandidate_OrderLine_ID, Integer.valueOf(PMM_PurchaseCandidate_OrderLine_ID)); } /** Get Purchase order candidate - order line. @return Purchase order candidate - order line */ @Override public int getPMM_PurchaseCandidate_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PMM_PurchaseCandidate_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bestellte Menge. @param QtyOrdered Bestellte Menge */ @Override public void setQtyOrdered (java.math.BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } /** Get Bestellte Menge. @return Bestellte Menge */ @Override public java.math.BigDecimal getQtyOrdered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null) return Env.ZERO; return bd; } /** Set Bestellte Menge (TU). @param QtyOrdered_TU Bestellte Menge (TU) */ @Override public void setQtyOrdered_TU (java.math.BigDecimal QtyOrdered_TU) { set_Value (COLUMNNAME_QtyOrdered_TU, QtyOrdered_TU); } /** Get Bestellte Menge (TU). @return Bestellte Menge (TU) */ @Override public java.math.BigDecimal getQtyOrdered_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_TU); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_OrderLine.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public TopicSubscription setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } public List<String> getProcessDefinitionIdIn() { return processDefinitionIdIn; } public TopicSubscription setProcessDefinitionIdIn(List<String> processDefinitionIds) { this.processDefinitionIdIn = processDefinitionIds; return this; } public String getProcessDefinitionKey() { return processDefinitionKey; } public TopicSubscription setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; return this; } public List<String> getProcessDefinitionKeyIn() { return processDefinitionKeyIn; } public TopicSubscription setProcessDefinitionKeyIn(List<String> processDefinitionKeys) { this.processDefinitionKeyIn = processDefinitionKeys; return this; } public String getProcessDefinitionVersionTag() { return processDefinitionVersionTag; } public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) { this.processDefinitionVersionTag = processDefinitionVersionTag; } public HashMap<String, Object> getProcessVariables() { return (HashMap<String, Object>) processVariables; } public void setProcessVariables(Map<String, Object> processVariables) { if (this.processVariables == null) { this.processVariables = new HashMap<>(); } for (Map.Entry<String, Object> processVariable : processVariables.entrySet()) { this.processVariables.put(processVariable.getKey(), processVariable.getValue()); } } public boolean isWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId;
} public List<String> getTenantIdIn() { return tenantIdIn; } public TopicSubscription setTenantIdIn(List<String> tenantIds) { this.tenantIdIn = tenantIds; return this; } public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((topicName == null) ? 0 : topicName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TopicSubscriptionImpl other = (TopicSubscriptionImpl) obj; if (topicName == null) { if (other.topicName != null) return false; } else if (!topicName.equals(other.topicName)) { return false; } return true; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionImpl.java
1
请完成以下Java代码
private static class PasswordModifyRequest implements ExtendedRequest { @Serial private static final long serialVersionUID = 3154223576081503237L; private static final byte SEQUENCE_TYPE = 48; private static final String PASSWORD_MODIFY_OID = "1.3.6.1.4.1.4203.1.11.1"; private static final byte USER_IDENTITY_OCTET_TYPE = -128; private static final byte OLD_PASSWORD_OCTET_TYPE = -127; private static final byte NEW_PASSWORD_OCTET_TYPE = -126; private final ByteArrayOutputStream value = new ByteArrayOutputStream(); PasswordModifyRequest(String userIdentity, String oldPassword, String newPassword) { ByteArrayOutputStream elements = new ByteArrayOutputStream(); if (userIdentity != null) { berEncode(USER_IDENTITY_OCTET_TYPE, userIdentity.getBytes(), elements); } if (oldPassword != null) { berEncode(OLD_PASSWORD_OCTET_TYPE, oldPassword.getBytes(), elements); } if (newPassword != null) { berEncode(NEW_PASSWORD_OCTET_TYPE, newPassword.getBytes(), elements); } berEncode(SEQUENCE_TYPE, elements.toByteArray(), this.value); } @Override public String getID() { return PASSWORD_MODIFY_OID; } @Override public byte[] getEncodedValue() { return this.value.toByteArray(); } @Override public ExtendedResponse createExtendedResponse(String id, byte[] berValue, int offset, int length) { return null; } /** * Only minimal support for <a target="_blank" href= * "https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf"> BER * encoding </a>; just what is necessary for the Password Modify request. * */ private void berEncode(byte type, byte[] src, ByteArrayOutputStream dest) { int length = src.length; dest.write(type); if (length < 128) { dest.write(length);
} else if ((length & 0x0000_00FF) == length) { dest.write((byte) 0x81); dest.write((byte) (length & 0xFF)); } else if ((length & 0x0000_FFFF) == length) { dest.write((byte) 0x82); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } else if ((length & 0x00FF_FFFF) == length) { dest.write((byte) 0x83); dest.write((byte) ((length >> 16) & 0xFF)); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } else { dest.write((byte) 0x84); dest.write((byte) ((length >> 24) & 0xFF)); dest.write((byte) ((length >> 16) & 0xFF)); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } try { dest.write(src); } catch (IOException ex) { throw new IllegalArgumentException("Failed to BER encode provided value of type: " + type); } } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsManager.java
1
请在Spring Boot框架中完成以下Java代码
public class AuditTrailFilter implements Filter { private final ProducerTemplate producerTemplate; public AuditTrailFilter(@NonNull final ProducerTemplate producerTemplate) { this.producerTemplate = producerTemplate; } @Override public void doFilter( @NonNull final ServletRequest servletRequest, @NonNull final ServletResponse servletResponse, @NonNull final FilterChain filterChain) throws IOException { final HttpServletRequest httpRequest = (HttpServletRequest)(servletRequest); final HttpServletResponse httpResponse = (HttpServletResponse)(servletResponse); try { final RequestWrapper requestWrapper = addAuditTrailHeaders(httpRequest); filterChain.doFilter(requestWrapper, httpResponse); } catch (final Exception exception) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage()); } } @NonNull private RequestWrapper addAuditTrailHeaders(@NonNull final HttpServletRequest httpRequest) { final RequestWrapper requestWrapper = new RequestWrapper(httpRequest); final TokenCredentials credentials = (TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials(); if (credentials.getAuditTrailEndpoint() == null) { return requestWrapper;
} final JsonSeqNoResponse jsonSeqNoResponse = (JsonSeqNoResponse)producerTemplate .sendBody("direct:" + ExternalSystemCamelConstants.MF_SEQ_NO_ROUTE_ID, ExchangePattern.InOut, null); if (jsonSeqNoResponse == null) { throw new RuntimeCamelException("Failed to retrieve traceId!"); } requestWrapper.setHeader(HEADER_TRACE_ID, jsonSeqNoResponse.getSeqNo()); requestWrapper.setHeader(HEADER_AUDIT_TRAIL, credentials.getAuditTrailEndpoint()); requestWrapper.setHeader(HEADER_PINSTANCE_ID, credentials.getPInstance().toString()); if (credentials.getExternalSystemValue() != null) { requestWrapper.setHeader(HEADER_EXTERNAL_SYSTEM_VALUE, credentials.getExternalSystemValue()); } return requestWrapper; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\AuditTrailFilter.java
2
请完成以下Java代码
public class X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v extends org.compiere.model.PO implements I_EDI_M_HU_PI_Item_Product_Lookup_UPC_v, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1994744480L; /** Standard Constructor */ public X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v (final Properties ctx, final int EDI_M_HU_PI_Item_Product_Lookup_UPC_v_ID, @Nullable final String trxName) { super (ctx, EDI_M_HU_PI_Item_Product_Lookup_UPC_v_ID, trxName); } /** Load Constructor */ public X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v (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 setGLN (final @Nullable java.lang.String GLN) { set_Value (COLUMNNAME_GLN, GLN); } @Override public java.lang.String getGLN() { return get_ValueAsString(COLUMNNAME_GLN); } @Override public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID) { if (M_HU_PI_Item_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID); }
@Override public int getM_HU_PI_Item_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_ID); } @Override public void setStoreGLN (final @Nullable java.lang.String StoreGLN) { set_ValueNoCheck (COLUMNNAME_StoreGLN, StoreGLN); } @Override public java.lang.String getStoreGLN() { return get_ValueAsString(COLUMNNAME_StoreGLN); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v.java
1
请完成以下Java代码
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setWriteAudit (final boolean WriteAudit) { set_Value (COLUMNNAME_WriteAudit, WriteAudit); } @Override public boolean isWriteAudit() { return get_ValueAsBoolean(COLUMNNAME_WriteAudit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config.java
1
请完成以下Java代码
public class ImportDelete extends JavaProcess { /** Table be deleted */ private int p_AD_Table_ID = 0; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (name.equals("AD_Table_ID")) p_AD_Table_ID = ((BigDecimal)para[i].getParameter()).intValue(); else log.error("Unknown Parameter: " + name); } } // prepare /**
* Perform process. * @return clear Message * @throws Exception */ protected String doIt() throws Exception { log.info("AD_Table_ID=" + p_AD_Table_ID); // get Table Info MTable table = new MTable (getCtx(), p_AD_Table_ID, get_TrxName()); if (table.get_ID() == 0) throw new IllegalArgumentException ("No AD_Table_ID=" + p_AD_Table_ID); String tableName = table.getTableName(); if (!tableName.startsWith("I")) throw new IllegalArgumentException ("Not an import table = " + tableName); // Delete String sql = "DELETE FROM " + tableName + " WHERE AD_Client_ID=" + getAD_Client_ID(); int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); String msg = Msg.translate(getCtx(), tableName + "_ID") + " #" + no; return msg; } // ImportDelete } // ImportDelete
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\ImportDelete.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getSampleCount() { return sampleCount; } public ServerFlowConfig setSampleCount(Integer sampleCount) { this.sampleCount = sampleCount; return this; } public Double getMaxAllowedQps() { return maxAllowedQps; } public ServerFlowConfig setMaxAllowedQps(Double maxAllowedQps) { this.maxAllowedQps = maxAllowedQps;
return this; } @Override public String toString() { return "ServerFlowConfig{" + "namespace='" + namespace + '\'' + ", exceedCount=" + exceedCount + ", maxOccupyRatio=" + maxOccupyRatio + ", intervalMs=" + intervalMs + ", sampleCount=" + sampleCount + ", maxAllowedQps=" + maxAllowedQps + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\config\ServerFlowConfig.java
2
请完成以下Java代码
private static BigDecimal getEquivalentInSmallerTemporalUnit(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit) { if (unit == ChronoUnit.DAYS) { return durationBD.multiply(BigDecimal.valueOf(WORK_HOURS_PER_DAY));// This refers to work hours, not calendar hours } if (unit == ChronoUnit.HOURS) { return durationBD.multiply(BigDecimal.valueOf(60)); } if (unit == ChronoUnit.MINUTES) { return durationBD.multiply(BigDecimal.valueOf(60)); } if (unit == ChronoUnit.SECONDS) { return durationBD.multiply(BigDecimal.valueOf(1000));
} throw Check.newException("No smaller temporal unit defined for {}", unit); } public static boolean isCompleteDays(@NonNull final Duration duration) { if (duration.isZero()) { return true; } final Duration daysAsDuration = Duration.ofDays(duration.toDays()); return daysAsDuration.equals(duration); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\DurationUtils.java
1
请在Spring Boot框架中完成以下Java代码
public List<DMARK1> getDMARK1() { if (dmark1 == null) { dmark1 = new ArrayList<DMARK1>(); } return this.dmark1; } /** * Gets the value of the dqvar1 property. * * @return * possible object is * {@link DQVAR1 } * */ public DQVAR1 getDQVAR1() {
return dqvar1; } /** * Sets the value of the dqvar1 property. * * @param value * allowed object is * {@link DQVAR1 } * */ public void setDQVAR1(DQVAR1 value) { this.dqvar1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DETAILXlief.java
2
请完成以下Java代码
public void setChildElements(Map<String, List<DmnExtensionElement>> childElements) { this.childElements = childElements; } @Override public DmnExtensionElement clone() { DmnExtensionElement clone = new DmnExtensionElement(); clone.setValues(this); return clone; } public void setValues(DmnExtensionElement otherElement) { setName(otherElement.getName()); setNamespacePrefix(otherElement.getNamespacePrefix()); setNamespace(otherElement.getNamespace()); setElementText(otherElement.getElementText()); setAttributes(otherElement.getAttributes());
childElements = new LinkedHashMap<>(); if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) { for (String key : otherElement.getChildElements().keySet()) { List<DmnExtensionElement> otherElementList = otherElement.getChildElements().get(key); if (otherElementList != null && !otherElementList.isEmpty()) { List<DmnExtensionElement> elementList = new ArrayList<>(); for (DmnExtensionElement dmnExtensionElement : otherElementList) { elementList.add(dmnExtensionElement.clone()); } childElements.put(key, elementList); } } } } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionElement.java
1
请在Spring Boot框架中完成以下Java代码
public Page<SysRole> listAllSysRole(Page<SysRole> page, SysRole role) { return page.setRecords(sysRoleMapper.listAllSysRole(page,role)); } @Override public SysRole getRoleNoTenant(String roleCode) { return sysRoleMapper.getRoleNoTenant(roleCode); } @Override public Result importExcelCheckRoleCode(MultipartFile file, ImportParams params) throws Exception { List<Object> listSysRoles = ExcelImportUtil.importExcel(file.getInputStream(), SysRole.class, params); int totalCount = listSysRoles.size(); List<String> errorStrs = new ArrayList<>(); // 去除 listSysRoles 中重复的数据 for (int i = 0; i < listSysRoles.size(); i++) { String roleCodeI =((SysRole)listSysRoles.get(i)).getRoleCode(); for (int j = i + 1; j < listSysRoles.size(); j++) { String roleCodeJ =((SysRole)listSysRoles.get(j)).getRoleCode(); // 发现重复数据 if (roleCodeI.equals(roleCodeJ)) { errorStrs.add("第 " + (j + 1) + " 行的 roleCode 值:" + roleCodeI + " 已存在,忽略导入"); listSysRoles.remove(j); break; } } } // 去掉 sql 中的重复数据 Integer errorLines=0; Integer successLines=0; List<String> list = ImportExcelUtil.importDateSave(listSysRoles, ISysRoleService.class, errorStrs, CommonConstant.SQL_INDEX_UNIQ_SYS_ROLE_CODE); errorLines+=list.size(); successLines+=(listSysRoles.size()-errorLines); return ImportExcelUtil.imporReturnRes(errorLines,successLines,list); } @Override @Transactional(rollbackFor = Exception.class) public boolean deleteRole(String roleid) {
//1.删除角色和用户关系 sysRoleMapper.deleteRoleUserRelation(roleid); //2.删除角色和权限关系 sysRoleMapper.deleteRolePermissionRelation(roleid); //3.删除角色 this.removeById(roleid); return true; } @Override @Transactional(rollbackFor = Exception.class) public boolean deleteBatchRole(String[] roleIds) { //1.删除角色和用户关系 sysUserMapper.deleteBathRoleUserRelation(roleIds); //2.删除角色和权限关系 sysUserMapper.deleteBathRolePermissionRelation(roleIds); //3.删除角色 this.removeByIds(Arrays.asList(roleIds)); return true; } @Override public Long getRoleCountByTenantId(String id, Integer tenantId) { return sysRoleMapper.getRoleCountByTenantId(id,tenantId); } @Override public void checkAdminRoleRejectDel(String ids) { LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<>(); query.in(SysRole::getId,Arrays.asList(ids.split(SymbolConstant.COMMA))); query.eq(SysRole::getRoleCode,"admin"); Long adminRoleCount = sysRoleMapper.selectCount(query); if(adminRoleCount>0){ throw new JeecgBootException("admin角色,不允许删除!"); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysRoleServiceImpl.java
2
请完成以下Java代码
private static JSONDocumentField toJSONDocumentField(@NonNull final String clearanceNote,@NonNull final JSONOptions jsonOpts) { final Object jsonValue = Values.valueToJsonObject(clearanceNote, jsonOpts); return JSONDocumentField.ofNameAndValue(I_M_HU.COLUMNNAME_ClearanceNote, jsonValue) .setDisplayed(true) .setMandatory(false) .setReadonly(true) .setWidgetType(JSONLayoutWidgetType.Text); } /** * Intercepts {@link IAttributeStorage} events and forwards them to {@link Execution#getCurrentDocumentChangesCollector()}. */ @EqualsAndHashCode private static final class AttributeStorage2ExecutionEventsForwarder implements IAttributeStorageListener { public static void bind(final IAttributeStorage storage, final DocumentPath documentPath) { final AttributeStorage2ExecutionEventsForwarder forwarder = new AttributeStorage2ExecutionEventsForwarder(documentPath); storage.addListener(forwarder); } private final DocumentPath documentPath; private AttributeStorage2ExecutionEventsForwarder(@NonNull final DocumentPath documentPath) { this.documentPath = documentPath; } private void forwardEvent(final IAttributeStorage storage, final IAttributeValue attributeValue) {
final IDocumentChangesCollector changesCollector = Execution.getCurrentDocumentChangesCollector(); final AttributeCode attributeCode = attributeValue.getAttributeCode(); final Object jsonValue = HUEditorRowAttributesHelper.extractJSONValue(storage, attributeValue, JSONOptions.newInstance()); final DocumentFieldWidgetType widgetType = HUEditorRowAttributesHelper.extractWidgetType(attributeValue); changesCollector.collectEvent(MutableDocumentFieldChangedEvent.of(documentPath, attributeCode.getCode(), widgetType) .setValue(jsonValue)); } @Override public void onAttributeValueCreated(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { forwardEvent(storage, attributeValue); } @Override public void onAttributeValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld) { forwardEvent(storage, attributeValue); } @Override public void onAttributeValueDeleted(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { throw new UnsupportedOperationException(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributes.java
1
请完成以下Java代码
public String toString() { return "HUAttributeTransferRequest [huContext=" + huContext + ", product=" + productId + ", qty=" + qty + ", uom=" + uom + ", attributeStorageFrom=" + attributeStorageFrom + ", attributeStorageTo=" + attributeStorageTo + ", huStorageFrom=" + huStorageFrom + ", huStorageTo=" + huStorageTo + "]"; } @Override public IHUContext getHUContext() { return huContext; } @Override public ProductId getProductId() { return productId; } @Override public BigDecimal getQty() { return qty; } @Override public I_C_UOM getC_UOM() { return uom; } @Override public IAttributeSet getAttributesFrom() { return attributeStorageFrom; } @Override public IAttributeStorage getAttributesTo() { return attributeStorageTo; } @Override public IHUStorage getHUStorageFrom() { return huStorageFrom;
} @Override public IHUStorage getHUStorageTo() { return huStorageTo; } @Override public BigDecimal getQtyUnloaded() { return qtyUnloaded; } @Override public boolean isVHUTransfer() { return vhuTransfer; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequest.java
1
请在Spring Boot框架中完成以下Java代码
public String insertPayment(Payment payment) { Date date = new Date(); Timestamp nowAsTS = new Timestamp(date.getTime()); String sql = "INSERT INTO payments(paymentId, orderId, amount, method, createdAt, status) VALUES(?,?,?,?,?,?);"; try (Connection conn = this.connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, payment.getPaymentId()); pstmt.setString(2, payment.getOrderId()); pstmt.setDouble(3, payment.getAmount()); pstmt.setString(4, payment.getPaymentMethod().toString()); pstmt.setTimestamp(5, nowAsTS); pstmt.setString(6, payment.getStatus().name()); pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); return e.getMessage(); } return ""; } public void updatePaymentStatus(Payment payment) { String sql = "UPDATE payments SET status=? WHERE paymentId=?;"; try (Connection conn = this.connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, payment.getStatus().name()); pstmt.setString(2, payment.getPaymentId()); pstmt.executeUpdate();
} catch (SQLException e) { System.out.println(e.getMessage()); } } public void readPayment(String orderId, Payment payment) { String sql = "SELECT paymentId, orderId, amount, method, createdAt, status FROM payments WHERE orderId = ?"; try (Connection conn = this.connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, orderId); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { payment.setPaymentId(rs.getString("paymentId")); payment.setOrderId(rs.getString("orderId")); payment.setAmount(rs.getDouble("amount")); payment.setCreatedAt(rs.getLong("createdAt")); payment.setStatus(Payment.Status.valueOf(rs.getString("status"))); } } catch (SQLException e) { System.out.println(e.getMessage()); } } }
repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\dao\PaymentsDAO.java
2
请完成以下Spring Boot application配置
# Temporal Cloud Configuration Profile # To use this profile: # 1. Set environment variables for your Temporal Cloud connection # 2. Run with: mvn spring-boot:run -Dspring-boot.run.profiles=cloud # # Required environment variables: # TEMPORAL_ADDRESS - Your Temporal Cloud namespace address (e.g., your-namespace.tmprl.cloud:7233) # TEMPORAL_NAMESPACE - Your Temporal Cloud namespace (e.g., your-namespace.account-id) # TEMPORAL_CERT_PATH - Path to your client certificate file (e.g., /path/to/client.pem) # TEMPORAL_KEY_PATH - Path to your client private key file (e.g., /path/to/client.key) spring: temporal: connection: mtls: enabled: true target: ${TEMPORAL_ADDRESS} cert-chain: ${TEMPORAL_CERT_PATH} private-key: ${TEMPORAL_KEY_PATH} namespace: ${TEMPORAL_NAMESPACE} # Disable local tracing for cloud (unless you have cloud tracing configured) sleuth: otel: exp
orter: otlp: endpoint: ${OTEL_ENDPOINT:} # Set to empty or configure your cloud OTLP endpoint temporal: ui: # Update these to point to Temporal Cloud Web UI webui: url: https://cloud.temporal.io/namespaces/${TEMPORAL_NAMESPACE} # Grafana and Jaeger may not be available in cloud setup grafana: url: ${GRAFANA_URL:} jaeger: url: ${JAEGER_URL:}
repos\spring-boot-demo-main\src\main\resources\application-cloud.yml
2
请完成以下Java代码
public abstract class HistoricDetailEntity implements HistoricDetail, PersistentObject, Serializable { private static final long serialVersionUID = 1L; protected String id; protected String processInstanceId; protected String activityInstanceId; protected String taskId; protected String executionId; protected Date time; protected String detailType; @Override public Object getPersistentState() { // details are not updatable so we always provide the same object as the state return HistoricDetailEntity.class; } public void delete() { DbSqlSession dbSqlSession = Context .getCommandContext() .getDbSqlSession(); dbSqlSession.delete(this); } // getters and setters ////////////////////////////////////////////////////// @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override
public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntity.java
1
请完成以下Java代码
private final Object getSegmentValue(final AccountDimension accountDimension, @NonNull final AcctSchemaElementType elementType) { Check.assumeNotNull(elementType, "elementType not null"); if (elementType.equals(AcctSchemaElementType.Organization)) { return accountDimension.getAD_Org_ID(); } else if (elementType.equals(AcctSchemaElementType.Account)) { return accountDimension.getC_ElementValue_ID(); } else if (elementType.equals(AcctSchemaElementType.SubAccount)) { return accountDimension.getC_SubAcct_ID(); } else if (elementType.equals(AcctSchemaElementType.Product)) { return accountDimension.getM_Product_ID(); } else if (elementType.equals(AcctSchemaElementType.BPartner)) { return accountDimension.getC_BPartner_ID(); } else if (elementType.equals(AcctSchemaElementType.Campaign)) { return accountDimension.getC_Campaign_ID(); } else if (elementType.equals(AcctSchemaElementType.LocationFrom)) { return accountDimension.getC_LocFrom_ID(); } else if (elementType.equals(AcctSchemaElementType.LocationTo)) { return accountDimension.getC_LocTo_ID(); } else if (elementType.equals(AcctSchemaElementType.Project)) { return accountDimension.getC_Project_ID(); } else if (elementType.equals(AcctSchemaElementType.SalesRegion)) { return accountDimension.getC_SalesRegion_ID(); } else if (elementType.equals(AcctSchemaElementType.OrgTrx)) { return accountDimension.getAD_OrgTrx_ID(); } else if (elementType.equals(AcctSchemaElementType.Activity)) { return accountDimension.getC_Activity_ID(); } else if (elementType.equals(AcctSchemaElementType.UserList1)) { return accountDimension.getUser1_ID(); }
else if (elementType.equals(AcctSchemaElementType.UserList2)) { return accountDimension.getUser2_ID(); } else if (elementType.equals(AcctSchemaElementType.UserElementString1)) { return accountDimension.getUserElementString1(); } else if (elementType.equals(AcctSchemaElementType.UserElementString2)) { return accountDimension.getUserElementString2(); } else if (elementType.equals(AcctSchemaElementType.UserElementString3)) { return accountDimension.getUserElementString3(); } else if (elementType.equals(AcctSchemaElementType.UserElementString4)) { return accountDimension.getUserElementString4(); } else if (elementType.equals(AcctSchemaElementType.UserElementString5)) { return accountDimension.getUserElementString5(); } else if (elementType.equals(AcctSchemaElementType.UserElementString6)) { return accountDimension.getUserElementString6(); } else if (elementType.equals(AcctSchemaElementType.UserElementString7)) { return accountDimension.getUserElementString7(); } else { // Unknown return -1; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AccountDimensionValidator.java
1
请完成以下Java代码
protected boolean afterSave(final boolean newRecord, final boolean success) { if (newRecord) // Add to all automatic roles { // Add to all automatic roles ... handled elsewhere } // Menu/Workflow update else if (is_ValueChanged("IsActive") || is_ValueChanged("Name") || is_ValueChanged("Description") || is_ValueChanged("Help")) { final MMenu[] menues = MMenu.get(getCtx(), "AD_Window_ID=" + getAD_Window_ID(), get_TrxName()); for (final MMenu menue : menues) { menue.setName(getName()); menue.setDescription(getDescription()); menue.setIsActive(isActive()); menue.save(); } // final X_AD_WF_Node[] nodes = getWFNodes(getCtx(), "AD_Window_ID=" + getAD_Window_ID(), get_TrxName()); for (final X_AD_WF_Node node : nodes) { boolean changed = false; if (node.isActive() != isActive()) { node.setIsActive(isActive()); changed = true; } if (node.isCentrallyMaintained()) { node.setName(getName()); node.setDescription(getDescription()); node.setHelp(getHelp()); changed = true; } if (changed) { node.save();
} } } return success; } public static X_AD_WF_Node[] getWFNodes(final Properties ctx, final String whereClause, final String trxName) { String sql = "SELECT * FROM AD_WF_Node"; if (whereClause != null && whereClause.length() > 0) { sql += " WHERE " + whereClause; } final ArrayList<X_AD_WF_Node> list = new ArrayList<>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trxName); rs = pstmt.executeQuery(); while (rs.next()) { list.add(new X_AD_WF_Node(ctx, rs, trxName)); } } catch (final Exception e) { s_log.error(sql, e); } finally { DB.close(rs, pstmt); } final X_AD_WF_Node[] retValue = new X_AD_WF_Node[list.size()]; list.toArray(retValue); return retValue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWindow.java
1
请完成以下Java代码
public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; }
public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public Date getLastFetch() { return lastFetch; } public void setLastFetch(Date lastFetch) { this.lastFetch = lastFetch; } @Override public String toString() { return "MetricPositionEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", hostname='" + hostname + '\'' + ", lastFetch=" + lastFetch + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricPositionEntity.java
1
请完成以下Java代码
public void setScrappedQty (final @Nullable BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } @Override public BigDecimal getScrappedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ScrappedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTargetQty (final @Nullable BigDecimal TargetQty) { set_Value (COLUMNNAME_TargetQty, TargetQty); } @Override public BigDecimal getTargetQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TargetQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); }
@Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_OrderLine.java
1
请完成以下Java代码
private boolean isMainProductHu(final HuId huId) { return getView().streamByIds(DocumentIdsSelection.ALL) .filter(row -> row.getType().isMainProduct() || row.isReceipt()) .flatMap(row -> row.getIncludedRows().stream()) .filter(row -> row.getType().isHUOrHUStorage()) .map(PPOrderLineRow::getHuId) .anyMatch(huId::equals); } private boolean hasPrintFormatAssigned() { final int cnt = Services.get(IQueryBL.class) .createQueryBuilder(I_M_Product_PrintFormat.class) .addInArrayFilter(I_M_Product_PrintFormat.COLUMNNAME_M_Product_ID, retrieveSelectedProductIDs()) .create() .count(); return cnt > 0; } private Set<ProductId> retrieveSelectedProductIDs() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); final ImmutableList<PPOrderLineRow> selectedRows = getView() .streamByIds(selectedRowIds) .collect(ImmutableList.toImmutableList()); final Set<ProductId> productIds = new HashSet<>(); for (final PPOrderLineRow row : selectedRows) { productIds.add(row.getProductId()); } return productIds; } private ReportResult printLabel() { final PInstanceRequest pinstanceRequest = createPInstanceRequest(); final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest); final ProcessInfo jasperProcessInfo = ProcessInfo.builder() .setCtx(getCtx()) .setProcessCalledFrom(ProcessCalledFrom.WebUI) .setAD_Process_ID(getPrintFormat().getReportProcessId()) .setAD_PInstance(adPInstanceDAO.getById(pinstanceId)) .setReportLanguage(getProcessInfo().getReportLanguage()) .setJRDesiredOutputType(OutputType.PDF) .build(); final ReportsClient reportsClient = ReportsClient.get(); return reportsClient.report(jasperProcessInfo);
} private PInstanceRequest createPInstanceRequest() { return PInstanceRequest.builder() .processId(getPrintFormat().getReportProcessId()) .processParams(ImmutableList.of( ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId()), ProcessInfoParameter.of("AD_PrintFormat_ID", printFormatId))) .build(); } private String buildFilename() { final String instance = String.valueOf(getPinstanceId().getRepoId()); final String title = getProcessInfo().getTitle(); return Joiner.on("_").skipNulls().join(instance, title) + ".pdf"; } private PrintFormat getPrintFormat() { return pfRepo.getById(PrintFormatId.ofRepoId(printFormatId)); } public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (Objects.equals(I_M_Product.COLUMNNAME_M_Product_ID, parameter.getColumnName())) { return retrieveSelectedProductIDs().stream().findFirst().orElse(null); } return DEFAULT_VALUE_NOTAVAILABLE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_PrintLabel.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Event{" + "id=" + id + ", name='" + name + '\'' + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}'; } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\jpa\localdatetimequery\Event.java
1
请完成以下Java代码
public class ValidationResultType { @XmlAttribute(name = "remark") protected String remark; @XmlAttribute(name = "record_id") protected Integer recordId; @XmlAttribute(name = "cost_unit") protected String costUnit; @XmlAttribute(name = "status", required = true) @XmlSchemaType(name = "unsignedShort") protected int status; /** * Gets the value of the remark property. * * @return * possible object is * {@link String } * */ public String getRemark() { return remark; } /** * Sets the value of the remark property. * * @param value * allowed object is * {@link String } * */ public void setRemark(String value) { this.remark = value; } /** * Gets the value of the recordId property. * * @return * possible object is * {@link Integer } * */ public Integer getRecordId() { return recordId; } /** * Sets the value of the recordId property. * * @param value * allowed object is * {@link Integer } *
*/ public void setRecordId(Integer value) { this.recordId = value; } /** * Gets the value of the costUnit property. * * @return * possible object is * {@link String } * */ public String getCostUnit() { return costUnit; } /** * Sets the value of the costUnit property. * * @param value * allowed object is * {@link String } * */ public void setCostUnit(String value) { this.costUnit = value; } /** * Gets the value of the status property. * */ public int getStatus() { return status; } /** * Sets the value of the status property. * */ public void setStatus(int value) { this.status = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ValidationResultType.java
1
请在Spring Boot框架中完成以下Java代码
public class AD_Role_CopyTemplateCustomizer implements CopyTemplateCustomizer { private final IMsgBL msgBL = Services.get(IMsgBL.class); private final IUserDAO userDAO = Services.get(IUserDAO.class); private static final AdMessageKey MSG_AD_Role_Name_Unique = AdMessageKey.of("AD_Role_Unique_Name"); private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd:HH:mm:ss"); @Override public String getTableName() {return I_AD_Role.Table_Name;} @Override public ValueToCopy extractValueToCopy(final POInfo poInfo, final String columnName) { return I_AD_Role.COLUMNNAME_Name.equals(columnName) ? ValueToCopy.explicitValueToSet(makeUniqueName()) : ValueToCopy.NOT_SPECIFIED;
} private String makeUniqueName() { final Properties ctx = Env.getCtx(); final int adUserId = Env.getAD_User_ID(ctx); final String adLanguage = Env.getAD_Language(ctx); final String timestampStr = DATE_FORMATTER.format(LocalDateTime.now()); final String userName = userDAO.retrieveUserFullName(adUserId); // Create the name using the text from the specific AD_Message. return msgBL.getMsg(adLanguage, MSG_AD_Role_Name_Unique, new String[] { userName, timestampStr }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\AD_Role_CopyTemplateCustomizer.java
2
请完成以下Java代码
private final ITrxItemChunkProcessor<IT, RT> createProcessor() { ITrxItemProcessor<IT, RT> processor = getProcessor(); if (itemsPerBatch != null) { processor = FixedBatchTrxItemProcessor.of(processor, itemsPerBatch); } return TrxItemProcessor2TrxItemChunkProcessorWrapper.wrapIfNeeded(processor); } private final ITrxItemProcessorContext createProcessorContext() { if (_processorCtx != null) { return _processorCtx; } final Properties ctx = _ctx != null ? _ctx : Env.getCtx(); final ITrx trx = trxManager.getTrx(_trxName); final ITrxItemProcessorContext processorCtx = executorService.createProcessorContext(ctx, trx); return processorCtx; } @Override public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx) { setContext(ctx, ITrx.TRXNAME_None); return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx, final String trxName) { this._processorCtx = null; this._ctx = ctx; this._trxName = trxName; return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setContext(final ITrxItemProcessorContext processorCtx) { this._processorCtx = processorCtx; this._ctx = null; this._trxName = null; return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setProcessor(final ITrxItemProcessor<IT, RT> processor) { this._processor = processor; return this; } private final ITrxItemProcessor<IT, RT> getProcessor() { Check.assumeNotNull(_processor, "processor is set");
return _processor; } @Override public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler) { this._exceptionHandler = exceptionHandler; return this; } private final ITrxItemExceptionHandler getExceptionHandler() { return _exceptionHandler; } @Override public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy) { this._onItemErrorPolicy = onItemErrorPolicy; return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch) { if (itemsPerBatch == Integer.MAX_VALUE) { this.itemsPerBatch = null; } else { this.itemsPerBatch = itemsPerBatch; } return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints) { this._useTrxSavepoints = useTrxSavepoints; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public DeliveryCost importCharges(Amount importCharges) { this.importCharges = importCharges; return this; } /** * Get importCharges * * @return importCharges **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Amount getImportCharges() { return importCharges; } public void setImportCharges(Amount importCharges) { this.importCharges = importCharges; } public DeliveryCost shippingCost(Amount shippingCost) { this.shippingCost = shippingCost; return this; } /** * Get shippingCost * * @return shippingCost **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Amount getShippingCost() { return shippingCost; } public void setShippingCost(Amount shippingCost) { this.shippingCost = shippingCost; } public DeliveryCost shippingIntermediationFee(Amount shippingIntermediationFee) { this.shippingIntermediationFee = shippingIntermediationFee; return this; } /** * Get shippingIntermediationFee * * @return shippingIntermediationFee **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Amount getShippingIntermediationFee() { return shippingIntermediationFee; } public void setShippingIntermediationFee(Amount shippingIntermediationFee) { this.shippingIntermediationFee = shippingIntermediationFee; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeliveryCost deliveryCost = (DeliveryCost)o; return Objects.equals(this.importCharges, deliveryCost.importCharges) && Objects.equals(this.shippingCost, deliveryCost.shippingCost) && Objects.equals(this.shippingIntermediationFee, deliveryCost.shippingIntermediationFee); } @Override public int hashCode() { return Objects.hash(importCharges, shippingCost, shippingIntermediationFee); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeliveryCost {\n"); sb.append(" importCharges: ").append(toIndentedString(importCharges)).append("\n"); sb.append(" shippingCost: ").append(toIndentedString(shippingCost)).append("\n"); sb.append(" shippingIntermediationFee: ").append(toIndentedString(shippingIntermediationFee)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\DeliveryCost.java
2
请在Spring Boot框架中完成以下Java代码
class AnnotationDrivenParser implements BeanDefinitionParser { @Override public @Nullable BeanDefinition parse(Element element, ParserContext parserContext) { Object source = parserContext.extractSource(element); // Register component for the surrounding <rabbit:annotation-driven> element. CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); parserContext.pushContainingComponent(compDefinition); // Nest the concrete post-processor bean in the surrounding component. BeanDefinitionRegistry registry = parserContext.getRegistry(); if (registry.containsBeanDefinition(RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)) { parserContext.getReaderContext().error( "Only one RabbitListenerAnnotationBeanPostProcessor may exist within the context.", source); } else { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RabbitListenerAnnotationBeanPostProcessor.class); builder.getRawBeanDefinition().setSource(source); String endpointRegistry = element.getAttribute("registry"); if (StringUtils.hasText(endpointRegistry)) { builder.addPropertyReference("endpointRegistry", endpointRegistry); } else { registerDefaultEndpointRegistry(source, parserContext); } String containerFactory = element.getAttribute("container-factory"); if (StringUtils.hasText(containerFactory)) { builder.addPropertyValue("containerFactoryBeanName", containerFactory); } String handlerMethodFactory = element.getAttribute("handler-method-factory"); if (StringUtils.hasText(handlerMethodFactory)) {
builder.addPropertyReference("messageHandlerMethodFactory", handlerMethodFactory); } registerInfrastructureBean(parserContext, builder, RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); } // Finally register the composite component. parserContext.popAndRegisterContainingComponent(); return null; } private static void registerDefaultEndpointRegistry(@Nullable Object source, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RabbitListenerEndpointRegistry.class); builder.getRawBeanDefinition().setSource(source); registerInfrastructureBean(parserContext, builder, RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); } private static void registerInfrastructureBean( ParserContext parserContext, BeanDefinitionBuilder builder, String beanName) { builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); parserContext.getRegistry().registerBeanDefinition(beanName, builder.getBeanDefinition()); BeanDefinitionHolder holder = new BeanDefinitionHolder(builder.getBeanDefinition(), beanName); parserContext.registerComponent(new BeanComponentDefinition(holder)); } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\AnnotationDrivenParser.java
2
请完成以下Java代码
private static String getLocationString(@Nullable final LocationId locationId) { if (locationId == null) { return "?"; } final MLocation loc = MLocation.get(Env.getCtx(), locationId.getRepoId(), ITrx.TRXNAME_ThreadInherited); if (loc == null || loc.getC_Location_ID() != locationId.getRepoId()) { return "?"; } return loc.toString(); } private static String getLocationString(final BPartnerLocationAndCaptureId bpLocationId) { if (bpLocationId == null) { return "?"; } final LocationId locationId; if (bpLocationId.getLocationCaptureId() != null)
{ locationId = bpLocationId.getLocationCaptureId(); } else { final I_C_BPartner_Location bpLocation = Services.get(IBPartnerDAO.class).getBPartnerLocationByIdEvenInactive(bpLocationId.getBpartnerLocationId()); locationId = bpLocation != null ? LocationId.ofRepoIdOrNull(bpLocation.getC_Location_ID()) : null; } if (locationId == null) { return "?"; } final I_C_Location location = Services.get(ILocationDAO.class).getById(locationId); return location != null ? location.toString() : locationId.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\TaxNotFoundException.java
1
请完成以下Java代码
public int getNonBlockingRetryDeliveryAttempt() { return fromBytes(RetryTopicHeaders.DEFAULT_HEADER_ATTEMPTS); } private int fromBytes(String headerName) { byte[] header = getHeader(headerName, byte[].class); return header == null ? 1 : ByteBuffer.wrap(header).getInt(); } /** * Get a header value with a specific type. * @param <T> the type. * @param key the header name. * @param type the type's {@link Class}. * @return the value, if present. * @throws IllegalArgumentException if the type is not correct. */ @SuppressWarnings("unchecked") @Nullable public <T> T getHeader(String key, Class<T> type) { Object value = getHeader(key); if (value == null) { return null; }
if (!type.isAssignableFrom(value.getClass())) { throw new IllegalArgumentException("Incorrect type specified for header '" + key + "'. Expected [" + type + "] but actual type is [" + value.getClass() + "]"); } return (T) value; } @Override protected MessageHeaderAccessor createAccessor(Message<?> message) { return wrap(message); } /** * Create an instance from the payload and headers of the given Message. * @param message the message. * @return the accessor. */ public static KafkaMessageHeaderAccessor wrap(Message<?> message) { return new KafkaMessageHeaderAccessor(message); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\KafkaMessageHeaderAccessor.java
1
请完成以下Java代码
public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } public static TopicRequestDto fromTopicSubscription(TopicSubscription topicSubscription, long clientLockDuration) { Long lockDuration = topicSubscription.getLockDuration(); if (lockDuration == null) { lockDuration = clientLockDuration; } String topicName = topicSubscription.getTopicName(); List<String> variables = topicSubscription.getVariableNames(); String businessKey = topicSubscription.getBusinessKey(); TopicRequestDto topicRequestDto = new TopicRequestDto(topicName, lockDuration, variables, businessKey); if (topicSubscription.getProcessDefinitionId() != null) { topicRequestDto.setProcessDefinitionId(topicSubscription.getProcessDefinitionId()); } if (topicSubscription.getProcessDefinitionIdIn() != null) { topicRequestDto.setProcessDefinitionIdIn(topicSubscription.getProcessDefinitionIdIn()); } if (topicSubscription.getProcessDefinitionKey() != null) { topicRequestDto.setProcessDefinitionKey(topicSubscription.getProcessDefinitionKey()); } if (topicSubscription.getProcessDefinitionKeyIn() != null) { topicRequestDto.setProcessDefinitionKeyIn(topicSubscription.getProcessDefinitionKeyIn()); } if (topicSubscription.isWithoutTenantId()) { topicRequestDto.setWithoutTenantId(topicSubscription.isWithoutTenantId()); } if (topicSubscription.getTenantIdIn() != null) { topicRequestDto.setTenantIdIn(topicSubscription.getTenantIdIn());
} if(topicSubscription.getProcessDefinitionVersionTag() != null) { topicRequestDto.setProcessDefinitionVersionTag(topicSubscription.getProcessDefinitionVersionTag()); } if (topicSubscription.getProcessVariables() != null) { topicRequestDto.setProcessVariables(topicSubscription.getProcessVariables()); } if (topicSubscription.isLocalVariables()) { topicRequestDto.setLocalVariables(topicSubscription.isLocalVariables()); } if(topicSubscription.isIncludeExtensionProperties()) { topicRequestDto.setIncludeExtensionProperties(topicSubscription.isIncludeExtensionProperties()); } return topicRequestDto; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\dto\TopicRequestDto.java
1
请完成以下Java代码
public class WEBUI_ServicesCompanies_Toggle_Processed extends JavaProcess implements IProcessPrecondition { private final IQueryBL queryBL = Services.get(IQueryBL.class); private static final String PARAM_PROCESSED = "Processed"; @Param(parameterName = PARAM_PROCESSED, mandatory = true) private boolean processed; @Override protected String doIt() throws Exception { final IQueryBuilder<I_S_Issue> updateProcessedQuery = queryBL .createQueryBuilder(I_S_Issue.class) .addEqualsFilter(I_S_Issue.COLUMNNAME_Processed, !processed); final IQueryFilter<I_S_Issue> selectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (selectionFilter == null) { throw new AdempiereException("@NoSelection@"); } updateProcessedQuery.filter(selectionFilter); final ICompositeQueryUpdater<I_S_Issue> processedUpdater = queryBL .createCompositeQueryUpdater(I_S_Issue.class) .addSetColumnValue(I_S_Issue.COLUMNNAME_Processed, processed);
updateProcessedQuery.create().update(processedUpdater); return MSG_OK; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\issues\WEBUI_ServicesCompanies_Toggle_Processed.java
1
请完成以下Java代码
public class AmqpMessageReturnedException extends AmqpException { @Serial private static final long serialVersionUID = 1866579721126554167L; private final transient ReturnedMessage returned; public AmqpMessageReturnedException(String message, ReturnedMessage returned) { super(message); this.returned = returned; } public Message getReturnedMessage() { return this.returned.getMessage(); } public int getReplyCode() { return this.returned.getReplyCode(); } public String getReplyText() { return this.returned.getReplyText(); } public String getExchange() { return this.returned.getExchange(); }
public String getRoutingKey() { return this.returned.getRoutingKey(); } public ReturnedMessage getReturned() { return this.returned; } @Override public String toString() { return "AmqpMessageReturnedException: " + getMessage() + ", " + this.returned.toString(); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\AmqpMessageReturnedException.java
1
请完成以下Java代码
public static int toRepoId(@Nullable final RoleId id) { return toRepoId(id, -1); } public static int toRepoId(@Nullable final RoleId id, final int defaultValue) { return id != null ? id.getRepoId() : defaultValue; } public static boolean equals(final RoleId id1, final RoleId id2) { return Objects.equals(id1, id2); } int repoId; private RoleId(final int repoId) { this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "AD_Role_ID"); }
@Override @JsonValue public int getRepoId() { return repoId; } public boolean isSystem() {return isSystem(repoId);} public static boolean isSystem(final int repoId) {return repoId == SYSTEM.repoId;} public boolean isRegular() {return isRegular(repoId);} public static boolean isRegular(final int repoId) {return !isSystem(repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\RoleId.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("fetcher", fetcher) .toString(); } private LookupValuesList getLookupValuesList(final Evaluatee parentEvaluatee) { return cacheByPartition.getOrLoad( createLookupDataSourceContext(parentEvaluatee), evalCtx -> fetcher.retrieveEntities(evalCtx).getValues()); } @NonNull private LookupDataSourceContext createLookupDataSourceContext(final Evaluatee parentEvaluatee) { return fetcher.newContextForFetchingList() .setParentEvaluatee(parentEvaluatee) .putFilter(LookupDataSourceContext.FILTER_Any, FIRST_ROW, Integer.MAX_VALUE) .build(); } @Override public LookupValuesPage findEntities(final Evaluatee ctx, final String filter, final int firstRow, final int pageLength) { final LookupValuesList partition = getLookupValuesList(ctx); if (partition.isEmpty()) { return LookupValuesPage.EMPTY; } final Predicate<LookupValue> filterPredicate = LookupValueFilterPredicates.of(filter); final LookupValuesList allMatchingValues; if (filterPredicate == LookupValueFilterPredicates.MATCH_ALL) { allMatchingValues = partition; } else { allMatchingValues = partition.filter(filterPredicate); } return allMatchingValues.pageByOffsetAndLimit(firstRow, pageLength); } @Override public LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength) { return findEntities(ctx, null, 0, pageLength); } @Override public LookupValue findById(final Object idObj) { final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey()); if (idNormalized == null) { return null; }
final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getById(idNormalized); } @Override public @NonNull LookupValuesList findByIdsOrdered(@NonNull final Collection<?> ids) { final ImmutableList<Object> idsNormalized = LookupValue.normalizeIds(ids, fetcher.isNumericKey()); if (idsNormalized.isEmpty()) { return LookupValuesList.EMPTY; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getByIdsInOrder(idsNormalized); } @Override public DocumentZoomIntoInfo getDocumentZoomInto(final int id) { final String tableName = fetcher.getLookupTableName() .orElseThrow(() -> new IllegalStateException("Failed converting id=" + id + " to " + DocumentZoomIntoInfo.class + " because the fetcher returned null TableName: " + fetcher)); return DocumentZoomIntoInfo.of(tableName, id); } @Override public Optional<WindowId> getZoomIntoWindowId() { return fetcher.getZoomIntoWindowId(); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(cacheByPartition.stats()); } @Override public void cacheInvalidate() { cacheByPartition.reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\FullyCachedLookupDataSource.java
1
请完成以下Java代码
public void setColumnName (String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName); } public String getColumnName () { return (String)get_Value(COLUMNNAME_ColumnName); } /** Set Query Criteria Function. @param QueryCriteriaFunction column used for adding a sql function to query criteria */ public void setQueryCriteriaFunction (String QueryCriteriaFunction) { set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction); } /** Get Query Criteria Function. @return column used for adding a sql function to query criteria
*/ public String getQueryCriteriaFunction () { return (String)get_Value(COLUMNNAME_QueryCriteriaFunction); } @Override public void setDefaultValue (String DefaultValue) { set_Value (COLUMNNAME_DefaultValue, DefaultValue); } @Override public String getDefaultValue () { return (String)get_Value(COLUMNNAME_DefaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java
1
请完成以下Java代码
public ResponseEntity<ArticleModel> getArticleBySlug(@PathVariable String slug) { return of(articleService.getArticleBySlug(slug) .map(ArticleModel::fromArticle)); } @PutMapping("/articles/{slug}") public ArticleModel putArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug, @RequestBody ArticlePutRequestDTO dto) { final var articleUpdated = articleService.updateArticle(jwtPayload.getUserId(), slug, dto.toUpdateRequest()); return ArticleModel.fromArticle(articleUpdated); } @PostMapping("/articles/{slug}/favorite") public ArticleModel favoriteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug) { var articleFavorited = articleService.favoriteArticle(jwtPayload.getUserId(), slug);
return ArticleModel.fromArticle(articleFavorited); } @DeleteMapping("/articles/{slug}/favorite") public ArticleModel unfavoriteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug) { var articleUnfavored = articleService.unfavoriteArticle(jwtPayload.getUserId(), slug); return ArticleModel.fromArticle(articleUnfavored); } @ResponseStatus(NO_CONTENT) @DeleteMapping("/articles/{slug}") public void deleteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug) { articleService.deleteArticleBySlug(jwtPayload.getUserId(), slug); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\article\ArticleRestController.java
1
请完成以下Java代码
public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public void setProcessDefinitionVersion(Integer processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setStartTime(Date startTime) { this.startTime = startTime; } public void setEndTime(Date endTime) {
this.endTime = endTime; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricScopeInstanceEntity.java
1
请在Spring Boot框架中完成以下Java代码
public XMLGregorianCalendar getPriceValidTo() { return priceValidTo; } /** * Sets the value of the priceValidTo property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setPriceValidTo(XMLGregorianCalendar value) { this.priceValidTo = value; } /** * Gets the value of the parties property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parties property. * * <p>
* For example, to add a new item, do as follows: * <pre> * getParties().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BusinessEntityType } * * */ public List<BusinessEntityType> getParties() { if (parties == null) { parties = new ArrayList<BusinessEntityType>(); } return this.parties; } }
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\PriceSpecificationType.java
2
请完成以下Java代码
public static ITrx unboxToNull(@Nullable final ITrx trx) { return trx != instance ? trx : null; } private NullTrxPlaceholder() { } @Override public String getTrxName() { throw new UnsupportedOperationException(); } @Override public boolean start() { throw new UnsupportedOperationException(); } @Override public boolean close() { throw new UnsupportedOperationException(); } @Override public boolean isActive() { throw new UnsupportedOperationException(); } @Override public boolean isCommittedOK() { throw new UnsupportedOperationException(); } @Override public boolean isAutoCommit() { throw new UnsupportedOperationException(); } @Override public Date getStartTime() { throw new UnsupportedOperationException(); } @Override public boolean commit(final boolean throwException) throws SQLException { throw new UnsupportedOperationException(); } @Override public boolean rollback() { throw new UnsupportedOperationException(); } @Override public boolean rollback(final boolean throwException) throws SQLException { throw new UnsupportedOperationException(); }
@Override public boolean rollback(final ITrxSavepoint savepoint) throws DBException { throw new UnsupportedOperationException(); } @Override public ITrxSavepoint createTrxSavepoint(final String name) throws DBException { throw new UnsupportedOperationException(); } @Override public void releaseSavepoint(final ITrxSavepoint savepoint) { throw new UnsupportedOperationException(); } @Override public ITrxListenerManager getTrxListenerManager() { throw new UnsupportedOperationException(); } @Override public ITrxManager getTrxManager() { throw new UnsupportedOperationException(); } @Override public <T> T setProperty(final String name, final Object value) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name, final Supplier<T> valueInitializer) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer) { throw new UnsupportedOperationException(); } @Override public <T> T setAndGetProperty(final String name, final Function<T, T> valueRemappingFunction) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\NullTrxPlaceholder.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-consumer-application cloud: # Spring Cloud Stream 配置项,对应 BindingServiceProperties 类 stream: # Binding 配置项,对应 BindingProperties Map bindings: demo01-input: destination: DEMO-TOPIC-01 # 目的地。这里使用 RocketMQ Topic content-type: application/json # 内容格式。这里使用 JSON group: demo01-consumer-group-DEMO-TOPIC-01 # 消费者分组 # Consumer 配置项,对应 ConsumerProperties 类 consumer: max-attempts: 1 # Spring Cloud Stream RocketMQ 配置项 rocketmq: # RocketMQ Binder 配置项,对应 RocketMQBinderConfigurationProperties 类 binder: name-server: 127.0.0.1:9876 # RocketMQ Namesrv 地址 # RocketMQ 自定义 Binding 配置项,对应 RocketMQBindingProperties Map bindings:
demo01-input: # RocketMQ Consumer 配置项,对应 RocketMQConsumerProperties 类 consumer: enabled: true # 是否开启消费,默认为 true broadcasting: false # 是否使用广播消费,默认为 false 使用集群消费 delay-level-when-next-consume: 0 # 异步消费消息模式下消费失败重试策略,默认为 0 server: port: ${random.int[10000,19999]} # 随机端口,方便启动多个消费者
repos\SpringBoot-Labs-master\labx-06-spring-cloud-stream-rocketmq\labx-06-sca-stream-rocketmq-consumer-error-handler\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
private boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } return o1 != null && o1.equals(o2); } public static String nestedPrefix(String prefix, String name) { String nestedPrefix = (prefix != null) ? prefix : ""; String dashedName = ConventionUtils.toDashedCase(name); nestedPrefix += nestedPrefix.isEmpty() ? dashedName : "." + dashedName; return nestedPrefix; } private static <T extends Comparable<T>> List<T> flattenValues(Map<?, List<T>> map) { List<T> content = new ArrayList<>();
for (List<T> values : map.values()) { content.addAll(values); } Collections.sort(content); return content; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(String.format("items: %n")); this.items.values().forEach((itemMetadata) -> result.append("\t").append(String.format("%s%n", itemMetadata))); return result.toString(); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ConfigurationMetadata.java
2
请完成以下Java代码
public boolean isPreserveDocumentPostedStatus() { return _preserveDocumentPostedStatus; } /** * If set, the document's "Posted" status shall not been changed. */ public PostingException setPreserveDocumentPostedStatus() { _preserveDocumentPostedStatus = true; resetMessageBuilt(); return this; } public PostingException setDocLine(final DocLine<?> docLine) { _docLine = docLine; resetMessageBuilt(); return this; } public DocLine<?> getDocLine() { return _docLine; }
@SuppressWarnings("unused") public PostingException setLogLevel(@NonNull final Level logLevel) { this._logLevel = logLevel; return this; } /** * @return recommended log level to be used when reporting this issue */ public Level getLogLevel() { return _logLevel; } @Override public PostingException setParameter( final @NonNull String parameterName, final @Nullable Object parameterValue) { super.setParameter(parameterName, parameterValue); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\PostingException.java
1
请完成以下Java代码
public class PurchaseOrderPriceCalculator { private final IPricingBL pricingBL = Services.get(IPricingBL.class); PurchaseOrderPricingInfo pricingInfo; @Builder private PurchaseOrderPriceCalculator(@NonNull final PurchaseOrderPricingInfo pricingInfo) { this.pricingInfo = pricingInfo; } public IPricingResult calculatePrice() { final IEditablePricingContext pricingCtx = createPricingContext() .setFailIfNotCalculated(); try { return pricingBL.calculatePrice(pricingCtx); } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex) .setParameter("pricingContext", pricingCtx); } } private IEditablePricingContext createPricingContext() { final IEditablePricingContext context = pricingBL.createPricingContext() .setFailIfNotCalculated()
.setOrgId(pricingInfo.getOrgId()) .setProductId(pricingInfo.getProductId()) .setBPartnerId(pricingInfo.getBpartnerId()) .setQty(pricingInfo.getQuantity()) .setConvertPriceToContextUOM(pricingInfo.isConvertPriceToContextUOM()) .setSOTrx(SOTrx.PURCHASE) .setCountryId(pricingInfo.getCountryId()) .setManualPriceEnabled(pricingInfo.getIsManualPrice()); if (pricingInfo.getIsManualPrice()) { context.setUomId(pricingInfo.getPriceEnteredUomId()) .setCurrencyId(pricingInfo.getCurrencyId()) .setManualPrice(pricingInfo.getPriceEntered()); } return context; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\PurchaseOrderPriceCalculator.java
1
请在Spring Boot框架中完成以下Java代码
public static final class AllClusterNotAvailableConditions extends AllNestedConditions { public AllClusterNotAvailableConditions() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @Conditional(ClusterNotAvailableCondition.class) static class IsClusterNotAvailableCondition { } @Conditional(NotCloudFoundryEnvironmentCondition.class) static class IsNotCloudFoundryEnvironmentCondition { } @Conditional(NotKubernetesEnvironmentCondition.class) static class IsNotKubernetesEnvironmentCondition { } } public static final class ClusterNotAvailableCondition extends ClusterAwareConfiguration.ClusterAwareCondition { @Override public synchronized boolean matches(@NonNull ConditionContext conditionContext, @NonNull AnnotatedTypeMetadata typeMetadata) { return !super.matches(conditionContext, typeMetadata); } }
public static final class NotCloudFoundryEnvironmentCondition implements Condition { @Override public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { return !CloudPlatform.CLOUD_FOUNDRY.isActive(context.getEnvironment()); } } public static final class NotKubernetesEnvironmentCondition implements Condition { @Override public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { return !CloudPlatform.KUBERNETES.isActive(context.getEnvironment()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterNotAvailableConfiguration.java
2
请完成以下Java代码
public class AdminServerModule extends SimpleModule { /** * Construct the module with a pattern for registration metadata keys. The values of * the matched metadata keys will be sanitized before serializing to json. * @param metadataKeyPatterns pattern for metadata keys which should be sanitized */ public AdminServerModule(String[] metadataKeyPatterns) { super(AdminServerModule.class.getName()); addDeserializer(Registration.class, new RegistrationDeserializer()); setSerializerModifier(new RegistrationBeanSerializerModifier(new SanitizingMapSerializer(metadataKeyPatterns))); setMixInAnnotation(InstanceDeregisteredEvent.class, InstanceDeregisteredEventMixin.class); setMixInAnnotation(InstanceEndpointsDetectedEvent.class, InstanceEndpointsDetectedEventMixin.class);
setMixInAnnotation(InstanceEvent.class, InstanceEventMixin.class); setMixInAnnotation(InstanceInfoChangedEvent.class, InstanceInfoChangedEventMixin.class); setMixInAnnotation(InstanceRegisteredEvent.class, InstanceRegisteredEventMixin.class); setMixInAnnotation(InstanceRegistrationUpdatedEvent.class, InstanceRegistrationUpdatedEventMixin.class); setMixInAnnotation(InstanceStatusChangedEvent.class, InstanceStatusChangedEventMixin.class); setMixInAnnotation(BuildVersion.class, BuildVersionMixin.class); setMixInAnnotation(Endpoint.class, EndpointMixin.class); setMixInAnnotation(Endpoints.class, EndpointsMixin.class); setMixInAnnotation(Info.class, InfoMixin.class); setMixInAnnotation(InstanceId.class, InstanceIdMixin.class); setMixInAnnotation(StatusInfo.class, StatusInfoMixin.class); setMixInAnnotation(Tags.class, TagsMixin.class); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\utils\jackson\AdminServerModule.java
1
请完成以下Java代码
public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String... args) { // Using Security Util to simulate a logged in user securityUtil.logInAs("bob"); // Let's create a Group Task (not assigned, all the members of the group can claim it) // Here 'bob' is the owner of the created task logger.info("> Creating a Group Task for 'activitiTeam'"); taskRuntime.create( TaskPayloadBuilder.create() .withName("First Team Task") .withDescription("This is something really important") .withCandidateGroup("activitiTeam") .withPriority(10) .build() ); // Let's log in as 'other' user that doesn't belong to the 'activitiTeam' group securityUtil.logInAs("other"); // Let's get all my tasks (as 'other' user) logger.info("> Getting all the tasks"); Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10)); // No tasks are returned logger.info("> Other cannot see the task: " + tasks.getTotalItems()); // Now let's switch to a user that belongs to the activitiTeam securityUtil.logInAs("john"); // Let's get 'john' tasks logger.info("> Getting all the tasks"); tasks = taskRuntime.tasks(Pageable.of(0, 10));
// 'john' can see and claim the task logger.info("> john can see the task: " + tasks.getTotalItems()); String availableTaskId = tasks.getContent().get(0).getId(); // Let's claim the task, after the claim, nobody else can see the task and 'john' becomes the assignee logger.info("> Claiming the task"); taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(availableTaskId).build()); // Let's complete the task logger.info("> Completing the task"); taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(availableTaskId).build()); } @Bean public TaskRuntimeEventListener<TaskAssignedEvent> taskAssignedListener() { return taskAssigned -> logger.info( ">>> Task Assigned: '" + taskAssigned.getEntity().getName() + "' We can send a notification to the assginee: " + taskAssigned.getEntity().getAssignee() ); } @Bean public TaskRuntimeEventListener<TaskCompletedEvent> taskCompletedListener() { return taskCompleted -> logger.info( ">>> Task Completed: '" + taskCompleted.getEntity().getName() + "' We can send a notification to the owner: " + taskCompleted.getEntity().getOwner() ); } }
repos\Activiti-develop\activiti-examples\activiti-api-basic-task-example\src\main\java\org\activiti\examples\DemoApplication.java
1
请完成以下Java代码
final class UserIdWithGroupsCollection { @NonNull public static UserIdWithGroupsCollection of(final Collection<UserGroupUserAssignment> assignments) { if (assignments.isEmpty()) { return EMPTY; } else { return new UserIdWithGroupsCollection(assignments); } } private static final UserIdWithGroupsCollection EMPTY = new UserIdWithGroupsCollection(); private final UserId userId; private final ImmutableSetMultimap<UserGroupId, Range<Instant>> validDates; private UserIdWithGroupsCollection() { validDates = ImmutableSetMultimap.of(); userId = null; } private UserIdWithGroupsCollection(final Collection<UserGroupUserAssignment> assignments) { Check.assumeNotEmpty(assignments, "assignments is not empty"); userId = getUserId(assignments); validDates = assignments.stream() .collect(ImmutableSetMultimap.toImmutableSetMultimap( UserGroupUserAssignment::getUserGroupId,// keyFunction, UserGroupUserAssignment::getValidDates // valueFunction )); } @NonNull private static UserId getUserId(final Collection<UserGroupUserAssignment> assignments) { final ImmutableSet<UserId> userIds = assignments.stream().map(UserGroupUserAssignment::getUserId).collect(ImmutableSet.toImmutableSet()); if (userIds.size() > 1) {
throw new AdempiereException("More than one user found for " + assignments); } return userIds.stream().findFirst().orElseThrow(() -> new AdempiereException("UserId should always be present on UserGroupUserAssignment" + assignments)); } public ImmutableSet<UserGroupId> getAssignedGroupIds(@NonNull final Instant date) { final Set<UserGroupId> allUserGroupIds = validDates.asMap().keySet(); return allUserGroupIds.stream() .filter(userGroupId -> hasGroupAssignment(userGroupId, date)) .collect(ImmutableSet.toImmutableSet()); } private boolean hasGroupAssignment(@NonNull final UserGroupId userGroupId, @NonNull final Instant date) { return validDates .get(userGroupId) .stream() .anyMatch(range -> range.contains(date)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserIdWithGroupsCollection.java
1
请完成以下Java代码
public I_ExternalSystem_Config getExternalSystem_Config() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class); } @Override public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Config_ProCareManagement_ID (final int ExternalSystem_Config_ProCareManagement_ID) { if (ExternalSystem_Config_ProCareManagement_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, null); else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, ExternalSystem_Config_ProCareManagement_ID); } @Override public int getExternalSystem_Config_ProCareManagement_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement.java
1
请在Spring Boot框架中完成以下Java代码
public void setTerminatedTime(Date terminatedTime) { this.terminatedTime = terminatedTime; } public Date getExitTime() { return exitTime; } public void setExitTime(Date exitTime) { this.exitTime = exitTime; } public Date getEndedTime() { return endedTime; } public void setEndedTime(Date endedTime) { this.endedTime = endedTime; } public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public boolean isCompletable() { return completable; } public void setCompletable(boolean completable) { this.completable = completable; } public String getEntryCriterionId() { return entryCriterionId; } public void setEntryCriterionId(String entryCriterionId) { this.entryCriterionId = entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; }
public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getCompletedBy() { return completedBy; } public void setCompletedBy(String completedBy) { this.completedBy = completedBy; } public String getExtraValue() { return extraValue; } public void setExtraValue(String extraValue) { this.extraValue = extraValue; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void setLocalVariables(List<RestVariable> localVariables){ this.localVariables = localVariables; } public List<RestVariable> getLocalVariables() { return localVariables; } public void addLocalVariable(RestVariable restVariable) { localVariables.add(restVariable); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public List<String> getAccepted() { return (!this.activeProfiles.isEmpty()) ? this.activeProfiles : this.defaultProfiles; } /** * Return if the given profile is active. * @param profile the profile to test * @return if the profile is active */ public boolean isAccepted(String profile) { return getAccepted().contains(profile); } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("active", getActive().toString()); creator.append("default", getDefault().toString()); creator.append("accepted", getAccepted().toString()); return creator.toString(); } /** * A profiles type that can be obtained. */ private enum Type { ACTIVE(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, Environment::getActiveProfiles, true, Collections.emptySet()), DEFAULT(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, Environment::getDefaultProfiles, false, Collections.singleton("default")); private final Function<Environment, String[]> getter; private final boolean mergeWithEnvironmentProfiles; private final String name; private final Set<String> defaultValue; Type(String name, Function<Environment, String[]> getter, boolean mergeWithEnvironmentProfiles, Set<String> defaultValue) {
this.name = name; this.getter = getter; this.mergeWithEnvironmentProfiles = mergeWithEnvironmentProfiles; this.defaultValue = defaultValue; } String getName() { return this.name; } String[] get(Environment environment) { return this.getter.apply(environment); } Set<String> getDefaultValue() { return this.defaultValue; } boolean isMergeWithEnvironmentProfiles() { return this.mergeWithEnvironmentProfiles; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\Profiles.java
2
请完成以下Java代码
public static PurchaseOrderAggregationKey fromPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem) { return PurchaseOrderAggregationKey.builder() .orgId(purchaseOrderItem.getOrgId()) .externalSystemId(purchaseOrderItem.getExternalSystemId()) .externalId(purchaseOrderItem.getExternalHeaderId()) .warehouseId(purchaseOrderItem.getWarehouseId()) .vendorId(purchaseOrderItem.getVendorId()) .datePromised(purchaseOrderItem.getDatePromised()) .dateOrdered(purchaseOrderItem.getDateOrdered()) .forecastLineId(purchaseOrderItem.getForecastLineId()) .dimension(purchaseOrderItem.getDimension()) .externalPurchaseOrderUrl(purchaseOrderItem.getExternalPurchaseOrderUrl()) .poReference(purchaseOrderItem.getPOReference()) .build(); } public static PurchaseOrderAggregationKey fromPurchaseCandidate(@NonNull final PurchaseCandidate purchaseCandidate) { return PurchaseOrderAggregationKey.builder() .orgId(purchaseCandidate.getOrgId()) .externalId(purchaseCandidate.getExternalHeaderId()) .externalSystemId(purchaseCandidate.getExternalSystemId()) .poReference(purchaseCandidate.getPOReference()) .warehouseId(purchaseCandidate.getWarehouseId())
.vendorId(purchaseCandidate.getVendorId()) .datePromised(purchaseCandidate.getPurchaseDatePromised()) .dateOrdered(purchaseCandidate.getPurchaseDateOrdered()) .forecastLineId(purchaseCandidate.getForecastLineId()) .dimension(purchaseCandidate.getDimension()) .externalPurchaseOrderUrl(purchaseCandidate.getExternalPurchaseOrderUrl()) .build(); } public static PurchaseOrderAggregationKey cast(final Object obj) { return (PurchaseOrderAggregationKey)obj; } @Override public int compareTo(@NonNull final PurchaseOrderAggregationKey other) { return COMPARATOR.compare(this, other); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseOrderAggregationKey.java
1
请在Spring Boot框架中完成以下Java代码
public Object findAndRemove() { // 设置查询条件参数 String name = "zhangsansan"; // 创建条件对象 Criteria criteria = Criteria.where("name").is(name); // 创建查询对象,然后将条件对象添加到其中 Query query = new Query(criteria); // 执行删除查找到的匹配的第一条文档,并返回删除的文档信息 User result = mongoTemplate.findAndRemove(query, User.class, COLLECTION_NAME); // 输出结果信息 String resultInfo = "成功删除文档信息,文档内容为:" + result; log.info(resultInfo); return result; } /** * 删除【符合条件】的【全部文档】,并返回删除的文档。 * * @return 删除的全部用户信息 */ public Object findAllAndRemove() {
// 设置查询条件参数 int age = 22; // 创建条件对象 Criteria criteria = Criteria.where("age").is(age); // 创建查询对象,然后将条件对象添加到其中 Query query = new Query(criteria); // 执行删除查找到的匹配的全部文档,并返回删除的全部文档信息 List<User> resultList = mongoTemplate.findAllAndRemove(query, User.class, COLLECTION_NAME); // 输出结果信息 String resultInfo = "成功删除文档信息,文档内容为:" + resultList; log.info(resultInfo); return resultList; } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\RemoveService.java
2
请完成以下Java代码
public String[] getPermissions() { return permissions; } public void setPermissions(String[] permissions) { this.permissions = permissions; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public Integer getResourceType() { return resourceType; } public void setResourceType(Integer resourceType) { this.resourceType = resourceType; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getRootProcessInstanceId() { return rootProcessInstanceId;
} public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } private static Permission[] getPermissions(Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) { int givenResourceType = dbAuthorization.getResourceType(); Permission[] permissionsByResourceType = ((ProcessEngineConfigurationImpl) engineConfiguration).getPermissionProvider().getPermissionsForResource(givenResourceType); return dbAuthorization.getPermissions(permissionsByResourceType); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationDto.java
1
请在Spring Boot框架中完成以下Java代码
public class WeixinConfigUtil { private static final Log LOG = LogFactory.getLog(WeixinConfigUtil.class); /** * 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例) */ private static Properties properties = new Properties(); private WeixinConfigUtil() { } // 通过类装载器装载进来 static { try { // 从类路径下读取属性文件 properties.load(WeixinConfigUtil.class.getClassLoader() .getResourceAsStream("weixinpay_config.properties")); } catch (IOException e) { LOG.error(e); } } /** * 函数功能说明 :读取配置项 Administrator 2012-12-14 修改者名字 : 修改日期 : 修改内容 : * * @参数: * @return void * @throws */ public static String readConfig(String key) {
return (String) properties.get(key); } //app_id public static final String appId = (String) properties.get("appId"); //商户号 public static final String mch_id = (String) properties.get("mch_id"); //商户秘钥 public static final String partnerKey = (String) properties.get("partnerKey"); //小程序支付 public static final String xAuthUrl = (String) properties.get("x_auth_url"); public static final String xGrantType = (String) properties.get("x_grant_type"); public static final String xAppId = (String) properties.get("x_appId"); public static final String xPartnerKey = (String) properties.get("x_partnerKey"); public static final String xPayKey = (String) properties.get("x_payKey"); public static final String xMchId = (String) properties.get("x_mch_id"); public static final String x_notify_url = (String) properties.get("x_notify_url"); }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\WeixinConfigUtil.java
2
请完成以下Java代码
public final class PublicKeyCredentialRpEntity { private final String name; private final String id; private PublicKeyCredentialRpEntity(String name, String id) { this.name = name; this.id = id; } /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialentity-name">name</a> * property is a human-palatable name for the entity. Its function depends on what the * PublicKeyCredentialEntity represents for the Relying Party, intended only for * display. * @return the name */ public String getName() { return this.name; } /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrpentity-id">id</a> * property is a unique identifier for the Relying Party entity, which sets the * <a href="https://www.w3.org/TR/webauthn-3/#rp-id">RP ID</a>. * @return the relying party id */ public String getId() { return this.id; } /** * Creates a new {@link PublicKeyCredentialRpEntityBuilder} * @return a new {@link PublicKeyCredentialRpEntityBuilder} */ public static PublicKeyCredentialRpEntityBuilder builder() { return new PublicKeyCredentialRpEntityBuilder(); } /** * Used to create a {@link PublicKeyCredentialRpEntity}. * * @author Rob Winch
* @since 6.4 */ public static final class PublicKeyCredentialRpEntityBuilder { private @Nullable String name; private @Nullable String id; private PublicKeyCredentialRpEntityBuilder() { } /** * Sets the {@link #getName()} property. * @param name the name property * @return the {@link PublicKeyCredentialRpEntityBuilder} */ public PublicKeyCredentialRpEntityBuilder name(String name) { this.name = name; return this; } /** * Sets the {@link #getId()} property. * @param id the id * @return the {@link PublicKeyCredentialRpEntityBuilder} */ public PublicKeyCredentialRpEntityBuilder id(String id) { this.id = id; return this; } /** * Creates a new {@link PublicKeyCredentialRpEntity}. * @return a new {@link PublicKeyCredentialRpEntity}. */ public PublicKeyCredentialRpEntity build() { Assert.notNull(this.name, "name cannot be null"); Assert.notNull(this.id, "id cannot be null"); return new PublicKeyCredentialRpEntity(this.name, this.id); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialRpEntity.java
1
请完成以下Java代码
protected boolean tryReleaseShared(int arg) { for (; ; ) { // 通过循环和CAS来保证安全的释放锁 int count = getState(); if (compareAndSetState(count, count + arg)) { setExclusiveOwnerThread(null); return true; } } } @Override protected boolean isHeldExclusively() { return getState() <= 0; } public Condition newCondition() { return new ConditionObject(); } } private Sync sync; /** * @param count 能同时获取到锁的线程数 */ public SharedLock(int count) { this.sync = new Sync(count); } @Override public void lock() { sync.acquireShared(1); } @Override public void lockInterruptibly() throws InterruptedException { sync.acquireSharedInterruptibly(1); } @Override public boolean tryLock() { try { return sync.tryAcquireSharedNanos(1, 100L); } catch (InterruptedException e) { return false; } } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
} @Override public void unlock() { sync.releaseShared(1); } @Override public Condition newCondition() { return sync.newCondition(); } public static void main(String[] args) { final Lock lock = new SharedLock(5); // 启动10个线程 for (int i = 0; i < 100; i++) { new Thread(() -> { lock.lock(); try { System.out.println(Thread.currentThread().getName()); Thread.sleep(1000); } catch (Exception e) { } finally { lock.unlock(); } }).start(); } // 每隔1秒换行 for (int i = 0; i < 20; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\SharedLock.java
1
请完成以下Java代码
public void setAlwaysReauthenticate(boolean alwaysReauthenticate) { this.alwaysReauthenticate = alwaysReauthenticate; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.eventPublisher = applicationEventPublisher; } public void setAuthenticationManager(AuthenticationManager newManager) { this.authenticationManager = newManager; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } /** * Only {@code AuthorizationFailureEvent} will be published. If you set this property * to {@code true}, {@code AuthorizedEvent}s will also be published. * @param publishAuthorizationSuccess default value is {@code false} */ public void setPublishAuthorizationSuccess(boolean publishAuthorizationSuccess) { this.publishAuthorizationSuccess = publishAuthorizationSuccess; } /** * By rejecting public invocations (and setting this property to <tt>true</tt>), * essentially you are ensuring that every secure object invocation advised by * <code>AbstractSecurityInterceptor</code> has a configuration attribute defined. * This is useful to ensure a "fail safe" mode where undeclared secure objects will be * rejected and configuration omissions detected early. An * <tt>IllegalArgumentException</tt> will be thrown by the * <tt>AbstractSecurityInterceptor</tt> if you set this property to <tt>true</tt> and * an attempt is made to invoke a secure object that has no configuration attributes. * @param rejectPublicInvocations set to <code>true</code> to reject invocations of * secure objects that have no configuration attributes (by default it is * <code>false</code> which treats undeclared secure objects as "public" or * unauthorized). */ public void setRejectPublicInvocations(boolean rejectPublicInvocations) { this.rejectPublicInvocations = rejectPublicInvocations; }
public void setRunAsManager(RunAsManager runAsManager) { this.runAsManager = runAsManager; } public void setValidateConfigAttributes(boolean validateConfigAttributes) { this.validateConfigAttributes = validateConfigAttributes; } private void publishEvent(ApplicationEvent event) { if (this.eventPublisher != null) { this.eventPublisher.publishEvent(event); } } private static class NoOpAuthenticationManager implements AuthenticationManager { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { throw new AuthenticationServiceException("Cannot authenticate " + authentication); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AbstractSecurityInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public void setVerboseMode( boolean verboseMode ) { this.verboseMode = verboseMode; } public boolean setVerboseMode() { return this.verboseMode; } // public static void main(String[] args) { // // // set verboseMode based on the environment variable // verboseMode = ("true".equals(System.getenv("EVCACHE_SAMPLE_VERBOSE"))); // // if (verboseMode) { // System.out.println("To run this sample app without using Gradle:"); // System.out.println("java -cp " + System.getProperty("java.class.path") + " com.netflix.evcache.sample.EVCacheClientSample"); // } // // try { // EVCacheClientSample evCacheClientSample = new EVCacheClientSample(); // // // Set ten keys to different values // for (int i = 0; i < 10; i++) { // String key = "key_" + i; // String value = "data_" + i; // // Set the TTL to 24 hours // int ttl = 10;
// evCacheClientSample.setKey(key, value, ttl); // } // // // Do a "get" for each of those same keys // for (int i = 0; i < 10; i++) { // String key = "key_" + i; // String value = evCacheClientSample.getKey(key); // System.out.println("Get of " + key + " returned " + value); // } // } catch (Exception e) { // e.printStackTrace(); // } // // // System.exit(0); // } }
repos\Spring-Boot-In-Action-master\springbt_evcache\src\main\java\cn\codesheep\springbt_evcache\config\EVCacheClientSample.java
2
请完成以下Java代码
private static void logColorUsingJANSI() { AnsiConsole.systemInstall(); System.out.println(ansi().fgRed().a("Some red text").fgYellow().a(" and some yellow text").reset()); AnsiConsole.systemUninstall(); } } /* * More ANSI codes: * * Always conclude your logging with the ANSI reset code: "\u001B[0m" * * In each case, replace # with the corresponding number: *
* 0 = black * 1 = red * 2 = green * 3 = yellow * 4 = blue * 5 = purple * 6 = cyan (light blue) * 7 = white * * \u001B[3#m = color font * \u001B[4#m = color background * \u001B[1;3#m = bold font * \u001B[4;3#m = underlined font * \u001B[3;3#m = italics font (not widely supported, works in VS Code) */
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\color\PrintColor.java
1
请在Spring Boot框架中完成以下Java代码
public float getCriticalHeapPercentage() { return this.criticalHeapPercentage; } public void setCriticalHeapPercentage(float criticalHeapPercentage) { this.criticalHeapPercentage = criticalHeapPercentage; } public float getCriticalOffHeapPercentage() { return this.criticalOffHeapPercentage; } public void setCriticalOffHeapPercentage(float criticalOffHeapPercentage) { this.criticalOffHeapPercentage = criticalOffHeapPercentage; } public boolean isEnableAutoRegionLookup() { return this.enableAutoRegionLookup; } public void setEnableAutoRegionLookup(boolean enableAutoRegionLookup) { this.enableAutoRegionLookup = enableAutoRegionLookup; } public float getEvictionHeapPercentage() { return this.evictionHeapPercentage; } public void setEvictionHeapPercentage(float evictionHeapPercentage) { this.evictionHeapPercentage = evictionHeapPercentage; } public float getEvictionOffHeapPercentage() { return this.evictionOffHeapPercentage; } public void setEvictionOffHeapPercentage(float evictionOffHeapPercentage) { this.evictionOffHeapPercentage = evictionOffHeapPercentage; } public String getLogLevel() { return this.logLevel; } public void setLogLevel(String logLevel) { this.logLevel = logLevel; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public OffHeapProperties getOffHeap() { return this.offHeap; } public PeerCacheProperties getPeer() { return this.peer; } public CacheServerProperties getServer() { return this.server; } public static class CompressionProperties { private String compressorBeanName; private String[] regionNames = {}; public String getCompressorBeanName() {
return this.compressorBeanName; } public void setCompressorBeanName(String compressorBeanName) { this.compressorBeanName = compressorBeanName; } public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } public static class OffHeapProperties { private String memorySize; private String[] regionNames = {}; public String getMemorySize() { return this.memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java
2
请完成以下Java代码
public ITranslatableString toTranslatableString(@NonNull final Money money) { final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(money.getCurrencyId()); return TranslatableStrings.builder() .append(money.toBigDecimal(), DisplayType.Amount) .append(" ") .append(currencyCode.toThreeLetterCode()) .build(); } public Amount toAmount(@NonNull final Money money) { return money.toAmount(currencyRepository::getCurrencyCodeById); } public Amount toAmount(@NonNull final BigDecimal value, @NonNull final CurrencyId currencyId) { final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(currencyId); return Amount.of(value, currencyCode); } public Money toMoney(@NonNull final Amount amount) { final CurrencyId currencyId = currencyRepository.getCurrencyIdByCurrencyCode(amount.getCurrencyCode()); return Money.of(amount.getAsBigDecimal(), currencyId); }
public Money multiply( @NonNull final Quantity qty, @NonNull final ProductPrice price) { final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final Quantity qtyInPriceUnit = uomConversionBL.convertQuantityTo( qty, UOMConversionContext.of(price.getProductId()), price.getUomId()); return multiply(qtyInPriceUnit, price.toMoney()); } public Money multiply(@NonNull final Quantity qty, @NonNull final Money money) { final CurrencyPrecision currencyPrecision = currencyRepository .getById(money.getCurrencyId()) .getPrecision(); final BigDecimal moneyAmount = money.toBigDecimal(); final BigDecimal netAmt = qty.toBigDecimal().multiply(moneyAmount); return Money.of( currencyPrecision.round(netAmt), money.getCurrencyId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\money\MoneyService.java
1
请在Spring Boot框架中完成以下Java代码
public class WarehouseRepository { @NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class); @VisibleForTesting public static WarehouseRepository newInstanceForUnitTesting() { Adempiere.assertUnitTestMode(); return new WarehouseRepository(); } private final CCache<Integer, WarehouseMap> cache = CCache.<Integer, WarehouseMap>builder() .tableName(I_M_Warehouse.Table_Name) .build(); @NonNull public Warehouse getById (@NonNull final WarehouseId warehouseId) { return getWarehouseMap().getById(warehouseId); } private WarehouseMap getWarehouseMap() { return cache.getOrLoad(0, this::retrieveWarehouseMap); } private WarehouseMap retrieveWarehouseMap() { final ImmutableList<Warehouse> warehouses = queryBL.createQueryBuilder(I_M_Warehouse.class) //.addOnlyActiveRecordsFilter() .create() .stream() .map(WarehouseRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new WarehouseMap(warehouses); } private static Warehouse fromRecord(@NonNull final I_M_Warehouse warehouse) { return Warehouse.builder() .warehouseId(WarehouseId.ofRepoId(warehouse.getM_Warehouse_ID())) .name(warehouse.getName()) .resourceId(ResourceId.ofRepoIdOrNull(warehouse.getPP_Plant_ID())) .active(warehouse.isActive()) .build(); }
@NonNull public ImmutableSet<WarehouseId> getAllActiveIds() { return getWarehouseMap().allActive.stream() .map(Warehouse::getWarehouseId) .collect(ImmutableSet.toImmutableSet()); } // // // // // private static final class WarehouseMap { @Getter private final ImmutableList<Warehouse> allActive; private final ImmutableMap<WarehouseId, Warehouse> byId; WarehouseMap(final List<Warehouse> list) { this.allActive = list.stream().filter(Warehouse::isActive).collect(ImmutableList.toImmutableList()); this.byId = Maps.uniqueIndex(list, Warehouse::getWarehouseId); } @NonNull public Warehouse getById(@NonNull final WarehouseId id) { final Warehouse warehouse = byId.get(id); if (warehouse == null) { throw new AdempiereException("Warehouse not found by ID: " + id); } return warehouse; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\WarehouseRepository.java
2
请完成以下Java代码
public String toString() { return "MLanguage[" + getAD_Language() + "-" + getName() + ",Language=" + getLanguageISO() + ",Country=" + getCountryCode() + "]"; } @Override protected boolean beforeSave(final boolean newRecord) { if (is_ValueChanged(COLUMNNAME_DatePattern)) { assertValidDatePattern(this); } return true; } private static final void assertValidDatePattern(I_AD_Language language) { final String datePattern = language.getDatePattern(); if (Check.isEmpty(datePattern)) { return; // OK } if (datePattern.indexOf("MM") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Month (MM)");
} if (datePattern.indexOf("dd") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Day (dd)"); } if (datePattern.indexOf("yy") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Year (yy)"); } final Locale locale = new Locale(language.getLanguageISO(), language.getCountryCode()); final SimpleDateFormat dateFormat = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale); try { dateFormat.applyPattern(datePattern); } catch (final Exception e) { throw new AdempiereException("@Error@ @DatePattern@ - " + e.getMessage(), e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLanguage.java
1
请完成以下Java代码
public ChannelDefinitionEntity findChannelDefinitionByKeyAndVersionAndTenantId(String channelDefinitionKey, Integer eventVersion, String tenantId) { Map<String, Object> params = new HashMap<>(); params.put("channelDefinitionKey", channelDefinitionKey); params.put("eventVersion", eventVersion); params.put("tenantId", tenantId); List<ChannelDefinitionEntity> results = getDbSqlSession().selectList("selectChannelDefinitionsByKeyAndVersionAndTenantId", params); if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { throw new FlowableException("There are " + results.size() + " event definitions with key = '" + channelDefinitionKey + "' and version = '" + eventVersion + "' in tenant = '" + tenantId + "'."); } return null; } @Override @SuppressWarnings("unchecked") public List<ChannelDefinition> findChannelDefinitionsByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectChannelDefinitionByNativeQuery", parameterMap); }
@Override public long findChannelDefinitionCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectChannelDefinitionCountByNativeQuery", parameterMap); } @Override public void updateChannelDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateChannelDefinitionTenantIdForDeploymentId", params); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\data\impl\MybatisChannelDefinitionDataManager.java
1
请完成以下Java代码
public void afterPropertiesSet() throws Exception { this.advisor = new ProcessStartingPointcutAdvisor(this.processEngine); } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AopInfrastructureBean) { // Ignore AOP infrastructure such as scoped proxies. return bean; } Class<?> targetClass = AopUtils.getTargetClass(bean); if (AopUtils.canApply(this.advisor, targetClass)) { if (bean instanceof Advised) { ((Advised) bean).addAdvisor(0, this.advisor); return bean; } else { ProxyFactory proxyFactory = new ProxyFactory(bean);
// Copy our properties (proxyTargetClass etc) inherited from ProxyConfig. proxyFactory.copyFrom(this); proxyFactory.addAdvisor(this.advisor); return proxyFactory.getProxy(this.beanClassLoader); } } else { // No async proxy needed. return bean; } } public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\ProcessStartAnnotationBeanPostProcessor.java
1
请完成以下Java代码
public String getObjectTypeName() { return objectTypeName; } public void setObjectTypeName(String objectTypeName) { this.objectTypeName = objectTypeName; } public String getValueSerialized() { return serializedValue; } public void setSerializedValue(String serializedValue) { this.serializedValue = serializedValue; } public boolean isDeserialized() { return isDeserialized; } @Override public Object getValue() { if(isDeserialized) { return super.getValue(); } else { throw new IllegalStateException("Object is not deserialized."); } } @SuppressWarnings("unchecked") public <T> T getValue(Class<T> type) { Object value = getValue(); if(type.isAssignableFrom(value.getClass())) { return (T) value; } else { throw new IllegalArgumentException("Value '"+value+"' is not of type '"+type+"'."); } } public Class<?> getObjectType() { Object value = getValue();
if(value == null) { return null; } else { return value.getClass(); } } @Override public SerializableValueType getType() { return (SerializableValueType) super.getType(); } public void setTransient(boolean isTransient) { this.isTransient = isTransient; } @Override public String toString() { return "ObjectValue [" + "value=" + value + ", isDeserialized=" + isDeserialized + ", serializationDataFormat=" + serializationDataFormat + ", objectTypeName=" + objectTypeName + ", serializedValue="+ (serializedValue != null ? (serializedValue.length() + " chars") : null) + ", isTransient=" + isTransient + "]"; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\ObjectValueImpl.java
1
请完成以下Spring Boot application配置
# dubbo 配置项,对应 DubboConfigurationProperties 配置类 dubbo: # Dubbo 应用配置 application: name: user-service-provider # 应用名 # Dubbo 注册中心配置 registry: address: zookeeper://127.0.0.1:2181 # 注册中心地址。配置多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。 # Dubbo 元数据中心配置 metadata-report: address: zookeeper://127.0.0.1:2181 # 元数据中心地址。元数据中心的说明,可见 http://dubbo.apache.org/zh-cn/docs/user/references/metadata/introduction.html # Dubbo 服务提供者协议配置 protocol: port: -1 # 协议端口。使用 -1 表示随机端口。 name: dubbo # 使用 `dubbo://` 协议。更多协议,可见 http://dubbo.apache.org/zh-cn/docs/user/references/protoco
l/introduction.html 文档 # Dubbo 服务提供者配置 provider: timeout: 1000 # 【重要】远程服务调用超时时间,单位:毫秒。默认为 1000 毫秒,胖友可以根据自己业务修改 UserRpcService: version: 1.0.0 # 配置扫描 Dubbo 自定义的 @Service 注解,暴露成 Dubbo 服务提供者 scan: base-packages: cn.iocoder.springboot.lab30.rpc.service
repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-annotations-demo\user-rpc-service-provider-02\src\main\resources\application.yaml
2
请完成以下Java代码
public Set<Permission> getCachedPermissions() { return cachedPermissions; } public int getRevisionNext() { return revision + 1; } public Object getPersistentState() { HashMap<String, Object> state = new HashMap<String, Object>(); state.put("userId", userId); state.put("groupId", groupId); state.put("resourceType", resourceType); state.put("resourceId", resourceId); state.put("permissions", permissions); state.put("removalTime", removalTime); state.put("rootProcessInstanceId", rootProcessInstanceId); return state; } @Override public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String getRootProcessInstanceId() { return rootProcessInstanceId;
} public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", authorizationType=" + authorizationType + ", permissions=" + permissions + ", userId=" + userId + ", groupId=" + groupId + ", resourceType=" + resourceType + ", resourceId=" + resourceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationEntity.java
1
请完成以下Java代码
public TranslatableStringBuilder append(final Boolean value) { if (value == null) { return append("?"); } else { return append(msgBL.getTranslatableMsgText(value)); } } public TranslatableStringBuilder appendADMessage( final AdMessageKey adMessage, final Object... msgParameters) { final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters); return append(value); } @Deprecated public TranslatableStringBuilder appendADMessage( @NonNull final String adMessage, final Object... msgParameters) { return appendADMessage(AdMessageKey.of(adMessage), msgParameters); } public TranslatableStringBuilder insertFirstADMessage( final AdMessageKey adMessage, final Object... msgParameters) {
final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters); return insertFirst(value); } @Deprecated public TranslatableStringBuilder insertFirstADMessage( final String adMessage, final Object... msgParameters) { return insertFirstADMessage(AdMessageKey.of(adMessage), msgParameters); } public TranslatableStringBuilder appendADElement(final String columnName) { final ITranslatableString value = msgBL.translatable(columnName); return append(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableStringBuilder.java
1
请完成以下Java代码
protected void processEventSync(EventSubscriptionEntity eventSubscriptionEntity, Object payload) { // A compensate event needs to be deleted before the handlers are called if (eventSubscriptionEntity instanceof CompensateEventSubscriptionEntity) { delete(eventSubscriptionEntity); } EventHandler eventHandler = getProcessEngineConfiguration().getEventHandler( eventSubscriptionEntity.getEventType() ); if (eventHandler == null) { throw new ActivitiException( "Could not find eventhandler for event of type '" + eventSubscriptionEntity.getEventType() + "'." ); } eventHandler.handleEvent(eventSubscriptionEntity, payload, getCommandContext()); } protected void scheduleEventAsync(EventSubscriptionEntity eventSubscriptionEntity, Object payload) { JobEntity message = getJobEntityManager().create(); message.setJobType(JobEntity.JOB_TYPE_MESSAGE); message.setJobHandlerType(ProcessEventJobHandler.TYPE); message.setJobHandlerConfiguration(eventSubscriptionEntity.getId()); message.setTenantId(eventSubscriptionEntity.getTenantId()); // TODO: support payload // if(payload != null) { // message.setEventPayload(payload); // } getJobManager().scheduleAsyncJob(message); } protected List<SignalEventSubscriptionEntity> toSignalEventSubscriptionEntityList( List<EventSubscriptionEntity> result ) { List<SignalEventSubscriptionEntity> signalEventSubscriptionEntities = new ArrayList< SignalEventSubscriptionEntity >(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) { signalEventSubscriptionEntities.add((SignalEventSubscriptionEntity) eventSubscriptionEntity); } return signalEventSubscriptionEntities; } protected List<MessageEventSubscriptionEntity> toMessageEventSubscriptionEntityList( List<EventSubscriptionEntity> result ) { List<MessageEventSubscriptionEntity> messageEventSubscriptionEntities = new ArrayList< MessageEventSubscriptionEntity >(result.size()); for (EventSubscriptionEntity eventSubscriptionEntity : result) { messageEventSubscriptionEntities.add((MessageEventSubscriptionEntity) eventSubscriptionEntity); } return messageEventSubscriptionEntities; } public EventSubscriptionDataManager getEventSubscriptionDataManager() { return eventSubscriptionDataManager; } public void setEventSubscriptionDataManager(EventSubscriptionDataManager eventSubscriptionDataManager) { this.eventSubscriptionDataManager = eventSubscriptionDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntityManagerImpl.java
1
请完成以下Java代码
public static void insertMultipleDocumentsWithStringArray() { List<String> coursesList1 = new ArrayList<>(); coursesList1.add("Chemistry"); coursesList1.add("Geography"); Document student1 = new Document().append("studentId", "STUD3") .append("name", "Sarah") .append("age", 12) .append("courses", coursesList1); List<String> coursesList2 = new ArrayList<>(); coursesList2.add("Maths"); coursesList2.add("History"); Document student2 = new Document().append("studentId", "STUD4") .append("name", "Tom") .append("age", 13) .append("courses", coursesList2); List<Document> students = new ArrayList<>(); students.add(student1); students.add(student2); collection.insertMany(students); Bson filter = in("studentId", "STUD3", "STUD4"); FindIterable<Document> documents = collection.find(filter); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void insertSingleDocumentWithObjectArray() { Document course1 = new Document().append("name", "C1") .append("points", 5); Document course2 = new Document().append("name", "C2") .append("points", 7); List<Document> coursesList = new ArrayList<>(); coursesList.add(course1); coursesList.add(course2); Document student = new Document().append("studentId", "STUD5") .append("name", "Avin") .append("age", 13)
.append("courses", coursesList); collection.insertOne(student); Bson filter = eq("studentId", "STUD5"); FindIterable<Document> documents = collection.find(filter); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void main(String args[]) { setUp(); insertSingleBsonDocumentWithStringArray(); insertSingleDocumentWithStringArray(); insertMultipleDocumentsWithStringArray(); insertSingleDocumentWithObjectArray(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\insert\InsertArrayOperation.java
1
请完成以下Java代码
public String translate() { final String msgValue = "de.metas.purchasecandidate.AvailabilityResult_" + this.toString(); return Services.get(IMsgBL.class).translate(Env.getCtx(), msgValue); } public static Type ofAvailabilityResponseItemType(@NonNull final AvailabilityResponseItem.Type type) { if (AvailabilityResponseItem.Type.AVAILABLE == type) { return Type.AVAILABLE; } else { return Type.NOT_AVAILABLE; } } } TrackingId trackingId; Type type; Quantity qty; ZonedDateTime datePromised; String availabilityText; VendorGatewayService vendorGatewayServicethatWasUsed;
@Builder private AvailabilityResult( @Nullable TrackingId trackingId, @NonNull final Type type, @NonNull final Quantity qty, @Nullable final ZonedDateTime datePromised, @Nullable final String availabilityText, @Nullable final VendorGatewayService vendorGatewayServicethatWasUsed) { this.trackingId = trackingId; this.type = type; this.qty = qty; this.datePromised = datePromised; this.availabilityText = availabilityText; this.vendorGatewayServicethatWasUsed = vendorGatewayServicethatWasUsed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityResult.java
1
请完成以下Java代码
public int getC_Flatrate_DataEntry_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_DataEntry_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override
public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setQty_Reported (final @Nullable BigDecimal Qty_Reported) { set_Value (COLUMNNAME_Qty_Reported, Qty_Reported); } @Override public BigDecimal getQty_Reported() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry_Detail.java
1
请完成以下Java代码
protected void createJobDefinitionOperationLogEntry(UserOperationLogContext opLogContext, Long previousPriority, JobDefinitionEntity jobDefinition) { PropertyChange propertyChange = new PropertyChange( JOB_DEFINITION_OVERRIDING_PRIORITY, previousPriority, jobDefinition.getOverridingJobPriority()); UserOperationLogContextEntry entry = UserOperationLogContextEntryBuilder .entry(UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY, EntityTypes.JOB_DEFINITION) .inContextOf(jobDefinition) .propertyChanges(propertyChange) .category(UserOperationLogEntry.CATEGORY_OPERATOR) .create(); opLogContext.addEntry(entry); }
protected void createCascadeJobsOperationLogEntry(UserOperationLogContext opLogContext, JobDefinitionEntity jobDefinition) { // old value is unknown PropertyChange propertyChange = new PropertyChange( SetJobPriorityCmd.JOB_PRIORITY_PROPERTY, null, jobDefinition.getOverridingJobPriority()); UserOperationLogContextEntry entry = UserOperationLogContextEntryBuilder .entry(UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY, EntityTypes.JOB) .inContextOf(jobDefinition) .propertyChanges(propertyChange) .category(UserOperationLogEntry.CATEGORY_OPERATOR) .create(); opLogContext.addEntry(entry); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetJobDefinitionPriorityCmd.java
1
请完成以下Java代码
private I_M_AttributeSetInstance getFromASI() { return _fromASI; } /** * Sets an M_AttributeSet_ID to override the one that is coming from "fromASI". * <p> * If the parameter is zero or negative, then it will be ignored, so the attribute set from "fromASI" will be used. */ public ASICopy overrideAttributeSetId(final AttributeSetId overrideAttributeSetId) { _overrideAttributeSetId = overrideAttributeSetId; return this; } private AttributeSetId getOverrideAttributeSetId() { return _overrideAttributeSetId; } /** * Adds a filter to attribute instances of "fromASI". */ public ASICopy filter(final Predicate<I_M_AttributeInstance> filter) { Preconditions.checkNotNull(filter, "filter is null"); if (attributeInstanceFilters == null) { attributeInstanceFilters = new ArrayList<>(); } attributeInstanceFilters.add(filter); return this; } /** * Creates and returns a copy of "fromASI". */ public I_M_AttributeSetInstance copy() { final I_M_AttributeSetInstance fromASI = getFromASI(); // // Copy ASI header final I_M_AttributeSetInstance toASI; { toASI = InterfaceWrapperHelper.newInstance(I_M_AttributeSetInstance.class, fromASI); InterfaceWrapperHelper.copyValues(fromASI, toASI, true); // honorIsCalculated=true final AttributeSetId overrideAttributeSetId = getOverrideAttributeSetId(); if (overrideAttributeSetId != null) { toASI.setM_AttributeSet_ID(overrideAttributeSetId.getRepoId()); }
asiDAO.save(toASI); } // // Copy attribute instances for (final I_M_AttributeInstance fromAI : asiDAO.retrieveAttributeInstances(fromASI)) { // Check/skip attribute instance if (isSkip(fromAI)) { continue; } final I_M_AttributeInstance toAI = InterfaceWrapperHelper.newInstance(I_M_AttributeInstance.class, toASI); InterfaceWrapperHelper.copyValues(fromAI, toAI, true); // honorIsCalculated=true toAI.setAD_Org_ID(toASI.getAD_Org_ID()); toAI.setM_AttributeSetInstance(toASI); asiDAO.save(toAI); } // return toASI; } private boolean isSkip(final I_M_AttributeInstance fromAI) { if (attributeInstanceFilters == null || attributeInstanceFilters.isEmpty()) { return false; // don't skip } for (final Predicate<I_M_AttributeInstance> filter : attributeInstanceFilters) { final boolean accept = filter.test(fromAI); if (!accept) { return true; // skip } } return false; // don't skip } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\ASICopy.java
1
请在Spring Boot框架中完成以下Java代码
public Access anyExchange() { return matcher(PayloadExchangeMatchers.anyExchange()); } protected AuthorizationPayloadInterceptor build() { AuthorizationPayloadInterceptor result = new AuthorizationPayloadInterceptor(this.authzBuilder.build()); result.setOrder(PayloadInterceptorOrder.AUTHORIZATION.getOrder()); return result; } public Access route(String pattern) { RSocketMessageHandler handler = getBean(RSocketMessageHandler.class); PayloadExchangeMatcher matcher = new RoutePayloadExchangeMatcher(handler.getMetadataExtractor(), handler.getRouteMatcher(), pattern); return matcher(matcher); } public Access matcher(PayloadExchangeMatcher matcher) { return new Access(matcher); } public final class Access { private final PayloadExchangeMatcher matcher; private Access(PayloadExchangeMatcher matcher) { this.matcher = matcher; } public AuthorizePayloadsSpec authenticated() { return access(AuthenticatedReactiveAuthorizationManager.authenticated()); } public AuthorizePayloadsSpec hasAuthority(String authority) { return access(AuthorityReactiveAuthorizationManager.hasAuthority(authority)); }
public AuthorizePayloadsSpec hasRole(String role) { return access(AuthorityReactiveAuthorizationManager.hasRole(role)); } public AuthorizePayloadsSpec hasAnyRole(String... roles) { return access(AuthorityReactiveAuthorizationManager.hasAnyRole(roles)); } public AuthorizePayloadsSpec permitAll() { return access((a, ctx) -> Mono.just(new AuthorizationDecision(true))); } public AuthorizePayloadsSpec hasAnyAuthority(String... authorities) { return access(AuthorityReactiveAuthorizationManager.hasAnyAuthority(authorities)); } public AuthorizePayloadsSpec access( ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authorization) { AuthorizePayloadsSpec.this.authzBuilder .add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization)); return AuthorizePayloadsSpec.this; } public AuthorizePayloadsSpec denyAll() { return access((a, ctx) -> Mono.just(new AuthorizationDecision(false))); } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurity.java
2
请在Spring Boot框架中完成以下Java代码
public class IssueHierarchy { private final Node<IssueEntity> root; public static IssueHierarchy of(@NonNull final Node<IssueEntity> root) { return new IssueHierarchy(root); } /** * @see Node#listAllNodesBelow() */ public ImmutableList<IssueEntity> listIssues() { return root.listAllNodesBelow() .stream() .map(Node::getValue) .collect(ImmutableList.toImmutableList()); } public boolean hasNodeForId(@NonNull final IssueId issueId) { return listIssues().stream().map(IssueEntity::getIssueId).anyMatch(issueId::equals); } public ImmutableList<IssueEntity> getUpStreamForId(@NonNull final IssueId issueId) { final Optional<IssueEntity> issue = getIssueForId(issueId);
if (!issue.isPresent()) { return ImmutableList.of(); } return this.root.getNode(issue.get()) .map(Node::getUpStream) .orElse(new ArrayList<>()) .stream() .map(Node::getValue) .collect(ImmutableList.toImmutableList()); } private Optional<IssueEntity> getIssueForId(@NonNull final IssueId issueId) { return listIssues() .stream() .filter(issueEntity -> issueId.equalsNullSafe(issueEntity.getIssueId())) .findFirst(); } private IssueHierarchy(final Node<IssueEntity> root) { this.root = root; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\hierarchy\IssueHierarchy.java
2
请完成以下Java代码
public Object invoke(InvocationContext ctx) throws Exception { try { Object result = ctx.proceed(); StartProcess startProcessAnnotation = ctx.getMethod().getAnnotation(StartProcess.class); String name = startProcessAnnotation.name(); String key = startProcessAnnotation.value(); Map<String, Object> variables = extractVariables(startProcessAnnotation, ctx); if (name.length() > 0) { businessProcess.startProcessByName(name, variables); } else { businessProcess.startProcessByKey(key, variables); } return result; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof Exception) { throw (Exception) cause; } else { throw e; } } catch (Exception e) { throw new FlowableException("Error while starting process using @StartProcess on method '" + ctx.getMethod() + "': " + e.getMessage(), e); } } private Map<String, Object> extractVariables(StartProcess startProcessAnnotation, InvocationContext ctx) throws Exception { Map<String, Object> variables = new HashMap<>(); for (Field field : ctx.getMethod().getDeclaringClass().getDeclaredFields()) {
if (!field.isAnnotationPresent(ProcessVariable.class)) { continue; } field.setAccessible(true); ProcessVariable processStartVariable = field.getAnnotation(ProcessVariable.class); String fieldName = processStartVariable.value(); if (fieldName == null || fieldName.length() == 0) { fieldName = field.getName(); } Object value = field.get(ctx.getTarget()); variables.put(fieldName, value); } return variables; } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\annotation\StartProcessInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public class MSV3ServerRestEndpoint { private static final Logger ROOT_LOGGER = LoggerFactory.getLogger(MSV3ServerRestEndpoint.class.getPackage().getName()); @Autowired private MSV3ServerPeerService msv3ServerPeerService; @GetMapping("/requestUpdateFromServerPeer") public void requestUpdateFromServerPeer() { msv3ServerPeerService.requestAllUpdates(); } @PutMapping("/logLevel") public void setLoggerLevel(@RequestBody final String logLevelStr) { final Level level = toSLF4JLevel(logLevelStr); getSLF4JRootLogger().setLevel(level); } @GetMapping("/logLevel") public String getLoggerLevel() {
Level level = getSLF4JRootLogger().getLevel(); return level != null ? level.toString() : null; } private ch.qos.logback.classic.Logger getSLF4JRootLogger() { return (ch.qos.logback.classic.Logger)ROOT_LOGGER; } private static Level toSLF4JLevel(final String logLevelStr) { if (logLevelStr == null) { return null; } return Level.toLevel(logLevelStr.trim()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\MSV3ServerRestEndpoint.java
2
请在Spring Boot框架中完成以下Java代码
public class RestTemplateConfiguration { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } } @RestController static class TestController { @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/hello") public String hello(String name) { // 获得服务 `demo-provider` 的一个实例 ServiceInstance instance = loadBalancerClient.choose("demo-provider"); // 发起调用 String targetUrl = instance.getUri() + "/echo?name=" + name; String response = restTemplate.getForObject(targetUrl, String.class); // 返回结果
return "consumer:" + response; } @GetMapping("/hello02") public String hello02(String name) { // 直接使用 RestTemplate 调用服务 `demo-provider` String targetUrl = "http://demo-provider/echo?name=" + name; String response = restTemplate.getForObject(targetUrl, String.class); // 返回结果 return "consumer:" + response; } } }
repos\SpringBoot-Labs-master\labx-02-spring-cloud-netflix-ribbon\labx-02-scn-ribbon-demo02A-consumer\src\main\java\cn\iocoder\springcloudnetflix\labx02\ribbondemo\consumer\DemoConsumerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public ServletApiConfigurer<H> rolePrefix(String rolePrefix) { this.securityContextRequestFilter.setRolePrefix(rolePrefix); return this; } @Override @SuppressWarnings("unchecked") public void configure(H http) { this.securityContextRequestFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); ExceptionHandlingConfigurer<H> exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class); AuthenticationEntryPoint authenticationEntryPoint = (exceptionConf != null) ? exceptionConf.getAuthenticationEntryPoint(http) : null; this.securityContextRequestFilter.setAuthenticationEntryPoint(authenticationEntryPoint); LogoutConfigurer<H> logoutConf = http.getConfigurer(LogoutConfigurer.class); List<LogoutHandler> logoutHandlers = (logoutConf != null) ? logoutConf.getLogoutHandlers() : null; this.securityContextRequestFilter.setLogoutHandlers(logoutHandlers); AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class);
if (trustResolver != null) { this.securityContextRequestFilter.setTrustResolver(trustResolver); } ApplicationContext context = http.getSharedObject(ApplicationContext.class); if (context != null) { context.getBeanProvider(GrantedAuthorityDefaults.class) .ifUnique((grantedAuthorityDefaults) -> this.securityContextRequestFilter .setRolePrefix(grantedAuthorityDefaults.getRolePrefix())); this.securityContextRequestFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); } this.securityContextRequestFilter = postProcess(this.securityContextRequestFilter); http.addFilter(this.securityContextRequestFilter); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\ServletApiConfigurer.java
2
请完成以下Java代码
public Q contentType(String contentType) { return header(HttpBaseRequest.HEADER_CONTENT_TYPE, contentType); } public String getContentType() { return getHeader(HttpBaseRequest.HEADER_CONTENT_TYPE); } @SuppressWarnings("unchecked") public Q payload(String payload) { setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD, payload); return (Q) this; } public String getPayload() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD); } public Q get() { return method(HttpGet.METHOD_NAME); } public Q post() { return method(HttpPost.METHOD_NAME); } public Q put() { return method(HttpPut.METHOD_NAME); } public Q delete() { return method(HttpDelete.METHOD_NAME); } public Q patch() { return method(HttpPatch.METHOD_NAME); } public Q head() { return method(HttpHead.METHOD_NAME); } public Q options() { return method(HttpOptions.METHOD_NAME); } public Q trace() {
return method(HttpTrace.METHOD_NAME); } public Map<String, Object> getConfigOptions() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG); } public Object getConfigOption(String field) { Map<String, Object> config = getConfigOptions(); if (config != null) { return config.get(field); } return null; } @SuppressWarnings("unchecked") public Q configOption(String field, Object value) { if (field == null || field.isEmpty() || value == null) { LOG.ignoreConfig(field, value); } else { Map<String, Object> config = getConfigOptions(); if (config == null) { config = new HashMap<>(); setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config); } config.put(field, value); } return (Q) this; } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java
1