instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
private <T extends ReactiveOAuth2AuthorizedClientProvider> T getAuthorizedClientProviderByType( Collection<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders, Class<T> providerClass) { T authorizedClientProvider = null; for (ReactiveOAuth2AuthorizedClientProvider current : authorizedClientProviders) { if (providerClass.isInstance(current)) { assertAuthorizedClientProviderIsNull(authorizedClientProvider); authorizedClientProvider = providerClass.cast(current); } } return authorizedClientProvider; } private static void assertAuthorizedClientProviderIsNull( ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider) { if (authorizedClientProvider != null) { // @formatter:off throw new BeanInitializationException(String.format( "Unable to create a %s bean. Expected one bean of type %s, but found multiple. " + "Please consider defining only a single bean of this type, or define a %s bean yourself.", ReactiveOAuth2AuthorizedClientManager.class.getName(), authorizedClientProvider.getClass().getName(), ReactiveOAuth2AuthorizedClientManager.class.getName()));
// @formatter:on } } private <T> String[] getBeanNamesForType(Class<T> beanClass) { return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, beanClass, true, true); } private <T> T getBeanOfType(ResolvableType resolvableType) { ObjectProvider<T> objectProvider = this.beanFactory.getBeanProvider(resolvableType, true); return objectProvider.getIfAvailable(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\ReactiveOAuth2ClientConfiguration.java
2
请完成以下Java代码
public void setParentMenu_ID (int ParentMenu_ID) { if (ParentMenu_ID < 1) set_Value (COLUMNNAME_ParentMenu_ID, null); else set_Value (COLUMNNAME_ParentMenu_ID, Integer.valueOf(ParentMenu_ID)); } /** Get Parent Menu. @return Parent Menu */ public int getParentMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ParentMenu_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Position. @param Position Position */ public void setPosition (String Position) { set_Value (COLUMNNAME_Position, Position); } /** Get Position. @return Position */ public String getPosition () { return (String)get_Value(COLUMNNAME_Position); } /** Set Sequence. @param Sequence Sequence */ public void setSequence (BigDecimal Sequence) { set_Value (COLUMNNAME_Sequence, Sequence); } /** Get Sequence. @return Sequence */ public BigDecimal getSequence () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence); if (bd == null) return Env.ZERO; return bd;
} /** Set Web Menu. @param U_WebMenu_ID Web Menu */ public void setU_WebMenu_ID (int U_WebMenu_ID) { if (U_WebMenu_ID < 1) set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null); else set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID)); } /** Get Web Menu. @return Web Menu */ public int getU_WebMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_WebMenu.java
1
请完成以下Java代码
public Query createNativeQuery(String sqlString, Class resultClass) { return delegate.createNativeQuery(sqlString, resultClass); } public Query createNativeQuery(String sqlString, String resultSetMapping) { return delegate.createNativeQuery(sqlString, resultSetMapping); } public StoredProcedureQuery createNamedStoredProcedureQuery(String name) { return delegate.createNamedStoredProcedureQuery(name); } public StoredProcedureQuery createStoredProcedureQuery(String procedureName) { return delegate.createStoredProcedureQuery(procedureName); } public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) { return delegate.createStoredProcedureQuery(procedureName, resultClasses); } public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) { return delegate.createStoredProcedureQuery(procedureName, resultSetMappings); } public void joinTransaction() { delegate.joinTransaction(); } public boolean isJoinedToTransaction() { return delegate.isJoinedToTransaction(); } public <T> T unwrap(Class<T> cls) { return delegate.unwrap(cls); } public Object getDelegate() { return delegate.getDelegate(); } public void close() { log.info("[I229] close"); delegate.close(); } public boolean isOpen() { boolean isOpen = delegate.isOpen(); log.info("[I236] isOpen: " + isOpen); return isOpen; } public EntityTransaction getTransaction() { log.info("[I240] getTransaction()"); return delegate.getTransaction(); } public EntityManagerFactory getEntityManagerFactory() { return delegate.getEntityManagerFactory(); } public CriteriaBuilder getCriteriaBuilder() {
return delegate.getCriteriaBuilder(); } public Metamodel getMetamodel() { return delegate.getMetamodel(); } public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) { return delegate.createEntityGraph(rootType); } public EntityGraph<?> createEntityGraph(String graphName) { return delegate.createEntityGraph(graphName); } public EntityGraph<?> getEntityGraph(String graphName) { return delegate.getEntityGraph(graphName); } public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) { return delegate.getEntityGraphs(entityClass); } public EntityManagerWrapper(EntityManager delegate) { this.delegate = delegate; } } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\CarsODataJPAServiceFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class JobController { @Autowired private JobScheduler jobScheduler; @Autowired private SampleJobService sampleJobService; @GetMapping("/run-job") public String runJob( @RequestParam(value = "name", defaultValue = "Hello World") String name) { jobScheduler.enqueue(() -> sampleJobService.execute(name)); return "Job is enqueued."; } @GetMapping("/schedule-job") public String scheduleJob(
@RequestParam(value = "name", defaultValue = "Hello World") String name, @RequestParam(value = "when", defaultValue = "PT3H") String when) { // old API, job first followed by time /* jobScheduler.schedule(() -> sampleJobService.execute(name), Instant.now().plus(Duration.parse(when))); */ // new API, time first followed by job jobScheduler.schedule( Instant.now().plus(Duration.parse(when)), () -> sampleJobService.execute(name) ); return "Job is scheduled."; } }
repos\spring-boot-master\spring-boot-jobrunr\src\main\java\com\mkyong\api\JobController.java
2
请完成以下Java代码
public DocLineSortItemFinder setDocBaseType(final String docBaseType) { _docTypeSet = true; _docBaseType = docBaseType; return this; } @Override public DocLineSortItemFinder setC_DocType(final I_C_DocType docType) { _docTypeSet = true; _docType = docType; return this; } private final String getDocBaseType() { Check.assume(_docTypeSet, "DocType or DocbaseType was set"); if (_docType != null) { return _docType.getDocBaseType(); } else if (_docBaseType != null) { return _docBaseType; } else
{ // throw new AdempiereException("DocBaseType not found"); // can be null return null; } } @Override public DocLineSortItemFinder setC_BPartner_ID(final int bpartnerId) { _bpartnerIdSet = true; _bpartnerId = bpartnerId; return this; } private final int getC_BPartner_ID() { Check.assume(_bpartnerIdSet, "C_BPartner_ID was set"); return _bpartnerId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\docline\sort\api\impl\DocLineSortItemFinder.java
1
请完成以下Java代码
public void setIsApplyToCUs (final boolean IsApplyToCUs) { set_Value (COLUMNNAME_IsApplyToCUs, IsApplyToCUs); } @Override public boolean isApplyToCUs() { return get_ValueAsBoolean(COLUMNNAME_IsApplyToCUs); } @Override public void setIsApplyToLUs (final boolean IsApplyToLUs) { set_Value (COLUMNNAME_IsApplyToLUs, IsApplyToLUs); } @Override public boolean isApplyToLUs() { return get_ValueAsBoolean(COLUMNNAME_IsApplyToLUs); } @Override public void setIsApplyToTUs (final boolean IsApplyToTUs) { set_Value (COLUMNNAME_IsApplyToTUs, IsApplyToTUs); } @Override public boolean isApplyToTUs() { return get_ValueAsBoolean(COLUMNNAME_IsApplyToTUs); } @Override public void setIsAutoPrint (final boolean IsAutoPrint) { set_Value (COLUMNNAME_IsAutoPrint, IsAutoPrint); } @Override public boolean isAutoPrint() { return get_ValueAsBoolean(COLUMNNAME_IsAutoPrint); } @Override public void setLabelReport_Process_ID (final int LabelReport_Process_ID)
{ if (LabelReport_Process_ID < 1) set_Value (COLUMNNAME_LabelReport_Process_ID, null); else set_Value (COLUMNNAME_LabelReport_Process_ID, LabelReport_Process_ID); } @Override public int getLabelReport_Process_ID() { return get_ValueAsInt(COLUMNNAME_LabelReport_Process_ID); } @Override public void setM_HU_Label_Config_ID (final int M_HU_Label_Config_ID) { if (M_HU_Label_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, M_HU_Label_Config_ID); } @Override public int getM_HU_Label_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Label_Config_ID); } @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Label_Config.java
1
请完成以下Java代码
public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; }
public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public int getStrategy() { return strategy; } public void setStrategy(int strategy) { this.strategy = strategy; } @Override public Rule toRule(){ AuthorityRule rule=new AuthorityRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\AuthorityRuleCorrectEntity.java
1
请在Spring Boot框架中完成以下Java代码
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
请完成以下Java代码
public void setDocStatus (java.lang.String DocStatus) { set_Value (COLUMNNAME_DocStatus, DocStatus); } /** Get Belegstatus. @return The current status of the document */ @Override public java.lang.String getDocStatus () { return (java.lang.String)get_Value(COLUMNNAME_DocStatus); } /** Set Nr.. @param DocumentNo Document sequence number of the document */ @Override public void setDocumentNo (java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } /** Get Nr.. @return Document sequence number of the document */ @Override public java.lang.String getDocumentNo () { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false;
} /** Set Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customs_Invoice.java
1
请完成以下Java代码
public Integer component1() { return getId(); } @Override public String component2() { return getTitle(); } @Override public String component3() { return getDescription(); } @Override public Integer component4() { return getAuthorId(); } @Override public Integer value1() { return getId(); } @Override public String value2() { return getTitle(); } @Override public String value3() { return getDescription(); } @Override public Integer value4() { return getAuthorId(); } @Override public ArticleRecord value1(Integer value) { setId(value); return this; } @Override public ArticleRecord value2(String value) {
setTitle(value); return this; } @Override public ArticleRecord value3(String value) { setDescription(value); return this; } @Override public ArticleRecord value4(Integer value) { setAuthorId(value); return this; } @Override public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ArticleRecord */ public ArticleRecord() { super(Article.ARTICLE); } /** * Create a detached, initialised ArticleRecord */ public ArticleRecord(Integer id, String title, String description, Integer authorId) { super(Article.ARTICLE); set(0, id); set(1, title); set(2, description); set(3, authorId); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java
1
请完成以下Java代码
public LinkedListNode<T> search(T value) { this.lock.readLock().lock(); try { return head.search(value); } finally { this.lock.readLock().unlock(); } } public LinkedListNode<T> add(T value) { this.lock.writeLock().lock(); try { head = new Node<T>(value, head, this); if (tail.isEmpty()) { tail = head; } size.incrementAndGet(); return head; } finally { this.lock.writeLock().unlock(); } } public boolean addAll(Collection<T> values) { this.lock.writeLock().lock(); try { for (T value : values) { if (add(value).isEmpty()) { return false; } } return true; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> remove(T value) { this.lock.writeLock().lock(); try { LinkedListNode<T> linkedListNode = head.search(value); if (!linkedListNode.isEmpty()) { if (linkedListNode == tail) { tail = tail.getPrev(); } if (linkedListNode == head) { head = head.getNext(); } linkedListNode.detach(); size.decrementAndGet(); } return linkedListNode; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> removeTail() { this.lock.writeLock().lock();
try { LinkedListNode<T> oldTail = tail; if (oldTail == head) { tail = head = dummyNode; } else { tail = tail.getPrev(); oldTail.detach(); } if (!oldTail.isEmpty()) { size.decrementAndGet(); } return oldTail; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> moveToFront(LinkedListNode<T> node) { return node.isEmpty() ? dummyNode : updateAndMoveToFront(node, node.getElement()); } public LinkedListNode<T> updateAndMoveToFront(LinkedListNode<T> node, T newValue) { this.lock.writeLock().lock(); try { if (node.isEmpty() || (this != (node.getListReference()))) { return dummyNode; } detach(node); add(newValue); return head; } finally { this.lock.writeLock().unlock(); } } private void detach(LinkedListNode<T> node) { if (node != tail) { node.detach(); if (node == head) { head = head.getNext(); } size.decrementAndGet(); } else { removeTail(); } } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\DoublyLinkedList.java
1
请完成以下Java代码
public boolean isAdditionalCustomQuery() { return get_ValueAsBoolean(COLUMNNAME_IsAdditionalCustomQuery); } @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); } @Override public int getLeichMehl_PluFile_ConfigGroup_ID()
{ return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_ConfigGroup.java
1
请完成以下Java代码
private boolean checkPostalExists(@NonNull final CountryId countryId, final String postal) { return queryBL .createQueryBuilder(I_C_Postal.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Postal.COLUMN_C_Country_ID, countryId) .filter(PostalQueryFilter.of(postal)) .create() .anyMatch(); } private void addToCPostal(@NonNull final I_C_Location location) { final I_C_Postal postal = InterfaceWrapperHelper.newInstance(I_C_Postal.class); postal.setPostal(location.getPostal()); // postal.setPostal_Add(location.getPostal_Add()); final int countryId = location.getC_Country_ID(); if (countryId <= 0) { throw new AdempiereException("@NotFound@ @C_Country_ID@: " + location); } postal.setC_Country_ID(countryId); // final int regionId = location.getC_Region_ID(); if (regionId > 0) { postal.setC_Region_ID(regionId); } postal.setRegionName(location.getRegionName()); // final int cityId = location.getC_City_ID(); if (cityId > 0) { postal.setC_City_ID(cityId); } postal.setCity(location.getCity()); InterfaceWrapperHelper.save(postal); logger.debug("Created a new C_Postal record for {}: {}", location, postal); } @Override public String toString(I_C_Location location) { return location.toString(); } @Override public String mkAddress(final I_C_Location location) { final String bPartnerBlock = null;
final String userBlock = null; final I_C_BPartner bPartner = null; return mkAddress(location, bPartner, bPartnerBlock, userBlock); } @Override public String mkAddress(final I_C_Location location, final I_C_BPartner bPartner, String bPartnerBlock, String userBlock) { final I_C_Country countryLocal = countryDAO.getDefault(Env.getCtx()); final boolean isLocalAddress = location.getC_Country_ID() == countryLocal.getC_Country_ID(); return mkAddress(location, isLocalAddress, bPartner, bPartnerBlock, userBlock); } public String mkAddress( I_C_Location location, boolean isLocalAddress, final I_C_BPartner bPartner, String bPartnerBlock, String userBlock) { final String adLanguage; final OrgId orgId; if (bPartner == null) { adLanguage = countryDAO.getDefault(Env.getCtx()).getAD_Language(); orgId = Env.getOrgId(); } else { adLanguage = bPartner.getAD_Language(); orgId = OrgId.ofRepoId(bPartner.getAD_Org_ID()); } return AddressBuilder.builder() .orgId(orgId) .adLanguage(adLanguage) .build() .buildAddressString(location, isLocalAddress, bPartnerBlock, userBlock); } @Override public I_C_Location duplicate(@NonNull final I_C_Location location) { final I_C_Location locationNew = InterfaceWrapperHelper.newInstance(I_C_Location.class, location); InterfaceWrapperHelper.copyValues(location, locationNew); InterfaceWrapperHelper.save(locationNew); return locationNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\LocationBL.java
1
请完成以下Java代码
public void setJsonRequest (java.lang.String JsonRequest) { set_Value (COLUMNNAME_JsonRequest, JsonRequest); } @Override public java.lang.String getJsonRequest() { return (java.lang.String)get_Value(COLUMNNAME_JsonRequest); } @Override public void setPP_Order_ExportAudit_ID (int PP_Order_ExportAudit_ID) { if (PP_Order_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ExportAudit_ID, Integer.valueOf(PP_Order_ExportAudit_ID)); } @Override public int getPP_Order_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ExportAudit_ID); } @Override public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_ExportAudit.java
1
请完成以下Java代码
public boolean isTaxIncluded() { return taxIncluded; } public void setTaxIncluded(boolean taxIncluded) { this.taxIncluded = taxIncluded; } /** * Negate all line amounts */ public void negateAllLineAmounts() { for (final IInvoiceCandAggregate lineAgg : getLines()) { lineAgg.negateLineAmounts(); } } /** * Calculates total net amount by summing up all {@link IInvoiceLineRW#getNetLineAmt()}s. * * @return total net amount */ public Money calculateTotalNetAmtFromLines() { final List<IInvoiceCandAggregate> lines = getLines(); Check.assume(lines != null && !lines.isEmpty(), "Invoice {} was not aggregated yet", this); Money totalNetAmt = Money.zero(currencyId); for (final IInvoiceCandAggregate lineAgg : lines) { for (final IInvoiceLineRW line : lineAgg.getAllLines()) { final Money lineNetAmt = line.getNetLineAmt(); totalNetAmt = totalNetAmt.add(lineNetAmt); } } return totalNetAmt; } public void setPaymentTermId(@Nullable final PaymentTermId paymentTermId) { this.paymentTermId = paymentTermId; } @Override public PaymentTermId getPaymentTermId() { return paymentTermId; } public void setPaymentRule(@Nullable final String paymentRule) { this.paymentRule = paymentRule; } @Override
public String getPaymentRule() { return paymentRule; } @Override public String getExternalId() { return externalId; } @Override public int getC_Async_Batch_ID() { return C_Async_Batch_ID; } public void setC_Async_Batch_ID(final int C_Async_Batch_ID) { this.C_Async_Batch_ID = C_Async_Batch_ID; } public String setExternalId(String externalId) { return this.externalId = externalId; } @Override public int getC_Incoterms_ID() { return C_Incoterms_ID; } public void setC_Incoterms_ID(final int C_Incoterms_ID) { this.C_Incoterms_ID = C_Incoterms_ID; } @Override public String getIncotermLocation() { return incotermLocation; } public void setIncotermLocation(final String incotermLocation) { this.incotermLocation = incotermLocation; } @Override public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;} public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
1
请完成以下Java代码
public class POSOrderExternalId { @NonNull private final String value; private POSOrderExternalId(@NonNull final String value) { final String valueNorm = normalizeValue(value); if (valueNorm == null) { throw new AdempiereException("Invalid external ID: `" + value + "`"); } this.value = valueNorm; } @Nullable private static String normalizeValue(@Nullable final String value) { return StringUtils.trimBlankToNull(value); } @JsonCreator public static POSOrderExternalId ofString(@NonNull final String value) { return new POSOrderExternalId(value); }
public static Set<POSOrderExternalId> ofCommaSeparatedString(@Nullable final String string) { return CollectionUtils.ofCommaSeparatedSet(string, POSOrderExternalId::ofString); } public static Set<String> toStringSet(@NonNull final Collection<POSOrderExternalId> collection) { return collection.stream() .map(POSOrderExternalId::getAsString) .collect(ImmutableSet.toImmutableSet()); } @Override @Deprecated public String toString() {return value;} @JsonValue public String getAsString() {return value;} public static boolean equals(@Nullable final POSOrderExternalId id1, @Nullable final POSOrderExternalId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderExternalId.java
1
请完成以下Java代码
private IEventBus getEventBus() {return eventBusFactory.getEventBus(EVENTS_TOPIC);} private void handleEvent(@NonNull final SumUpTransactionStatusChangedEvent event) { fireLocalListeners(event); } private void fireLocalListeners(final @NonNull SumUpTransactionStatusChangedEvent event) { try (final IAutoCloseable ignored = Env.switchContext(newTemporaryCtx(event))) { statusChangedListeners.forEach(listener -> listener.onStatusChanged(event)); } } private static Properties newTemporaryCtx(final @NonNull SumUpTransactionStatusChangedEvent event) { final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, event.getClientId()); Env.setOrgId(ctx, event.getOrgId()); return ctx; } private void fireLocalAndRemoteListenersAfterTrxCommit(final @NonNull SumUpTransactionStatusChangedEvent event) { trxManager.accumulateAndProcessAfterCommit( SumUpEventsDispatcher.class.getSimpleName(), ImmutableList.of(event), this::fireLocalAndRemoteListenersNow); } private void fireLocalAndRemoteListenersNow(@NonNull final List<SumUpTransactionStatusChangedEvent> events) { final IEventBus eventBus = getEventBus(); // NOTE: we don't have to fireLocalListeners // because we assume we will also get back this event and then we will handle it events.forEach(eventBus::enqueueObject); } public void fireNewTransaction(@NonNull final SumUpTransaction trx) { fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofNewTransaction(trx)); }
public void fireStatusChangedIfNeeded( @NonNull final SumUpTransaction trx, @NonNull final SumUpTransaction trxPrev) { if (!isForceSendingChangeEvents() && hasChanges(trx, trxPrev)) { return; } fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofChangedTransaction(trx, trxPrev)); } private static boolean hasChanges(final @NonNull SumUpTransaction trx, final @NonNull SumUpTransaction trxPrev) { return SumUpTransactionStatus.equals(trx.getStatus(), trxPrev.getStatus()) && trx.isRefunded() == trxPrev.isRefunded(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpEventsDispatcher.java
1
请在Spring Boot框架中完成以下Java代码
public class MybatisBatchDataManager extends AbstractDataManager<BatchEntity> implements BatchDataManager { protected BatchServiceConfiguration batchServiceConfiguration; public MybatisBatchDataManager(BatchServiceConfiguration batchServiceConfiguration) { this.batchServiceConfiguration = batchServiceConfiguration; } @Override public Class<? extends BatchEntity> getManagedEntityClass() { return BatchEntityImpl.class; } @Override public BatchEntity create() { return new BatchEntityImpl(); } @Override @SuppressWarnings("unchecked") public List<Batch> findBatchesBySearchKey(String searchKey) { HashMap<String, Object> params = new HashMap<>(); params.put("searchKey", searchKey); params.put("searchKey2", searchKey); return getDbSqlSession().selectList("selectBatchesBySearchKey", params); } @Override @SuppressWarnings("unchecked") public List<Batch> findAllBatches() { return getDbSqlSession().selectList("selectAllBatches"); } @Override
@SuppressWarnings("unchecked") public List<Batch> findBatchesByQueryCriteria(BatchQueryImpl batchQuery) { return getDbSqlSession().selectList("selectBatchByQueryCriteria", batchQuery, getManagedEntityClass()); } @Override public long findBatchCountByQueryCriteria(BatchQueryImpl batchQuery) { return (Long) getDbSqlSession().selectOne("selectBatchCountByQueryCriteria", batchQuery); } @Override public void deleteBatches(BatchQueryImpl batchQuery) { getDbSqlSession().delete("bulkDeleteBytesForBatches", batchQuery, getManagedEntityClass()); getDbSqlSession().delete("bulkDeleteBatchPartsForBatches", batchQuery, getManagedEntityClass()); getDbSqlSession().delete("bulkDeleteBatches", batchQuery, getManagedEntityClass()); } @Override protected IdGenerator getIdGenerator() { return batchServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\data\impl\MybatisBatchDataManager.java
2
请完成以下Java代码
public class WEBUI_PackingHUsView_AddHUsToShipperTransportation extends PackingHUsViewBasedProcess implements IProcessPrecondition { private final transient IHUShipperTransportationBL huShipperTransportationBL = Services.get(IHUShipperTransportationBL.class); @Param(parameterName = I_M_ShipperTransportation.COLUMNNAME_M_ShipperTransportation_ID, mandatory = true) private int shipperTransportationId; @Override protected final ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } final boolean eligibleHUsFound = streamEligibleHURows() .findAny() .isPresent(); if (!eligibleHUsFound) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU)); } return ProcessPreconditionsResolution.accept(); }
@Override protected final String doIt() throws Exception { final List<I_M_HU> hus = retrieveEligibleHUs(); huShipperTransportationBL.addHUsToShipperTransportation(ShipperTransportationId.ofRepoId(shipperTransportationId), CreatePackageForHURequest.ofHUsList(hus)); return MSG_OK; } @Override protected final void postProcess(final boolean success) { if (!success) { return; } getView().invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PackingHUsView_AddHUsToShipperTransportation.java
1
请完成以下Java代码
public int getC_RevenueRecognition_Plan_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_Plan_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getC_RevenueRecognition_Plan_ID())); } /** Set Revenue Recognition Run. @param C_RevenueRecognition_Run_ID Revenue Recognition Run or Process */ public void setC_RevenueRecognition_Run_ID (int C_RevenueRecognition_Run_ID) { if (C_RevenueRecognition_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Run_ID, Integer.valueOf(C_RevenueRecognition_Run_ID)); } /** Get Revenue Recognition Run. @return Revenue Recognition Run or Process */ public int getC_RevenueRecognition_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_Run_ID); if (ii == null) return 0; return ii.intValue(); } public I_GL_Journal getGL_Journal() throws RuntimeException { return (I_GL_Journal)MTable.get(getCtx(), I_GL_Journal.Table_Name) .getPO(getGL_Journal_ID(), get_TrxName()); } /** Set Journal.
@param GL_Journal_ID General Ledger Journal */ public void setGL_Journal_ID (int GL_Journal_ID) { if (GL_Journal_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, Integer.valueOf(GL_Journal_ID)); } /** Get Journal. @return General Ledger Journal */ public int getGL_Journal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Journal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Recognized Amount. @param RecognizedAmt Recognized Amount */ public void setRecognizedAmt (BigDecimal RecognizedAmt) { set_ValueNoCheck (COLUMNNAME_RecognizedAmt, RecognizedAmt); } /** Get Recognized Amount. @return Recognized Amount */ public BigDecimal getRecognizedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition_Run.java
1
请完成以下Java代码
public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } @Override public java.lang.String getTechnicalNote() { return get_ValueAsString(COLUMNNAME_TechnicalNote); } /** * TooltipType AD_Reference_ID=541141 * Reference name: TooltipType */ public static final int TOOLTIPTYPE_AD_Reference_ID=541141; /** DescriptionFallbackToTableIdentifier = DTI */ public static final String TOOLTIPTYPE_DescriptionFallbackToTableIdentifier = "DTI"; /** TableIdentifier = T */ public static final String TOOLTIPTYPE_TableIdentifier = "T"; /** Description = D */ public static final String TOOLTIPTYPE_Description = "D"; @Override public void setTooltipType (final java.lang.String TooltipType) { set_Value (COLUMNNAME_TooltipType, TooltipType); } @Override public java.lang.String getTooltipType() { return get_ValueAsString(COLUMNNAME_TooltipType); } @Override public void setWEBUI_View_PageLength (final int WEBUI_View_PageLength) { set_Value (COLUMNNAME_WEBUI_View_PageLength, WEBUI_View_PageLength); } @Override
public int getWEBUI_View_PageLength() { return get_ValueAsInt(COLUMNNAME_WEBUI_View_PageLength); } /** * WhenChildCloningStrategy AD_Reference_ID=541756 * Reference name: AD_Table_CloningStrategy */ public static final int WHENCHILDCLONINGSTRATEGY_AD_Reference_ID=541756; /** Skip = S */ public static final String WHENCHILDCLONINGSTRATEGY_Skip = "S"; /** AllowCloning = A */ public static final String WHENCHILDCLONINGSTRATEGY_AllowCloning = "A"; /** AlwaysInclude = I */ public static final String WHENCHILDCLONINGSTRATEGY_AlwaysInclude = "I"; @Override public void setWhenChildCloningStrategy (final java.lang.String WhenChildCloningStrategy) { set_Value (COLUMNNAME_WhenChildCloningStrategy, WhenChildCloningStrategy); } @Override public java.lang.String getWhenChildCloningStrategy() { return get_ValueAsString(COLUMNNAME_WhenChildCloningStrategy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table.java
1
请完成以下Java代码
public void updateTaskSuspensionStateByProcessDefinitionKey(String processDefinitionKey, SuspensionState suspensionState) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("processDefinitionKey", processDefinitionKey); parameters.put("isProcessDefinitionTenantIdSet", false); parameters.put("suspensionState", suspensionState.getStateCode()); getDbEntityManager().update(TaskEntity.class, "updateTaskSuspensionStateByParameters", configureParameterizedQuery(parameters)); } public void updateTaskSuspensionStateByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String processDefinitionTenantId, SuspensionState suspensionState) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("processDefinitionKey", processDefinitionKey); parameters.put("isProcessDefinitionTenantIdSet", true); parameters.put("processDefinitionTenantId", processDefinitionTenantId); parameters.put("suspensionState", suspensionState.getStateCode()); getDbEntityManager().update(TaskEntity.class, "updateTaskSuspensionStateByParameters", configureParameterizedQuery(parameters)); } public void updateTaskSuspensionStateByCaseExecutionId(String caseExecutionId, SuspensionState suspensionState) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("caseExecutionId", caseExecutionId); parameters.put("suspensionState", suspensionState.getStateCode()); getDbEntityManager().update(TaskEntity.class, "updateTaskSuspensionStateByParameters", configureParameterizedQuery(parameters)); } // helper ///////////////////////////////////////////////////////////
protected void createDefaultAuthorizations(TaskEntity task) { if(isAuthorizationEnabled()) { ResourceAuthorizationProvider provider = getResourceAuthorizationProvider(); AuthorizationEntity[] authorizations = provider.newTask(task); saveDefaultAuthorizations(authorizations); } } protected void configureQuery(TaskQueryImpl query) { getAuthorizationManager().configureTaskQuery(query); getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskManager.java
1
请完成以下Java代码
public class ProcessEngineFactoryBean implements FactoryBean<ProcessEngine>, DisposableBean, ApplicationContextAware { protected ProcessEngineConfigurationImpl processEngineConfiguration; protected ApplicationContext applicationContext; protected ProcessEngine processEngine; @Override public void destroy() throws Exception { if (processEngine != null) { processEngine.close(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public ProcessEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (processEngineConfiguration.getBeans() == null) { processEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.processEngine = processEngineConfiguration.buildProcessEngine(); return this.processEngine; } protected void configureExternallyManagedTransactions() { if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringProcessEngineConfiguration engineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) { processEngineConfiguration.setTransactionsExternallyManaged(true); } } } @Override public Class<ProcessEngine> getObjectType() { return ProcessEngine.class; } @Override public boolean isSingleton() { return true; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-spring\src\main\java\org\flowable\spring\ProcessEngineFactoryBean.java
1
请完成以下Java代码
public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public void setM_HU_PI_Attribute_ID (final int M_HU_PI_Attribute_ID) { if (M_HU_PI_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Attribute_ID, M_HU_PI_Attribute_ID); } @Override public int getM_HU_PI_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class); } @Override public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } /** * PropagationType AD_Reference_ID=540404 * Reference name: M_HU_PI_Attribute_PropagationType */ public static final int PROPAGATIONTYPE_AD_Reference_ID=540404; /** TopDown = TOPD */ public static final String PROPAGATIONTYPE_TopDown = "TOPD"; /** BottomUp = BOTU */ public static final String PROPAGATIONTYPE_BottomUp = "BOTU"; /** NoPropagation = NONE */ public static final String PROPAGATIONTYPE_NoPropagation = "NONE"; @Override public void setPropagationType (final java.lang.String PropagationType) { set_Value (COLUMNNAME_PropagationType, PropagationType); } @Override public java.lang.String getPropagationType() { return get_ValueAsString(COLUMNNAME_PropagationType); }
@Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSplitterStrategy_JavaClass_ID (final int SplitterStrategy_JavaClass_ID) { if (SplitterStrategy_JavaClass_ID < 1) set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, null); else set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, SplitterStrategy_JavaClass_ID); } @Override public int getSplitterStrategy_JavaClass_ID() { return get_ValueAsInt(COLUMNNAME_SplitterStrategy_JavaClass_ID); } @Override public void setUseInASI (final boolean UseInASI) { set_Value (COLUMNNAME_UseInASI, UseInASI); } @Override public boolean isUseInASI() { return get_ValueAsBoolean(COLUMNNAME_UseInASI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Attribute.java
1
请完成以下Java代码
public String getCustomerId() { return customerId; } public void setCustomerId(final String customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(final String customerName) { this.customerName = customerName; } public String getCompanyName() { return companyName;
} public void setCompanyName(final String companyName) { this.companyName = companyName; } public Map<String, Order> getOrders() { return orders; } public void setOrders(final Map<String, Order> orders) { this.orders = orders; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\persistence\model\Customer.java
1
请在Spring Boot框架中完成以下Java代码
public class CredentialsService { private final VaultTemplate vaultTemplate; private final VaultKeyValueOperations vaultKeyValueOperations; private final CredentialsRepository credentialsRepository; @Autowired public CredentialsService(VaultTemplate vaultTemplate, CredentialsRepository credentialsRepository) { this.vaultTemplate = vaultTemplate; this.credentialsRepository = credentialsRepository; this.vaultKeyValueOperations = vaultTemplate.opsForKeyValue("credentials/myapp", VaultKeyValueOperationsSupport.KeyValueBackend.KV_2); } /** * To Secure Credentials * @param credentials * @return VaultResponse * @throws URISyntaxException */ public void secureCredentials(Credentials credentials) { vaultKeyValueOperations.put(credentials.getUsername(), credentials);
} /** * To Retrieve Credentials * @return Credentials */ public Credentials accessCredentials(String username) { VaultResponseSupport<Credentials> response = vaultKeyValueOperations.get(username, Credentials.class); return response.getData(); } public Credentials saveCredentials(Credentials credentials) { return credentialsRepository.save(credentials); } public Optional<Credentials> findById(String username) { return credentialsRepository.findById(username); } }
repos\tutorials-master\spring-vault\src\main\java\com\baeldung\springvault\CredentialsService.java
2
请完成以下Java代码
private String getSessionKey(String sessionId) { return this.namespace + ":sessions:" + sessionId; } /** * Set the namespace for the keys. * @param namespace the namespace */ public void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be null or empty"); this.namespace = namespace; this.expirationsKey = this.namespace + ":sessions:expirations"; } /** * Configure the clock used when retrieving expired sessions for clean-up. * @param clock the clock */ public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } /** * Configures how many sessions will be queried at a time to be cleaned up. Defaults * to 100. * @param cleanupCount how many sessions to be queried, must be bigger than 0. */ public void setCleanupCount(int cleanupCount) { Assert.state(cleanupCount > 0, "cleanupCount must be greater than 0"); this.cleanupCount = cleanupCount; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetRedisSessionExpirationStore.java
1
请完成以下Java代码
public static ShipmentScheduleId ofString(@NonNull final String repoIdStr) { return RepoIdAwares.ofObject(repoIdStr, ShipmentScheduleId.class, ShipmentScheduleId::ofRepoId); } public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<ShipmentScheduleId> ids) { if (ids.isEmpty()) { return ImmutableSet.of(); } return ids.stream().map(ShipmentScheduleId::getRepoId).collect(ImmutableSet.toImmutableSet()); } public static ImmutableSet<ShipmentScheduleId> fromIntSet(@NonNull final Collection<Integer> repoIds) { if (repoIds.isEmpty()) { return ImmutableSet.of(); } return repoIds.stream().map(ShipmentScheduleId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } int repoId; private ShipmentScheduleId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_ShipmentSchedule_ID"); } @Override @JsonValue public int getRepoId() { return repoId;
} public static int toRepoId(@Nullable final ShipmentScheduleId id) { return id != null ? id.getRepoId() : -1; } public TableRecordReference toTableRecordReference() { return TableRecordReference.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, getRepoId()); } public static boolean equals(@Nullable final ShipmentScheduleId id1, @Nullable final ShipmentScheduleId id2) {return Objects.equals(id1, id2);} public static TableRecordReferenceSet toTableRecordReferenceSet(@NonNull final Collection<ShipmentScheduleId> ids) { return TableRecordReferenceSet.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, ids); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\ShipmentScheduleId.java
1
请在Spring Boot框架中完成以下Java代码
public void addVariable(RestVariable variable) { variables.add(variable); } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) {
this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java
2
请完成以下Java代码
public Exception cannotParseDuration(String expressions) { return new ProcessEngineException(exceptionMessage( "028", "Cannot parse duration '{}'.", expressions)); } public void logParsingRetryIntervals(String intervals, Exception e) { logWarn( "029", "Exception while parsing retry intervals '{}'", intervals, e.getMessage(), e); } public void logJsonException(Exception e) { logDebug( "030", "Exception while parsing JSON: {}", e.getMessage(), e); } public void logAccessExternalSchemaNotSupported(Exception e) { logDebug( "031", "Could not restrict external schema access. " + "This indicates that this is not supported by your JAXP implementation: {}", e.getMessage()); } public void logMissingPropertiesFile(String file) { logWarn("032", "Could not find the '{}' file on the classpath. " + "If you have removed it, please restore it.", file); } public ProcessEngineException exceptionDuringFormParsing(String cause, String resourceName) { return new ProcessEngineException( exceptionMessage("033", "Could not parse Camunda Form resource {}. Cause: {}", resourceName, cause)); }
public void debugCouldNotResolveCallableElement( String callingProcessDefinitionId, String activityId, Throwable cause) { logDebug("046", "Could not resolve a callable element for activity {} in process {}. Reason: {}", activityId, callingProcessDefinitionId, cause.getMessage()); } public ProcessEngineException exceptionWhileSettingXxeProcessing(Throwable cause) { return new ProcessEngineException(exceptionMessage( "047", "Exception while configuring XXE processing: {}", cause.getMessage()), cause); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EngineUtilLogger.java
1
请在Spring Boot框架中完成以下Java代码
public void setCurrencyCode(String value) { this.currencyCode = value; } /** * Quantity mentioned in the sales report. Please use quantity's qualifier to specify the meaning more detailed. * * @return * possible object is * {@link ExtendedQuantityType } * */ public ExtendedQuantityType getAdditionalQuantitiy() { return additionalQuantitiy; } /** * Sets the value of the additionalQuantitiy property. * * @param value * allowed object is * {@link ExtendedQuantityType } * */ public void setAdditionalQuantitiy(ExtendedQuantityType value) { this.additionalQuantitiy = value; } /** * DEPRICATED - please Document/Details/ItemList/ListLineItem/ListLineItemExtension/ListLineItemExtension/AdditionalBusinessPartner instead Gets the value of the additionalBusinessPartner 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 additionalBusinessPartner property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalBusinessPartner().add(newItem); * </pre> * * * <p>
* Objects of the following type(s) are allowed in the list * {@link BusinessEntityType } * * */ public List<BusinessEntityType> getAdditionalBusinessPartner() { if (additionalBusinessPartner == null) { additionalBusinessPartner = new ArrayList<BusinessEntityType>(); } return this.additionalBusinessPartner; } /** * Other references if no dedicated field is available.Gets the value of the additionalReference 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 additionalReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<ReferenceType>(); } return this.additionalReference; } }
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\SLSRPTListLineExtensionType.java
2
请完成以下Java代码
public OAuth2ProtectedResourceMetadata build() { validate(); return new OAuth2ProtectedResourceMetadata(this.claims); } private void validate() { Assert.notNull(this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.RESOURCE), "resource cannot be null"); validateURL(this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.RESOURCE), "resource must be a valid URL"); if (this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.AUTHORIZATION_SERVERS) != null) { Assert.isInstanceOf(List.class, this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.AUTHORIZATION_SERVERS), "authorization_servers must be of type List"); Assert.notEmpty( (List<?>) this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.AUTHORIZATION_SERVERS), "authorization_servers cannot be empty"); List<?> authorizationServers = (List<?>) this.claims .get(OAuth2ProtectedResourceMetadataClaimNames.AUTHORIZATION_SERVERS); authorizationServers.forEach((authorizationServer) -> validateURL(authorizationServer, "authorization_server must be a valid URL")); } if (this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.SCOPES_SUPPORTED) != null) { Assert.isInstanceOf(List.class, this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.SCOPES_SUPPORTED), "scopes must be of type List"); Assert.notEmpty((List<?>) this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.SCOPES_SUPPORTED), "scopes cannot be empty"); } if (this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.BEARER_METHODS_SUPPORTED) != null) { Assert.isInstanceOf(List.class, this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.BEARER_METHODS_SUPPORTED), "bearer methods must be of type List"); Assert.notEmpty( (List<?>) this.claims.get(OAuth2ProtectedResourceMetadataClaimNames.BEARER_METHODS_SUPPORTED), "bearer methods cannot be empty"); } } @SuppressWarnings("unchecked") private void addClaimToClaimList(String name, String value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>()); ((List<String>) this.claims.get(name)).add(value); } @SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(valuesConsumer, "valuesConsumer cannot be null"); this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>()); List<String> values = (List<String>) this.claims.get(name); valuesConsumer.accept(values); } private static void validateURL(Object url, String errorMessage) { if (URL.class.isAssignableFrom(url.getClass())) { return; } try { new URI(url.toString()).toURL(); } catch (Exception ex) { throw new IllegalArgumentException(errorMessage, ex); } } } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\OAuth2ProtectedResourceMetadata.java
1
请完成以下Java代码
/* package */ final I_C_UOM getC_UOMOrNull(final List<I_M_HU_Storage> storages) { if (storages == null || storages.isEmpty()) { return null; } if (storages.size() == 1) { return IHUStorageBL.extractUOM(storages.get(0)); } I_C_UOM foundUOM = null; String foundUOMType = null; for (final I_M_HU_Storage storage : storages) { // // Retrieve storage UOM final I_C_UOM storageUOM = IHUStorageBL.extractUOM(storage); final String storageUOMType = storageUOM.getUOMType(); if (foundUOM == null) { // This is actually the initial (and only) assignment foundUOM = storageUOM; foundUOMType = storageUOMType; continue; } if (foundUOM.getC_UOM_ID() == storageUOM.getC_UOM_ID()) { // each uom is compatible with itself continue; } // Validated for null before with that Check if (Objects.equals(foundUOMType, storageUOMType)) { if (Check.isEmpty(storageUOMType, true)) { // if both UOMs' types are empty/null, then we have to thread them as incompatible; exit loop & return null return null; } // We don't care about it if it's the same UOMType continue; }
// Incompatible UOM types encountered; exit loop & return null return null; } return foundUOM; } @Override public final UOMType getC_UOMTypeOrNull(final I_M_HU hu) { // FIXME: optimize more! final List<I_M_HU_Storage> storages = retrieveStorages(hu); if (storages.isEmpty()) { // // TODO hardcoded (quickfix in 07088, skyped with teo - we need a compatible UOM type before storages are created when propagating WeightNet) return UOMType.Weight; } final I_C_UOM uom = getC_UOMOrNull(storages); if (uom == null) { return null; } return UOMType.ofNullableCodeOrOther(uom.getUOMType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\AbstractHUStorageDAO.java
1
请完成以下Java代码
public ProcessPreconditionsResolution get() { return processDescriptor.checkPreconditionsApplicable(preconditionsContext); } } private static final class ProcessParametersCallout { private static void forwardValueToCurrentProcessInstance(final ICalloutField calloutField) { final JavaProcess processInstance = JavaProcess.currentInstance(); final String parameterName = calloutField.getColumnName(); final IRangeAwareParams source = createSource(calloutField); // Ask the instance to load the parameter processInstance.loadParameterValueNoFail(parameterName, source); } private static IRangeAwareParams createSource(final ICalloutField calloutField) { final String parameterName = calloutField.getColumnName(); final Object fieldValue = calloutField.getValue(); if (fieldValue instanceof LookupValue) { final Object idObj = ((LookupValue)fieldValue).getId(); return ProcessParams.ofValueObject(parameterName, idObj); } else if (fieldValue instanceof DateRangeValue) { final DateRangeValue dateRange = (DateRangeValue)fieldValue; return ProcessParams.of( parameterName, TimeUtil.asDate(dateRange.getFrom()), TimeUtil.asDate(dateRange.getTo())); } else { return ProcessParams.ofValueObject(parameterName, fieldValue);
} } } private static final class ProcessParametersDataBindingDescriptorBuilder implements DocumentEntityDataBindingDescriptorBuilder { public static final ProcessParametersDataBindingDescriptorBuilder instance = new ProcessParametersDataBindingDescriptorBuilder(); private static final DocumentEntityDataBindingDescriptor dataBinding = () -> ADProcessParametersRepository.instance; @Override public DocumentEntityDataBindingDescriptor getOrBuild() { return dataBinding; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessDescriptorsFactory.java
1
请完成以下Java代码
public static List<Term> segment(String text) { return ANALYZER.seg(text); } /** * 分词 * * @param text 文本 * @return 分词结果 */ public static List<Term> segment(char[] text) { return ANALYZER.seg(text); } /** * 切分为句子形式 * * @param text 文本 * @return 句子列表 */ public static List<List<Term>> seg2sentence(String text) { return ANALYZER.seg2sentence(text); } /** * 词法分析 * * @param sentence * @return 结构化句子 */
public static Sentence analyze(final String sentence) { return ANALYZER.analyze(sentence); } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) { return ANALYZER.seg2sentence(text, shortest); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\NLPTokenizer.java
1
请完成以下Java代码
public ContextPath newChild(@NonNull final String name) { return newChild(ContextPathElement.ofName(name)); } public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor) { return newChild(ContextPathElement.ofNameAndId( extractName(entityDescriptor), AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull()) )); } private ContextPath newChild(@NonNull final ContextPathElement element) { return new ContextPath(ImmutableList.<ContextPathElement>builder() .addAll(elements) .add(element) .build()); } public AdWindowId getAdWindowId() { return AdWindowId.ofRepoId(elements.get(0).getId()); } @Override public int compareTo(@NonNull final ContextPath other) { return toJson().compareTo(other.toJson()); } } @Value class ContextPathElement { @NonNull String name; int id; @JsonCreator
public static ContextPathElement ofJson(@NonNull final String json) { try { final int idx = json.indexOf("/"); if (idx > 0) { String name = json.substring(0, idx); int id = Integer.parseInt(json.substring(idx + 1)); return new ContextPathElement(name, id); } else { return new ContextPathElement(json, -1); } } catch (final Exception ex) { throw new AdempiereException("Failed parsing: " + json, ex); } } public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);} public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);} @Override public String toString() {return toJson();} @JsonValue public String toJson() {return id > 0 ? name + "/" + id : name;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java
1
请完成以下Java代码
public void setAsText(String text) throws java.lang.IllegalArgumentException { throw new java.lang.IllegalArgumentException("AdempiereColorEditor.setAsText not supported"); } // setAsText /** * If the property value must be one of a set of known tagged values, * then this method should return an array of the tags. This can * be used to represent (for example) enum values. If a PropertyEditor * supports tags, then it should support the use of setAsText with * a tag value as a way of setting the value and the use of getAsText * to identify the current value. * * @return The tag values for this property. May be null if this * property cannot be represented as a tagged value. */ @Override public String[] getTags() { return null; } // getTags /** * A PropertyEditor may choose to make available a full custom Component * that edits its property value. It is the responsibility of the * PropertyEditor to hook itself up to its editor Component itself and * to report property value changes by firing a PropertyChange event. * <P> * The higher-level code that calls getCustomEditor may either embed * the Component in some larger property sheet, or it may put it in * its own individual dialog, or ... * * @return A java.awt.Component that will allow a human to directly * edit the current property value. May be null if this is * not supported. */ @Override public Component getCustomEditor() { return this; } // getCustomEditor /** * Determines whether this property editor supports a custom editor. * * @return True if the propertyEditor can provide a custom editor. */ @Override public boolean supportsCustomEditor() { return true;
} // supportsCustomEditor /** * Register a listener for the PropertyChange event. When a * PropertyEditor changes its value it should fire a PropertyChange * event on all registered PropertyChangeListeners, specifying the * null value for the property name and itself as the source. * * @param listener An object to be invoked when a PropertyChange * event is fired. */ @Override public void addPropertyChangeListener(PropertyChangeListener listener) { super.addPropertyChangeListener(listener); } // addPropertyChangeListener /** * Remove a listener for the PropertyChange event. * * @param listener The PropertyChange listener to be removed. */ @Override public void removePropertyChangeListener(PropertyChangeListener listener) { super.removePropertyChangeListener(listener); } // removePropertyChangeListener } // AdempiereColorEditor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\swing\ColorEditor.java
1
请完成以下Java代码
public boolean isValid() { if (record == null) { return false; } final int productID = record.getM_Product_ID(); final BigDecimal qty = record.getQty(); // 06730: Removed TU restrictions for now. We can choose no handling unit for a product, even if it has associated TUs. // final int partnerID = (null == record.getC_BPartner()) ? 0 : record.getC_BPartner().getC_BPartner_ID(); // final Timestamp dateOrdered = record.getDateOrdered(); if (productID <= 0) { return false; } if (qty == null || qty.signum() == 0) { return false; } // TODO: check record values // 06730: Removed TU restrictions for now. We can choose no handling unit for a product, even if it has associated TUs. // final boolean hasTUs = Services.get(IHUOrderBL.class).hasTUs(Env.getCtx(), partnerID, productID, dateOrdered); // // if (hasTUs) // { // // if (record.getM_HU_PI_Item_Product_ID() <= 0) // { // return false; // } // // if (record.getQtyPacks() == null || record.getQtyPacks().signum() <= 0) // { // return false; // } // } return true; } @Override public void setSource(final Object model) { if (model instanceof IHUPackingAware) { record = (IHUPackingAware)model; } else if (InterfaceWrapperHelper.isInstanceOf(model, I_C_Order.class)) { final I_C_Order order = InterfaceWrapperHelper.create(model, I_C_Order.class); record = new OrderHUPackingAware(order); } else { record = null; } }
@Override public void apply(final Object model) { if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OrderLine.class)) { logger.debug("Skip applying because it's not an order line: {}", model); return; } final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class); applyOnOrderLine(orderLine); } public void applyOnOrderLine(final I_C_OrderLine orderLine) { final IHUPackingAware to = new OrderLineHUPackingAware(orderLine); Services.get(IHUPackingAwareBL.class).prepareCopyFrom(record) .overridePartner(false) .copyTo(to); } @Override public boolean isCreateNewRecord() { if (isValid()) { return true; } return false; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingGridRowBuilder.java
1
请完成以下Java代码
public static byte[] toByteArray(@NonNull final InputStream in) throws RuntimeException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { final byte[] buf = new byte[1024 * 4]; int len = -1; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final IOException e) { throw new RuntimeException(e); } return out.toByteArray(); } /** * Close given closeable stream. * * No errors will be thrown. * * @param closeable */ public static void close(final Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (final IOException e) { e.printStackTrace(); } } /** * Close all given input streams. * * No errors will be thrown. * * @param closeables */ public static void close(final Closeable... closeables)
{ if (closeables == null || closeables.length == 0) { return; } for (final Closeable closeable : closeables) { close(closeable); } } /** * Copy data from input stream to output stream. * * NOTE: no matter what, both streams are closed after this call. * * @throws RuntimeException if something fails */ public static void copy(@NonNull final OutputStream out, @NonNull final InputStream in) { try { final byte[] buf = new byte[4 * 1024]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final IOException e) { throw new RuntimeException(e.getLocalizedMessage(), e); } finally { close(out); close(in); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\IOStreamUtils.java
1
请完成以下Java代码
public class SaveAttachmentCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected Attachment attachment; public SaveAttachmentCmd(Attachment attachment) { this.attachment = attachment; } public Object execute(CommandContext commandContext) { AttachmentEntity updateAttachment = commandContext.getAttachmentEntityManager().findById(attachment.getId()); String processInstanceId = updateAttachment.getProcessInstanceId(); String processDefinitionId = null; if (updateAttachment.getProcessInstanceId() != null) { ExecutionEntity process = commandContext.getExecutionEntityManager().findById(processInstanceId); if (process != null) { processDefinitionId = process.getProcessDefinitionId(); } } executeInternal(commandContext, updateAttachment, processInstanceId, processDefinitionId); return null; } protected void executeInternal( CommandContext commandContext, AttachmentEntity updateAttachment, String processInstanceId, String processDefinitionId
) { updateAttachment.setName(attachment.getName()); updateAttachment.setDescription(attachment.getDescription()); if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createEntityEvent( ActivitiEventType.ENTITY_UPDATED, attachment, processInstanceId, processInstanceId, processDefinitionId ) ); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SaveAttachmentCmd.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Payroll List Type. @param HR_ListType_ID Payroll List Type */ public void setHR_ListType_ID (int HR_ListType_ID) { if (HR_ListType_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID)); } /** Get Payroll List Type. @return Payroll List Type */ public int getHR_ListType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_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()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java
1
请完成以下Java代码
public class CCheckBoxMenuItem extends JCheckBoxMenuItem { /** * */ private static final long serialVersionUID = 6701152155152356260L; public CCheckBoxMenuItem () { super (); } // CCheckBoxMenuItem public CCheckBoxMenuItem (Icon icon) { super (icon); } // CCheckBoxMenuItem public CCheckBoxMenuItem (String text) { super (text); } // CCheckBoxMenuItem public CCheckBoxMenuItem (Action a) { super (a); } // CCheckBoxMenuItem public CCheckBoxMenuItem (String text, Icon icon) { super (text, icon); } // CCheckBoxMenuItem public CCheckBoxMenuItem (String text, boolean b) { super (text, b); } // CCheckBoxMenuItem public CCheckBoxMenuItem (String text, Icon icon, boolean b) { super (text, icon, b); } // CCheckBoxMenuItem /** * Set Text * @param text text
*/ @Override public void setText (String text) { if (text == null) { super.setText(text); return; } int pos = text.indexOf('&'); if (pos != -1 && text.length() > pos) // We have a nemonic - creates ALT-_ { int mnemonic = text.toUpperCase().charAt(pos+1); if (mnemonic != ' ') { setMnemonic(mnemonic); text = text.substring(0, pos) + text.substring(pos+1); } } super.setText (text); if (getName() == null) setName (text); } // setText } // CCheckBoxMenuItem
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CCheckBoxMenuItem.java
1
请完成以下Java代码
public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore; } public boolean isTenantIdSet() { return isTenantIdSet; } public List<HistoricTaskInstanceQueryImpl> getQueries() { return queries; } public boolean isOrQueryActive() { return isOrQueryActive; } public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) { orQuery.isOrQueryActive = true; this.queries.add(orQuery); } public void setOrQueryActive() { isOrQueryActive = true; } @Override public HistoricTaskInstanceQuery or() { if (this != queries.get(0)) {
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public HistoricTaskInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Column getAD_Column() { return get_ValueAsPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class); } @Override public void setAD_Column(final org.compiere.model.I_AD_Column AD_Column) { set_ValueFromPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class, AD_Column); } @Override public void setAD_Column_ID (final int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID); } @Override public int getAD_Column_ID() { return get_ValueAsInt(COLUMNNAME_AD_Column_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID) { if (WEBUI_Board_CardField_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID); } @Override public int getWEBUI_Board_CardField_ID() {
return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java
1
请完成以下Java代码
private final PackageableRow getSingleSelectedPackageableRow(final boolean returnNullIfNotFound) { final PickingSlotView pickingSlotView = getPickingSlotView(); final ViewId packageablesViewId = pickingSlotView.getParentViewId(); if (packageablesViewId == null) { if (returnNullIfNotFound) { return null; } throw new AdempiereException("Packageables view is not available"); } final DocumentId packageableRowId = pickingSlotView.getParentRowId(); if (packageableRowId == null) { if (returnNullIfNotFound) { return null; } throw new AdempiereException("There is no single packageable row selected"); } final PackageableView packageableView = PackageableView.cast(viewsRepo.getView(packageablesViewId)); return packageableView.getById(packageableRowId); } protected PickingSlotRow getPickingSlotRow() { final HUEditorView huView = getView(); final DocumentId pickingSlotRowId = huView.getParentRowId(); final PickingSlotView pickingSlotView = getPickingSlotView(); return pickingSlotView.getById(pickingSlotRowId); } protected final void invalidateAndGoBackToPickingSlotsView() { // https://github.com/metasfresh/metasfresh-webui-frontend/issues/1447 // commenting this out because we now close the current view; currently this is a must, // because currently the frontend then load *this* view's data into the pickingSlotView // invalidateView(); invalidatePickingSlotsView(); invalidatePackablesView(); // After this process finished successfully go back to the picking slots view getResult().setWebuiViewToOpen(WebuiViewToOpen.builder() .viewId(getPickingSlotView().getViewId().getViewId()) .target(ViewOpenTarget.IncludedView) .build()); } protected final void invalidatePickingSlotsView() { final PickingSlotView pickingSlotsView = getPickingSlotViewOrNull(); if (pickingSlotsView == null) { return; } invalidateView(pickingSlotsView.getViewId()); } protected final void invalidatePackablesView()
{ final PickingSlotView pickingSlotsView = getPickingSlotViewOrNull(); if (pickingSlotsView == null) { return; } final ViewId packablesViewId = pickingSlotsView.getParentViewId(); if (packablesViewId == null) { return; } invalidateView(packablesViewId); } protected final void addHUIdToCurrentPickingSlot(@NonNull final HuId huId) { final PickingSlotView pickingSlotsView = getPickingSlotView(); final PickingSlotRow pickingSlotRow = getPickingSlotRow(); final PickingSlotId pickingSlotId = pickingSlotRow.getPickingSlotId(); final ShipmentScheduleId shipmentScheduleId = pickingSlotsView.getCurrentShipmentScheduleId(); pickingCandidateService.pickHU(PickRequest.builder() .shipmentScheduleId(shipmentScheduleId) .pickFrom(PickFrom.ofHuId(huId)) .pickingSlotId(pickingSlotId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\HUsToPickViewBasedProcess.java
1
请完成以下Java代码
public void setPurchaseDefault(final Boolean purchaseDefault) { this.purchaseDefault = purchaseDefault; this.purchaseDefaultSet = true; } public void setSubjectMatter(final Boolean subjectMatter) { this.subjectMatter = subjectMatter; this.subjectMatterSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setMetasfreshBPartnerId(final JsonMetasfreshId metasfreshBPartnerId) { this.metasfreshBPartnerId = metasfreshBPartnerId; this.metasfreshBPartnerIdSet = true; } public void setBirthday(final LocalDate birthday) {
this.birthday = birthday; this.birthdaySet = true; } public void setInvoiceEmailEnabled(@Nullable final Boolean invoiceEmailEnabled) { this.invoiceEmailEnabled = invoiceEmailEnabled; invoiceEmailEnabledSet = true; } public void setTitle(final String title) { this.title = title; this.titleSet = true; } public void setPhone2(final String phone2) { this.phone2 = phone2; this.phone2Set = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestContact.java
1
请完成以下Java代码
public final class ROCellEditor extends DefaultCellEditor { /** * */ private static final long serialVersionUID = 1957123963696065686L; /** * Constructor */ public ROCellEditor() { this(-1); // horizontalAignment=-1=nothing (backward compatiblity) } public ROCellEditor(final int horizontalAlignment) { super(new JTextField()); if (horizontalAlignment >= 0)
{ final JTextField textField = (JTextField)editorComponent; textField.setHorizontalAlignment(horizontalAlignment); } } // ROCellEditor /** * Indicate RO * @param anEvent * @return false */ @Override public boolean isCellEditable(EventObject anEvent) { return false; } // isCellEditable } // ROCellEditor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\ROCellEditor.java
1
请完成以下Java代码
public UserId getAdUserId() { return adUserId; } public boolean isFavorite(final MenuNode menuNode) { return menuIds.contains(menuNode.getAD_Menu_ID()); } public void setFavorite(final int adMenuId, final boolean favorite) { if (favorite) { menuIds.add(adMenuId); } else { menuIds.remove(adMenuId); } } public static class Builder { private UserId adUserId; private final Set<Integer> menuIds = new HashSet<>(); private Builder() { }
public MenuTreeRepository.UserMenuFavorites build() { return new UserMenuFavorites(this); } public Builder adUserId(final UserId adUserId) { this.adUserId = adUserId; return this; } public Builder addMenuIds(final List<Integer> adMenuIds) { if (adMenuIds.isEmpty()) { return this; } menuIds.addAll(adMenuIds); return this; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuTreeRepository.java
1
请完成以下Java代码
public class SubmitStartFormCmd extends NeedsActiveProcessDefinitionCmd<ProcessInstance> { private static final long serialVersionUID = 1L; protected final String businessKey; protected Map<String, String> properties; public SubmitStartFormCmd(String processDefinitionId, String businessKey, Map<String, String> properties) { super(processDefinitionId); this.businessKey = businessKey; this.properties = properties; } @Override protected ProcessInstance execute(CommandContext commandContext, ProcessDefinition processDefinition) { ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) processDefinition; ExecutionEntity processInstance = null; if (businessKey != null) {
processInstance = processDefinitionEntity.createProcessInstance(businessKey); } else { processInstance = processDefinitionEntity.createProcessInstance(); } commandContext.getHistoryManager() .reportFormPropertiesSubmitted(processInstance, properties, null); StartFormHandler startFormHandler = processDefinitionEntity.getStartFormHandler(); startFormHandler.submitFormProperties(properties, processInstance); processInstance.start(); return processInstance; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\SubmitStartFormCmd.java
1
请完成以下Java代码
public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } /** * DocStatus AD_Reference_ID=131 * Reference name: _Document Status */ public static final int DOCSTATUS_AD_Reference_ID=131; /** Drafted = DR */ public static final String DOCSTATUS_Drafted = "DR"; /** Completed = CO */ public static final String DOCSTATUS_Completed = "CO"; /** Approved = AP */ public static final String DOCSTATUS_Approved = "AP"; /** NotApproved = NA */ public static final String DOCSTATUS_NotApproved = "NA"; /** Voided = VO */ public static final String DOCSTATUS_Voided = "VO"; /** Invalid = IN */ public static final String DOCSTATUS_Invalid = "IN"; /** Reversed = RE */ public static final String DOCSTATUS_Reversed = "RE"; /** Closed = CL */ public static final String DOCSTATUS_Closed = "CL"; /** Unknown = ?? */ public static final String DOCSTATUS_Unknown = "??"; /** InProgress = IP */ public static final String DOCSTATUS_InProgress = "IP";
/** WaitingPayment = WP */ public static final String DOCSTATUS_WaitingPayment = "WP"; /** WaitingConfirmation = WC */ public static final String DOCSTATUS_WaitingConfirmation = "WC"; @Override public void setDocStatus (final @Nullable java.lang.String DocStatus) { throw new IllegalArgumentException ("DocStatus is virtual column"); } @Override public java.lang.String getDocStatus() { return get_ValueAsString(COLUMNNAME_DocStatus); } @Override public void setQtyOrdered (final BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_Order_Line_Alloc.java
1
请完成以下Java代码
public class Msg { private String title; private String content; private String etraInfo; public Msg(String title, String content, String etraInfo) { super(); this.title = title; this.content = content; this.etraInfo = etraInfo; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title;
} public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getEtraInfo() { return etraInfo; } public void setEtraInfo(String etraInfo) { this.etraInfo = etraInfo; } }
repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\domain\Msg.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String genre; private int age; private int sellrank; private int royalties; private int rating; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSellrank() { return sellrank; }
public void setSellrank(int sellrank) { this.sellrank = sellrank; } public int getRoyalties() { return royalties; } public void setRoyalties(int royalties) { this.royalties = royalties; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + ", sellrank=" + sellrank + ", royalties=" + royalties + ", rating=" + rating + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseViewUpdateInsertDelete\src\main\java\com\bookstore\entity\Author.java
2
请在Spring Boot框架中完成以下Java代码
public Result<?> clearMessage(@PathVariable(value = "conversationId") String conversationId) { return chatService.clearMessage(conversationId); } /** * 继续接收消息 * * @param requestId * @return * @author chenrui * @date 2025/8/11 17:49 */ @IgnoreAuth @GetMapping(value = "/receive/{requestId}") public SseEmitter receiveByRequestId(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.receiveByRequestId(requestId); } /** * 根据请求ID停止某个请求的处理 * * @param requestId 请求的唯一标识符,用于识别和停止特定的请求 * @return 返回一个Result对象,表示停止请求的结果 * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/stop/{requestId}") public Result<?> stop(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.stop(requestId); } /** * 上传文件 * for [QQYUN-12135]AI聊天,上传图片提示非法token * * @param request * @param response * @return * @throws Exception * @author chenrui * @date 2025/4/25 11:04 */
@IgnoreAuth @PostMapping(value = "/upload") public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception { String bizPath = "airag"; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获取上传文件对象 MultipartFile file = multipartRequest.getFile("file"); String savePath; if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) { savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath); } else { savePath = CommonUtils.upload(file, bizPath, uploadType); } Result<?> result = new Result<>(); result.setMessage(savePath); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragChatController.java
2
请完成以下Java代码
private void datasetsComputedTime(@Nullable final Instant datasetsComputedTime) { this.datasetsComputedTime = datasetsComputedTime; } private void builtDatasets(final ImmutableList<KPIDataSet> builtDatasets) { if (datasets != null && !datasets.isEmpty()) { throw new AdempiereException("Setting builtDatasets not allowed when some datasets builder were previously set"); } this.builtDatasets = builtDatasets; } public Builder range(@Nullable final TimeRange range) { this.range = range; return this; } @Nullable public TimeRange getRange() { return range; } public Builder datasetsComputeDuration(@Nullable final Duration datasetsComputeDuration) { this.datasetsComputeDuration = datasetsComputeDuration; return this; } public void putValue(
@NonNull final String dataSetName, @NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSet(dataSetName).putValue(dataSetValueKey, fieldName, value); } public void putValueIfAbsent( @NonNull final String dataSetName, @NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSet(dataSetName).putValueIfAbsent(dataSetValueKey, fieldName, value); } public Builder error(@NonNull final Exception exception) { final ITranslatableString errorMessage = AdempiereException.isUserValidationError(exception) ? AdempiereException.extractMessageTrl(exception) : TranslatableStrings.adMessage(MSG_FailedLoadingKPI); this.error = WebuiError.of(exception, errorMessage); return this; } public Builder error(@NonNull final ITranslatableString errorMessage) { this.error = WebuiError.of(errorMessage); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataResult.java
1
请完成以下Java代码
private List<I_C_Contract_Change> retrieveAllForTermAndNewStatus( @NonNull final I_C_Flatrate_Term term, @NonNull final String newStatus) { final IQueryBL queryBL = Services.get(IQueryBL.class); final List<I_C_Contract_Change> entries = queryBL.createQueryBuilder(I_C_Contract_Change.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Contract_Change.COLUMN_C_Flatrate_Transition_ID, term.getC_Flatrate_Conditions().getC_Flatrate_Transition_ID()) .addEqualsFilter(I_C_Contract_Change.COLUMN_Action, X_C_Contract_Change.ACTION_Statuswechsel) .addEqualsFilter(I_C_Contract_Change.COLUMN_ContractStatus, newStatus) .addInArrayFilter(I_C_Contract_Change.COLUMN_C_Flatrate_Conditions_ID, term.getC_Flatrate_Conditions_ID(), 0, null) .orderBy().addColumn(I_C_Contract_Change.COLUMN_C_Contract_Change_ID).endOrderBy() .create() .list(); return entries; } /** * If the given list is empty or if there is no entry that has a deadline before the given * <code>referenceDate</code>, then the method returns <code>null</code>. * * @param entries * the entries to evaluate. May be empty, but is assumed to be not <code>null</code> * @param referenceDate * @param termEndDate * @return */ protected final I_C_Contract_Change getEarliestEntryForRefDate( @NonNull final List<I_C_Contract_Change> entries, final Timestamp referenceDate, final Timestamp termEndDate) { I_C_Contract_Change applicableEntry = null; for (final I_C_Contract_Change entry : entries) { final Timestamp deadLineForEntry = Services.get(ISubscriptionBL.class).mkNextDate(entry.getDeadLineUnit(), entry.getDeadLine() * -1, termEndDate); if (referenceDate.after(deadLineForEntry)) { // 'changeDate' is after the deadline set for 'entry' continue;
} if (applicableEntry == null) { // we found the first entry that is still before the deadline applicableEntry = entry; continue; } final Timestamp deadLineForCurrentApplicableEntry = Services.get(ISubscriptionBL.class).mkNextDate(entry.getDeadLineUnit(), entry.getDeadLine() * -1, termEndDate); if (deadLineForEntry.before(deadLineForCurrentApplicableEntry)) { applicableEntry = entry; } } return applicableEntry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\AbstractContractChangeDAO.java
1
请完成以下Java代码
private List<GridTab> getChildren(GridTab tab) { List<GridTab> list = tabChildrenMap.get(tab.getAD_Tab_ID()); if (list != null) { return list; } list = new ArrayList<>(); tabChildrenMap.put(tab.getAD_Tab_ID(), list); for (GridTab t : tabs) { if (t.getParentTabNo() == tab.getTabNo() && t.getTabNo() != tab.getTabNo()) { list.add(t); } } return list; } /** AD_Tab_ID(parent) -> list of GridTab (children) */ private Map<Integer, List<GridTab>> tabChildrenMap = new HashMap<>(); private GridController createGridController(GridTab tab, int width, int height) { final GridController gc = new GridController(); gc.initGrid(tab, true, // onlyMultiRow windowNo, null, // APanel null); // GridWindow
if (width > 0 && height > 0) { gc.setPreferredSize(new Dimension(width, height)); } // tab.addPropertyChangeListener(this); m_mapVTables.put(tab.getAD_Tab_ID(), gc.getTable()); return gc; } private void vtableAutoSizeAll() { for (VTable t : m_mapVTables.values()) { t.autoSize(true); } } /** Map AD_Tab_ID -> VTable */ private Map<Integer, VTable> m_mapVTables = new HashMap<>(); @Override public void dispose() { if (frame != null) { frame.dispose(); } frame = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\form\swing\OrderOverview.java
1
请完成以下Java代码
public class ProcurementFlatrateHandler extends FallbackFlatrateTermEventListener { public static final String TYPE_CONDITIONS = I_C_Flatrate_Conditions.TYPE_CONDITIONS_Procuremnt; /** * Does not delete the data entries on reactivate! */ @Override protected void deleteFlatrateTermDataEntriesOnReactivate(final de.metas.contracts.model.I_C_Flatrate_Term term) { // nothing } /** * Create new {@link de.metas.contracts.model.I_C_Flatrate_DataEntry}s using {@link PMMContractBuilder#newBuilder(I_C_Flatrate_Term)}. * The new dataEntries use data from the dataEntries of the given <code>oldTerm</code>. * * @task https://github.com/metasfresh/metasfresh/issues/549 */ @Override public void afterSaveOfNextTermForPredecessor(final de.metas.contracts.model.I_C_Flatrate_Term next, final de.metas.contracts.model.I_C_Flatrate_Term predecessor) { final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class); final I_C_Flatrate_Term oldTermtoUse = InterfaceWrapperHelper.create(predecessor, I_C_Flatrate_Term.class); final I_C_Flatrate_Term newTermtoUse = InterfaceWrapperHelper.create(next, I_C_Flatrate_Term.class); newTermtoUse.setPMM_Product(oldTermtoUse.getPMM_Product()); InterfaceWrapperHelper.save(newTermtoUse); final List<I_C_Flatrate_DataEntry> oldDataEntries = flatrateDAO.retrieveDataEntries(predecessor, null, null); final PMMContractBuilder builder = newPMMContractBuilder(newTermtoUse) .setComplete(false); oldDataEntries .forEach(e -> { Check.errorUnless(e.getC_Period() != null, "{} has a missing C_Period", e);
final Timestamp dateOldEntry = e.getC_Period().getStartDate(); final Timestamp dateNewEntry; if (dateOldEntry.before(newTermtoUse.getStartDate())) { dateNewEntry = TimeUtil.addYears(dateOldEntry, 1); } else { dateNewEntry = dateOldEntry; } if (InterfaceWrapperHelper.isNull(e, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM)) { // if the current entry has a null value, then also the new entry shall have a null value builder.setFlatrateAmtPerUOM(dateNewEntry, null); } else { builder.setFlatrateAmtPerUOM(dateNewEntry, e.getFlatrateAmtPerUOM()); } builder.addQtyPlanned(dateNewEntry, e.getQty_Planned()); }); builder.build(); } @VisibleForTesting PMMContractBuilder newPMMContractBuilder(final I_C_Flatrate_Term term) { return PMMContractBuilder.newBuilder(term); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\contracts\ProcurementFlatrateHandler.java
1
请完成以下Java代码
public void setDATEV_ExportLine_ID (final int DATEV_ExportLine_ID) { if (DATEV_ExportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_DATEV_ExportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_DATEV_ExportLine_ID, DATEV_ExportLine_ID); } @Override public int getDATEV_ExportLine_ID() { return get_ValueAsInt(COLUMNNAME_DATEV_ExportLine_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_ValueNoCheck (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setDocBaseType (final @Nullable java.lang.String DocBaseType) { set_Value (COLUMNNAME_DocBaseType, DocBaseType); } @Override public java.lang.String getDocBaseType() { return get_ValueAsString(COLUMNNAME_DocBaseType); } @Override public void setDocumentNo (final @Nullable java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setDR_Account (final @Nullable java.lang.String DR_Account) { set_Value (COLUMNNAME_DR_Account, DR_Account); } @Override public java.lang.String getDR_Account() { return get_ValueAsString(COLUMNNAME_DR_Account); } @Override public void setDueDate (final @Nullable java.sql.Timestamp DueDate) { set_ValueNoCheck (COLUMNNAME_DueDate, DueDate); } @Override public java.sql.Timestamp getDueDate() { return get_ValueAsTimestamp(COLUMNNAME_DueDate); } @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx) { set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); }
@Override public void setPOReference (final @Nullable java.lang.String POReference) { set_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setPostingType (final @Nullable java.lang.String PostingType) { set_ValueNoCheck (COLUMNNAME_PostingType, PostingType); } @Override public java.lang.String getPostingType() { return get_ValueAsString(COLUMNNAME_PostingType); } @Override public void setTaxAmtSource (final @Nullable BigDecimal TaxAmtSource) { set_ValueNoCheck (COLUMNNAME_TaxAmtSource, TaxAmtSource); } @Override public BigDecimal getTaxAmtSource() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtSource); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setVATCode (final @Nullable java.lang.String VATCode) { set_ValueNoCheck (COLUMNNAME_VATCode, VATCode); } @Override public java.lang.String getVATCode() { return get_ValueAsString(COLUMNNAME_VATCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportLine.java
1
请完成以下Java代码
class SpringSessionBackedSessionInformation<S extends Session> extends SessionInformation { static final String EXPIRED_ATTR = SpringSessionBackedSessionInformation.class.getName() + ".EXPIRED"; private static final Log logger = LogFactory.getLog(SpringSessionBackedSessionInformation.class); private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; private final SessionRepository<S> sessionRepository; SpringSessionBackedSessionInformation(S session, SessionRepository<S> sessionRepository) { super(resolvePrincipal(session), session.getId(), Date.from(session.getLastAccessedTime())); this.sessionRepository = sessionRepository; Boolean expired = session.getAttribute(EXPIRED_ATTR); if (Boolean.TRUE.equals(expired)) { super.expireNow(); } } /** * Tries to determine the principal's name from the given Session. * @param session the session * @return the principal's name, or empty String if it couldn't be determined */ private static String resolvePrincipal(Session session) { String principalName = session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { return principalName; } SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT); if (securityContext != null && securityContext.getAuthentication() != null) { return securityContext.getAuthentication().getName(); }
return ""; } @Override public void expireNow() { if (logger.isDebugEnabled()) { logger.debug("Expiring session " + getSessionId() + " for user '" + getPrincipal() + "', presumably because maximum allowed concurrent " + "sessions was exceeded"); } super.expireNow(); S session = this.sessionRepository.findById(getSessionId()); if (session != null) { session.setAttribute(EXPIRED_ATTR, Boolean.TRUE); this.sessionRepository.save(session); } else { logger.info("Could not find Session with id " + getSessionId() + " to mark as expired"); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedSessionInformation.java
1
请完成以下Java代码
public class CourseEntity { private String name; private List<String> codes; private Map<String, Student> students = new HashMap<String, Student>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getCodes() { return codes; }
public void setCodes(List<String> codes) { this.codes = codes; } public void setStudent(String id, Student student) { students.put(id, student); } public Student getStudent(String enrolledId) { return students.get(enrolledId); } public Map<String, Student> getStudents() { return students; } }
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\beanutils\CourseEntity.java
1
请完成以下Java代码
public ClusterAppAssignMap setNamespaceSet(Set<String> namespaceSet) { this.namespaceSet = namespaceSet; return this; } public Boolean getBelongToApp() { return belongToApp; } public ClusterAppAssignMap setBelongToApp(Boolean belongToApp) { this.belongToApp = belongToApp; return this; } public Double getMaxAllowedQps() { return maxAllowedQps; } public ClusterAppAssignMap setMaxAllowedQps(Double maxAllowedQps) { this.maxAllowedQps = maxAllowedQps; return this;
} @Override public String toString() { return "ClusterAppAssignMap{" + "machineId='" + machineId + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", belongToApp=" + belongToApp + ", clientSet=" + clientSet + ", namespaceSet=" + namespaceSet + ", maxAllowedQps=" + maxAllowedQps + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterAppAssignMap.java
1
请完成以下Java代码
public class SwingContextProvider implements ContextProvider { private final Properties rootCtx = new Properties(); private final InheritableThreadLocal<Properties> temporaryCtxHolder = new InheritableThreadLocal<>(); private final AbstractPropertiesProxy ctxProxy = new AbstractPropertiesProxy() { @Override protected Properties getDelegate() { return getActualContext(); } private static final long serialVersionUID = 0; }; @Override public void init() { // nothing to do here } @Override public Properties getContext() { return ctxProxy; } private final Properties getActualContext() { final Properties temporaryCtx = temporaryCtxHolder.get(); if (temporaryCtx != null) { return temporaryCtx; } return rootCtx; } @Override public IAutoCloseable switchContext(final Properties ctx) { Check.assumeNotNull(ctx, "ctx not null"); // If we were asked to set the context proxy (the one which we are returning everytime), // then it's better to do nothing because this could end in a StackOverflowException. if (ctx == ctxProxy) { return NullAutoCloseable.instance; } final Properties previousTempCtx = temporaryCtxHolder.get(); temporaryCtxHolder.set(ctx); return new IAutoCloseable() { private boolean closed = false;
@Override public void close() { if (closed) { return; } if (previousTempCtx != null) { temporaryCtxHolder.set(previousTempCtx); } else { temporaryCtxHolder.remove(); } closed = true; } }; } @Override public void reset() { temporaryCtxHolder.remove(); rootCtx.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\SwingContextProvider.java
1
请完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMenuItems() { return menuItems; } public void setMenuItems(String menuItems) { this.menuItems = menuItems; } @Override public int compareTo(Role o) { if(id == o.getId()){ return 0; }else if(id > o.getId()){ return 1; }else{ return -1; } }
@Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(obj instanceof Role){ if(this.id == ((Role)obj).getId()){ return true; } } return false; } @Override public String toString() { return "Role{" + "id=" + id + ", name=" + name + ", roleLevel=" + roleLevel + ", description=" + description + '}'; } }
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\Role.java
1
请完成以下Java代码
class TabularStringWriter { @NonNull private final String identString; private final StringBuilder result = new StringBuilder(); private StringBuilder line = null; @Builder private TabularStringWriter(final int ident) { this.identString = ident > 0 ? Strings.repeat("\t", ident) : ""; } public String getAsString() { lineEnd(); return result.toString(); } public void appendCell(final String value, int width) { final String valueNorm = CoalesceUtil.coalesceNotNull(value, ""); if (line == null) { line = new StringBuilder(); } if (line.length() == 0) { line.append(identString); line.append("|"); }
line.append(" ").append(Strings.padEnd(valueNorm, width, ' ')).append(" |"); } public void lineEnd() { if (line != null) { if (result.length() > 0) { result.append("\n"); } result.append(line); } line = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\TabularStringWriter.java
1
请完成以下Java代码
public class WordCount { public static boolean wordCount(String inputFilePath, String outputFilePath) { // We use default options PipelineOptions options = PipelineOptionsFactory.create(); // to create the pipeline Pipeline p = Pipeline.create(options); // Here is our workflow graph PCollection<KV<String, Long>> wordCount = p .apply("(1) Read all lines", TextIO.read().from(inputFilePath)) .apply("(2) Flatmap to a list of words", FlatMapElements.into(TypeDescriptors.strings()) .via(line -> Arrays.asList(line.split("\\s")))) .apply("(3) Lowercase all", MapElements.into(TypeDescriptors.strings()) .via(word -> word.toLowerCase())) .apply("(4) Trim punctuations", MapElements.into(TypeDescriptors.strings()) .via(word -> trim(word))) .apply("(5) Filter stopwords", Filter.by(word -> !isStopWord(word))) .apply("(6) Count words", Count.perElement()); // We convert the PCollection to String so that we can write it to file wordCount.apply(MapElements.into(TypeDescriptors.strings()) .via(count -> count.getKey() + " --> " + count.getValue())) .apply(TextIO.write().to(outputFilePath)); // Finally we must run the pipeline, otherwise it's only a definition p.run().waitUntilFinish(); return true; } public static boolean isStopWord(String word) { String[] stopwords = {"am", "are", "is", "i", "you", "me", "he", "she", "they", "them", "was", "were", "from", "in", "of", "to", "be", "him", "her", "us", "and", "or"}; for (String stopword : stopwords) { if (stopword.compareTo(word) == 0) {
return true; } } return false; } public static String trim(String word) { return word.replace("(","") .replace(")", "") .replace(",", "") .replace(".", "") .replace("\"", "") .replace("'", "") .replace(":", "") .replace(";", "") .replace("-", "") .replace("?", "") .replace("!", ""); } }
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\beam\WordCount.java
1
请完成以下Java代码
public void removeUserFromCampaign( @NonNull final User user, @NonNull final CampaignId campaignId) { final Campaign campaign = campaignRepository.getById(campaignId); BPartnerLocationId billToDefaultLocationId = null; if (user.getBpartnerId() != null) { billToDefaultLocationId = bpartnerDAO.getBilltoDefaultLocationIdByBpartnerId(user.getBpartnerId()); } final ContactPerson contactPerson = ContactPerson.newForUserPlatformAndLocation(user, campaign.getPlatformId(), billToDefaultLocationId); final ContactPerson savedContactPerson = contactPersonRepository.save(contactPerson); contactPersonRepository.revokeConsent(savedContactPerson); campaignRepository.removeContactPersonFromCampaign(savedContactPerson, campaign);
} public void saveSyncResults(@NonNull final List<? extends SyncResult> syncResults) { for (final SyncResult syncResult : syncResults) { campaignRepository.saveCampaignSyncResult(syncResult); } } public Campaign saveSyncResult(@NonNull final SyncResult syncResult) { return campaignRepository.saveCampaignSyncResult(syncResult); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\CampaignService.java
1
请完成以下Java代码
public I_CM_CStage getCM_CStage() throws RuntimeException { return (I_CM_CStage)MTable.get(getCtx(), I_CM_CStage.Table_Name) .getPO(getCM_CStage_ID(), get_TrxName()); } /** Set Web Container Stage. @param CM_CStage_ID Web Container Stage contains the staging content like images, text etc. */ public void setCM_CStage_ID (int CM_CStage_ID) { if (CM_CStage_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_CStage_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_CStage_ID, Integer.valueOf(CM_CStage_ID)); } /** Get Web Container Stage. @return Web Container Stage contains the staging content like images, text etc. */ public int getCM_CStage_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_CStage_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Content HTML. @param ContentHTML Contains the content itself */ public void setContentHTML (String ContentHTML) { set_Value (COLUMNNAME_ContentHTML, ContentHTML); } /** Get Content HTML. @return Contains the content itself */ public String getContentHTML () { return (String)get_Value(COLUMNNAME_ContentHTML); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () {
return (String)get_Value(COLUMNNAME_Help); } /** Set Valid. @param IsValid Element is valid */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Valid. @return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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_CM_CStage_Element.java
1
请完成以下Java代码
public class DummyDevice extends AbstractBaseDevice { private static final Logger logger = LogManager.getLogger(DummyDevice.class); public DummyDevice() { registerHandler(DummyDeviceRequest.class, this::handleRequest); } public static Set<String> getDeviceRequestClassnames() { return ImmutableSet.of(DummyDeviceRequest.class.getName()); } @Override public IDeviceResponseGetConfigParams getRequiredConfigParams() { return ImmutableList::of; } @Override public IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler() { return this::handleRequest; } private IDeviceResponse handleRequest(final DeviceRequestConfigureDevice request) {
IDeviceResponse response = new IDeviceResponse() { }; logger.info("handleRequest: {} => {}", request, response); return response; } private DummyDeviceResponse handleRequest(final DummyDeviceRequest request) { final DummyDeviceResponse response = DummyDeviceConfigPool.generateRandomResponse(); logger.info("handleRequest: {} => {}", request, response); return response; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDevice.java
1
请完成以下Java代码
public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the schmeNm property. * * @return * possible object is * {@link AccountSchemeName1Choice } * */ public AccountSchemeName1Choice getSchmeNm() { return schmeNm; } /** * Sets the value of the schmeNm property. * * @param value * allowed object is * {@link AccountSchemeName1Choice }
* */ public void setSchmeNm(AccountSchemeName1Choice value) { this.schmeNm = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String } * */ public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\GenericAccountIdentification1.java
1
请完成以下Java代码
public static class Input { @JsonProperty("@type") private String type; // TextInput, DateInput, MultichoiceInput private String id; private boolean isMultiple; private String title; private boolean isMultiSelect; @Data public static class Choice { private final String display; private final String value; } } @Data
public static class Action { @JsonProperty("@type") private final String type; // HttpPOST private final String name; private final String target; // url } @Data public static class Target { private final String os; private final String uri; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\TeamsMessageCard.java
1
请完成以下Java代码
public void setCM_ChatType_ID (int CM_ChatType_ID) { if (CM_ChatType_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID)); } /** Get Chat Type. @return Type of discussion / chat */ public int getCM_ChatType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** ModerationType AD_Reference_ID=395 */ public static final int MODERATIONTYPE_AD_Reference_ID=395; /** Not moderated = N */ public static final String MODERATIONTYPE_NotModerated = "N"; /** Before Publishing = B */ public static final String MODERATIONTYPE_BeforePublishing = "B"; /** After Publishing = A */ public static final String MODERATIONTYPE_AfterPublishing = "A"; /** Set Moderation Type. @param ModerationType Type of moderation */ public void setModerationType (String ModerationType) { set_Value (COLUMNNAME_ModerationType, ModerationType); } /** Get Moderation Type. @return Type of moderation */ public String getModerationType ()
{ return (String)get_Value(COLUMNNAME_ModerationType); } /** 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_CM_ChatType.java
1
请完成以下Java代码
public boolean canConvert(final String filterId) { return PostgresFTSDocumentFilterDescriptorsProviderFactory.FILTER_ID.equals(filterId); } @Nullable @Override public FilterSql getSql( @NonNull final DocumentFilter filter, @NonNull final SqlOptions sqlOpts, @NonNull final SqlDocumentFilterConverterContext context) { final String searchText = filter.getParameterValueAsString(FTSDocumentFilterDescriptorsProviderFactory.PARAM_SearchText, null); if (Check.isBlank(searchText)) { return FilterSql.ALLOW_ALL; } final String mainTableAlias = sqlOpts.getTableNameOrAlias(); final String ftsTableAlias = "fts_bpartner"; final String ftsTableName = "C_BPartner_FTS"; final String keyColumnName = "C_BPartner_ID"; final String mainTableKeyColumn = mainTableAlias + "." + keyColumnName; // https://www.postgresql.org/docs/current/textsearch.html final SqlAndParams.Builder whereClause = SqlAndParams.builder() .append(mainTableKeyColumn).append(" IN (") .append("SELECT ").append(keyColumnName).append(" FROM ").append(ftsTableName) .append(" WHERE fts_document @@ websearch_to_tsquery(get_fts_config(), ?)", searchText); final SqlAndParams.Builder orderByClause = SqlAndParams.builder() .append("(SELECT ts_rank(").append(ftsTableAlias).append(".fts_document, websearch_to_tsquery(get_fts_config(), ?))", searchText) .append(" FROM ").append(ftsTableName).append(" ").append(ftsTableAlias) .append(" WHERE ").append(ftsTableAlias).append(".").append(keyColumnName).append(" = ").append(mainTableKeyColumn) .append(") DESC NULLS LAST"); final BigDecimal distance = sysConfigBL.getBigDecimalValue(SYSCONFIG_DISTANCE, BigDecimal.ONE); if (distance.compareTo(BigDecimal.ZERO) > 0 && BigDecimal.ONE.compareTo(distance) > 0) { // https://www.postgresql.org/docs/current/pgtrgm.html (ngram search)
final int fuzzySearchLimit = sysConfigBL.getIntValue(SYSCONFIG_NGRAM_LIMIT, 1000); whereClause.append(" UNION ") .append("(SELECT ").append(keyColumnName).append(" FROM ").append(ftsTableName) .append(" WHERE fts_string <-> ? < ?", searchText, distance) .append(" ORDER BY fts_string <-> ? ASC", searchText) .append(" LIMIT ?)", fuzzySearchLimit); orderByClause.append(", ") .append("(SELECT ").append(ftsTableAlias).append(".fts_string <-> ?", searchText) .append(" FROM ").append(ftsTableName).append(" ").append(ftsTableAlias) .append(" WHERE ").append(ftsTableAlias).append(".").append(keyColumnName).append(" = ").append(mainTableKeyColumn) .append(") ASC NULLS LAST"); } whereClause.append(" )"); return FilterSql.builder().whereClause(whereClause.build()).orderBy(orderByClause.build()).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\fullTextSearch\PostgresFTSDocumentFilterConverter.java
1
请完成以下Java代码
public int hashCode() { return new HashcodeBuilder() .append(AD_Table_ID) .append(Record_ID) .append(C_DunningLevels) .append(active) .append(applyClientSecurity) .append(processed) .append(writeOff) .toHashcode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } final DunningCandidateQuery other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(AD_Table_ID, other.AD_Table_ID) .append(Record_ID, other.Record_ID) .append(C_DunningLevels, other.C_DunningLevels) .append(active, other.active) .append(applyClientSecurity, other.applyClientSecurity) .append(processed, this.processed) .append(writeOff, this.writeOff) .isEqual(); } @Override public int getAD_Table_ID() { return AD_Table_ID; } public void setAD_Table_ID(int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } public void setRecord_ID(int record_ID) { Record_ID = record_ID; } @Override public List<I_C_DunningLevel> getC_DunningLevels() { return C_DunningLevels; } public void setC_DunningLevels(List<I_C_DunningLevel> c_DunningLevels) { C_DunningLevels = c_DunningLevels; } @Override public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public boolean isApplyClientSecurity() { return applyClientSecurity; } public void setApplyClientSecurity(boolean applyClientSecurity) { this.applyClientSecurity = applyClientSecurity; }
@Override public Boolean getProcessed() { return processed; } public void setProcessed(Boolean processed) { this.processed = processed; } @Override public Boolean getWriteOff() { return writeOff; } public void setWriteOff(Boolean writeOff) { this.writeOff = writeOff; } @Override public String getAdditionalWhere() { return additionalWhere; } public void setAdditionalWhere(String additionalWhere) { this.additionalWhere = additionalWhere; } @Override public ApplyAccessFilter getApplyAccessFilter() { return applyAccessFilter; } public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter) { this.applyAccessFilter = applyAccessFilter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java
1
请完成以下Java代码
public Date resolveDuedate(String duedate, Task task) { return resolveDuedate(duedate); } public Date resolveDuedate(String duedate) { return resolveDuedate(duedate, (Date)null); } public Date resolveDuedate(String duedate, Date startDate) { Date resolvedDuedate = startDate == null ? ClockUtil.getCurrentTime() : startDate; String[] tokens = duedate.split(" and "); for (String token : tokens) { resolvedDuedate = addSingleUnitQuantity(resolvedDuedate, token); } return resolvedDuedate; } protected Date addSingleUnitQuantity(Date startDate, String singleUnitQuantity) { int spaceIndex = singleUnitQuantity.indexOf(" "); if (spaceIndex==-1 || singleUnitQuantity.length() < spaceIndex+1) { throw new ProcessEngineException("invalid duedate format: "+singleUnitQuantity);
} String quantityText = singleUnitQuantity.substring(0, spaceIndex); Integer quantity = Integer.valueOf(quantityText); String unitText = singleUnitQuantity .substring(spaceIndex+1) .trim() .toLowerCase(); int unit = units.get(unitText); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(startDate); calendar.add(unit, quantity); return calendar.getTime(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\calendar\DefaultBusinessCalendar.java
1
请完成以下Java代码
public int getRepoId() { return userId.getRepoId(); } public static int toRepoId(@Nullable final BPartnerContactId id) { return id != null ? id.getRepoId() : -1; } @Nullable public static UserId toUserIdOrNull(@Nullable final BPartnerContactId id) { return id != null ? id.getUserId() : null; } public static boolean equals(@Nullable final BPartnerContactId id1, @Nullable final BPartnerContactId id2) { return Objects.equals(id1, id2); } @JsonCreator public static BPartnerContactId ofJsonString(@NonNull final String idStr)
{ try { final List<String> parts = Splitter.on("-").splitToList(idStr); return of( BPartnerId.ofRepoId(Integer.parseInt(parts.get(0))), UserId.ofRepoId(Integer.parseInt(parts.get(1)))); } catch (Exception ex) { throw new AdempiereException("Invalid BPartnerContactId string: " + idStr, ex); } } @JsonValue public String toJson() { return bpartnerId.getRepoId() + "-" + userId.getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerContactId.java
1
请完成以下Java代码
public void generateModifiedDocument() { try { SAXReader reader = new SAXReader(); Document document = reader.read(file); List<Node> nodes = document.selectNodes("/tutorials/tutorial"); for (Node node : nodes) { Element element = (Element) node; Iterator<Element> iterator = element.elementIterator("title"); while (iterator.hasNext()) { Element title = (Element) iterator.next(); title.setText(title.getText() + " updated"); } } XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_dom4j_updated.xml"))); writer.write(document); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void generateNewDocument() { try { Document document = DocumentHelper.createDocument(); Element root = document.addElement("XMLTutorials"); Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01"); tutorialElement.addAttribute("type", "xml"); tutorialElement.addElement("title").addText("XML with Dom4J"); tutorialElement.addElement("description").addText("XML handling with Dom4J"); tutorialElement.addElement("date").addText("14/06/2016");
tutorialElement.addElement("author").addText("Dom4J tech writer"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_dom4j_new.xml")), format); writer.write(document); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\Dom4JParser.java
1
请在Spring Boot框架中完成以下Java代码
public String importTo(Class<?> type, List<String> jsonLines) { List<Document> mongoDocs = generateMongoDocs(jsonLines, type); String collection = type.getAnnotation(org.springframework.data.mongodb.core.mapping.Document.class) .value(); int inserts = insertInto(collection, mongoDocs); return inserts + "/" + jsonLines.size(); } public String importTo(String collection, List<String> jsonLines) { List<Document> mongoDocs = generateMongoDocs(jsonLines); int inserts = insertInto(collection, mongoDocs); return inserts + "/" + jsonLines.size(); } private int insertInto(String collection, List<Document> mongoDocs) { try { Collection<Document> inserts = mongo.insert(mongoDocs, collection); return inserts.size(); } catch (DataIntegrityViolationException e) { log.error("importing docs", e); if (e.getCause() instanceof MongoBulkWriteException) { return ((MongoBulkWriteException) e.getCause()).getWriteResult() .getInsertedCount(); } return 0; } } private List<Document> generateMongoDocs(List<String> lines) { return generateMongoDocs(lines, null); } private <T> List<Document> generateMongoDocs(List<String> lines, Class<T> type) { ObjectMapper mapper = new ObjectMapper();
List<Document> docs = new ArrayList<>(); for (String json : lines) { try { if (type != null) { T v = mapper.readValue(json, type); json = mapper.writeValueAsString(v); } docs.add(Document.parse(json)); } catch (Throwable e) { log.error("parsing: " + json, e); } } return docs; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\json\convertfile\service\ImportJsonService.java
2
请完成以下Java代码
public class DateUtil { public static Date toDate(Object dateObject) { if (dateObject == null) { throw new IllegalArgumentException("date object cannot be empty"); } if (dateObject instanceof Date) { return (Date) dateObject; } else if (dateObject instanceof LocalDate) { JodaDeprecationLogger.LOGGER.warn("Using Joda-Time LocalDate has been deprecated and will be removed in a future version."); return ((LocalDate) dateObject).toDate(); } else if (dateObject instanceof java.time.LocalDate) { return Date.from(((java.time.LocalDate) dateObject).atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); } else { DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd"); LocalDate dateTime = dtf.parseLocalDate((String) dateObject); return dateTime.toDate(); } } public static Date addDate(Object startDate, Object years, Object months, Object days) { LocalDate currentDate = new LocalDate(startDate); currentDate = currentDate.plusYears(intValue(years)); currentDate = currentDate.plusMonths(intValue(months)); currentDate = currentDate.plusDays(intValue(days)); return currentDate.toDate(); } public static Date subtractDate(Object startDate, Object years, Object months, Object days) { LocalDate currentDate = new LocalDate(startDate); currentDate = currentDate.minusYears(intValue(years)); currentDate = currentDate.minusMonths(intValue(months)); currentDate = currentDate.minusDays(intValue(days));
return currentDate.toDate(); } public static Date now() { return new LocalDate().toDate(); } protected static Integer intValue(Object value) { Integer intValue = null; if (value instanceof Integer) { intValue = (Integer) value; } else { intValue = Integer.valueOf(value.toString()); } return intValue; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\util\DateUtil.java
1
请完成以下Java代码
public <T extends OAuth2Token> Builder invalidate(T token) { Assert.notNull(token, "token cannot be null"); if (this.tokens.get(token.getClass()) == null) { return this; } token(token, (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)); if (OAuth2RefreshToken.class.isAssignableFrom(token.getClass())) { Token<?> accessToken = this.tokens.get(OAuth2AccessToken.class); token(accessToken.getToken(), (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)); Token<?> authorizationCode = this.tokens.get(OAuth2AuthorizationCode.class); if (authorizationCode != null && !authorizationCode.isInvalidated()) { token(authorizationCode.getToken(), (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)); } } return this; } protected final Builder tokens(Map<Class<? extends OAuth2Token>, Token<?>> tokens) { this.tokens = new HashMap<>(tokens); return this; } /** * Adds an attribute associated to the authorization. * @param name the name of the attribute * @param value the value of the attribute * @return the {@link Builder} */ public Builder attribute(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.attributes.put(name, value); return this; } /** * A {@code Consumer} of the attributes {@code Map} allowing the ability to add, * replace, or remove.
* @param attributesConsumer a {@link Consumer} of the attributes {@code Map} * @return the {@link Builder} */ public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) { attributesConsumer.accept(this.attributes); return this; } /** * Builds a new {@link OAuth2Authorization}. * @return the {@link OAuth2Authorization} */ public OAuth2Authorization build() { Assert.hasText(this.principalName, "principalName cannot be empty"); Assert.notNull(this.authorizationGrantType, "authorizationGrantType cannot be null"); OAuth2Authorization authorization = new OAuth2Authorization(); if (!StringUtils.hasText(this.id)) { this.id = UUID.randomUUID().toString(); } authorization.id = this.id; authorization.registeredClientId = this.registeredClientId; authorization.principalName = this.principalName; authorization.authorizationGrantType = this.authorizationGrantType; authorization.authorizedScopes = Collections.unmodifiableSet(!CollectionUtils.isEmpty(this.authorizedScopes) ? new HashSet<>(this.authorizedScopes) : new HashSet<>()); authorization.tokens = Collections.unmodifiableMap(this.tokens); authorization.attributes = Collections.unmodifiableMap(this.attributes); return authorization; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2Authorization.java
1
请完成以下Java代码
public Map<DocumentId, InvoiceRow> getDocumentId2TopLevelRows() { return rowsHolder.getDocumentId2TopLevelRows(); } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs) { return recordRefs.streamIds(I_C_Invoice.Table_Name, InvoiceId::ofRepoId) .map(InvoiceRow::convertInvoiceIdToDocumentId) .filter(rowsHolder.isRelevantForRefreshingByDocumentId()) .collect(DocumentIdsSelection.toDocumentIdsSelection()); } @Override public void invalidateAll() { invalidate(DocumentIdsSelection.ALL); } @Override public void invalidate(@NonNull final DocumentIdsSelection rowIds) { final ImmutableSet<InvoiceId> invoiceIds = rowsHolder.getRecordIdsToRefresh(rowIds, InvoiceRow::convertDocumentIdToInvoiceId); final ImmutableMap<DocumentId, InvoiceRow> oldRowsById = rowsHolder.getDocumentId2TopLevelRows(); final List<InvoiceRow> newRows = repository.getInvoiceRowsListByInvoiceId(invoiceIds, evaluationDate) .stream() .map(newRow -> mergeFromOldRow(newRow, oldRowsById)) .collect(ImmutableList.toImmutableList()); rowsHolder.compute(rows -> rows.replacingRows(rowIds, newRows)); } private static InvoiceRow mergeFromOldRow( @NonNull final InvoiceRow newRow, @NonNull final ImmutableMap<DocumentId, InvoiceRow> oldRowsById) { final InvoiceRow oldRow = oldRowsById.get(newRow.getId()); if (oldRow == null) { return newRow; } return newRow.withPreparedForAllocation(oldRow.isPreparedForAllocation()); } public void addInvoice(@NonNull final InvoiceId invoiceId) { final InvoiceRow row = repository.getInvoiceRowByInvoiceId(invoiceId, evaluationDate).orElse(null); if (row == null) {
throw new AdempiereException("@InvoiceNotOpen@"); } rowsHolder.compute(rows -> rows.addingRow(row)); } @Override public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests) { final DocumentId rowIdToChange = ctx.getRowId(); rowsHolder.compute(rows -> rows.changingRow(rowIdToChange, row -> InvoiceRowReducers.reduce(row, fieldChangeRequests))); } public ImmutableList<InvoiceRow> getRowsWithPreparedForAllocationFlagSet() { return getAllRows() .stream() .filter(InvoiceRow::isPreparedForAllocation) .collect(ImmutableList.toImmutableList()); } public void markPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds) { rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationSet)); } public void unmarkPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds) { rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationUnset)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRows.java
1
请完成以下Java代码
public void setWindowType (final java.lang.String WindowType) { set_Value (COLUMNNAME_WindowType, WindowType); } @Override public java.lang.String getWindowType() { return get_ValueAsString(COLUMNNAME_WindowType); } @Override public void setWinHeight (final int WinHeight) { set_Value (COLUMNNAME_WinHeight, WinHeight); } @Override public int getWinHeight() { return get_ValueAsInt(COLUMNNAME_WinHeight); } @Override public void setWinWidth (final int WinWidth) { set_Value (COLUMNNAME_WinWidth, WinWidth); }
@Override public int getWinWidth() { return get_ValueAsInt(COLUMNNAME_WinWidth); } @Override public void setZoomIntoPriority (final int ZoomIntoPriority) { set_Value (COLUMNNAME_ZoomIntoPriority, ZoomIntoPriority); } @Override public int getZoomIntoPriority() { return get_ValueAsInt(COLUMNNAME_ZoomIntoPriority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window.java
1
请完成以下Java代码
public <T extends ModelElementInstance> T newInstance(Class<T> type) { return newInstance(type, null); } public <T extends ModelElementInstance> T newInstance(Class<T> type, String id) { ModelElementType modelElementType = model.getType(type); if(modelElementType != null) { return newInstance(modelElementType, id); } else { throw new ModelException("Cannot create instance of ModelType "+type+": no such type registered."); } } public <T extends ModelElementInstance> T newInstance(ModelElementType type) { return newInstance(type, null); } @SuppressWarnings("unchecked") public <T extends ModelElementInstance> T newInstance(ModelElementType type, String id) { ModelElementInstance modelElementInstance = type.newInstance(this); if (id != null && !id.isEmpty()) { ModelUtil.setNewIdentifier(type, modelElementInstance, id, false); } else { ModelUtil.setGeneratedUniqueIdentifier(type, modelElementInstance, false); } return (T) modelElementInstance; } public Model getModel() { return model; } public ModelElementType registerGenericType(String namespaceUri, String localName) { ModelElementType elementType = model.getTypeForName(namespaceUri, localName); if (elementType == null) { elementType = modelBuilder.defineGenericType(localName, namespaceUri); model = (ModelImpl) modelBuilder.build(); } return elementType; } @SuppressWarnings("unchecked") public <T extends ModelElementInstance> T getModelElementById(String id) { if (id == null) { return null; } DomElement element = document.getElementById(id); if(element != null) { return (T) ModelUtil.getModelElement(element, this); } else { return null; } }
public Collection<ModelElementInstance> getModelElementsByType(ModelElementType type) { Collection<ModelElementType> extendingTypes = type.getAllExtendingTypes(); List<ModelElementInstance> instances = new ArrayList<ModelElementInstance>(); for (ModelElementType modelElementType : extendingTypes) { if(!modelElementType.isAbstract()) { instances.addAll(modelElementType.getInstances(this)); } } return instances; } @SuppressWarnings("unchecked") public <T extends ModelElementInstance> Collection<T> getModelElementsByType(Class<T> referencingClass) { return (Collection<T>) getModelElementsByType(getModel().getType(referencingClass)); } @Override public ModelInstance clone() { return new ModelInstanceImpl(model, modelBuilder, document.clone()); } @Override public ValidationResults validate(Collection<ModelElementValidator<?>> validators) { return new ModelInstanceValidator(this, validators).validate(); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelInstanceImpl.java
1
请完成以下Java代码
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 getGL_JournalBatch_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Line No. @param Line Unique line for this document */ public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Line No. @return Unique line for this document */ public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Shipment/Receipt Line. @param M_InOutLine_ID Line on Shipment or Receipt document */ public void setM_InOutLine_ID (int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID)); } /** Get Shipment/Receipt Line. @return Line on Shipment or Receipt document */
public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Addition.java
1
请在Spring Boot框架中完成以下Java代码
public List<Product> listAll() { List<Product> products = new ArrayList<>(); productRepository.findAll().forEach(products::add); //fun with Java 8 return products; } @Override public Product getById(Long id) { return productRepository.findById(id).orElse(null); } @Override public Product saveOrUpdate(Product product) { productRepository.save(product); return product; }
@Override public void delete(Long id) { productRepository.deleteById(id); } @Override public Product saveOrUpdateProductForm(ProductForm productForm) { Product savedProduct = saveOrUpdate(productFormToProduct.convert(productForm)); System.out.println("Saved Product Id: " + savedProduct.getId()); return savedProduct; } }
repos\SpringBootVulExploit-master\repository\springboot-mysql-jdbc-rce\src\main\java\code\landgrey\services\ProductServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class JsonExternalId { String value; @JsonCreator public static JsonExternalId of(@NonNull final String value) { return new JsonExternalId(value); } @Nullable public static JsonExternalId ofOrNull(@Nullable final String value) { if (EmptyUtil.isBlank(value)) { return null; } return new JsonExternalId(value); } private JsonExternalId(@NonNull final String value) { if (value.trim().isEmpty()) { throw new RuntimeException("Param value=" + value + " may not be empty"); } this.value = value;
} @JsonValue public String getValue() { return value; } public static boolean equals(@Nullable final JsonExternalId id1, @Nullable final JsonExternalId id2) { return Objects.equals(id1, id2); } public static String toValue(@Nullable final JsonExternalId externalId) { if (externalId == null) { return null; } return externalId.getValue(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\common\JsonExternalId.java
2
请完成以下Java代码
void perform() { lock.lock(); LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock"); try { LOG.info("Thread - " + Thread.currentThread().getName() + " processing"); counter++; } catch (Exception exception) { LOG.error(" Interrupted Exception ", exception); } finally { lock.unlock(); LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock"); } } private void performTryLock() { LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock"); try { boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS); if (isLockAcquired) { try { LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock"); LOG.info("Thread - " + Thread.currentThread().getName() + " processing"); sleep(1000); } finally { lock.unlock(); LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock"); } } } catch (InterruptedException exception) { LOG.error(" Interrupted Exception ", exception); } LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock"); } public ReentrantLock getLock() { return lock; } boolean isLocked() { return lock.isLocked(); } boolean hasQueuedThreads() {
return lock.hasQueuedThreads(); } int getCounter() { return counter; } public static void main(String[] args) { final int threadCount = 2; final ExecutorService service = Executors.newFixedThreadPool(threadCount); final SharedObjectWithLock object = new SharedObjectWithLock(); service.execute(object::perform); service.execute(object::performTryLock); service.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SharedObjectWithLock.java
1
请完成以下Java代码
public void modifiers(KotlinModifier... modifiers) { this.modifiers = Arrays.asList(modifiers); } List<KotlinModifier> getModifiers() { return this.modifiers; } /** * Adds a property declaration. * @param propertyDeclaration the property declaration */ public void addPropertyDeclaration(KotlinPropertyDeclaration propertyDeclaration) { this.propertyDeclarations.add(propertyDeclaration); } /** * Returns the property declarations. * @return the property declaration */ public List<KotlinPropertyDeclaration> getPropertyDeclarations() { return this.propertyDeclarations;
} /** * Adds the function declaration. * @param methodDeclaration the function declaration */ public void addFunctionDeclaration(KotlinFunctionDeclaration methodDeclaration) { this.functionDeclarations.add(methodDeclaration); } /** * Returns the function declarations. * @return the function declarations */ public List<KotlinFunctionDeclaration> getFunctionDeclarations() { return this.functionDeclarations; } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinTypeDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static Map<String, Map<String, Object>> toMap() { OrderFromEnum[] ary = OrderFromEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { OrderFromEnum[] ary = OrderFromEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); list.add(map); } return list; }
public static OrderFromEnum getEnum(String name) { OrderFromEnum[] arry = OrderFromEnum.values(); for (int i = 0; i < arry.length; i++) { if (arry[i].name().equalsIgnoreCase(name)) { return arry[i]; } } return null; } /** * 取枚举的json字符串 * * @return */ public static String getJsonStr() { OrderFromEnum[] enums = OrderFromEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (OrderFromEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\OrderFromEnum.java
2
请完成以下Java代码
public class ConnectorParseListener extends AbstractBpmnParseListener { @Override public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) { parseConnectorElement(serviceTaskElement, scope, activity); } @Override public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) { Element messageEventDefinitionElement = endEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION); if (messageEventDefinitionElement != null) { parseConnectorElement(messageEventDefinitionElement, scope, activity); } } @Override public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { Element messageEventDefinitionElement = intermediateEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION); if (messageEventDefinitionElement != null) { parseConnectorElement(messageEventDefinitionElement, scope, activity); } } @Override public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) { parseConnectorElement(businessRuleTaskElement, scope, activity); }
@Override public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) { parseConnectorElement(sendTaskElement, scope, activity); } protected void parseConnectorElement(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) { Element connectorDefinition = findCamundaExtensionElement(serviceTaskElement, "connector"); if (connectorDefinition != null) { Element connectorIdElement = connectorDefinition.element("connectorId"); String connectorId = null; if (connectorIdElement != null) { connectorId = connectorIdElement.getText().trim(); } if (connectorIdElement == null || connectorId.isEmpty()) { throw new BpmnParseException("No 'id' defined for connector.", connectorDefinition); } IoMapping ioMapping = parseInputOutput(connectorDefinition); activity.setActivityBehavior(new ServiceTaskConnectorActivityBehavior(connectorId, ioMapping)); } } }
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ConnectorParseListener.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Nutrition Fact. @param M_Nutrition_Fact_ID Nutrition Fact */ @Override public void setM_Nutrition_Fact_ID (int M_Nutrition_Fact_ID) { if (M_Nutrition_Fact_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, Integer.valueOf(M_Nutrition_Fact_ID)); } /** Get Nutrition Fact. @return Nutrition Fact */ @Override
public int getM_Nutrition_Fact_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Nutrition_Fact_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Nutrition_Fact.java
1
请在Spring Boot框架中完成以下Java代码
final class PackingInfo { public static final PackingInfo NONE = new PackingInfo(); @NonNull BigDecimal qtyCUsPerTU; @NonNull String description; @Builder public PackingInfo( @NonNull final BigDecimal qtyCUsPerTU, final String description) { Check.assumeGreaterThanZero(qtyCUsPerTU, "qtyCUsPerTU"); this.qtyCUsPerTU = qtyCUsPerTU; this.description = description != null ? description.trim() : ""; } /** NO Packing constructor */ private PackingInfo() { this.description = ""; this.qtyCUsPerTU = BigDecimal.ONE; } public boolean isNone() { return NONE.equals(this); }
public BigDecimal computeQtyUserEnteredByQtyCUs(@NonNull final Quantity qtyCUs) { return computeQtyUserEnteredByQtyCUs(qtyCUs.toBigDecimal()); } public BigDecimal computeQtyUserEnteredByQtyCUs(@NonNull final BigDecimal qtyCUs) { return isNone() ? qtyCUs : computeQtyTUsByQtyCUs(qtyCUs); } public BigDecimal computeQtyCUsByQtyUserEntered(@NonNull final BigDecimal qtyUserEntered) { return isNone() ? qtyUserEntered : computeQtyCUsByQtyTUs(qtyUserEntered); } private BigDecimal computeQtyTUsByQtyCUs(final BigDecimal qtyCUs) { return qtyCUs.divide(qtyCUsPerTU, 0, RoundingMode.UP); } private BigDecimal computeQtyCUsByQtyTUs(final BigDecimal qtyTUs) { return qtyTUs.multiply(qtyCUsPerTU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\PackingInfo.java
2
请完成以下Java代码
public boolean isFailRollbackIfTrxNotStarted() { return failRollbackIfTrxNotStarted; } public void assertNoActiveTransactions() { final List<ITrx> activeTrxs = getActiveTransactionsList(); Check.assume(activeTrxs.isEmpty(), "Expected no active transactions but got: {}", activeTrxs); } /** * Ask the transactions to log their major events like COMMIT, ROLLBACK. * Those events will be visible on {@link PlainTrx#toString()}. *
* @param debugTrxLog */ public void setDebugTrxLog(boolean debugTrxLog) { this.debugTrxLog = debugTrxLog; } /** * @see #setDebugTrxLog(boolean) */ public boolean isDebugTrxLog() { return debugTrxLog; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrxManager.java
1
请完成以下Java代码
public void addNamespace(String prefix, String uri) { namespaceMap.put(prefix, uri); } public boolean containsNamespacePrefix(String prefix) { return namespaceMap.containsKey(prefix); } public String getNamespace(String prefix) { return namespaceMap.get(prefix); } public Map<String, String> getNamespaces() { return namespaceMap; } public String getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; } public String getSourceSystemId() { return sourceSystemId; } public void setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; } public List<String> getUserTaskFormTypes() { return userTaskFormTypes; } public void setUserTaskFormTypes(List<String> userTaskFormTypes) { this.userTaskFormTypes = userTaskFormTypes; } public List<String> getStartEventFormTypes() {
return startEventFormTypes; } public void setStartEventFormTypes(List<String> startEventFormTypes) { this.startEventFormTypes = startEventFormTypes; } @JsonIgnore public Object getEventSupport() { return eventSupport; } public void setEventSupport(Object eventSupport) { this.eventSupport = eventSupport; } public String getStartFormKey(String processId) { FlowElement initialFlowElement = getProcessById(processId).getInitialFlowElement(); if (initialFlowElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) initialFlowElement; return startEvent.getFormKey(); } return null; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BpmnModel.java
1
请完成以下Java代码
public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } @Override public void setX (final @Nullable java.lang.String X) { set_Value (COLUMNNAME_X, X); } @Override public java.lang.String getX() { return get_ValueAsString(COLUMNNAME_X); } @Override public void setX1 (final @Nullable java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } @Override public java.lang.String getX1() { return get_ValueAsString(COLUMNNAME_X1); } @Override public void setY (final @Nullable java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); }
@Override public java.lang.String getY() { return get_ValueAsString(COLUMNNAME_Y); } @Override public void setZ (final @Nullable java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } @Override public java.lang.String getZ() { return get_ValueAsString(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java
1
请完成以下Java代码
public LogicExpressionResult revaluate(final LogicExpressionResult readonly) { if (alwaysReturnResult != null) { return alwaysReturnResult; } if (userRolePermissions == null) { return readonly; } final Map<String, String> newParameters = computeNewParametersIfChanged(readonly.getUsedParameters(), userRolePermissions); return newParameters != null ? revaluate(readonly, newParameters) : readonly; } @Nullable private static Map<String, String> computeNewParametersIfChanged( @NonNull final Map<CtxName, String> usedParameters, @NonNull final IUserRolePermissions userRolePermissions) { if (usedParameters.isEmpty()) { return null; } HashMap<String, String> newParameters = null; // lazy, instantiated only if needed for (final Map.Entry<CtxName, String> usedParameterEntry : usedParameters.entrySet()) { final CtxName usedParameterName = usedParameterEntry.getKey(); if (CTXNAME_AD_Role_Group.equalsByName(usedParameterName)) { final String usedValue = normalizeRoleGroupValue(usedParameterEntry.getValue()); final String newValue = normalizeRoleGroupValue(userRolePermissions.getRoleGroup() != null ? userRolePermissions.getRoleGroup().getName() : null); if (!Objects.equals(usedValue, newValue)) { newParameters = newParameters == null ? copyToNewParameters(usedParameters) : newParameters; newParameters.put(CTXNAME_AD_Role_Group.getName(), newValue); } } } return newParameters; } private static String normalizeRoleGroupValue(String roleGroupValue) {
String result = LogicExpressionEvaluator.stripQuotes(roleGroupValue); result = StringUtils.trimBlankToNull(result); return result != null ? result : ""; } @NonNull private static HashMap<String, String> copyToNewParameters(final @NonNull Map<CtxName, String> usedParameters) { final HashMap<String, String> newParameters = new HashMap<>(usedParameters.size()); for (Map.Entry<CtxName, String> entry : usedParameters.entrySet()) { newParameters.put(entry.getKey().getName(), entry.getValue()); } return newParameters; } private static LogicExpressionResult revaluate( @NonNull final LogicExpressionResult result, @NonNull final Map<String, String> newParameters) { try { return result.getExpression().evaluateToResult(Evaluatees.ofMap(newParameters), IExpressionEvaluator.OnVariableNotFound.Fail); } catch (final Exception ex) { // shall not happen logger.warn("Failed evaluating expression using `{}`. Returning previous result: {}", newParameters, result, ex); return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldLogicExpressionResultRevaluator.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean authenticate(final String username, final String password) { User user = userRepository.findByUsernameAndPassword(username, password); return user != null; } public List<String> search(final String username) { List<User> userList = userRepository.findByUsernameLikeIgnoreCase(username); if (userList == null) { return Collections.emptyList(); } return userList.stream() .map(User::getUsername) .collect(Collectors.toList()); } public void create(final String username, final String password) { User newUser = new User(username,digestSHA(password)); newUser.setId(LdapUtils.emptyLdapName()); userRepository.save(newUser); } public void modify(final String username, final String password) {
User user = userRepository.findByUsername(username); user.setPassword(password); userRepository.save(user); } private String digestSHA(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); base64 = Base64.getEncoder() .encodeToString(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return "{SHA}" + base64; } }
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\ldap\data\service\UserService.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Long getProductAttributeId() { return productAttributeId; } public void setProductAttributeId(Long productAttributeId) { this.productAttributeId = productAttributeId; }
public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", productAttributeId=").append(productAttributeId); sb.append(", value=").append(value); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeValue.java
1
请完成以下Java代码
public void newRow() { stopEditor(true); final FindAdvancedSearchTableModel model = getModel(); model.newRow(); final int rowIndex = model.getRowCount() - 1; getSelectionModel().setSelectionInterval(rowIndex, rowIndex); requestFocusInWindow(); } public void deleteCurrentRow() { stopEditor(false); final int rowIndex = getSelectedRow();
if (rowIndex >= 0) { final FindAdvancedSearchTableModel model = getModel(); model.removeRow(rowIndex); // Select next row if possible final int rowToSelect = Math.min(rowIndex, model.getRowCount() - 1); if (rowToSelect >= 0) { getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect); } } requestFocusInWindow(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindAdvancedSearchTable.java
1
请在Spring Boot框架中完成以下Java代码
private String getPrefix(AnnotationAttributes annotationAttributes) { String prefix = annotationAttributes.getString("prefix").trim(); if (StringUtils.hasText(prefix) && !prefix.endsWith(".")) { prefix = prefix + "."; } return prefix; } private String[] getNames(AnnotationAttributes annotationAttributes) { String[] value = (String[]) annotationAttributes.get("value"); String[] name = (String[]) annotationAttributes.get("name"); Assert.state(value != null, "'value' must not be null"); Assert.state(name != null, "'name' must not be null"); Assert.state(value.length > 0 || name.length > 0, () -> "The name or value attribute of @%s must be specified" .formatted(ClassUtils.getShortName(this.annotationType))); Assert.state(value.length == 0 || name.length == 0, () -> "The name and value attributes of @%s are exclusive" .formatted(ClassUtils.getShortName(this.annotationType))); return (value.length > 0) ? value : name; } private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) { for (String name : this.names) { String key = this.prefix + name; if (resolver.containsProperty(key)) { if (!isMatch(resolver.getProperty(key), this.havingValue)) { nonMatching.add(name); } } else { if (!this.matchIfMissing) { missing.add(name); } } } } private boolean isMatch(@Nullable String value, String requiredValue) { if (StringUtils.hasLength(requiredValue)) {
return requiredValue.equalsIgnoreCase(value); } return !"false".equalsIgnoreCase(value); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("("); result.append(this.prefix); if (this.names.length == 1) { result.append(this.names[0]); } else { result.append("["); result.append(StringUtils.arrayToCommaDelimitedString(this.names)); result.append("]"); } if (StringUtils.hasLength(this.havingValue)) { result.append("=").append(this.havingValue); } result.append(")"); return result.toString(); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\OnPropertyCondition.java
2