instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void 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;
} @Override public void setQtyReceived (final BigDecimal QtyReceived) { set_Value (COLUMNNAME_QtyReceived, QtyReceived); } @Override public BigDecimal getQtyReceived() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getProvider() { return this.provider; } public void setProvider(@Nullable String provider) { this.provider = provider; } public @Nullable Resource getConfig() { return this.config; } public void setConfig(@Nullable Resource config) { this.config = config; } } /** * Redis-specific cache properties. */ public static class Redis { /** * Entry expiration. By default the entries never expire. */ private @Nullable Duration timeToLive; /** * Allow caching null values. */ private boolean cacheNullValues = true; /** * Key prefix. */ private @Nullable String keyPrefix; /** * Whether to use the key prefix when writing to Redis. */ private boolean useKeyPrefix = true; /** * Whether to enable cache statistics. */ private boolean enableStatistics; public @Nullable Duration getTimeToLive() { return this.timeToLive; } public void setTimeToLive(@Nullable Duration timeToLive) { this.timeToLive = timeToLive; } public boolean isCacheNullValues() { return this.cacheNullValues; }
public void setCacheNullValues(boolean cacheNullValues) { this.cacheNullValues = cacheNullValues; } public @Nullable String getKeyPrefix() { return this.keyPrefix; } public void setKeyPrefix(@Nullable String keyPrefix) { this.keyPrefix = keyPrefix; } public boolean isUseKeyPrefix() { return this.useKeyPrefix; } public void setUseKeyPrefix(boolean useKeyPrefix) { this.useKeyPrefix = useKeyPrefix; } public boolean isEnableStatistics() { return this.enableStatistics; } public void setEnableStatistics(boolean enableStatistics) { this.enableStatistics = enableStatistics; } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\CacheProperties.java
2
请完成以下Java代码
default BigDecimal getApprovalAmt(DocumentTableFields docFields) { return BigDecimal.ZERO; } // // Reporting default File createPDF(DocumentTableFields docFields) { throw new UnsupportedOperationException(); } // // Document processing /** @return the resulting document status */ default String prepareIt(DocumentTableFields docFields) { return IDocument.STATUS_InProgress; } default void approveIt(DocumentTableFields docFields) { // nothing } /** @return the resulting document status */ String completeIt(DocumentTableFields docFields); default void rejectIt(DocumentTableFields docFields) { throw new UnsupportedOperationException("The action RejectIt is not implemented by default"); }
default void voidIt(DocumentTableFields docFields) { throw new UnsupportedOperationException("The action VoidIt is not implemented by default"); } default void unCloseIt(DocumentTableFields docFields) { throw new UnsupportedOperationException("The action UnCloseIt is not implemented by default"); } default void reverseCorrectIt(DocumentTableFields docFields) { throw new UnsupportedOperationException("The action ReverseCorrectIt is not implemented by default"); } default void reverseAccrualIt(DocumentTableFields docFields) { throw new UnsupportedOperationException("The action ReverseAccrual It is not implemented by default"); } default void closeIt(DocumentTableFields docFields) { docFields.setProcessed(true); docFields.setDocAction(IDocument.ACTION_None); } default void reactivateIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException("Reactivate action is not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentHandler.java
1
请完成以下Java代码
public void setQtyDelivered (java.math.BigDecimal QtyDelivered) { set_Value (COLUMNNAME_QtyDelivered, QtyDelivered); } /** Get Gelieferte Menge. @return Delivered Quantity */ @Override public java.math.BigDecimal getQtyDelivered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered); if (bd == null) return Env.ZERO; return bd; } /** Set Berechn. Menge. @param QtyInvoiced Menge, die bereits in Rechnung gestellt wurde */ @Override public void setQtyInvoiced (java.math.BigDecimal QtyInvoiced) { set_Value (COLUMNNAME_QtyInvoiced, QtyInvoiced); } /** Get Berechn. Menge. @return Menge, die bereits in Rechnung gestellt wurde */ @Override public java.math.BigDecimal getQtyInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced); if (bd == null) return Env.ZERO; return bd; } @Override public org.compiere.model.I_M_RMALine getRef_RMALine() throws RuntimeException
{ return get_ValueAsPO(COLUMNNAME_Ref_RMALine_ID, org.compiere.model.I_M_RMALine.class); } @Override public void setRef_RMALine(org.compiere.model.I_M_RMALine Ref_RMALine) { set_ValueFromPO(COLUMNNAME_Ref_RMALine_ID, org.compiere.model.I_M_RMALine.class, Ref_RMALine); } /** Set Referenced RMA Line. @param Ref_RMALine_ID Referenced RMA Line */ @Override public void setRef_RMALine_ID (int Ref_RMALine_ID) { if (Ref_RMALine_ID < 1) set_Value (COLUMNNAME_Ref_RMALine_ID, null); else set_Value (COLUMNNAME_Ref_RMALine_ID, Integer.valueOf(Ref_RMALine_ID)); } /** Get Referenced RMA Line. @return Referenced RMA Line */ @Override public int getRef_RMALine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_RMALine_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_M_RMALine.java
1
请完成以下Java代码
private static SOTrx getSOTrx(final @NonNull CreateViewRequest request) { return Check.assumeNotNull(request.getParameterAs(VIEW_PARAM_SOTrx, SOTrx.class), "No soTrx parameter provided"); } @Nullable private DocumentFilter getEffectiveFilter(final @NonNull CreateViewRequest request) { if (request.isUseAutoFilters()) { final InvoiceAndLineId invoiceAndLineId = getInvoiceLineId(request); final I_C_Invoice invoice = invoiceBL.getById(invoiceAndLineId.getInvoiceId()); final BPartnerId bpartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final LookupValue bpartner = lookupDataSourceFactory.searchInTableLookup(I_C_BPartner.Table_Name).findById(bpartnerId); return DocumentFilter.equalsFilter(InOutCostsViewFilterHelper.FILTER_ID, InOutCostsViewFilterHelper.PARAM_C_BPartner_ID, bpartner); } else { return request.getFiltersUnwrapped(getFilterDescriptor()) .getFilterById(InOutCostsViewFilterHelper.FILTER_ID) .orElse(null); } } @SuppressWarnings("SameParameterValue") private RelatedProcessDescriptor createProcessDescriptor(final int sortNo, @NonNull final Class<?> processClass) { final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass); return RelatedProcessDescriptor.builder() .processId(processId) .anyTable().anyWindow() .displayPlace(RelatedProcessDescriptor.DisplayPlace.ViewQuickActions)
.sortNo(sortNo) .build(); } private DocumentFilterDescriptor getFilterDescriptor() { DocumentFilterDescriptor filterDescriptor = this._filterDescriptor; if (filterDescriptor == null) { final LookupDescriptorProviders lookupDescriptorProviders = lookupDataSourceFactory.getLookupDescriptorProviders(); filterDescriptor = this._filterDescriptor = InOutCostsViewFilterHelper.createFilterDescriptor(lookupDescriptorProviders); } return filterDescriptor; } @Override public InOutCostsView filterView( final @NonNull IView view, final @NonNull JSONFilterViewRequest filterViewRequest, final @NonNull Supplier<IViewsRepository> viewsRepo) { final InOutCostsView inOutCostsView = (InOutCostsView)view; return createView( CreateViewRequest.filterViewBuilder(view, filterViewRequest) .setParameter(VIEW_PARAM_SOTrx, inOutCostsView.getSoTrx()) .setParameter(VIEW_PARAM_invoiceLineId, inOutCostsView.getInvoiceLineId()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsViewFactory.java
1
请完成以下Java代码
public class ProcessImpl extends CmmnElementImpl implements Process { protected static Attribute<String> nameAttribute; protected static Attribute<String> implementationTypeAttribute; protected static ChildElementCollection<InputProcessParameter> inputCollection; protected static ChildElementCollection<OutputProcessParameter> outputCollection; public ProcessImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getImplementationType() { return implementationTypeAttribute.getValue(this); } public void setImplementationType(String implementationType) { implementationTypeAttribute.setValue(this, implementationType); } public Collection<InputProcessParameter> getInputs() { return inputCollection.get(this); } public Collection<OutputProcessParameter> getOutputs() { return outputCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Process.class, CMMN_ELEMENT_PROCESS) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Process>() { public Process newInstance(ModelTypeInstanceContext instanceContext) { return new ProcessImpl(instanceContext); }
}); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE) .defaultValue("http://www.omg.org/spec/CMMN/ProcessType/Unspecified") .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputCollection = sequenceBuilder.elementCollection(InputProcessParameter.class) .build(); outputCollection = sequenceBuilder.elementCollection(OutputProcessParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ReportServiceMain { @Autowired private ApplicationContext applicationContext; /** * By default, we run in headless mode. But using this system property, we can also run with headless=false. * The only known use of that is that metasfresh can open the initial license & connection dialog to store the initial properties file. */ static final String SYSTEM_PROPERTY_HEADLESS = "app-server-run-headless"; public static void main(final String[] args) { try (final IAutoCloseable c = ModelValidationEngine.postponeInit()) { Ini.setRunMode(RunMode.BACKEND); Adempiere.instance.startup(RunMode.BACKEND); final String headless = System.getProperty(SYSTEM_PROPERTY_HEADLESS, Boolean.toString(true)); new SpringApplicationBuilder(ReportServiceMain.class) .headless(StringUtils.toBoolean(headless)) // we need headless=false for initial connection setup popup (if any), usually this only applies on dev workstations. .web(WebApplicationType.SERVLET) .profiles(Profiles.PROFILE_ReportService, Profiles.PROFILE_ReportService_Standalone) .beanNameGenerator(new MetasfreshBeanNameGenerator()) .run(args); } // now init the model validation engine ModelValidationEngine.get(); }
@Bean @Primary public ObjectMapper jsonObjectMapper() { return JsonObjectMapperHolder.sharedJsonObjectMapper(); } @Profile(Profiles.PROFILE_NotTest) @Bean(Adempiere.BEAN_NAME) public Adempiere adempiere() { // as of right now, we are not interested in loading *any* model validator whatsoever within this service // therefore we don't e.g. have to deal with the async-processor. It just won't be started. ModelValidationEngine.setInitEntityTypes(Collections.emptyList()); final Adempiere adempiere = Env.getSingleAdempiereInstance(applicationContext); adempiere.startup(RunMode.BACKEND); return adempiere; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service-standalone\src\main\java\de\metas\report\ReportServiceMain.java
2
请在Spring Boot框架中完成以下Java代码
public class Quantity implements Comparable<Quantity> { @JsonCreator public static Quantity of(final int value) { if (value == 0) { return ZERO; } return new Quantity(value); } public static Quantity of(@NonNull final BigDecimal qty) { return of(qty.intValueExact()); } public static final Quantity ZERO = new Quantity(0); private static final int MAX_VALUE = 99999; private final int valueAsInt; private Quantity(final int value) { if (value < 0) { throw new IllegalArgumentException("Quantity shall be greater than " + value); } if (value > MAX_VALUE) { throw new IllegalArgumentException("The MSV3 standard allows a maximum quantity of " + value); } valueAsInt = value; } public Quantity min(final Quantity otherQty)
{ return valueAsInt <= otherQty.valueAsInt ? this : otherQty; } public Quantity min(final int otherQty) { return valueAsInt <= otherQty ? this : Quantity.of(otherQty); } public BigDecimal getValueAsBigDecimal() { return BigDecimal.valueOf(valueAsInt); } @JsonValue public int toJson() { return valueAsInt; } public boolean isZero() { return valueAsInt == 0; } @Override public int compareTo(@NonNull final Quantity other) { return this.valueAsInt - other.valueAsInt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\types\Quantity.java
2
请完成以下Java代码
public abstract class S_ExternalReference_SyncTo_ExternalSystem extends JavaProcess implements IProcessPrecondition, IProcessDefaultParametersProvider { private final ExternalSystemConfigRepo externalSystemConfigRepo = SpringContextHolder.instance.getBean(ExternalSystemConfigRepo.class); @Nullable @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (getExternalSystemParam().equals(parameter.getColumnName())) { final ImmutableList<ExternalSystemParentConfig> activeConfigs = externalSystemConfigRepo.getActiveByType(getExternalSystemType()) .stream() .collect(ImmutableList.toImmutableList()); return activeConfigs.size() == 1 ? activeConfigs.get(0).getChildConfig().getId().getRepoId() : IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId(); addLog("Calling with params: externalSystemChildConfigId: {}", externalSystemChildConfigId);
final Iterator<I_S_ExternalReference> externalRefIterator = getSelectedExternalReferenceRecords(); while (externalRefIterator.hasNext()) { final TableRecordReference externalReferenceRecordRef = TableRecordReference.of(externalRefIterator.next()); getExportExternalReferenceToExternalSystem().exportToExternalSystem(externalSystemChildConfigId, externalReferenceRecordRef, getPinstanceId()); } return JavaProcess.MSG_OK; } @NonNull private Iterator<I_S_ExternalReference> getSelectedExternalReferenceRecords() { final IQueryBuilder<I_S_ExternalReference> externalReferenceQuery = retrieveSelectedRecordsQueryBuilder(I_S_ExternalReference.class); return externalReferenceQuery .create() .iterate(I_S_ExternalReference.class); } protected abstract ExternalSystemType getExternalSystemType(); protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId(); protected abstract String getExternalSystemParam(); protected abstract ExportToExternalSystemService getExportExternalReferenceToExternalSystem(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\externalreference\S_ExternalReference_SyncTo_ExternalSystem.java
1
请完成以下Java代码
public Criteria andCommentOvertimeNotIn(List<Integer> values) { addCriterion("comment_overtime not in", values, "commentOvertime"); return (Criteria) this; } public Criteria andCommentOvertimeBetween(Integer value1, Integer value2) { addCriterion("comment_overtime between", value1, value2, "commentOvertime"); return (Criteria) this; } public Criteria andCommentOvertimeNotBetween(Integer value1, Integer value2) { addCriterion("comment_overtime not between", value1, value2, "commentOvertime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() {
return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderSettingExample.java
1
请完成以下Java代码
public String getProcessMsg() { return null; } @Override public int getDoc_User_ID() { return getCreatedBy(); } @Override public int getC_Currency_ID() { return 0; // N/A } @Override public BigDecimal getApprovalAmt() { return BigDecimal.ZERO; // N/A } @Override public File createPDF() { throw new UnsupportedOperationException(); // N/A
} @Override public String getDocumentInfo() { final I_C_DocType dt = MDocType.get(getCtx(), getC_DocType_ID()); return dt.getName() + " " + getDocumentNo(); } private PPOrderRouting getOrderRouting() { final IPPOrderRoutingRepository orderRoutingsRepo = Services.get(IPPOrderRoutingRepository.class); final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return orderRoutingsRepo.getByOrderId(orderId); } private PPOrderRoutingActivityId getActivityId() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return PPOrderRoutingActivityId.ofRepoId(orderId, getPP_Order_Node_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPCostCollector.java
1
请在Spring Boot框架中完成以下Java代码
public class ContactPerson implements DataRecord { public static ContactPerson newForUserPlatformAndLocation( @NonNull final User user, @NonNull final PlatformId platformId, @Nullable final BPartnerLocationId bpLocationId) { final EmailAddress emailaddress = StringUtils.trimBlankToOptional(user.getEmailAddress()) .map(EmailAddress::ofString) .orElse(null); return ContactPerson.builder() .platformId(platformId) .name(user.getName()) .userId(user.getId()) .bPartnerId(user.getBpartnerId()) .bpLocationId(bpLocationId) .address(emailaddress) .language(user.getLanguage()) .build(); } public static Optional<ContactPerson> cast(@Nullable final DataRecord dataRecord) { return dataRecord instanceof ContactPerson ? Optional.of((ContactPerson)dataRecord) : Optional.empty(); } String name; @Nullable UserId userId; @Nullable BPartnerId bPartnerId; @Nullable ContactAddress address; /** * might be null if the contact person was not stored yet */ @Nullable ContactPersonId contactPersonId; /** * the remote system's ID which we can use to sync with the campaign on the remote marketing tool */ String remoteId; @NonNull PlatformId platformId;
@Nullable BPartnerLocationId bpLocationId; /** * If a {@link #bPartnerId} is not-null, then this is always the locationId of the respective {@link #bpLocationId}. * In that case, if the respective {@link #bpLocationId} is {@code null}, then this is also {@code null}. */ @Nullable LocationId locationId; @Nullable BoilerPlateId boilerPlateId; @Nullable Language language; public String getEmailAddressStringOrNull() { return EmailAddress.getEmailAddressStringOrNull(getAddress()); } public boolean hasEmailAddress() { return getEmailAddressStringOrNull() != null; } public DeactivatedOnRemotePlatform getDeactivatedOnRemotePlatform() { return EmailAddress.getDeactivatedOnRemotePlatform(getAddress()); } public ContactPerson withContactPersonId(@NonNull final ContactPersonId contactPersonId) { return !ContactPersonId.equals(this.contactPersonId, contactPersonId) ? toBuilder().contactPersonId(contactPersonId).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\ContactPerson.java
2
请完成以下Java代码
public void deleteHistoricPlanItemInstancesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesForNonExistingCaseInstances", null, getManagedEntityClass()); } @Override @SuppressWarnings("unchecked") public List<HistoricPlanItemInstance> findWithVariablesByCriteria(HistoricPlanItemInstanceQueryImpl historicPlanItemInstanceQuery) { setSafeInValueLists(historicPlanItemInstanceQuery); return getDbSqlSession().selectList("selectHistoricPlanItemInstancesWithLocalVariablesByQueryCriteria", historicPlanItemInstanceQuery, getManagedEntityClass()); } @Override public Class<? extends HistoricPlanItemInstanceEntity> getManagedEntityClass() { return HistoricPlanItemInstanceEntityImpl.class; } @Override public HistoricPlanItemInstanceEntity create() { return new HistoricPlanItemInstanceEntityImpl();
} @Override public HistoricPlanItemInstanceEntity create(PlanItemInstance planItemInstance) { return new HistoricPlanItemInstanceEntityImpl(planItemInstance); } protected void setSafeInValueLists(HistoricPlanItemInstanceQueryImpl planItemInstanceQuery) { if (planItemInstanceQuery.getInvolvedGroups() != null) { planItemInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(planItemInstanceQuery.getInvolvedGroups())); } if(planItemInstanceQuery.getCaseInstanceIds() != null) { planItemInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(planItemInstanceQuery.getCaseInstanceIds())); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisHistoricPlanItemInstanceDataManager.java
1
请完成以下Java代码
public Mono<MapSession> findById(String id) { // @formatter:off return Mono.defer(() -> Mono.justOrEmpty(this.sessions.get(id)) .filter((session) -> !session.isExpired()) .map(MapSession::new) .doOnNext((session) -> session.setSessionIdGenerator(this.sessionIdGenerator)) .switchIfEmpty(deleteById(id).then(Mono.empty()))); // @formatter:on } @Override public Mono<Void> deleteById(String id) { return Mono.fromRunnable(() -> this.sessions.remove(id)); } @Override public Mono<MapSession> createSession() { // @formatter:off return Mono.fromSupplier(() -> this.sessionIdGenerator.generate()) .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) .map((sessionId) -> { MapSession result = new MapSession(sessionId); result.setMaxInactiveInterval(this.defaultMaxInactiveInterval); result.setSessionIdGenerator(this.sessionIdGenerator); return result;
}); // @formatter:on } /** * Sets the {@link SessionIdGenerator} to use. * @param sessionIdGenerator the non-null {@link SessionIdGenerator} to use * @since 3.2 */ public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { Assert.notNull(sessionIdGenerator, "sessionIdGenerator cannot be null"); this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\ReactiveMapSessionRepository.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("columnName", columnName) .toString(); } @Override public int hashCode() { return Objects.hash(columnName); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false;
} if (getClass() != obj.getClass()) { return false; } final CalloutMethodPointcutKey other = (CalloutMethodPointcutKey)obj; return columnName.equals(other.columnName); } public String getColumnName() { return columnName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\CalloutMethodPointcutKey.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Image getAD_Image() { return get_ValueAsPO(COLUMNNAME_AD_Image_ID, org.compiere.model.I_AD_Image.class); } @Override public void setAD_Image(final org.compiere.model.I_AD_Image AD_Image) { set_ValueFromPO(COLUMNNAME_AD_Image_ID, org.compiere.model.I_AD_Image.class, AD_Image); } @Override public void setAD_Image_ID (final int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, AD_Image_ID); } @Override public int getAD_Image_ID() { return get_ValueAsInt(COLUMNNAME_AD_Image_ID); } @Override public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID) { if (M_HazardSymbol_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID); } @Override public int getM_HazardSymbol_ID() { return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_ID); }
@Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_HazardSymbol.java
1
请在Spring Boot框架中完成以下Java代码
public class AttributeValueId implements RepoIdAware { int repoId; @JsonCreator public static AttributeValueId ofRepoId(final int repoId) { return new AttributeValueId(repoId); } public static AttributeValueId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(final AttributeValueId attributeValueId) { return attributeValueId != null ? attributeValueId.getRepoId() : -1;
} private AttributeValueId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_AttributeValue_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(final AttributeValueId id1, final AttributeValueId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeValueId.java
2
请完成以下Java代码
public class BOMCostElementPrice { public static BOMCostElementPrice zero( @NonNull final CostElementId costElementId, @NonNull final CurrencyId currencyId, @NonNull final UomId uomId) { return builder() .costElementId(costElementId) .costPrice(CostPrice.zero(currencyId, uomId)) .build(); } private RepoIdAware id; @NonNull private final CostElementId costElementId; @NonNull private CostPrice costPrice; @Nullable public <ID extends RepoIdAware> ID getId(@NonNull final Class<ID> idType) { final RepoIdAware id = getId(); return id != null ? idType.cast(id) : null; } public UomId getUomId() { return getCostPrice().getUomId(); } @NonNull public static UomId extractUniqueUomId(@NonNull final Collection<BOMCostElementPrice> list) {
return CollectionUtils.extractSingleElement(list, BOMCostElementPrice::getUomId); } public void clearOwnCostPrice() { setCostPrice(getCostPrice().withZeroOwnCostPrice()); } public void clearComponentsCostPrice() { setCostPrice(getCostPrice().withZeroComponentsCostPrice()); } public void setComponentsCostPrice(CostAmount componentsCostPrice) { setCostPrice(getCostPrice().withComponentsCostPrice(componentsCostPrice)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMCostElementPrice.java
1
请在Spring Boot框架中完成以下Java代码
public boolean verify(String hostname, SSLSession session) { return(true); } // verify } // FakeHostnameVerifier /** * This class allow any X509 certificates to be used to authenticate the * remote side of a secure socket, including self-signed certificates. * * @author Francis Labrie */ public static class FakeX509TrustManager implements X509TrustManager { /** * Empty array of certificate authority certificates. */ private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; /** * Always trust for client SSL chain peer certificate * chain with any authType authentication types. * * @param chain the peer certificate chain. * @param authType the authentication type based on the client * certificate. */ public void checkClientTrusted(X509Certificate[] chain, String authType) { } // checkClientTrusted /** * Always trust for server SSL chain peer certificate * chain with any authType exchange algorithm types. *
* @param chain the peer certificate chain. * @param authType the key exchange algorithm used. */ public void checkServerTrusted(X509Certificate[] chain, String authType) { } // checkServerTrusted /** * Return an empty array of certificate authority certificates which * are trusted for authenticating peers. * * @return a empty array of issuer certificates. */ public X509Certificate[] getAcceptedIssuers() { return(_AcceptedIssuers); } // getAcceptedIssuers } // FakeX509TrustManager } // SSLUtilities
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\taxiMaster\SSLUtilities.java
2
请在Spring Boot框架中完成以下Java代码
public class FlowableInboundGateway extends MessagingGatewaySupport { private String executionId = "executionId"; private String processInstanceId = "processInstanceId"; private String processDefinitionId = "processDefinitionId"; private final ProcessVariableHeaderMapper headerMapper; private ProcessEngine processEngine; private Set<String> sync = new ConcurrentSkipListSet<>(); public FlowableInboundGateway(ProcessEngine processEngine, String... pvsOrHeadersToPreserve) { Collections.addAll(this.sync, pvsOrHeadersToPreserve); this.processEngine = processEngine; this.headerMapper = new ProcessVariableHeaderMapper(sync); this.initializeDefaultPreservedHeaders(); } protected void initializeDefaultPreservedHeaders() { this.sync.add(executionId); this.sync.add(processDefinitionId); this.sync.add(processInstanceId); } public void execute(IntegrationActivityBehavior receiveTaskActivityBehavior, DelegateExecution execution) { Map<String, Object> stringObjectMap = new HashMap<>();
stringObjectMap.put(executionId, execution.getId()); stringObjectMap.put(processInstanceId, execution.getProcessInstanceId()); stringObjectMap.put(processDefinitionId, execution.getProcessDefinitionId()); stringObjectMap.putAll(headerMapper.toHeaders(execution.getVariables())); MessageBuilder<?> mb = MessageBuilder.withPayload(execution).copyHeaders(stringObjectMap); Message<?> reply = sendAndReceiveMessage(mb.build()); if (null != reply) { Map<String, Object> vars = new HashMap<>(); headerMapper.fromHeaders(reply.getHeaders(), vars); for (String k : vars.keySet()) { processEngine.getRuntimeService().setVariable(execution.getId(), k, vars.get(k)); } receiveTaskActivityBehavior.leave(execution); } } public void signal(IntegrationActivityBehavior receiveTaskActivityBehavior, DelegateExecution execution, String signalName, Object data) { receiveTaskActivityBehavior.leave(execution); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\integration\FlowableInboundGateway.java
2
请完成以下Java代码
public static <T extends Comparable> ComparableComparator<T> getInstance() { return getInstance(NULLSFIRST_DEFAULT); } public static <T extends Comparable> ComparableComparator<T> getInstance(final boolean nullsFirst) { @SuppressWarnings("unchecked") final ComparableComparator<T> cmp = (ComparableComparator<T>)(nullsFirst ? instanceNullsFirst : instanceNullsLast); return cmp; } public static <T extends Comparable> ComparableComparator<T> getInstance(Class<T> clazz) { return getInstance(NULLSFIRST_DEFAULT); } public static <T extends Comparable> ComparableComparator<T> getInstance(final Class<T> clazz, final boolean nullsFirst) { return getInstance(nullsFirst); } private final boolean nullsFirst; public ComparableComparator() { this(NULLSFIRST_DEFAULT); } public ComparableComparator(final boolean nullsFirst) { this.nullsFirst = nullsFirst; } @Override public int compare(T o1, T o2) {
if (o1 == o2) { return 0; } if (o1 == null) { return nullsFirst ? -1 : +1; } if (o2 == null) { return nullsFirst ? +1 : -1; } @SuppressWarnings("unchecked") final int cmp = o1.compareTo(o2); return cmp; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\ComparableComparator.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentReadonly { public static final DocumentReadonly NOT_READONLY = builder() .parentActive(true).active(true) .processed(false) .processing(false) .build(); public static DocumentReadonly ofParent(final DocumentReadonly parentDocumentReadonly) { return builder() .parentActive(parentDocumentReadonly.active) .active(parentDocumentReadonly.active) .processed(parentDocumentReadonly.processed) .processing(parentDocumentReadonly.processing) .parentEnforcingReadOnly(parentDocumentReadonly.computeForceReadOnlyChildDocuments()) .fieldsReadonly(null) // unknown (will fallback to not-readonly) .build(); } boolean parentActive; boolean active; boolean processed; boolean processing; boolean parentEnforcingReadOnly; ExtendedMemorizingSupplier<ReadOnlyInfo> fieldsReadonly; @NonFinal public BooleanWithReason computeFieldReadonly(final String fieldName, final boolean alwaysUpdateable) { // Case: parent document is not active => fields of this document shall be completely readonly (including the IsActive flag) if (!parentActive) { return BooleanWithReason.TRUE; // readonly } if (parentEnforcingReadOnly) { return BooleanWithReason.TRUE; // readonly } // Case: this or parent document is processed => fields of this document shall be completely readonly if they were not flagged with AlwaysUpdateable if (processed || processing)
{ return alwaysUpdateable ? BooleanWithReason.FALSE : BooleanWithReason.TRUE; // readonly if not always updateable } // Case: this document is not active => fields of this document shall be completely readonly, BUT NOT the IsActive flag. // We shall alow user to edit it if (!active) { if (WindowConstants.FIELDNAME_IsActive.equals(fieldName)) { return BooleanWithReason.FALSE; // not readonly } else { return BooleanWithReason.TRUE; // readonly } } // If we reached this point, it means the document and parent document are active and not processed // => readonly if fields are readonly. final ReadOnlyInfo isReadOnly = fieldsReadonly != null ? fieldsReadonly.get() : null; return Optional.ofNullable(isReadOnly) .map(ReadOnlyInfo::getIsReadOnlyWithReason) .filter(BooleanWithReason::isTrue) .orElse(BooleanWithReason.FALSE); } public boolean computeForceReadOnlyChildDocuments() { if (parentEnforcingReadOnly) { return true; } return Optional.ofNullable(fieldsReadonly) .map(ExtendedMemorizingSupplier::get) .map(ReadOnlyInfo::isForceReadOnlySubDocuments) .orElse(false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentReadonly.java
2
请完成以下Java代码
public class User { private String firstname; private String lastname; private String emailId; public String getFirstname() { return firstname; } public void setFirstname(final String firstname) { this.firstname = firstname; } public String getLastname() { return lastname;
} public void setLastname(final String lastname) { this.lastname = lastname; } public String getEmailId() { return emailId; } public void setEmailId(final String emailId) { this.emailId = emailId; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\model\User.java
1
请完成以下Java代码
private final class Resolve implements Runnable { private final Listener2 savedListener; /** * Creates a new Resolve that stores a snapshot of the relevant states of the resolver. * * @param listener The listener to send the results to. */ Resolve(final Listener2 listener) { this.savedListener = requireNonNull(listener, "listener"); } @Override public void run() { try {
this.savedListener.onResult(ResolutionResult.newBuilder() .setAddresses(ImmutableList.of( new EquivalentAddressGroup(getOwnAddress()))) .build()); } catch (final Exception e) { this.savedListener.onError(Status.UNAVAILABLE .withDescription("Failed to resolve own address").withCause(e)); } finally { SelfNameResolver.this.syncContext.execute(() -> SelfNameResolver.this.resolving = false); } } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\nameresolver\SelfNameResolver.java
1
请完成以下Java代码
public void setC_Currency(org.compiere.model.I_C_Currency C_Currency) { set_ValueFromPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class, C_Currency); } /** Set Währung. @param C_Currency_ID Die Währung für diesen Eintrag */ @Override public void setC_Currency_ID (int C_Currency_ID) { throw new IllegalArgumentException ("C_Currency_ID is virtual column"); } /** Get Währung. @return Die Währung für diesen Eintrag */ @Override public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum von. @param DateFrom Startdatum eines Abschnittes */ @Override public void setDateFrom (java.sql.Timestamp DateFrom) { set_Value (COLUMNNAME_DateFrom, DateFrom); } /** Get Datum von. @return Startdatum eines Abschnittes */ @Override public java.sql.Timestamp getDateFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateFrom);
} /** Set Freigegeben. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Freigegeben. @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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_CreditLimit.java
1
请完成以下Java代码
public class SuppressedExceptionsDemo { public static void demoSuppressedException(String filePath) throws IOException { FileInputStream fileIn = null; try { fileIn = new FileInputStream(filePath); } catch (FileNotFoundException e) { throw new IOException(e); } finally { fileIn.close(); } } public static void demoAddSuppressedException(String filePath) throws IOException { Throwable firstException = null; FileInputStream fileIn = null; try { fileIn = new FileInputStream(filePath); } catch (IOException e) { firstException = e;
} finally { try { fileIn.close(); } catch (NullPointerException npe) { if (firstException != null) { npe.addSuppressed(firstException); } throw npe; } } } public static void demoExceptionalResource() throws Exception { try (ExceptionalResource exceptionalResource = new ExceptionalResource()) { exceptionalResource.processSomething(); } } }
repos\tutorials-master\core-java-modules\core-java-exceptions-2\src\main\java\com\baeldung\suppressed\SuppressedExceptionsDemo.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchRestServiceImpl extends AbstractRestProcessEngineAware implements BatchRestService { public BatchRestServiceImpl(String engineName, ObjectMapper objectMapper) { super(engineName, objectMapper); } @Override public BatchResource getBatch(String batchId) { return new BatchResourceImpl(getProcessEngine(), batchId); } @Override public List<BatchDto> getBatches(UriInfo uriInfo, Integer firstResult, Integer maxResults) { BatchQueryDto queryDto = new BatchQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); BatchQuery query = queryDto.toQuery(getProcessEngine()); List<Batch> matchingBatches = QueryUtil.list(query, firstResult, maxResults); List<BatchDto> batchResults = new ArrayList<BatchDto>(); for (Batch matchingBatch : matchingBatches) { batchResults.add(BatchDto.fromBatch(matchingBatch)); } return batchResults; } @Override public CountResultDto getBatchesCount(UriInfo uriInfo) { ProcessEngine processEngine = getProcessEngine(); BatchQueryDto queryDto = new BatchQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); BatchQuery query = queryDto.toQuery(processEngine); long count = query.count(); return new CountResultDto(count); }
@Override public List<BatchStatisticsDto> getStatistics(UriInfo uriInfo, Integer firstResult, Integer maxResults) { BatchStatisticsQueryDto queryDto = new BatchStatisticsQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); BatchStatisticsQuery query = queryDto.toQuery(getProcessEngine()); List<BatchStatistics> batchStatisticsList = QueryUtil.list(query, firstResult, maxResults); List<BatchStatisticsDto> statisticsResults = new ArrayList<BatchStatisticsDto>(); for (BatchStatistics batchStatistics : batchStatisticsList) { statisticsResults.add(BatchStatisticsDto.fromBatchStatistics(batchStatistics)); } return statisticsResults; } @Override public CountResultDto getStatisticsCount(UriInfo uriInfo) { BatchStatisticsQueryDto queryDto = new BatchStatisticsQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); BatchStatisticsQuery query = queryDto.toQuery(getProcessEngine()); long count = query.count(); return new CountResultDto(count); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\BatchRestServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setField2(String field2) { this.field2 = field2; } public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } public String getField4() { return field4; } public void setField4(String field4) { this.field4 = field4; }
public String getField5() { return field5; } public void setField5(String field5) { this.field5 = field5; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\F2FPayResultVo.java
2
请完成以下Java代码
public String getReferenceNumber() { return referenceNumber; } /** * Sets the value of the referenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setReferenceNumber(String value) { this.referenceNumber = value; } /** * Gets the value of the codingLine property. * * @return * possible object is * {@link String } * */ public String getCodingLine() {
return codingLine; } /** * Sets the value of the codingLine property. * * @param value * allowed object is * {@link String } * */ public void setCodingLine(String value) { this.codingLine = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\Esr5Type.java
1
请完成以下Java代码
final class DocumentToInvalidateMap { private final HashMap<TableRecordReference, DocumentToInvalidate> documents = new HashMap<>(); public DocumentToInvalidate getDocumentToInvalidate(final TableRecordReference rootDocumentRef) { return documents.computeIfAbsent(rootDocumentRef, DocumentToInvalidate::new); } public boolean isEmpty() { return documents.isEmpty(); } public int size() { return documents.size(); } public TableRecordReferenceSet getRootRecords() { return TableRecordReferenceSet.of(documents.keySet()); } public Collection<DocumentToInvalidate> toCollection() { return documents.values(); } DocumentToInvalidateMap combine(@NonNull final DocumentToInvalidateMap other) { if (isEmpty()) { return other;
} else if (other.isEmpty()) { return other; } else { for (final Map.Entry<TableRecordReference, DocumentToInvalidate> e : other.documents.entrySet()) { this.documents.merge( e.getKey(), e.getValue(), (item1, item2) -> item1.combine(item2)); } return this; } } public static DocumentToInvalidateMap combine(@NonNull final List<DocumentToInvalidateMap> list) { if (list.isEmpty()) { return new DocumentToInvalidateMap(); } else if (list.size() == 1) { return list.get(0); } else { return list.stream().reduce(DocumentToInvalidateMap::combine).get(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentToInvalidateMap.java
1
请完成以下Java代码
public String toString() { return outputValues.toString(); } @Override public boolean containsValue(Object value) { return values().contains(value); } @Override public Object get(Object key) { TypedValue typedValue = outputValues.get(key); if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void clear() { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Set<Entry<String, Object>> entrySet() { Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) { DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue()); entrySet.add(entry); } return entrySet; } protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> {
protected final String key; protected final TypedValue typedValue; public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) { this.key = key; this.typedValue = typedValue; } @Override public String getKey() { return key; } @Override public Object getValue() { if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object setValue(Object value) { throw new UnsupportedOperationException("decision output entry is immutable"); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java
1
请完成以下Java代码
public class Person { private long personNum; @PrimaryKey private String firstName; private String lastName; private List phoneNumbers = new ArrayList(); public Person(long personNum, String firstName, String lastName) { super(); this.personNum = personNum; this.firstName = firstName; this.lastName = lastName; } public long getPersonNum() { return personNum; } public void setPersonNum(long personNum) { this.personNum = personNum; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() {
return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(List phoneNumbers) { this.phoneNumbers = phoneNumbers; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\xml\Person.java
1
请完成以下Java代码
public int getWaitTime() { return get_ValueAsInt(COLUMNNAME_WaitTime); } @Override public void setWorkflow_ID (final int Workflow_ID) { if (Workflow_ID < 1) set_Value (COLUMNNAME_Workflow_ID, null); else set_Value (COLUMNNAME_Workflow_ID, Workflow_ID); } @Override public int getWorkflow_ID() { return get_ValueAsInt(COLUMNNAME_Workflow_ID); } @Override public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() { return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setXPosition (final int XPosition) { set_Value (COLUMNNAME_XPosition, XPosition); } @Override public int getXPosition()
{ return get_ValueAsInt(COLUMNNAME_XPosition); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } @Override public void setYPosition (final int YPosition) { set_Value (COLUMNNAME_YPosition, YPosition); } @Override public int getYPosition() { return get_ValueAsInt(COLUMNNAME_YPosition); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java
1
请完成以下Java代码
private void setMasterEnddDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract) { if (importRecord.getMasterEndDate() != null) { contract.setMasterEndDate(importRecord.getMasterEndDate()); } } private boolean isEndedContract(@NonNull final I_I_Flatrate_Term importRecord) { final Timestamp contractEndDate = importRecord.getEndDate(); final Timestamp today = SystemTime.asDayTimestamp(); return contractEndDate != null && today.after(contractEndDate); } private void endContractIfNeeded(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract) { if (isEndedContract(importRecord)) { contract.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_Quit); contract.setNoticeDate(contract.getEndDate()); contract.setIsAutoRenew(false); contract.setProcessed(true); contract.setDocAction(X_C_Flatrate_Term.DOCACTION_None);
contract.setDocStatus(X_C_Flatrate_Term.DOCSTATUS_Completed); } } private void setTaxCategoryAndIsTaxIncluded(@NonNull final I_C_Flatrate_Term newTerm) { final IPricingResult pricingResult = calculateFlatrateTermPrice(newTerm); newTerm.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingResult.getTaxCategoryId())); newTerm.setIsTaxIncluded(pricingResult.isTaxIncluded()); } private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm) { return FlatrateTermPricing.builder() .termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID())) .qty(newTerm.getPlannedQtyPerUnit()) .term(newTerm) .priceDate(TimeUtil.asLocalDate(newTerm.getStartDate())) .build() .computeOrThrowEx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImporter.java
1
请在Spring Boot框架中完成以下Java代码
public static class Bundles { /** * PEM-encoded SSL trust material. */ private final Map<String, PemSslBundleProperties> pem = new LinkedHashMap<>(); /** * Java keystore SSL trust material. */ private final Map<String, JksSslBundleProperties> jks = new LinkedHashMap<>(); /** * Trust material watching. */ private final Watch watch = new Watch(); public Map<String, PemSslBundleProperties> getPem() { return this.pem; } public Map<String, JksSslBundleProperties> getJks() { return this.jks; } public Watch getWatch() { return this.watch; } public static class Watch { /** * File watching. */ private final File file = new File(); public File getFile() { return this.file; }
public static class File { /** * Quiet period, after which changes are detected. */ private Duration quietPeriod = Duration.ofSeconds(10); public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslProperties.java
2
请完成以下Java代码
public TableRecordReference getChildRecordOrNull() { if (childTableName != null && childRecordId >= 0) { return TableRecordReference.of(childTableName, childRecordId); } else { return null; } } public TableRecordReference getRecordEffective() { if (childTableName != null && childRecordId >= 0) { return TableRecordReference.of(childTableName, childRecordId); } else if (rootTableName != null && rootRecordId >= 0) { return TableRecordReference.of(rootTableName, rootRecordId); } else { throw new AdempiereException("Cannot extract effective record from " + this); } } public String getTableNameEffective() { return childTableName != null ? childTableName : rootTableName; } public static final class Builder { private String rootTableName; private int rootRecordId = -1; private String childTableName; private int childRecordId = -1;
private Builder() { } public CacheInvalidateRequest build() { final String debugFrom = DEBUG ? Trace.toOneLineStackTraceString() : null; return new CacheInvalidateRequest(rootTableName, rootRecordId, childTableName, childRecordId, debugFrom); } public Builder rootRecord(@NonNull final String tableName, final int recordId) { Check.assume(recordId >= 0, "recordId >= 0"); rootTableName = tableName; rootRecordId = recordId; return this; } public Builder childRecord(@NonNull final String tableName, final int recordId) { Check.assume(recordId >= 0, "recordId >= 0"); childTableName = tableName; childRecordId = recordId; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\CacheInvalidateRequest.java
1
请完成以下Java代码
public int getC_Activity_ID() { return activityID; } @Override public void setC_Activity_ID(final int activityID) { this.activityID = activityID; } @Override public Tax getC_Tax() { return tax; } @Override public void setC_Tax(final Tax tax) { this.tax = tax; } @Override public boolean isPrinted() { return printed; } @Override public void setPrinted(final boolean printed) { this.printed = printed; } @Override public int getLineNo() { return lineNo; }
@Override public void setLineNo(final int lineNo) { this.lineNo = lineNo; } @Override public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes); } @Override public List<IInvoiceLineAttribute> getInvoiceLineAttributes() { return invoiceLineAttributes; } @Override public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate() { return iciolsToUpdate; } @Override public int getC_PaymentTerm_ID() { return C_PaymentTerm_ID; } @Override public void setC_PaymentTerm_ID(final int paymentTermId) { C_PaymentTerm_ID = paymentTermId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java
1
请完成以下Java代码
public void setCorrelationKeys(Map<String, VariableValueDto> correlationKeys) { this.correlationKeys = correlationKeys; } public Map<String, VariableValueDto> getLocalCorrelationKeys() { return localCorrelationKeys; } public void setLocalCorrelationKeys(Map<String, VariableValueDto> localCorrelationKeys) { this.localCorrelationKeys = localCorrelationKeys; } public Map<String, VariableValueDto> getProcessVariables() { return processVariables; } public void setProcessVariables(Map<String, VariableValueDto> processVariables) { this.processVariables = processVariables; } public Map<String, VariableValueDto> getProcessVariablesLocal() { return processVariablesLocal; } public void setProcessVariablesLocal(Map<String, VariableValueDto> processVariablesLocal) { this.processVariablesLocal = processVariablesLocal; } public Map<String, VariableValueDto> getProcessVariablesToTriggeredScope() { return processVariablesToTriggeredScope; } public void setProcessVariablesToTriggeredScope(Map<String, VariableValueDto> processVariablesToTriggeredScope) { this.processVariablesToTriggeredScope = processVariablesToTriggeredScope; } public boolean isAll() { return all; } public void setAll(boolean all) { this.all = all; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isWithoutTenantId() {
return withoutTenantId; } public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public boolean isResultEnabled() { return resultEnabled; } public void setResultEnabled(boolean resultEnabled) { this.resultEnabled = resultEnabled; } public boolean isVariablesInResultEnabled() { return variablesInResultEnabled; } public void setVariablesInResultEnabled(boolean variablesInResultEnabled) { this.variablesInResultEnabled = variablesInResultEnabled; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\message\CorrelationMessageDto.java
1
请在Spring Boot框架中完成以下Java代码
public int getMaxWait() { return maxWait; } public void setMaxWait(int maxWait) { this.maxWait = maxWait; } public int getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public long getMaxEvictableIdleTimeMillis() { return maxEvictableIdleTimeMillis; } public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) { this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; }
public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public boolean isPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } public String getConnectionProperties() { return connectionProperties; } public void setConnectionProperties(String connectionProperties) { this.connectionProperties = connectionProperties; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidConfig.java
2
请完成以下Java代码
public BigDecimal getValue() { return value; } @Override public void setValue(@Nullable final BigDecimal value) { this.value = value != null ? value : BigDecimal.ZERO; } @Override public byte byteValue() { return value.byteValue(); } @Override public double doubleValue() { return value.doubleValue(); } @Override public float floatValue() { return value.floatValue(); } @Override public int intValue() { return value.intValue(); } @Override public long longValue() { return value.longValue(); } @Override public short shortValue() { return value.shortValue(); } public void add(final BigDecimal augend) { value = value.add(augend); } public void subtract(final BigDecimal subtrahend) { value = value.subtract(subtrahend); }
public void multiply(final BigDecimal multiplicand) { value = value.multiply(multiplicand); } public void divide(final BigDecimal divisor, final int scale, final RoundingMode roundingMode) { value = value.divide(divisor, scale, roundingMode); } public boolean comparesEqualTo(final BigDecimal val) { return value.compareTo(val) == 0; } public int signum() { return value.signum(); } public MutableBigDecimal min(final MutableBigDecimal value) { if (this.value.compareTo(value.getValue()) <= 0) { return this; } else { return value; } } public MutableBigDecimal max(final MutableBigDecimal value) { if (this.value.compareTo(value.getValue()) >= 0) { return this; } else { return value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\MutableBigDecimal.java
1
请完成以下Java代码
public class CollectionUtility { public static <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> input, final boolean desc) { LinkedHashMap<K, V> output = new LinkedHashMap<K, V>(input.size()); ArrayList<Map.Entry<K, V>> entryList = new ArrayList<Map.Entry<K, V>>(input.entrySet()); Collections.sort(entryList, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { if (desc) return o2.getValue().compareTo(o1.getValue()); return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<K, V> entry : entryList) { output.put(entry.getKey(), entry.getValue()); } return output; } public static <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> input) { return sortMapByValue(input, true); } public static String max(Map<String, Double> scoreMap) { double max = Double.NEGATIVE_INFINITY; String best = null; for (Map.Entry<String, Double> entry : scoreMap.entrySet()) { Double score = entry.getValue(); if (score > max) { max = score; best = entry.getKey(); } } return best; } /** * 分割数组为两个数组 * @param src 原数组 * @param rate 第一个数组所占的比例 * @return 两个数组 */ public static String[][] spiltArray(String[] src, double rate)
{ assert 0 <= rate && rate <= 1; String[][] output = new String[2][]; output[0] = new String[(int) (src.length * rate)]; output[1] = new String[src.length - output[0].length]; System.arraycopy(src, 0, output[0], 0, output[0].length); System.arraycopy(src, output[0].length, output[1], 0, output[1].length); return output; } /** * 分割Map,其中旧map直接被改变 * @param src * @param rate * @return */ public static Map<String, String[]> splitMap(Map<String, String[]> src, double rate) { assert 0 <= rate && rate <= 1; Map<String, String[]> output = new TreeMap<String, String[]>(); for (Map.Entry<String, String[]> entry : src.entrySet()) { String[][] array = spiltArray(entry.getValue(), rate); output.put(entry.getKey(), array[0]); entry.setValue(array[1]); } return output; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\utilities\CollectionUtility.java
1
请在Spring Boot框架中完成以下Java代码
public void addItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem item) { items.put(slot, item); } public void addItems(@NonNull final PackingSlot slot, @NonNull final Collection<? extends IPackingItem> items) { this.items.putAll(slot, items); } public PackingItemsMap copy() { return new PackingItemsMap(this); } public List<IPackingItem> removeBySlot(@NonNull final PackingSlot slot) { return items.removeAll(slot); } public void removeUnpackedItem(@NonNull final IPackingItem itemToRemove) { final boolean removed = items.remove(PackingSlot.UNPACKED, itemToRemove); if (!removed) { throw new AdempiereException("Unpacked item " + itemToRemove + " was not found in: " + items.get(PackingSlot.UNPACKED)); } } /** * Append given <code>itemPacked</code> to existing packed items * * @param slot * @param packedItem */ public void appendPackedItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem packedItem) { for (final IPackingItem item : items.get(slot)) { // add new item into the list only if is a real new item // NOTE: should be only one item with same grouping key if (PackingItemGroupingKey.equals(item.getGroupingKey(), packedItem.getGroupingKey())) { item.addParts(packedItem); return; } } // // No matching existing packed item where our item could be added was found // => add it here as a new item addItem(slot, packedItem); } /**
* * @return true if there exists at least one packed item */ public boolean hasPackedItems() { return streamPackedItems().findAny().isPresent(); } public boolean hasPackedItemsMatching(@NonNull final Predicate<IPackingItem> predicate) { return streamPackedItems().anyMatch(predicate); } public Stream<IPackingItem> streamPackedItems() { return items .entries() .stream() .filter(e -> !e.getKey().isUnpacked()) .map(e -> e.getValue()); } /** * * @return true if there exists at least one unpacked item */ public boolean hasUnpackedItems() { return !items.get(PackingSlot.UNPACKED).isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemsMap.java
2
请完成以下Java代码
public Long getCustomer_id() { return customer_id; } public void setCustoemr_id(Long custoemr_id) { this.customer_id = custoemr_id; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerEmail() { return customerEmail; } public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; } public Long getOrder_id() { return order_id; } public void setOrder_id(Long order_id) { this.order_id = order_id;
} public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Double getProductPrice() { return productPrice; } public void setProductPrice(Double productPrice) { this.productPrice = productPrice; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO.java
1
请在Spring Boot框架中完成以下Java代码
private void updateRoleName(JSONObject paramJson, JSONObject roleInfo) { String roleName = paramJson.getString("roleName"); if (!roleName.equals(roleInfo.getString("roleName"))) { userDao.updateRoleName(paramJson); } } /** * 为角色添加新权限 */ private void saveNewPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) { List<Integer> waitInsert = new ArrayList<>(); for (Integer newPerm : newPerms) { if (!oldPerms.contains(newPerm)) { waitInsert.add(newPerm); } } if (waitInsert.size() > 0) { userDao.insertRolePermission(roleId, waitInsert); } } /** * 删除角色 旧的 不再拥有的权限 */ private void removeOldPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) { List<Integer> waitRemove = new ArrayList<>(); for (Integer oldPerm : oldPerms) { if (!newPerms.contains(oldPerm)) { waitRemove.add(oldPerm); } } if (waitRemove.size() > 0) { userDao.removeOldPermission(roleId, waitRemove);
} } /** * 删除角色 */ @Transactional(rollbackFor = Exception.class) public JSONObject deleteRole(JSONObject jsonObject) { String roleId = jsonObject.getString("roleId"); int userCount = userDao.countRoleUser(roleId); if (userCount > 0) { return CommonUtil.errorJson(ErrorEnum.E_10008); } userDao.removeRole(roleId); userDao.removeRoleAllPermission(roleId); return CommonUtil.successJson(); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\UserService.java
2
请完成以下Java代码
public int getColumnIndex() { return columnIndex; } public void setColumnIndex(int columnIndex) { this.columnIndex = columnIndex; } /** * @return column index of the column on which we are groupping now */ public int getGroupColumnIndex() { return groupColumnIndex; } public void setGroupColumnIndex(int groupColumnIndex) { this.groupColumnIndex = groupColumnIndex;
} public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public Object[] getGroupLevel2Value() { return groupLevel2Value; } public void setGroupLevel2Value(Object[] groupLevel2Value) { this.groupLevel2Value = groupLevel2Value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\RModelCalculationContext.java
1
请在Spring Boot框架中完成以下Java代码
public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property. * * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the datequal property. * * @return * possible object is * {@link String } * */ public String getDATEQUAL() { return datequal; } /** * Sets the value of the datequal property. * * @param value * allowed object is * {@link String } * */ public void setDATEQUAL(String value) { this.datequal = value; } /** * Gets the value of the datefrom property. * * @return * possible object is * {@link String } * */ public String getDATEFROM() { return datefrom; } /** * Sets the value of the datefrom property. * * @param value * allowed object is * {@link String } * */ public void setDATEFROM(String value) { this.datefrom = value; }
/** * Gets the value of the dateto property. * * @return * possible object is * {@link String } * */ public String getDATETO() { return dateto; } /** * Sets the value of the dateto property. * * @param value * allowed object is * {@link String } * */ public void setDATETO(String value) { this.dateto = value; } /** * Gets the value of the days property. * * @return * possible object is * {@link String } * */ public String getDAYS() { return days; } /** * Sets the value of the days property. * * @param value * allowed object is * {@link String } * */ public void setDAYS(String value) { this.days = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DDATE1.java
2
请在Spring Boot框架中完成以下Java代码
public FilterRegistrationBean sentinelFilterRegistration() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(new CommonFilter()); registration.addUrlPatterns("/*"); registration.setName("sentinelFilter"); registration.setOrder(1); // If this is enabled, the entrance of all Web URL resources will be unified as a single context name. // In most scenarios that's enough, and it could reduce the memory footprint. registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "true"); logger.info("Sentinel servlet CommonFilter registered"); return registration; } @PostConstruct public void doInit() { Set<String> suffixSet = new HashSet<>(Arrays.asList(".js", ".css", ".html", ".ico", ".txt", ".woff", ".woff2")); // Example: register a UrlCleaner to exclude URLs of common static resources. WebCallbackManager.setUrlCleaner(url -> { if (StringUtil.isEmpty(url)) { return url; } if (suffixSet.stream().anyMatch(url::endsWith)) {
return null; } return url; }); } @Bean public FilterRegistrationBean authenticationFilterRegistration() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(loginAuthenticationFilter); registration.addUrlPatterns("/*"); registration.setName("authenticationFilter"); registration.setOrder(0); return registration; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\config\WebConfig.java
2
请完成以下Java代码
public void handleIntermediateEvent(EventSubscriptionEntity eventSubscription, Object payload, Object localPayload, Object payloadToTriggeredScope, CommandContext commandContext) { PvmExecutionImpl execution = eventSubscription.getExecution(); ActivityImpl activity = eventSubscription.getActivity(); ensureNotNull("Error while sending signal for event subscription '" + eventSubscription.getId() + "': " + "no activity associated with event subscription", "activity", activity); if (payload instanceof Map) { execution.setVariables((Map<String, Object>)payload); } if (localPayload instanceof Map) { execution.setVariablesLocal((Map<String, Object>) localPayload); } if (payloadToTriggeredScope instanceof Map) { if (ActivityTypes.INTERMEDIATE_EVENT_MESSAGE.equals(activity.getProperty(BpmnProperties.TYPE.getName()))) { execution.setVariablesLocal((Map<String, Object>) payloadToTriggeredScope); } else { execution.getProcessInstance().setPayloadForTriggeredScope((Map<String, Object>) payloadToTriggeredScope); } }
if(activity.equals(execution.getActivity())) { execution.signal("signal", null); } else { // hack around the fact that the start event is referenced by event subscriptions for event subprocesses // and not the subprocess itself if (activity.getActivityBehavior() instanceof EventSubProcessStartEventActivityBehavior) { activity = (ActivityImpl) activity.getFlowScope(); } execution.executeEventHandlerActivity(activity); } } @Override public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, Object localPayload, Object payloadToTriggeredScope, String businessKey, CommandContext commandContext) { handleIntermediateEvent(eventSubscription, payload, localPayload, payloadToTriggeredScope, commandContext); } @Override public String getEventHandlerType() { return eventType.name(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\event\EventHandlerImpl.java
1
请在Spring Boot框架中完成以下Java代码
private String determineEmbeddedDatabaseName(R2dbcProperties properties) { String databaseName = determineDatabaseName(properties); return (databaseName != null) ? databaseName : "testdb"; } private @Nullable String determineDatabaseName(R2dbcProperties properties) { if (properties.isGenerateUniqueName()) { return properties.determineUniqueName(); } if (StringUtils.hasLength(properties.getName())) { return properties.getName(); } return null; } private String determineEmbeddedUsername(R2dbcProperties properties) { String username = ifHasText(properties.getUsername()); return (username != null) ? username : "sa"; } private ConnectionFactoryBeanCreationException connectionFactoryBeanCreationException(String message, @Nullable String r2dbcUrl, EmbeddedDatabaseConnection embeddedDatabaseConnection) { return new ConnectionFactoryBeanCreationException(message, r2dbcUrl, embeddedDatabaseConnection); } private @Nullable String ifHasText(@Nullable String candidate) { return (StringUtils.hasText(candidate)) ? candidate : null; } static class ConnectionFactoryBeanCreationException extends BeanCreationException { private final @Nullable String url; private final EmbeddedDatabaseConnection embeddedDatabaseConnection; ConnectionFactoryBeanCreationException(String message, @Nullable String url, EmbeddedDatabaseConnection embeddedDatabaseConnection) {
super(message); this.url = url; this.embeddedDatabaseConnection = embeddedDatabaseConnection; } @Nullable String getUrl() { return this.url; } EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() { return this.embeddedDatabaseConnection; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryOptionsInitializer.java
2
请完成以下Java代码
public Date getEndTime() { return endTime; } @Override public void setEndTime(Date endTime) { this.endTime = endTime; } @Override public String getInstanceId() { return instanceId; } @Override public void setInstanceId(String instanceId) { this.instanceId = instanceId; } @Override public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getActivityId() { return activityId; } @Override public void setActivityId(String activityId) { this.activityId = activityId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public boolean isFailed() { return failed; } @Override public void setFailed(boolean failed) { this.failed = failed; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getExecutionJson() { return executionJson; } @Override public void setExecutionJson(String executionJson) { this.executionJson = executionJson;
} @Override public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; } @Override public String getDecisionName() { return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } @Override public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } @Override public String toString() { return "HistoricDecisionExecutionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class FactAcctQuery { @Nullable Set<FactAcctId> includeFactAcctIds; @Nullable AcctSchemaId acctSchemaId; @Nullable @Singular ImmutableSet<AccountConceptualName> accountConceptualNames; @Nullable @Singular ImmutableSet<ElementValueId> accountIds; @Nullable PostingType postingType; @Nullable CurrencyId currencyId; @Nullable Instant dateAcct; @Nullable Instant dateAcctLessOrEqualsTo; @Nullable Instant dateAcctGreaterOrEqualsTo; @Nullable String tableName; int recordId; int lineId; @Nullable TableRecordReference excludeRecordRef; @Nullable Boolean isOpenItem; @Nullable Boolean isOpenItemReconciled; @Nullable @Singular Set<FAOpenItemKey> openItemsKeys; @Nullable FAOpenItemTrxType openItemTrxType; @Nullable @Singular Set<DocStatus> docStatuses; @Nullable String documentNoLike;
@Nullable String descriptionLike; @Nullable String poReferenceLike; @NonNull @Builder.Default InSetPredicate<BPartnerId> bpartnerIds = InSetPredicate.any(); @Nullable OrderId salesOrderId; @Nullable String userElementString1Like; @Nullable String userElementString2Like; @Nullable String userElementString3Like; @Nullable String userElementString4Like; @Nullable String userElementString5Like; @Nullable String userElementString6Like; @Nullable String userElementString7Like; @SuppressWarnings("unused") public static class FactAcctQueryBuilder { public FactAcctQueryBuilder recordRef(@NonNull final TableRecordReference recordRef) { tableName(recordRef.getTableName()); recordId(recordRef.getRecord_ID()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\FactAcctQuery.java
2
请在Spring Boot框架中完成以下Java代码
public static String getBPartnersFromLocalFileRouteId(@NonNull final JsonExternalSystemRequest externalSystemRequest) { return "GetBPartnerFromLocalFile#" + externalSystemRequest.getExternalSystemChildConfigValue(); } @Override public String getServiceValue() { return "LocalFileSyncBPartners"; } @Override public String getExternalSystemTypeCode() { return PCM_SYSTEM_NAME; } @Override public String getEnableCommand() { return START_BPARTNER_SYNC_LOCAL_FILE_ROUTE; } @Override
public String getDisableCommand() { return STOP_BPARTNER_SYNC_LOCAL_FILE_ROUTE; } @NonNull public String getStartBPartnerRouteId() { return getExternalSystemTypeCode() + "-" + getEnableCommand(); } @NonNull public String getStopBPartnerRouteId() { return getExternalSystemTypeCode() + "-" + getDisableCommand(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\bpartner\LocalFileBPartnerSyncServicePCMRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public Saml2LogoutRequest resolve(HttpServletRequest request, Authentication authentication) { return this.delegate.resolve(request, authentication); } /** * Set a {@link Consumer} for modifying the OpenSAML {@link LogoutRequest} * @param parametersConsumer a consumer that accepts an * {@link LogoutRequestParameters} */ public void setParametersConsumer(Consumer<LogoutRequestParameters> parametersConsumer) { Assert.notNull(parametersConsumer, "parametersConsumer cannot be null"); this.delegate .setParametersConsumer((parameters) -> parametersConsumer.accept(new LogoutRequestParameters(parameters))); } /** * Use this {@link Clock} for determining the issued {@link Instant} * @param clock the {@link Clock} to use */ public void setClock(Clock clock) { Assert.notNull(clock, "clock must not be null"); this.delegate.setClock(clock); } /** * Use this {@link Converter} to compute the RelayState * @param relayStateResolver the {@link Converter} to use * @since 6.1 */ public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { Assert.notNull(relayStateResolver, "relayStateResolver cannot be null"); this.delegate.setRelayStateResolver(relayStateResolver); } public static final class LogoutRequestParameters { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final Authentication authentication;
private final LogoutRequest logoutRequest; public LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration, Authentication authentication, LogoutRequest logoutRequest) { this.request = request; this.registration = registration; this.authentication = authentication; this.logoutRequest = logoutRequest; } LogoutRequestParameters(BaseOpenSamlLogoutRequestResolver.LogoutRequestParameters parameters) { this(parameters.getRequest(), parameters.getRelyingPartyRegistration(), parameters.getAuthentication(), parameters.getLogoutRequest()); } public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public Authentication getAuthentication() { return this.authentication; } public LogoutRequest getLogoutRequest() { return this.logoutRequest; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestResolver.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Proxy { /** * The host of the proxy to use to connect to the remote application. */ private @Nullable String host; /** * The port of the proxy to use to connect to the remote application. */ private @Nullable Integer port; public @Nullable String getHost() { return this.host; }
public void setHost(@Nullable String host) { this.host = host; } public @Nullable Integer getPort() { return this.port; } public void setPort(@Nullable Integer port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsProperties.java
2
请完成以下Java代码
private AvailabilityMultiResult checkAvailability0(@NonNull final AvailabilityRequest request) { final VendorGatewayService vendorGatewayService = vendorGatewayRegistry .getSingleVendorGatewayService(request.getVendorId()) .orElse(null); if (vendorGatewayService == null) { // shall not happen because we already checked that return AvailabilityMultiResult.EMPTY; } final AvailabilityResponse availabilityResponse = vendorGatewayService.retrieveAvailability(request); final ImmutableList.Builder<AvailabilityResult> result = ImmutableList.builder(); for (final AvailabilityResponseItem responseItem : availabilityResponse.getAvailabilityResponseItems()) { final I_C_UOM uom = uomsRepo.getById(responseItem.getUomId()); final AvailabilityResult availabilityResult = AvailabilityResult .prepareBuilderFor(responseItem, uom) .build(); result.add(availabilityResult); } return AvailabilityMultiResult.of(result.build()); } private AdempiereException convertThrowable(@NonNull final Throwable throwable) { final boolean isAvailabilityRequestException = throwable instanceof AvailabilityRequestException; if (!isAvailabilityRequestException) {
return AdempiereException.wrapIfNeeded(throwable); } final AvailabilityRequestException availabilityRequestException = AvailabilityRequestException.cast(throwable); final ImmutableList<AvailabilityException.ErrorItem> errorItems = availabilityRequestException .getRequestItem2Exception() .entrySet() .stream() .map(entry -> AvailabilityException.ErrorItem.builder() .trackingId(entry.getKey().getTrackingId()) .error(entry.getValue()) .build()) .collect(ImmutableList.toImmutableList()); return new AvailabilityException(errorItems); } private boolean vendorProvidesAvailabilityCheck(final int vendorBPartnerId) { return vendorGatewayRegistry.getSingleVendorGatewayService(vendorBPartnerId).isPresent(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityCheckCommand.java
1
请完成以下Java代码
public File getActiveFileOrNull() { if (metasfreshRollingPolicy == null) { return null; } return metasfreshRollingPolicy.getActiveFileOrNull(); } public List<File> getLogFiles() { if (metasfreshRollingPolicy == null) { return ImmutableList.of(); } return metasfreshRollingPolicy.getLogFiles(); } public boolean isActiveLogFile(final File file) { if (file == null) { return false; } final File activeLogFile = getActiveFileOrNull(); if (activeLogFile == null) { return false; } return activeLogFile.equals(file); } public void flushActiveLogFile() { // TODO Auto-generated method stub } public void rotateLogFile()
{ if (metasfreshRollingPolicy != null) { final TimeBasedFileNamingAndTriggeringPolicy<?> triggeringPolicy = metasfreshRollingPolicy.getTimeBasedFileNamingAndTriggeringPolicy(); if (triggeringPolicy instanceof MetasfreshTimeBasedFileNamingAndTriggeringPolicy) { final MetasfreshTimeBasedFileNamingAndTriggeringPolicy<?> metasfreshTriggeringPolicy = (MetasfreshTimeBasedFileNamingAndTriggeringPolicy<?>)triggeringPolicy; metasfreshTriggeringPolicy.setForceRollover(); } } if (rollingFileAppender != null) { rollingFileAppender.rollover(); } } public void setDisabled(final boolean disabled) { if (rollingFileAppender instanceof MetasfreshFileAppender) { ((MetasfreshFileAppender<?>)rollingFileAppender).setDisabled(disabled); } } public boolean isDisabled() { if (rollingFileAppender instanceof MetasfreshFileAppender) { return ((MetasfreshFileAppender<?>)rollingFileAppender).isDisabled(); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshFileLoggerHelper.java
1
请完成以下Java代码
public I_AD_PrintColor getAD_PrintColor() throws RuntimeException { return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name) .getPO(getAD_PrintColor_ID(), get_TrxName()); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_Value (COLUMNNAME_AD_PrintColor_ID, null); else set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Channel. @param C_Channel_ID Sales Channel */ public void setC_Channel_ID (int C_Channel_ID) { if (C_Channel_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Channel_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Channel_ID, Integer.valueOf(C_Channel_ID)); } /** Get Channel. @return Sales Channel */ public int getC_Channel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Channel_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); } /** 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_C_Channel.java
1
请完成以下Java代码
static class Instance { /** * 特征向量 */ List<Integer> x; /** * 标签 */ int y; public Instance(List<Integer> x, int y) { this.x = x; this.y = y; } } /** * 准确率度量 */ static class BinaryClassificationFMeasure { float P, R, F1; public BinaryClassificationFMeasure(float p, float r, float f1) { P = p; R = r;
F1 = f1; } @Override public String toString() { return String.format("P=%.2f R=%.2f F1=%.2f", P, R, F1); } } public LinearModel getModel() { return model; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronClassifier.java
1
请完成以下Java代码
public List<I_C_Flatrate_Term> retrieveFlatrateTermsForOrderIdLatestFirst(@NonNull final OrderId orderId) { return Services.get(IQueryBL.class).createQueryBuilder(I_C_OrderLine.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId) .andCollectChildren(I_C_Flatrate_Term.COLUMN_C_OrderLine_Term_ID, I_C_Flatrate_Term.class) .orderByDescending(I_C_Flatrate_Term.COLUMN_EndDate) .create() .list(); } @Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#BPartnerId") @Override @Nullable public I_C_Flatrate_Term retrieveLatestFlatrateTermForBPartnerId(@NonNull final BPartnerId bpartnerId) { return Services.get(IQueryBL.class).createQueryBuilder(I_C_Flatrate_Term.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bpartnerId.getRepoId()) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_MasterEndDate, Direction.Descending, Nulls.Last) .addColumn(I_C_Flatrate_Term.COLUMNNAME_EndDate, Direction.Descending, Nulls.Last) .endOrderBy() .create() .first(); } @Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#BPartnerId") @Override @Nullable
public I_C_Flatrate_Term retrieveFirstFlatrateTermForBPartnerId(@NonNull final BPartnerId bpartnerId) { return Services.get(IQueryBL.class).createQueryBuilder(I_C_Flatrate_Term.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bpartnerId) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_MasterStartDate, Direction.Ascending, Nulls.Last) .addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate, Direction.Ascending, Nulls.Last) .endOrderBy() .create() .first(); } @Override @NonNull public <T extends I_C_Flatrate_Conditions> T getConditionsById(@NonNull final ConditionsId conditionsId, @NonNull final Class<T> modelClass) { return InterfaceWrapperHelper.load(conditionsId, modelClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractsDAO.java
1
请完成以下Java代码
public Builder setParameter(@NonNull final String name, @Nullable final Object value) { if (value == null) { if (parameters != null) { parameters.remove(name); } } else { if (parameters == null) { parameters = new LinkedHashMap<>(); } parameters.put(name, value); } return this; } public Builder setParameters(@NonNull final Map<String, Object> parameters) { parameters.forEach(this::setParameter); return this; } private ImmutableMap<String, Object> getParameters() { return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of(); } public Builder applySecurityRestrictions(final boolean applySecurityRestrictions) { this.applySecurityRestrictions = applySecurityRestrictions; return this; } private boolean isApplySecurityRestrictions() { return applySecurityRestrictions; } } // // // // // @ToString private static final class WrappedDocumentFilterList { public static WrappedDocumentFilterList ofFilters(final DocumentFilterList filters) { if (filters == null || filters.isEmpty()) { return EMPTY; }
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = null; return new WrappedDocumentFilterList(jsonFiltersEffective, filters); } public static WrappedDocumentFilterList ofJSONFilters(final List<JSONDocumentFilter> jsonFilters) { if (jsonFilters == null || jsonFilters.isEmpty()) { return EMPTY; } final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = ImmutableList.copyOf(jsonFilters); final DocumentFilterList filtersEffective = null; return new WrappedDocumentFilterList(jsonFiltersEffective, filtersEffective); } public static final WrappedDocumentFilterList EMPTY = new WrappedDocumentFilterList(); private final ImmutableList<JSONDocumentFilter> jsonFilters; private final DocumentFilterList filters; private WrappedDocumentFilterList(@Nullable final ImmutableList<JSONDocumentFilter> jsonFilters, @Nullable final DocumentFilterList filters) { this.jsonFilters = jsonFilters; this.filters = filters; } /** * empty constructor */ private WrappedDocumentFilterList() { filters = DocumentFilterList.EMPTY; jsonFilters = null; } public DocumentFilterList unwrap(final DocumentFilterDescriptorsProvider descriptors) { if (filters != null) { return filters; } if (jsonFilters == null || jsonFilters.isEmpty()) { return DocumentFilterList.EMPTY; } return JSONDocumentFilter.unwrapList(jsonFilters, descriptors); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CreateViewRequest.java
1
请完成以下Java代码
public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getTaskId() { return taskId; } public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public String getAssignee() { return assignee; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public Boolean getCanceled() { return canceled; } public Boolean getCompleteScope() { return completeScope; } public String getTenantId() { return tenantId; }
public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto, HistoricActivityInstance historicActivityInstance) { dto.id = historicActivityInstance.getId(); dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId(); dto.activityId = historicActivityInstance.getActivityId(); dto.activityName = historicActivityInstance.getActivityName(); dto.activityType = historicActivityInstance.getActivityType(); dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey(); dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId(); dto.processInstanceId = historicActivityInstance.getProcessInstanceId(); dto.executionId = historicActivityInstance.getExecutionId(); dto.taskId = historicActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId(); dto.assignee = historicActivityInstance.getAssignee(); dto.startTime = historicActivityInstance.getStartTime(); dto.endTime = historicActivityInstance.getEndTime(); dto.durationInMillis = historicActivityInstance.getDurationInMillis(); dto.canceled = historicActivityInstance.isCanceled(); dto.completeScope = historicActivityInstance.isCompleteScope(); dto.tenantId = historicActivityInstance.getTenantId(); dto.removalTime = historicActivityInstance.getRemovalTime(); dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityInstanceDto.java
1
请完成以下Java代码
public Collection<AllocableHU> getAllAllocableHUsInvolved() {return allocableHUs.values();} public void addSourceHUs(@NonNull final Set<HuId> huIds) { if (huIds.isEmpty()) { return; } for (final I_M_HU hu : pickFromHUsSupplier.getHusCache().getHUsByIds(huIds)) { final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); final ImmutableSet<ProductId> productIds = storageFactory .getStorage(hu) .getProductStorages() .stream() .map(IHUProductStorage::getProductId) .collect(ImmutableSet.toImmutableSet()); for (final ProductId productId : productIds) { sourceHUs.put(productId, huId); } } } public AllocableHUsList getAllocableHUs(@NonNull final AllocableHUsGroupingKey key) { return groups.computeIfAbsent(key, this::retrieveAvailableHUsToPick); } private AllocableHUsList retrieveAvailableHUsToPick(@NonNull final AllocableHUsGroupingKey key) { final ShipmentAllocationBestBeforePolicy bestBeforePolicy = ShipmentAllocationBestBeforePolicy.Expiring_First; final ProductId productId = key.getProductId(); final ImmutableList<PickFromHU> husEligibleToPick; final Set<HuId> productSourceHUs = sourceHUs.get(productId); if (!productSourceHUs.isEmpty()) { husEligibleToPick = productSourceHUs.stream() .map(pickFromHUsSupplier::createPickFromHUByTopLevelHUId) .sorted(PickFromHUsSupplier.getAllocationOrder(bestBeforePolicy)) .collect(ImmutableList.toImmutableList()); } else if (!key.isSourceHUsOnly()) { husEligibleToPick = pickFromHUsSupplier.getEligiblePickFromHUs(
PickFromHUsGetRequest.builder() .pickFromLocatorId(key.getPickFromLocatorId()) .productId(productId) .asiId(AttributeSetInstanceId.NONE) // TODO match attributes .bestBeforePolicy(bestBeforePolicy) .reservationRef(Optional.empty()) // TODO introduce some PP Order reservation .enforceMandatoryAttributesOnPicking(false) .build()); } else { husEligibleToPick = ImmutableList.of(); } final ImmutableList<AllocableHU> hus = CollectionUtils.map(husEligibleToPick, hu -> toAllocableHU(hu.getTopLevelHUId(), productId)); return new AllocableHUsList(hus); } private AllocableHU toAllocableHU(@NonNull final HuId huId, @NonNull final ProductId productId) { final AllocableHUKey key = AllocableHUKey.of(huId, productId); return allocableHUs.computeIfAbsent(key, this::createAllocableHU); } private AllocableHU createAllocableHU(@NonNull final AllocableHUKey key) { final HUsLoadingCache husCache = pickFromHUsSupplier.getHusCache(); final I_M_HU topLevelHU = husCache.getHUById(key.getTopLevelHUId()); return new AllocableHU(storageFactory, uomConverter, topLevelHU, key.getProductId()); } @Value(staticConstructor = "of") private static class AllocableHUKey { @NonNull HuId topLevelHUId; @NonNull ProductId productId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\manufacturing\issue\plan\AllocableHUsMap.java
1
请在Spring Boot框架中完成以下Java代码
public class CaseExecutionRestServiceImpl extends AbstractRestProcessEngineAware implements CaseExecutionRestService { public CaseExecutionRestServiceImpl(String engineName, final ObjectMapper objectMapper) { super(engineName, objectMapper); } @Override public CaseExecutionResource getCaseExecution(String caseExecutionId) { return new CaseExecutionResourceImpl(getProcessEngine(), caseExecutionId, getObjectMapper()); } @Override public List<CaseExecutionDto> getCaseExecutions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryCaseExecutions(queryDto, firstResult, maxResults); } @Override public List<CaseExecutionDto> queryCaseExecutions(CaseExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); CaseExecutionQuery query = queryDto.toQuery(engine); List<CaseExecution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults); List<CaseExecutionDto> executionResults = new ArrayList<CaseExecutionDto>(); for (CaseExecution execution : matchingExecutions) { CaseExecutionDto resultExecution = CaseExecutionDto.fromCaseExecution(execution); executionResults.add(resultExecution); } return executionResults; }
@Override public CountResultDto getCaseExecutionsCount(UriInfo uriInfo) { CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryCaseExecutionsCount(queryDto); } @Override public CountResultDto queryCaseExecutionsCount(CaseExecutionQueryDto queryDto) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); CaseExecutionQuery query = queryDto.toQuery(engine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseExecutionRestServiceImpl.java
2
请完成以下Java代码
public void setAD_Tree_SalesRegion_ID (int AD_Tree_SalesRegion_ID) { if (AD_Tree_SalesRegion_ID < 1) set_Value (COLUMNNAME_AD_Tree_SalesRegion_ID, null); else set_Value (COLUMNNAME_AD_Tree_SalesRegion_ID, Integer.valueOf(AD_Tree_SalesRegion_ID)); } /** Get Sales Region Tree. @return Tree to determine sales regional hierarchy */ public int getAD_Tree_SalesRegion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_SalesRegion_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); } /** 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 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 Reporting Hierarchy. @param PA_Hierarchy_ID Optional Reporting Hierarchy - If not selected the default hierarchy trees are used. */ public void setPA_Hierarchy_ID (int PA_Hierarchy_ID) { if (PA_Hierarchy_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Hierarchy_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Hierarchy_ID, Integer.valueOf(PA_Hierarchy_ID)); } /** Get Reporting Hierarchy. @return Optional Reporting Hierarchy - If not selected the default hierarchy trees are used. */ public int getPA_Hierarchy_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Hierarchy_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_PA_Hierarchy.java
1
请完成以下Java代码
public boolean evaluate(DelegateExecution execution) { return evaluate(execution, execution); } @Override public boolean evaluate(VariableScope scope, DelegateExecution execution) { ScriptInvocation invocation = new ScriptInvocation(script, scope, execution); try { Context .getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(invocation); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ProcessEngineException(e); } Object result = invocation.getInvocationResult(); ensureNotNull("condition script returns null", "result", result); ensureInstanceOf("condition script returns non-Boolean", "result", result, Boolean.class); return (Boolean) result; }
@Override public boolean tryEvaluate(VariableScope scope, DelegateExecution execution) { boolean result = false; try { result = evaluate(scope, execution); } catch (ProcessEngineException pex) { if (! (pex.getMessage().contains("No such property") || pex.getCause() instanceof ScriptEvaluationException) ) { throw pex; } } return result; } public ExecutableScript getScript() { return script; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\ScriptCondition.java
1
请完成以下Java代码
public DmnDecisionTableImpl handleElement(DmnElementTransformContext context, DecisionTable decisionTable) { return createFromDecisionTable(context, decisionTable); } protected DmnDecisionTableImpl createFromDecisionTable(DmnElementTransformContext context, DecisionTable decisionTable) { DmnDecisionTableImpl dmnDecisionTable = createDmnElement(context, decisionTable); dmnDecisionTable.setHitPolicyHandler(getHitPolicyHandler(context, decisionTable, dmnDecisionTable)); return dmnDecisionTable; } protected DmnDecisionTableImpl createDmnElement(DmnElementTransformContext context, DecisionTable decisionTable) { return new DmnDecisionTableImpl(); } protected DmnHitPolicyHandler getHitPolicyHandler(DmnElementTransformContext context, DecisionTable decisionTable, DmnDecisionTableImpl dmnDecisionTable) {
HitPolicy hitPolicy = decisionTable.getHitPolicy(); if (hitPolicy == null) { // use default hit policy hitPolicy = HitPolicy.UNIQUE; } BuiltinAggregator aggregation = decisionTable.getAggregation(); DmnHitPolicyHandler hitPolicyHandler = context.getHitPolicyHandlerRegistry().getHandler(hitPolicy, aggregation); if (hitPolicyHandler != null) { return hitPolicyHandler; } else { throw LOG.hitPolicyNotSupported(dmnDecisionTable, hitPolicy, aggregation); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnDecisionTableTransformHandler.java
1
请完成以下Java代码
public static CellValue toCellValue(@Nullable final Object value) { if (value == null) { return null; } final int displayType = extractDisplayTypeFromValue(value); return toCellValue(value, displayType); } public static CellValue toCellValue(final Object value, final int displayType) { if (value == null) { return null; } if (DisplayType.isDate(displayType)) { final Date date = TimeUtil.asDate(value); return CellValue.ofDate(date); } else if (displayType == DisplayType.Integer) { final Integer valueInteger = NumberUtils.asInteger(value, null); return valueInteger != null ? CellValue.ofNumber(valueInteger) : null; } else if (DisplayType.isNumeric(displayType)) { if (value instanceof Number) { return CellValue.ofNumber((Number)value); } else
{ final BigDecimal number = NumberUtils.asBigDecimal(value, null); return number != null ? CellValue.ofNumber(number) : null; } } else if (displayType == DisplayType.YesNo) { final boolean bool = DisplayType.toBoolean(value); return CellValue.ofBoolean(bool); } else { return CellValue.ofString(value.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\CellValues.java
1
请完成以下Java代码
public static void registerYamlPlugins(List<ProcessEnginePlugin> processEnginePlugins, List<CamundaBpmRunProcessEnginePluginProperty> pluginsInfo) { for (CamundaBpmRunProcessEnginePluginProperty pluginInfo : pluginsInfo) { String className = pluginInfo.getPluginClass(); ProcessEnginePlugin plugin = getOrCreatePluginInstance(processEnginePlugins, className); Map<String, Object> pluginParameters = pluginInfo.getPluginParameters(); populatePluginInstance(plugin, pluginParameters); LOG.processEnginePluginRegistered(className); } } protected static ProcessEnginePlugin getOrCreatePluginInstance( List<ProcessEnginePlugin> processEnginePlugins, String className) { try { // find class on classpath Class<? extends ProcessEnginePlugin> pluginClass = ReflectUtil .loadClass(className, null, ProcessEnginePlugin.class); // check if an instance of the process engine plugin is already present Optional<ProcessEnginePlugin> plugin = processEnginePlugins.stream() .filter(p -> pluginClass.isInstance(p)).findFirst(); // get existing plugin instance or create a new one and add it to the list return plugin.orElseGet(() -> { ProcessEnginePlugin newPlugin = ReflectUtil.createInstance(pluginClass); processEnginePlugins.add(newPlugin); return newPlugin;
}); } catch (ClassNotFoundException | ClassCastException | ProcessEngineException e) { throw LOG.failedProcessEnginePluginInstantiation(className, e); } } protected static void populatePluginInstance(ProcessEnginePlugin plugin, Map<String, Object> properties) { try { SpringBootStarterPropertyHelper.applyProperties(plugin, properties, false); } catch (SpringBootStarterException e) { throw LOG.pluginPropertyNotFound(plugin.getClass().getCanonicalName(), "", e); } } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\utils\CamundaBpmRunProcessEnginePluginHelper.java
1
请在Spring Boot框架中完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setImportErrorMsg (final @Nullable java.lang.String ImportErrorMsg) { set_Value (COLUMNNAME_ImportErrorMsg, ImportErrorMsg); } @Override public java.lang.String getImportErrorMsg() { return get_ValueAsString(COLUMNNAME_ImportErrorMsg); } @Override public void setJSONValue (final @Nullable java.lang.String JSONValue)
{ set_Value (COLUMNNAME_JSONValue, JSONValue); } @Override public java.lang.String getJSONValue() { return get_ValueAsString(COLUMNNAME_JSONValue); } @Override public void setS_FailedTimeBooking_ID (final int S_FailedTimeBooking_ID) { if (S_FailedTimeBooking_ID < 1) set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, null); else set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, S_FailedTimeBooking_ID); } @Override public int getS_FailedTimeBooking_ID() { return get_ValueAsInt(COLUMNNAME_S_FailedTimeBooking_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_FailedTimeBooking.java
2
请在Spring Boot框架中完成以下Java代码
class M_Inventory { private IInventoryDAO inventoryDAO = Services.get(IInventoryDAO.class); private final HUTraceEventsService huTraceEventsService; private final ITrxManager trxManager = Services.get(ITrxManager.class); public M_Inventory(@NonNull final HUTraceEventsService huTraceEventsService) { this.huTraceEventsService = huTraceEventsService; } @DocValidate(timings = { ModelValidator.TIMING_AFTER_CLOSE, ModelValidator.TIMING_AFTER_COMPLETE, ModelValidator.TIMING_AFTER_REACTIVATE, ModelValidator.TIMING_AFTER_REVERSEACCRUAL, ModelValidator.TIMING_AFTER_REVERSECORRECT,
ModelValidator.TIMING_AFTER_UNCLOSE, ModelValidator.TIMING_AFTER_VOID }, afterCommit = true) public void addTraceEvent(@NonNull final I_M_Inventory inventory) { Services.get(ITrxManager.class).runInNewTrx(() -> addTraceEvent0(inventory)); } private void addTraceEvent0(@NonNull final I_M_Inventory inventory) { final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID()); final List<I_M_InventoryLine> inventoryLines = inventoryDAO.retrieveLinesForInventoryId(inventoryId, I_M_InventoryLine.class); huTraceEventsService.createAndAddFor(inventory, inventoryLines); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\interceptor\M_Inventory.java
2
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); }
/** Set Text. @param TextSnippet Text */ @Override public void setTextSnippet (java.lang.String TextSnippet) { set_Value (COLUMNNAME_TextSnippet, TextSnippet); } /** Get Text. @return Text */ @Override public java.lang.String getTextSnippet () { return (java.lang.String)get_Value(COLUMNNAME_TextSnippet); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate.java
1
请在Spring Boot框架中完成以下Java代码
public void setCOUNTRY(String value) { this.country = value; } /** * Gets the value of the locationcode property. * * @return * possible object is * {@link String } * */ public String getLOCATIONCODE() { return locationcode; } /** * Sets the value of the locationcode property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONCODE(String value) { this.locationcode = value; } /** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the hfini1 property. * * @return * possible object is * {@link HFINI1 } * */ public HFINI1 getHFINI1() { return hfini1; } /** * Sets the value of the hfini1 property. * * @param value * allowed object is * {@link HFINI1 } * */ public void setHFINI1(HFINI1 value) { this.hfini1 = value; } /** * Gets the value of the hrfad1 property. * * @return * possible object is
* {@link HRFAD1 } * */ public HRFAD1 getHRFAD1() { return hrfad1; } /** * Sets the value of the hrfad1 property. * * @param value * allowed object is * {@link HRFAD1 } * */ public void setHRFAD1(HRFAD1 value) { this.hrfad1 = value; } /** * Gets the value of the hctad1 property. * * @return * possible object is * {@link HCTAD1 } * */ public HCTAD1 getHCTAD1() { return hctad1; } /** * Sets the value of the hctad1 property. * * @param value * allowed object is * {@link HCTAD1 } * */ public void setHCTAD1(HCTAD1 value) { this.hctad1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HADRE1.java
2
请完成以下Java代码
public class FileImporter extends BaseConnector implements IImportConnector { private Iterator<File> currentFiles; private File currentFile; @Override protected void openSpecific() { final String folder = (String)getCurrentParams().get( IInboundProcessorBL.LOCAL_FOLDER).getValue(); final List<File> files = inboundProcessorBL.getFiles(folder); currentFiles = files.iterator(); } @Override protected void closeSpecific() { currentFile = null; currentFiles = null; } private FileInputStream currentStream; @Override public InputStream connectNext(final boolean lastWasSuccess) { if (currentStream != null) { try { // note: close alone didn't suffice (at least in WinXP when // running in eclipse debug session) currentStream.getFD().sync(); currentStream.close(); } catch (IOException e) { throw new AdempiereException(e); } } if (lastWasSuccess && currentFile != null) { final String archiveFolder = (String)getCurrentParams().get( IInboundProcessorBL.ARCHIVE_FOLDER).getValue(); inboundProcessorBL.moveToArchive(currentFile, archiveFolder); } if (currentFiles.hasNext()) { currentFile = currentFiles.next(); try {
currentStream = new FileInputStream(currentFile); return currentStream; } catch (FileNotFoundException e) { ConfigException.throwNew(ConfigException.FILE_ACCESS_FAILED_2P, currentFile.getAbsolutePath(), e.getMessage()); } } return null; } @Override public List<Parameter> getParameters() { final List<Parameter> result = new ArrayList<Parameter>(); result.add(new Parameter(IInboundProcessorBL.LOCAL_FOLDER, "Import-Ordner", "Name of the folder to import from", DisplayType.FilePath, 1)); result.add(new Parameter(IInboundProcessorBL.ARCHIVE_FOLDER, "Archiv-Ordner", "Name of the folder to move files to after import", DisplayType.FilePath, 2)); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\spi\impl\FileImporter.java
1
请完成以下Java代码
public void matcherFromPreCompiledPatternResetMatches(Blackhole bh) { //With pre-compiled pattern and reusing the matcher // 1 Pattern object created // 1 Matcher objects created for (String value : values) { bh.consume(matcherFromPreCompiledPattern.reset(value).matches()); } } @Benchmark public void preCompiledPatternMatcherMatches(Blackhole bh) { // With pre-compiled pattern // 1 Pattern object created // 5_000_000 Matcher objects created for (String value : values) { bh.consume(preCompiledPattern.matcher(value).matches()); } } @Benchmark public void patternCompileMatcherMatches(Blackhole bh) { // Above approach "Pattern.matches(PATTERN, value)" makes this internally // 5_000_000 Pattern objects created // 5_000_000 Matcher objects created for (String value : values) { bh.consume(Pattern.compile(PATTERN).matcher(value).matches()); } } @Benchmark
public void patternMatches(Blackhole bh) { // Above approach "value.matches(PATTERN)" makes this internally // 5_000_000 Pattern objects created // 5_000_000 Matcher objects created for (String value : values) { bh.consume(Pattern.matches(PATTERN, value)); } } @Benchmark public void stringMatchs(Blackhole bh) { // 5_000_000 Pattern objects created // 5_000_000 Matcher objects created Instant start = Instant.now(); for (String value : values) { bh.consume(value.matches(PATTERN)); } } @Setup() public void setUp() { preCompiledPattern = Pattern.compile(PATTERN); matcherFromPreCompiledPattern = preCompiledPattern.matcher(""); values = new ArrayList<>(); for (int x = 1; x <= 5_000_000; x++) { values.add(String.valueOf(x)); } } }
repos\tutorials-master\core-java-modules\core-java-regex-3\src\main\java\com\baeldung\patternreuse\PatternPerformanceComparison.java
1
请在Spring Boot框架中完成以下Java代码
public class PmsMenuServiceImpl implements PmsMenuService { @Autowired private PmsMenuDao pmsMenuDao; @Autowired private PmsMenuRoleDao pmsMenuRoleDao; /** * 保存菜单PmsMenuDao * * @param menu */ public void savaMenu(PmsMenu menu) { pmsMenuDao.insert(menu); } /** * 根据父菜单ID获取该菜单下的所有子孙菜单.<br/> * * @param parentId * (如果为空,则为获取所有的菜单).<br/> * @return menuList. */ @SuppressWarnings("rawtypes") public List getListByParent(Long parentId) { return pmsMenuDao.listByParent(parentId); } /** * 根据id删除菜单 */ public void delete(Long id) { this.pmsMenuDao.delete(id); } /** * 根据角色id串获取菜单 * * @param roleIdsStr * @return */ @SuppressWarnings("rawtypes") public List listByRoleIds(String roleIdsStr) { return this.pmsMenuDao.listByRoleIds(roleIdsStr); } /** * 根据菜单ID查找菜单(可用于判断菜单下是否还有子菜单). * * @param parentId * . * @return menuList. */ public List<PmsMenu> listByParentId(Long parentId) { return pmsMenuDao.listByParentId(parentId); } /*** * 根据名称和是否叶子节点查询数据 * * @param isLeaf * 是否是叶子节点 * @param name * 节点名称 * @return */ public List<PmsMenu> getMenuByNameAndIsLeaf(Map<String, Object> map) { return pmsMenuDao.getMenuByNameAndIsLeaf(map); }
/** * 根据菜单ID获取菜单. * * @param pid * @return */ public PmsMenu getById(Long pid) { return pmsMenuDao.getById(pid); } /** * 更新菜单. * * @param menu */ public void update(PmsMenu menu) { pmsMenuDao.update(menu); } /** * 根据角色查找角色对应的菜单ID集 * * @param roleId * @return */ public String getMenuIdsByRoleId(Long roleId) { List<PmsMenuRole> menuList = pmsMenuRoleDao.listByRoleId(roleId); StringBuffer menuIds = new StringBuffer(""); if (menuList != null && !menuList.isEmpty()) { for (PmsMenuRole rm : menuList) { menuIds.append(rm.getMenuId()).append(","); } } return menuIds.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsMenuServiceImpl.java
2
请完成以下Java代码
public int getAge() { return age; } public void setAge(final int age) { this.age = age; } public LocalDate getCreationDate() { return creationDate; } public List<Possession> getPossessionList() { return possessionList; } public void setPossessionList(List<Possession> possessionList) { this.possessionList = possessionList; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [name=").append(name).append(", id=").append(id).append("]"); return builder.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && age == user.age && Objects.equals(name, user.name) && Objects.equals(creationDate, user.creationDate) && Objects.equals(email, user.email) && Objects.equals(status, user.status);
} @Override public int hashCode() { return Objects.hash(id, name, creationDate, age, email, status); } public LocalDate getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(LocalDate lastLoginDate) { this.lastLoginDate = lastLoginDate; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\User.java
1
请完成以下Java代码
public void updateComment(CommentDto comment) { ensureHistoryEnabled(Status.FORBIDDEN); ensureTaskExists(Status.NOT_FOUND); try { engine.getTaskService().updateTaskComment(taskId, comment.getId(), comment.getMessage()); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } public void deleteComments() { ensureHistoryEnabled(Status.FORBIDDEN); ensureTaskExists(Status.NOT_FOUND); TaskService taskService = engine.getTaskService(); try { taskService.deleteTaskComments(taskId); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } public CommentDto createComment(UriInfo uriInfo, CommentDto commentDto) { ensureHistoryEnabled(Status.FORBIDDEN); ensureTaskExists(Status.BAD_REQUEST); Comment comment; String processInstanceId = commentDto.getProcessInstanceId(); try { comment = engine.getTaskService().createComment(taskId, processInstanceId, commentDto.getMessage()); } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Not enough parameters submitted"); } URI uri = uriInfo.getBaseUriBuilder() .path(rootResourcePath) .path(TaskRestService.PATH) .path(taskId + "/comment/" + comment.getId()) .build(); CommentDto resultDto = CommentDto.fromComment(comment); // GET / resultDto.addReflexiveLink(uri, HttpMethod.GET, "self"); return resultDto; } private boolean isHistoryEnabled() {
IdentityService identityService = engine.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); try { identityService.clearAuthentication(); int historyLevel = engine.getManagementService().getHistoryLevel(); return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE; } finally { identityService.setAuthentication(currentAuthentication); } } private void ensureHistoryEnabled(Status status) { if (!isHistoryEnabled()) { throw new InvalidRequestException(status, "History is not enabled"); } } private void ensureTaskExists(Status status) { HistoricTaskInstance historicTaskInstance = engine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult(); if (historicTaskInstance == null) { throw new InvalidRequestException(status, "No task found for task id " + taskId); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\task\impl\TaskCommentResourceImpl.java
1
请完成以下Java代码
public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } @Override public ScriptInfo getScriptInfo() { return scriptInfo; } @Override public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo; } @Override public abstract AbstractFlowableHttpHandler clone();
public void setValues(AbstractFlowableHttpHandler otherHandler) { super.setValues(otherHandler); setImplementation(otherHandler.getImplementation()); setImplementationType(otherHandler.getImplementationType()); if (otherHandler.getScriptInfo() != null) { setScriptInfo(otherHandler.getScriptInfo().clone()); } fieldExtensions = new ArrayList<>(); if (otherHandler.getFieldExtensions() != null && !otherHandler.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherHandler.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\AbstractFlowableHttpHandler.java
1
请完成以下Java代码
private IHostIdentifier getHost() throws UnknownHostException { final String host = StringUtils.trimBlankToNull(p_Host); return host == null ? NetUtils.getLocalHost() : NetUtils.of(host); } private Stream<AttributeCode> streamAllAttributeCodes() { final IQueryBuilder<I_M_Attribute> queryBuilder = queryBL .createQueryBuilder(I_M_Attribute.class) .addOnlyActiveRecordsFilter() .addOnlyContextClientOrSystem() .orderBy(I_M_Attribute.COLUMN_M_Attribute_ID); if (p_M_Attribute_ID > 0) { queryBuilder.addEqualsFilter(I_M_Attribute.COLUMN_M_Attribute_ID, p_M_Attribute_ID); } return queryBuilder .create() .stream(I_M_Attribute.class) .map(attribute -> AttributeCode.ofString(attribute.getValue())); } private void accessDeviceNTimes(final DeviceAccessor deviceAccessor, final int times) { IntStream.rangeClosed(1, times) .forEach(time -> accessDevice(deviceAccessor, time)); } private void accessDevice(final DeviceAccessor deviceAccessor, final int time) { logger.info("Accessing({}) {}", time, deviceAccessor);
countDevicesChecked++; final Stopwatch stopwatch = Stopwatch.createStarted(); try { logger.debug("Getting response from {}", deviceAccessor); final Object value = deviceAccessor.acquireValue(); logger.debug("Got respose from {}: {}", deviceAccessor, value); addLog("OK(" + time + "): accessed " + deviceAccessor + " and got '" + value + "' in " + stopwatch); } catch (final Exception ex) { final String errmsg = "Error(" + time + "): Failed accessing " + deviceAccessor + ": " + ex.getLocalizedMessage(); addLog(errmsg); logger.warn(errmsg, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\adempiere\process\CheckAttributeAttachedDevices.java
1
请完成以下Java代码
public class ExternalWorkerCompletionBuilderImpl implements ExternalWorkerCompletionBuilder { protected final CommandExecutor commandExecutor; protected final String externalJobId; protected final String workerId; protected final JobServiceConfiguration jobServiceConfiguration; protected Map<String, Object> variables; public ExternalWorkerCompletionBuilderImpl(CommandExecutor commandExecutor, String externalJobId, String workerId, JobServiceConfiguration jobServiceConfiguration) { this.commandExecutor = commandExecutor; this.externalJobId = externalJobId; this.workerId = workerId; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public ExternalWorkerCompletionBuilder variables(Map<String, Object> variables) { if (this.variables == null) { this.variables = new LinkedHashMap<>(); } this.variables.putAll(variables); return this; } @Override public ExternalWorkerCompletionBuilder variable(String name, Object value) {
if (this.variables == null) { this.variables = new LinkedHashMap<>(); } this.variables.put(name, value); return this; } @Override public void complete() { commandExecutor.execute(new ExternalWorkerJobCompleteCmd(externalJobId, workerId, variables, jobServiceConfiguration)); } @Override public void bpmnError(String errorCode) { commandExecutor.execute(new ExternalWorkerJobBpmnErrorCmd(externalJobId, workerId, variables, errorCode, jobServiceConfiguration)); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\externalworker\ExternalWorkerCompletionBuilderImpl.java
1
请完成以下Java代码
protected HistoricBatchQuery createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createHistoricBatchQuery(); } protected void applyFilters(HistoricBatchQuery query) { if (batchId != null) { query.batchId(batchId); } if (type != null) { query.type(type); } if (completed != null) { query.completed(completed); } if (Boolean.TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } } protected void applySortBy(HistoricBatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { query.orderById(); } if (sortBy.equals(SORT_BY_BATCH_START_TIME_VALUE)) { query.orderByStartTime(); } if (sortBy.equals(SORT_BY_BATCH_END_TIME_VALUE)) { query.orderByEndTime(); } if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchQueryDto.java
1
请完成以下Java代码
public void setRepeatOffset(long repeatOffset) { this.repeatOffset = repeatOffset; } @Override public String getType() { return TYPE; } @Override public Object getPersistentState() { Map<String, Object> persistentState = (HashMap) super.getPersistentState(); persistentState.put("repeat", repeat); return persistentState; } @Override public String toString() { return this.getClass().getSimpleName()
+ "[repeat=" + repeat + ", id=" + id + ", revision=" + revision + ", duedate=" + duedate + ", repeatOffset=" + repeatOffset + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", retries=" + retries + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", deploymentId=" + deploymentId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TimerEntity.java
1
请在Spring Boot框架中完成以下Java代码
public InvoicableQtyBasedOnEnum getInvoicableQtyBasedOn() { return invoicableQtyBasedOn; } /** * Sets the value of the invoicableQtyBasedOn property. * * @param value * allowed object is * {@link InvoicableQtyBasedOnEnum } * */ public void setInvoicableQtyBasedOn(InvoicableQtyBasedOnEnum value) { this.invoicableQtyBasedOn = value; } /** * Gets the value of the cuombPartnerID property. * * @return * possible object is * {@link EDIExpCUOMType } * */ public EDIExpCUOMType getCUOMBPartnerID() { return cuombPartnerID; } /** * Sets the value of the cuombPartnerID property. * * @param value * allowed object is * {@link EDIExpCUOMType } * */ public void setCUOMBPartnerID(EDIExpCUOMType value) { this.cuombPartnerID = value; } /** * Gets the value of the qtyEnteredInBPartnerUOM property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getQtyEnteredInBPartnerUOM() { return qtyEnteredInBPartnerUOM; } /** * Sets the value of the qtyEnteredInBPartnerUOM property. *
* @param value * allowed object is * {@link BigDecimal } * */ public void setQtyEnteredInBPartnerUOM(BigDecimal value) { this.qtyEnteredInBPartnerUOM = value; } /** * Gets the value of the externalSeqNo property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getExternalSeqNo() { return externalSeqNo; } /** * Sets the value of the externalSeqNo property. * * @param value * allowed object is * {@link BigInteger } * */ public void setExternalSeqNo(BigInteger value) { this.externalSeqNo = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctopInvoic500VType.java
2
请完成以下Java代码
public String getSummary(final I_C_RfQResponse rfqResponse) { // NOTE: nulls shall be tolerated because the method is used for building exception error messages if (rfqResponse == null) { return "@C_RfQResponse_ID@ ?"; } return "@C_RfQResponse_ID@ #" + rfqResponse.getName(); } @Override public void updateQtyPromisedAndSave(final I_C_RfQResponseLine rfqResponseLine) { final BigDecimal qtyPromised = Services.get(IRfqDAO.class).calculateQtyPromised(rfqResponseLine); rfqResponseLine.setQtyPromised(qtyPromised); InterfaceWrapperHelper.save(rfqResponseLine); } // @Override // public void uncloseInTrx(final I_C_RfQResponse rfqResponse) // { // if (!isClosed(rfqResponse)) // { // throw new RfQDocumentNotClosedException(getSummary(rfqResponse)); // } // // // // final IRfQEventDispacher rfQEventDispacher = getRfQEventDispacher();
// rfQEventDispacher.fireBeforeUnClose(rfqResponse); // // // // // Mark as NOT closed // rfqResponse.setDocStatus(X_C_RfQResponse.DOCSTATUS_Completed); // InterfaceWrapperHelper.save(rfqResponse); // updateRfQResponseLinesStatus(rfqResponse); // // // // rfQEventDispacher.fireAfterUnClose(rfqResponse); // // // Make sure it's saved // InterfaceWrapperHelper.save(rfqResponse); // } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqBL.java
1
请完成以下Java代码
public void run() { if (m_links == null) return; URL url = null; try { url = new URL(m_urlString); } catch (Exception e) { System.err.println("OnlineHelp.Worker.run (url) - " + e); } if (url == null) return; // Read Reference Page try { URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); HTMLEditorKit kit = new HTMLEditorKit(); HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument(); doc.putProperty("IgnoreCharsetDirective", new Boolean(true)); kit.read(new InputStreamReader(is), doc, 0); // Get The Links to the Help Pages HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A); Object target = null; Object href = null; while (it != null && it.isValid()) { AttributeSet as = it.getAttributes(); // ~ href=/help/100/index.html target=Online title=My Test // System.out.println("~ " + as); // key keys if (target == null || href == null) { Enumeration<?> en = as.getAttributeNames(); while (en.hasMoreElements()) { Object o = en.nextElement(); if (target == null && o.toString().equals("target")) target = o; // javax.swing.text.html.HTML$Attribute else if (href == null && o.toString().equals("href")) href = o; } } if (target != null && "Online".equals(as.getAttribute(target))) { // Format: /help/<AD_Window_ID>/index.html
String hrefString = (String)as.getAttribute(href); if (hrefString != null) { try { // System.err.println(hrefString); String AD_Window_ID = hrefString.substring(hrefString.indexOf('/', 1), hrefString.lastIndexOf('/')); m_links.put(AD_Window_ID, hrefString); } catch (Exception e) { System.err.println("OnlineHelp.Worker.run (help) - " + e); } } } it.next(); } is.close(); } catch (ConnectException e) { // System.err.println("OnlineHelp.Worker.run URL=" + url + " - " + e); } catch (UnknownHostException uhe) { // System.err.println("OnlineHelp.Worker.run " + uhe); } catch (Exception e) { System.err.println("OnlineHelp.Worker.run (e) " + e); // e.printStackTrace(); } catch (Throwable t) { System.err.println("OnlineHelp.Worker.run (t) " + t); // t.printStackTrace(); } // System.out.println("OnlineHelp - Links=" + m_links.size()); } // run } // Worker
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\OnlineHelp.java
1
请完成以下Java代码
public Batch execute(CommandContext commandContext) { ensureAtLeastOneNotNull( "No process instances found.", processInstanceIds, processInstanceQuery, historicProcessInstanceQuery ); BatchElementConfiguration elementConfiguration = collectProcessInstanceIds(commandContext); List<String> ids = elementConfiguration.getIds(); ensureNotEmpty(BadUserRequestException.class, "Process instance ids cannot be empty", "process instance ids", ids); Batch batch = new BatchBuilder(commandContext) .type(Batch.TYPE_CORRELATE_MESSAGE) .config(getConfiguration(elementConfiguration)) .permission(BatchPermissions.CREATE_BATCH_CORRELATE_MESSAGE) .operationLogHandler(this::writeUserOperationLog) .build(); if (variables != null) { VariableUtil.setVariablesByBatchId(variables, batch.getId()); } return batch; } protected BatchElementConfiguration collectProcessInstanceIds(CommandContext commandContext) { BatchElementConfiguration elementConfiguration = new BatchElementConfiguration(); if (!CollectionUtil.isEmpty(processInstanceIds)) { ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl(); query.processInstanceIds(new HashSet<>(processInstanceIds)); elementConfiguration.addDeploymentMappings( commandContext.runWithoutAuthorization(query::listDeploymentIdMappings), processInstanceIds); } if (processInstanceQuery != null) { elementConfiguration.addDeploymentMappings(((ProcessInstanceQueryImpl) processInstanceQuery).listDeploymentIdMappings()); } if (historicProcessInstanceQuery != null) { elementConfiguration.addDeploymentMappings(((HistoricProcessInstanceQueryImpl) historicProcessInstanceQuery).listDeploymentIdMappings());
} return elementConfiguration; } protected BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) { return new MessageCorrelationBatchConfiguration( elementConfiguration.getIds(), elementConfiguration.getMappings(), messageName); } protected void writeUserOperationLog(CommandContext commandContext, int instancesCount) { List<PropertyChange> propChanges = new ArrayList<>(); propChanges.add(new PropertyChange("messageName", null, messageName)); propChanges.add(new PropertyChange("nrOfInstances", null, instancesCount)); propChanges.add(new PropertyChange("nrOfVariables", null, variables == null ? 0 : variables.size())); propChanges.add(new PropertyChange("async", null, true)); commandContext.getOperationLogManager() .logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_CORRELATE_MESSAGE, propChanges); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\CorrelateAllMessageBatchCmd.java
1
请完成以下Java代码
public class DefaultJobPriorityProvider extends DefaultPriorityProvider<JobDeclaration<?, ?>> { private final static JobExecutorLogger LOG = ProcessEngineLogger.JOB_EXECUTOR_LOGGER; @Override protected Long getSpecificPriority(ExecutionEntity execution, JobDeclaration<?, ?> param, String jobDefinitionId) { Long specificPriority = null; JobDefinitionEntity jobDefinition = getJobDefinitionFor(jobDefinitionId); if (jobDefinition != null) specificPriority = jobDefinition.getOverridingJobPriority(); if (specificPriority == null) { ParameterValueProvider priorityProvider = param.getJobPriorityProvider(); if (priorityProvider != null) { specificPriority = evaluateValueProvider(priorityProvider, execution, describeContext(param, execution)); } } return specificPriority; } @Override protected Long getProcessDefinitionPriority(ExecutionEntity execution, JobDeclaration<?, ?> jobDeclaration) { ProcessDefinitionImpl processDefinition = jobDeclaration.getProcessDefinition(); return getProcessDefinedPriority(processDefinition, BpmnParse.PROPERTYNAME_JOB_PRIORITY, execution, describeContext(jobDeclaration, execution)); } protected JobDefinitionEntity getJobDefinitionFor(String jobDefinitionId) { if (jobDefinitionId != null) { return Context.getCommandContext()
.getJobDefinitionManager() .findById(jobDefinitionId); } else { return null; } } protected Long getActivityPriority(ExecutionEntity execution, JobDeclaration<?, ?> jobDeclaration) { if (jobDeclaration != null) { ParameterValueProvider priorityProvider = jobDeclaration.getJobPriorityProvider(); if (priorityProvider != null) { return evaluateValueProvider(priorityProvider, execution, describeContext(jobDeclaration, execution)); } } return null; } @Override protected void logNotDeterminingPriority(ExecutionEntity execution, Object value, ProcessEngineException e) { LOG.couldNotDeterminePriority(execution, value, e); } protected String describeContext(JobDeclaration<?, ?> jobDeclaration, ExecutionEntity executionEntity) { return "Job " + jobDeclaration.getActivityId() + "/" + jobDeclaration.getJobHandlerType() + " instantiated " + "in context of " + executionEntity; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\DefaultJobPriorityProvider.java
1
请完成以下Java代码
public void setS_ResourceType_ID (int S_ResourceType_ID) { if (S_ResourceType_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ResourceType_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ResourceType_ID, Integer.valueOf(S_ResourceType_ID)); } /** Get Ressourcenart. @return Ressourcenart */ @Override public int getS_ResourceType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Endzeitpunkt. @param TimeSlotEnd Time when timeslot ends */ @Override public void setTimeSlotEnd (java.sql.Timestamp TimeSlotEnd) { set_Value (COLUMNNAME_TimeSlotEnd, TimeSlotEnd); } /** Get Endzeitpunkt. @return Time when timeslot ends */ @Override public java.sql.Timestamp getTimeSlotEnd () { return (java.sql.Timestamp)get_Value(COLUMNNAME_TimeSlotEnd); } /** Set Startzeitpunkt. @param TimeSlotStart Time when timeslot starts */ @Override public void setTimeSlotStart (java.sql.Timestamp TimeSlotStart) { set_Value (COLUMNNAME_TimeSlotStart, TimeSlotStart); } /** Get Startzeitpunkt. @return Time when timeslot starts */
@Override public java.sql.Timestamp getTimeSlotStart () { return (java.sql.Timestamp)get_Value(COLUMNNAME_TimeSlotStart); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceType.java
1
请完成以下Java代码
public String getFixedValue() { return fixedValue; } public void setFixedValue(String fixedValue) { this.fixedValue = fixedValue; } public String getJsonField() { return jsonField; } public void setJsonField(String jsonField) { this.jsonField = jsonField; } public String getJsonPointerExpression() { return jsonPointerExpression; }
public void setJsonPointerExpression(String jsonPointerExpression) { this.jsonPointerExpression = jsonPointerExpression; } public String getXmlXPathExpression() { return xmlXPathExpression; } public void setXmlXPathExpression(String xmlXPathExpression) { this.xmlXPathExpression = xmlXPathExpression; } public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\ChannelEventKeyDetection.java
1
请在Spring Boot框架中完成以下Java代码
public DataResponse<GroupResponse> getGroups(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { GroupQuery query = identityService.createGroupQuery(); if (allRequestParams.containsKey("id")) { query.groupId(allRequestParams.get("id")); } if (allRequestParams.containsKey("name")) { query.groupName(allRequestParams.get("name")); } if (allRequestParams.containsKey("nameLike")) { query.groupNameLike(allRequestParams.get("nameLike")); } if (allRequestParams.containsKey("type")) { query.groupType(allRequestParams.get("type")); } if (allRequestParams.containsKey("member")) { query.groupMember(allRequestParams.get("member")); } if (restApiInterceptor != null) { restApiInterceptor.accessGroupInfoWithQuery(query); } return paginateList(allRequestParams, query, "id", properties, restResponseFactory::createGroupResponseList); } @ApiOperation(value = "Create a group", tags = { "Groups" }, code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the group was created."), @ApiResponse(code = 400, message = "Indicates the id of the group was missing.") }) @PostMapping(value = "/groups", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public GroupResponse createGroup(@RequestBody GroupRequest groupRequest) { if (groupRequest.getId() == null) { throw new FlowableIllegalArgumentException("Id cannot be null."); }
// Check if a user with the given ID already exists so we return a CONFLICT if (identityService.createGroupQuery().groupId(groupRequest.getId()).count() > 0) { throw new FlowableConflictException("A group with id '" + groupRequest.getId() + "' already exists."); } Group created = identityService.newGroup(groupRequest.getId()); created.setId(groupRequest.getId()); created.setName(groupRequest.getName()); created.setType(groupRequest.getType()); if (restApiInterceptor != null) { restApiInterceptor.createNewGroup(created); } identityService.saveGroup(created); return restResponseFactory.createGroupResponse(created); } }
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\group\GroupCollectionResource.java
2
请完成以下Java代码
public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public Integer getResourceMode() { return resourceMode; } public void setResourceMode(Integer resourceMode) { this.resourceMode = resourceMode; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public Double getCount() { return count; } public void setCount(Double count) { this.count = count; } public Long getInterval() { return interval; } public void setInterval(Long interval) { this.interval = interval; } public Integer getIntervalUnit() { return intervalUnit; } public void setIntervalUnit(Integer intervalUnit) { this.intervalUnit = intervalUnit;
} public Integer getControlBehavior() { return controlBehavior; } public void setControlBehavior(Integer controlBehavior) { this.controlBehavior = controlBehavior; } public Integer getBurst() { return burst; } public void setBurst(Integer burst) { this.burst = burst; } public Integer getMaxQueueingTimeoutMs() { return maxQueueingTimeoutMs; } public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; } public GatewayParamFlowItemVo getParamItem() { return paramItem; } public void setParamItem(GatewayParamFlowItemVo paramItem) { this.paramItem = paramItem; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\rule\AddFlowRuleReqVo.java
1
请完成以下Java代码
public class User { private Integer id; private String name; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-ajax\src\main\java\cn\lanqiao\springboot3\entity\User.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]"; }
// Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java
1
请完成以下Java代码
public static String readMultipleCharacters(Reader reader, int length) throws IOException { char[] buffer = new char[length]; int charactersRead = reader.read(buffer, 0, length); if (charactersRead != -1) { return new String(buffer, 0, charactersRead); } else { return ""; } } public static String readFile(String path) { FileReader fileReader = null; try { fileReader = new FileReader(path); return readAllCharactersOneByOne(fileReader); } catch (IOException e) { e.printStackTrace(); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace();
} } } return null; } public static String readFileUsingTryWithResources(String path) { try (FileReader fileReader = new FileReader(path)) { return readAllCharactersOneByOne(fileReader); } catch (IOException e) { e.printStackTrace(); } return null; } }
repos\tutorials-master\core-java-modules\core-java-io-apis-3\src\main\java\com\baeldung\filereader\FileReaderExample.java
1
请在Spring Boot框架中完成以下Java代码
public Object getTransientVariable(String variableName) { return null; } @Override public Map<String, Object> getTransientVariables() { return null; } @Override public void removeTransientVariableLocal(String variableName) { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void removeTransientVariablesLocal() { throw new UnsupportedOperationException("Empty object, no variables can be removed"); }
@Override public void removeTransientVariable(String variableName) { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void removeTransientVariables() { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public String getTenantId() { return null; } }
repos\flowable-engine-main\modules\flowable-variable-service-api\src\main\java\org\flowable\variable\api\delegate\EmptyVariableScope.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isIgnoreUnknownKeys() { return this.ignoreUnknownKeys; } public void setIgnoreUnknownKeys(boolean ignoreUnknownKeys) { this.ignoreUnknownKeys = ignoreUnknownKeys; } public boolean isEncodeDefaults() { return this.encodeDefaults; } public void setEncodeDefaults(boolean encodeDefaults) { this.encodeDefaults = encodeDefaults; } public boolean isExplicitNulls() { return this.explicitNulls; } public void setExplicitNulls(boolean explicitNulls) { this.explicitNulls = explicitNulls; } public boolean isCoerceInputValues() { return this.coerceInputValues; } public void setCoerceInputValues(boolean coerceInputValues) { this.coerceInputValues = coerceInputValues; } public boolean isAllowStructuredMapKeys() { return this.allowStructuredMapKeys; } public void setAllowStructuredMapKeys(boolean allowStructuredMapKeys) { this.allowStructuredMapKeys = allowStructuredMapKeys; } public boolean isAllowSpecialFloatingPointValues() { return this.allowSpecialFloatingPointValues; } public void setAllowSpecialFloatingPointValues(boolean allowSpecialFloatingPointValues) { this.allowSpecialFloatingPointValues = allowSpecialFloatingPointValues; } public String getClassDiscriminator() { return this.classDiscriminator; } public void setClassDiscriminator(String classDiscriminator) { this.classDiscriminator = classDiscriminator; } public ClassDiscriminatorMode getClassDiscriminatorMode() { return this.classDiscriminatorMode; } public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) { this.classDiscriminatorMode = classDiscriminatorMode; } public boolean isDecodeEnumsCaseInsensitive() { return this.decodeEnumsCaseInsensitive; } public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) { this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive; } public boolean isUseAlternativeNames() { return this.useAlternativeNames; } public void setUseAlternativeNames(boolean useAlternativeNames) {
this.useAlternativeNames = useAlternativeNames; } public boolean isAllowTrailingComma() { return this.allowTrailingComma; } public void setAllowTrailingComma(boolean allowTrailingComma) { this.allowTrailingComma = allowTrailingComma; } public boolean isAllowComments() { return this.allowComments; } public void setAllowComments(boolean allowComments) { this.allowComments = allowComments; } /** * Enum representing strategies for JSON property naming. The values correspond to * {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot * be directly referenced. */ public enum JsonNamingStrategy { /** * Snake case strategy. */ SNAKE_CASE, /** * Kebab case strategy. */ KEBAB_CASE } }
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
2
请完成以下Java代码
public BigDecimal getScrapProcessingFeeForPercentage(final BigDecimal percentage) { if (percentage.compareTo(new BigDecimal("10.00")) < 0) { return BigDecimal.ZERO; } else { return new BigDecimal("0.06"); } } @Override public BigDecimal getScrapPercentageTreshold() { return new BigDecimal("10.00"); } @Override public boolean isFeeForProducedMaterial(final I_M_Product product) { return M_PRODUCT_SORTING_OUT_FEE_VALUE.equals(product.getValue()); } @Override public BigDecimal getFeeForProducedMaterial(final I_M_Product m_Product, final BigDecimal percentage) { final List<BigDecimal> percentages = new ArrayList<>(feeProductPercentage2fee.keySet()); // iterating from first to 2nd-last for (int i = 0; i < percentages.size() - 1; i++) { final BigDecimal currentPercentage = percentages.get(i); final BigDecimal nextPercentage = percentages.get(i + 1); if (currentPercentage.compareTo(percentage) <= 0 && nextPercentage.compareTo(percentage) > 0) { // found it: 'percentage' is in the interval that starts with 'currentPercentage' return feeProductPercentage2fee.get(currentPercentage); } } final BigDecimal lastInterval = percentages.get(percentages.size() - 1); return feeProductPercentage2fee.get(lastInterval); } @Override public Currency getCurrency() { return currencyDAO.getByCurrencyCode(CURRENCY_ISO); } public static void setOverallNumberOfInvoicings(final int overallNumberOfInvoicings) { HardCodedQualityBasedConfig.overallNumberOfInvoicings = overallNumberOfInvoicings; } @Override public int getOverallNumberOfInvoicings()
{ return overallNumberOfInvoicings; } public static void setQualityAdjustmentActive(final boolean qualityAdjustmentOn) { HardCodedQualityBasedConfig.qualityAdjustmentsActive = qualityAdjustmentOn; } @Override public I_M_Product getRegularPPOrderProduct() { final IContextAware ctxAware = getContext(); return productPA.retrieveProduct(ctxAware.getCtx(), M_PRODUCT_REGULAR_PP_ORDER_VALUE, true, // throwExIfProductNotFound ctxAware.getTrxName()); } /** * @return the date that was set with {@link #setValidToDate(Timestamp)}, or falls back to "now plus 2 months". Never returns <code>null</code>. */ @Override public Timestamp getValidToDate() { if (validToDate == null) { return TimeUtil.addMonths(SystemTime.asDate(), 2); } return validToDate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\HardCodedQualityBasedConfig.java
1
请完成以下Java代码
public String getClassname () { return (String)get_Value(COLUMNNAME_Classname); } /** Set Validierungscode. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validierungscode. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Beschreibung. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitaets-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitaets-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () {
return (String)get_Value(COLUMNNAME_EntityType); } /** 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()); } /** Type AD_Reference_ID=101 */ public static final int TYPE_AD_Reference_ID=101; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Java = J */ public static final String TYPE_Java = "J"; /** Java-Script = E */ public static final String TYPE_Java_Script = "E"; /** Composite = C */ public static final String TYPE_Composite = "C"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule.java
1
请完成以下Java代码
public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueDate (final @Nullable java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); } @Override public java.sql.Timestamp getValueDate() { return get_ValueAsTimestamp(COLUMNNAME_ValueDate); } @Override public void setValueDateInitial (final @Nullable java.sql.Timestamp ValueDateInitial) { set_Value (COLUMNNAME_ValueDateInitial, ValueDateInitial); } @Override public java.sql.Timestamp getValueDateInitial() { return get_ValueAsTimestamp(COLUMNNAME_ValueDateInitial); } @Override public void setValueInitial (final @Nullable java.lang.String ValueInitial)
{ set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial); } @Override public java.lang.String getValueInitial() { return get_ValueAsString(COLUMNNAME_ValueInitial); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial) { set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial); } @Override public BigDecimal getValueNumberInitial() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Attribute.java
1
请完成以下Java代码
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { if (isUserLogged()) { addToModelUserDetails(request.getSession()); } return true; } /** * Executed before after handler is executed. If view is a redirect view, we don't need to execute postHandle **/ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception { if (model != null && !isRedirectView(model)) { if (isUserLogged()) { addToModelUserDetails(model); } } } /** * Used before model is generated, based on session */ private void addToModelUserDetails(HttpSession session) { log.info("================= addToModelUserDetails ============================"); String loggedUsername = SecurityContextHolder.getContext() .getAuthentication() .getName(); session.setAttribute("username", loggedUsername); log.info("user(" + loggedUsername + ") session : " + session); log.info("================= addToModelUserDetails ============================"); } /** * Used when model is available */
private void addToModelUserDetails(ModelAndView model) { log.info("================= addToModelUserDetails ============================"); String loggedUsername = SecurityContextHolder.getContext() .getAuthentication() .getName(); model.addObject("loggedUsername", loggedUsername); log.trace("session : " + model.getModel()); log.info("================= addToModelUserDetails ============================"); } public static boolean isRedirectView(ModelAndView mv) { String viewName = mv.getViewName(); if (viewName.startsWith("redirect:/")) { return true; } View view = mv.getView(); return (view != null && view instanceof SmartView && ((SmartView) view).isRedirectView()); } public static boolean isUserLogged() { try { return !SecurityContextHolder.getContext() .getAuthentication() .getName() .equals("anonymousUser"); } catch (Exception e) { return false; } } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\web\interceptor\UserInterceptor.java
1