instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Map<String, Object> getDummyScalesInfo() { assertLoggedIn(); final ImmutableList<String> devicesInfo = DummyDeviceConfigPool.getAllDevices() .stream() .map(DeviceConfig::toString) .collect(ImmutableList.toImmutableList()); return ImmutableMap.<String, Object>builder() .put("config", getConfigInfo()) .put("devices", devicesInfo) .build(); } @GetMapping("/config") public Map<String, Object> configScales( @RequestParam(name = "enabled") final boolean enabled, @RequestParam(name = "responseMinValue", required = false, defaultValue = "-1") final int responseMinValue, @RequestParam(name = "responseMaxValue", required = false, defaultValue = "-1") final int responseMaxValue) { assertLoggedIn(); setEnabled(enabled); if (responseMinValue > 0) { DummyDeviceConfigPool.setResponseMinValue(responseMinValue); } if (responseMaxValue > 0) { DummyDeviceConfigPool.setResponseMaxValue(responseMaxValue); } return getConfigInfo(); } private void setEnabled(final boolean enabled) { DummyDeviceConfigPool.setEnabled(enabled);
deviceAccessorsHubFactory.cacheReset(); } private Map<String, Object> getConfigInfo() { return ImmutableMap.<String, Object>builder() .put("enabled", DummyDeviceConfigPool.isEnabled()) .put("responseMinValue", DummyDeviceConfigPool.getResponseMinValue().doubleValue()) .put("responseMaxValue", DummyDeviceConfigPool.getResponseMaxValue().doubleValue()) .build(); } @GetMapping("/addOrUpdate") public void addScale( @RequestParam("deviceName") final String deviceName, @RequestParam("attributes") final String attributesStr, @RequestParam(name = "onlyForWarehouseIds", required = false) final String onlyForWarehouseIdsStr) { assertLoggedIn(); final List<AttributeCode> attributes = CollectionUtils.ofCommaSeparatedList(attributesStr, AttributeCode::ofString); final List<WarehouseId> onlyForWarehouseIds = RepoIdAwares.ofCommaSeparatedList(onlyForWarehouseIdsStr, WarehouseId.class); DummyDeviceConfigPool.addDevice(DummyDeviceAddRequest.builder() .deviceName(deviceName) .assignedAttributeCodes(attributes) .onlyWarehouseIds(onlyForWarehouseIds) .build()); setEnabled(true); } @GetMapping("/removeDevice") public void addScale( @RequestParam("deviceName") final String deviceName) { assertLoggedIn(); DummyDeviceConfigPool.removeDeviceByName(deviceName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.webui\src\main\java\de\metas\device\rest\DummyDevicesRestControllerTemplate.java
1
请完成以下Java代码
public NamePair getDirect(final IValidationContext evalCtx, Object key, boolean saveInCache, boolean cacheLocal) { return get(evalCtx, key); } // getDirect /** * Dispose - clear items w/o firing events */ public void dispose() { if (p_data != null) { p_data.clear(); } p_data = null; m_selectedObject = null; m_tempData = null; m_loaded = false; } // dispose /** * Wait until async Load Complete */ public void loadComplete() { } // loadComplete /** * Set lookup model as mandatory, use in loading data * @param flag */ public void setMandatory(boolean flag) { m_mandatory = flag; } /** * Is lookup model mandatory * @return boolean */ public boolean isMandatory() { return m_mandatory; } /** * Is this lookup model populated * @return boolean */ public boolean isLoaded() { return m_loaded;
} /** * Returns a list of parameters on which this lookup depends. * * Those parameters will be fetched from context on validation time. * * @return list of parameter names */ public Set<String> getParameters() { return ImmutableSet.of(); } /** * * @return evaluation context */ public IValidationContext getValidationContext() { return IValidationContext.NULL; } /** * Suggests a valid value for given value * * @param value * @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned */ public NamePair suggestValidValue(final NamePair value) { return null; } /** * Returns true if given <code>display</code> value was rendered for a not found item. * To be used together with {@link #getDisplay} methods. * * @param display * @return true if <code>display</code> contains not found markers */ public boolean isNotFoundDisplayValue(String display) { return false; } } // Lookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java
1
请完成以下Java代码
public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines) { for (final IHUTrxListener listener : listeners) { listener.afterTrxProcessed(trxHdrRef, trxLines); } } @Override public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { for (final IHUTrxListener listener : listeners) { listener.afterLoad(huContext, loadResults); } } @Override public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) {
for (final IHUTrxListener listener : listeners) { listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx); } } @Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onSplitTransaction(huContext, unloadTrx, loadTrx); } } @Override public String toString() { return "CompositeHUTrxListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java
1
请完成以下Java代码
public CaseFileItem newInstance(ModelTypeInstanceContext instanceContext) { return new CaseFileItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); multiplicityAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_MULTIPLICITY, MultiplicityEnum.class) .defaultValue(MultiplicityEnum.Unspecified) .build(); definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .qNameAttributeReference(CaseFileItemDefinition.class) .build(); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .namespace(CMMN10_NS) .idAttributeReference(CaseFileItem.class) .build();
sourceRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); targetRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); SequenceBuilder sequence = typeBuilder.sequence(); childrenChild = sequence.element(Children.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public JwtTokenFilter jwtTokenFilter() { return new JwtTokenFilter(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .cors() .and() .exceptionHandling().authenticationEntryPoint(new Http401AuthenticationEntryPoint("Unauthenticated")) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() .antMatchers(HttpMethod.GET, "/articles/feed").authenticated() .antMatchers(HttpMethod.POST, "/users", "/users/login").permitAll() .antMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags").permitAll() .anyRequest().authenticated();
http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); } @Bean public CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(asList("*")); configuration.setAllowedMethods(asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")); // setAllowCredentials(true) is important, otherwise: // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. configuration.setAllowCredentials(true); // setAllowedHeaders is important! Without it, OPTIONS preflight request // will fail with 403 Invalid CORS request configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type")); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\security\WebSecurityConfig.java
2
请完成以下Java代码
public class HistoricPlanItemInstanceEntityManagerImpl extends AbstractEngineEntityManager<CmmnEngineConfiguration, HistoricPlanItemInstanceEntity, HistoricPlanItemInstanceDataManager> implements HistoricPlanItemInstanceEntityManager { public HistoricPlanItemInstanceEntityManagerImpl(CmmnEngineConfiguration cmmnEngineConfiguration, HistoricPlanItemInstanceDataManager historicPlanItemInstanceDataManager) { super(cmmnEngineConfiguration, historicPlanItemInstanceDataManager); } @Override public HistoricPlanItemInstanceEntity create(PlanItemInstance planItemInstance) { return dataManager.create(planItemInstance); } @Override public HistoricPlanItemInstanceQuery createHistoricPlanItemInstanceQuery() { return new HistoricPlanItemInstanceQueryImpl(engineConfiguration.getCommandExecutor()); } @Override public List<HistoricPlanItemInstance> findByCaseDefinitionId(String caseDefinitionId) { return dataManager.findByCaseDefinitionId(caseDefinitionId); } @Override public List<HistoricPlanItemInstance> findByCriteria(HistoricPlanItemInstanceQuery query) { return dataManager.findByCriteria((HistoricPlanItemInstanceQueryImpl) query);
} @Override public long countByCriteria(HistoricPlanItemInstanceQuery query) { return dataManager.countByCriteria((HistoricPlanItemInstanceQueryImpl) query); } @Override public void bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(Collection<String> caseInstanceIds) { dataManager.bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(caseInstanceIds); } @Override public void deleteHistoricPlanItemInstancesForNonExistingCaseInstances() { dataManager.deleteHistoricPlanItemInstancesForNonExistingCaseInstances(); } @Override public List<HistoricPlanItemInstance> findWithVariablesByCriteria(HistoricPlanItemInstanceQueryImpl historicPlanItemInstanceQuery) { return dataManager.findWithVariablesByCriteria(historicPlanItemInstanceQuery); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricPlanItemInstanceEntityManagerImpl.java
1
请完成以下Java代码
public Quantity getQtyToDeliver(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule schedule) { return shipmentScheduleBL.getQtyToDeliver(schedule); } @Override public Quantity getQtyScheduledForPicking(@NonNull final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentScheduleRecord) { return shipmentScheduleBL.getQtyScheduledForPicking(shipmentScheduleRecord); } @Override public Quantity getQtyRemainingToScheduleForPicking(@NonNull final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentScheduleRecord) { return shipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord); } @Override public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) {return;} final IShipmentScheduleInvalidateBL invalidSchedulesService = Services.get(IShipmentScheduleInvalidateBL.class); invalidSchedulesService.flagForRecompute(shipmentScheduleIds); } @Override public ShipmentScheduleLoadingCache<I_M_ShipmentSchedule> newLoadingCache()
{ return shipmentScheduleBL.newLoadingCache(I_M_ShipmentSchedule.class); } @Nullable @Override public ProjectId extractSingleProjectIdOrNull(@NonNull final List<ShipmentScheduleWithHU> candidates) { final Set<ProjectId> projectIdsFromShipmentSchedules = candidates.stream() .map(ShipmentScheduleWithHU::getProjectId) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (projectIdsFromShipmentSchedules.size() == 1) { return projectIdsFromShipmentSchedules.iterator().next(); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\HUShipmentScheduleBL.java
1
请完成以下Java代码
protected boolean closeNative() { // Assume that at this point the transaction is no longer active because it was never active or because it was commit/rollback first. assertNotActive("Transaction shall not be active at this point"); if (!activeSavepoints.isEmpty()) { throw new TrxException("Inconsistent transaction state: We were asked for close() but we still have active savepoints" + "\n Trx: " + this + "\n Active savepoints: " + activeSavepoints); } setTrxStatus(TrxStatus.CLOSED); return true; } protected final void assertActive(final String errmsg) { assertActive(true, errmsg); } public List<ITrxSavepoint> getActiveSavepoints() { return ImmutableList.copyOf(activeSavepoints); } protected final void assertNotActive(final String errmsg) { assertActive(false, errmsg); } protected void assertActive(final boolean activeExpected, final String errmsg) { final boolean activeActual = isActive(); if (activeActual != activeExpected) { final String errmsgToUse = "Inconsistent transaction state: " + errmsg; throw new TrxException(errmsgToUse + "\n Expected active: " + activeExpected + "\n Actual active: " + activeActual + "\n Trx: " + this); } } private TrxStatus getTrxStatus() { return trxStatus; } private void setTrxStatus(final TrxStatus trxStatus) { final String detailMsg = null; setTrxStatus(trxStatus, detailMsg); }
private void setTrxStatus(final TrxStatus trxStatus, @Nullable final String detailMsg) { final TrxStatus trxStatusOld = this.trxStatus; this.trxStatus = trxStatus; // Log it if (debugLog != null) { final StringBuilder msg = new StringBuilder(); msg.append(trxStatusOld).append("->").append(trxStatus); if (!Check.isEmpty(detailMsg, true)) { msg.append(" (").append(detailMsg).append(")"); } logTrxAction(msg.toString()); } } private void logTrxAction(final String message) { if (debugLog == null) { return; } debugLog.add(message); logger.info("{}: trx action: {}", getTrxName(), message); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrx.java
1
请完成以下Java代码
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { olCand.setM_HU_PI_Item_Product_Override_ID(huPiItemProductId); values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return olCand.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return olCandEffectiveValuesBL.getEffectiveUomId(olCand).getRepoId(); } @Override public void setC_UOM_ID(final int uomId) { values.setUomId(UomId.ofRepoIdOrNull(uomId)); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { olCand.setPrice_UOM_Internal_ID(uomId); } } @Override public BigDecimal getQtyTU() { return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand)); }
@Override public void setQtyTU(final BigDecimal qtyPacks) { values.setQtyTU(qtyPacks); } @Override public int getC_BPartner_ID() { final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand); return BPartnerId.toRepoId(bpartnerId); } @Override public void setC_BPartner_ID(final int partnerId) { olCand.setC_BPartner_Override_ID(partnerId); values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId)); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public ZonedDateTime getBirthDate() {
return birthDate; } public void setBirthDate(ZonedDateTime birthDate) { this.birthDate = birthDate; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\simple\model\User.java
1
请完成以下Java代码
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 getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Map<String, Attribute> getAttributes() { return attributes; } public void setAttributes(Map<String, Attribute> attributes) { this.attributes = attributes; } }
repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphqlreturnmap\entity\Product.java
1
请完成以下Java代码
public class WEBUI_M_HU_Clearance extends HUEditorProcessTemplate implements IProcessPrecondition { private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); @Param(parameterName = I_M_HU.COLUMNNAME_ClearanceStatus, mandatory = true) private String clearanceStatus; @Param(parameterName = I_M_HU.COLUMNNAME_ClearanceNote) private String clearanceNote; @Param(parameterName = I_M_HU.COLUMNNAME_ClearanceDate) private Instant clearanceDate; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception
{ final ClearanceStatusInfo clearanceStatusInfo = ClearanceStatusInfo.builder() .clearanceStatus(ClearanceStatus.ofCode(clearanceStatus)) .clearanceNote(clearanceNote) .clearanceDate(InstantAndOrgId.ofInstant(clearanceDate, getOrgId())) .build(); streamSelectedHUs(HUEditorRowFilter.Select.ALL) .forEach(hu -> handlingUnitsBL.setClearanceStatusRecursively(HuId.ofRepoId(hu.getM_HU_ID()), clearanceStatusInfo)); final HUEditorView view = getView(); view.invalidateAll(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Clearance.java
1
请完成以下Java代码
public int getCM_Container_URL_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_URL_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Last Result. @param Last_Result Contains data on the last check result */ public void setLast_Result (String Last_Result) { set_Value (COLUMNNAME_Last_Result, Last_Result); } /** Get Last Result. @return Contains data on the last check result */ public String getLast_Result () { return (String)get_Value(COLUMNNAME_Last_Result); } /** Set Status. @param Status
Status of the currently running check */ public void setStatus (String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ public String getStatus () { return (String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_URL.java
1
请在Spring Boot框架中完成以下Java代码
private ImmutableSet<WarehouseId> getIssueFromWarehouseIds() { return ppOrderBOMBL.getIssueFromWarehouseIds(manufacturingWarehouseId); } private @NonNull ImmutableSet<HuId> getPPOrderSourceHUIds() { if (_ppOrderSourceHUIds == null) { _ppOrderSourceHUIds = ppOrderSourceHUService.getSourceHUIds(ppOrderId); } return _ppOrderSourceHUIds; } @NonNull private SourceHUsCollection retrieveActiveSourceHusFromWarehouse(@NonNull final ProductId productId) { final List<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveMatchingSourceHuMarkers( SourceHUsService.MatchingSourceHusQuery.builder() .productId(productId) .warehouseIds(getIssueFromWarehouseIds()) .build() ); final List<I_M_HU> hus = handlingUnitsDAO.getByIds(extractHUIdsFromSourceHUs(sourceHUs)); return SourceHUsCollection.builder() .husThatAreFlaggedAsSource(ImmutableList.copyOf(hus)) .sourceHUs(sourceHUs) .build(); } @NonNull private SourceHUsCollection retrieveActiveSourceHusForHus(@NonNull final ProductId productId)
{ final ImmutableList<I_M_HU> activeHUsMatchingProduct = handlingUnitsDAO.createHUQueryBuilder() .setOnlyActiveHUs(true) .setAllowEmptyStorage() .addOnlyHUIds(getPPOrderSourceHUIds()) .addOnlyWithProductId(productId) .createQuery() .listImmutable(I_M_HU.class); final ImmutableList<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveSourceHuMarkers(extractHUIdsFromHUs(activeHUsMatchingProduct)); return SourceHUsCollection.builder() .husThatAreFlaggedAsSource(activeHUsMatchingProduct) .sourceHUs(sourceHUs) .build(); } private static ImmutableSet<HuId> extractHUIdsFromSourceHUs(final Collection<I_M_Source_HU> sourceHUs) { return sourceHUs.stream().map(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID())).collect(ImmutableSet.toImmutableSet()); } private static ImmutableSet<HuId> extractHUIdsFromHUs(final Collection<I_M_HU> hus) { return hus.stream().map(I_M_HU::getM_HU_ID).map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\SourceHUsCollectionProvider.java
2
请完成以下Java代码
public class Author { private String name; private int relatedArticleId; public Author(String name, int relatedArticleId) { this.name = name; this.relatedArticleId = relatedArticleId; } public int getRelatedArticleId() { return relatedArticleId; } public void setRelatedArticleId(int relatedArticleId) { this.relatedArticleId = relatedArticleId;
} public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "[name: " + name + ", relatedId: " + relatedArticleId + "]"; } }
repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\spliterator\Author.java
1
请在Spring Boot框架中完成以下Java代码
public static class V2 { /** * Default dimensions that are added to all metrics in the form of key-value * pairs. These are overwritten by Micrometer tags if they use the same key. */ private @Nullable Map<String, String> defaultDimensions; /** * Whether to enable Dynatrace metadata export. */ private boolean enrichWithDynatraceMetadata = true; /** * Prefix string that is added to all exported metrics. */ private @Nullable String metricKeyPrefix; /** * Whether to fall back to the built-in micrometer instruments for Timer and * DistributionSummary. */ private boolean useDynatraceSummaryInstruments = true; /** * Whether to export meter metadata (unit and description) to the Dynatrace * backend. */ private boolean exportMeterMetadata = true; public @Nullable Map<String, String> getDefaultDimensions() { return this.defaultDimensions; } public void setDefaultDimensions(@Nullable Map<String, String> defaultDimensions) { this.defaultDimensions = defaultDimensions; } public boolean isEnrichWithDynatraceMetadata() { return this.enrichWithDynatraceMetadata; }
public void setEnrichWithDynatraceMetadata(Boolean enrichWithDynatraceMetadata) { this.enrichWithDynatraceMetadata = enrichWithDynatraceMetadata; } public @Nullable String getMetricKeyPrefix() { return this.metricKeyPrefix; } public void setMetricKeyPrefix(@Nullable String metricKeyPrefix) { this.metricKeyPrefix = metricKeyPrefix; } public boolean isUseDynatraceSummaryInstruments() { return this.useDynatraceSummaryInstruments; } public void setUseDynatraceSummaryInstruments(boolean useDynatraceSummaryInstruments) { this.useDynatraceSummaryInstruments = useDynatraceSummaryInstruments; } public boolean isExportMeterMetadata() { return this.exportMeterMetadata; } public void setExportMeterMetadata(boolean exportMeterMetadata) { this.exportMeterMetadata = exportMeterMetadata; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatraceProperties.java
2
请完成以下Java代码
public class PlainPrintingQueueSource extends AbstractPrintingQueueSource { @Getter private final PrintingQueueProcessingInfo processingInfo; private final I_C_Printing_Queue item; private final Iterator<I_C_Printing_Queue> relatedItems; public PlainPrintingQueueSource( @NonNull final I_C_Printing_Queue item, @NonNull final Iterator<I_C_Printing_Queue> relatedItems, @NonNull final PrintingQueueProcessingInfo processingInfo) { this.item = item; this.relatedItems = relatedItems; this.processingInfo = processingInfo; } @Override public Iterator<I_C_Printing_Queue> createItemsIterator() { return new SingletonIterator<>(item); } /** * @return empty iterator. */
@Override public Iterator<I_C_Printing_Queue> createRelatedItemsIterator(@NonNull final I_C_Printing_Queue item) { return relatedItems; } /** * @return ITrx#TRXNAME_ThreadInherited */ @Override public String getTrxName() { return ITrx.TRXNAME_ThreadInherited; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PlainPrintingQueueSource.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_DirectDebit[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Amount. @param Amount Amount in a defined currency */ public void setAmount (String Amount) { throw new IllegalArgumentException ("Amount is virtual column"); } /** Get Amount. @return Amount in a defined currency */ public String getAmount () { return (String)get_Value(COLUMNNAME_Amount); } /** Set Bank statement line. @param C_BankStatementLine_ID Line on a statement from this Bank */ public void setC_BankStatementLine_ID (int C_BankStatementLine_ID) { if (C_BankStatementLine_ID < 1) set_Value (COLUMNNAME_C_BankStatementLine_ID, null); else set_Value (COLUMNNAME_C_BankStatementLine_ID, Integer.valueOf(C_BankStatementLine_ID)); } /** Get Bank statement line. @return Line on a statement from this Bank */ public int getC_BankStatementLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_DirectDebit_ID. @param C_DirectDebit_ID C_DirectDebit_ID */ public void setC_DirectDebit_ID (int C_DirectDebit_ID) { if (C_DirectDebit_ID < 1) throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory."); set_ValueNoCheck (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID)); }
/** Get C_DirectDebit_ID. @return C_DirectDebit_ID */ public int getC_DirectDebit_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Dtafile. @param Dtafile Copy of the *.dta stored as plain text */ public void setDtafile (String Dtafile) { set_Value (COLUMNNAME_Dtafile, Dtafile); } /** Get Dtafile. @return Copy of the *.dta stored as plain text */ public String getDtafile () { return (String)get_Value(COLUMNNAME_Dtafile); } /** Set IsRemittance. @param IsRemittance IsRemittance */ public void setIsRemittance (boolean IsRemittance) { set_Value (COLUMNNAME_IsRemittance, Boolean.valueOf(IsRemittance)); } /** Get IsRemittance. @return IsRemittance */ public boolean isRemittance () { Object oo = get_Value(COLUMNNAME_IsRemittance); 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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebit.java
1
请完成以下Java代码
private GroupType createAndAddGroupToBuffer(@NonNull final Object itemHashKey, @NonNull final ItemType item) { // We put a null value to map (before actually creating the group), // to make sure the previous groups are closed before the new group is actually created _itemHashKey2group.put(itemHashKey, null); final GroupType group = createGroup(itemHashKey, item); _itemHashKey2group.put(itemHashKey, group); _countGroups++; return group; } private void closeGroupAndCollect(final GroupType group) { closeGroup(group); if (closedGroupsCollector != null) { closedGroupsCollector.add(group); } } /** * Close all groups from buffer. As a result, after this call the groups buffer will be empty. */ public final void closeAllGroups() { final GroupType exceptGroup = null; // no exception closeAllGroupsExcept(exceptGroup); } /** * Close all groups, but not the last used one. Last used one is considered that group where we added last item. */ public final void closeAllGroupExceptLastUsed() { closeAllGroupsExcept(_lastGroupUsed); } /** * Close all groups. * * @param exceptGroup optional group to except from closing */ private void closeAllGroupsExcept(@Nullable final GroupType exceptGroup) { final Iterator<GroupType> groups = _itemHashKey2group.values().iterator(); while (groups.hasNext()) { final GroupType group = groups.next(); if (group == null)
{ continue; } // Skip the excepted group if (group == exceptGroup) { continue; } closeGroupAndCollect(group); groups.remove(); } } /** * @return how many groups were created */ public final int getGroupsCount() { return _countGroups; } /** * @return how many items were added */ public final int getItemsCount() { return _countItems; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MapReduceAggregator.java
1
请完成以下Java代码
public org.compiere.model.I_M_Attribute getM_Attribute() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class); } @Override public void setM_Attribute(org.compiere.model.I_M_Attribute M_Attribute) { set_ValueFromPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class, M_Attribute); } /** Set Merkmal. @param M_Attribute_ID Produkt-Merkmal */ @Override public void setM_Attribute_ID (int M_Attribute_ID) { if (M_Attribute_ID < 1) set_Value (COLUMNNAME_M_Attribute_ID, null); else set_Value (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID)); } /** Get Merkmal. @return Produkt-Merkmal */ @Override public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MKTG_ContactPerson_Attribute. @param MKTG_ContactPerson_Attribute_ID MKTG_ContactPerson_Attribute */ @Override public void setMKTG_ContactPerson_Attribute_ID (int MKTG_ContactPerson_Attribute_ID) { if (MKTG_ContactPerson_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_Attribute_ID, Integer.valueOf(MKTG_ContactPerson_Attribute_ID)); }
/** Get MKTG_ContactPerson_Attribute. @return MKTG_ContactPerson_Attribute */ @Override public int getMKTG_ContactPerson_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); } @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_Attribute.java
1
请完成以下Java代码
public GraphQlResponse execute(GraphQlRequest request) { Map<String, Object> body = this.restClient.post() .contentType(this.contentType) .accept(MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE) .body(request.toMap()) .exchange((httpRequest, httpResponse) -> { if (httpResponse.getStatusCode().equals(HttpStatus.OK)) { return httpResponse.bodyTo(MAP_TYPE); } else if (httpResponse.getStatusCode().is4xxClientError() && isGraphQlResponse(httpResponse)) { return httpResponse.bodyTo(MAP_TYPE); } else if (httpResponse.getStatusCode().is4xxClientError()) { throw HttpClientErrorException.create(httpResponse.getStatusText(), httpResponse.getStatusCode(), httpResponse.getStatusText(), httpResponse.getHeaders(), getBody(httpResponse), getCharset(httpResponse)); } else { throw HttpServerErrorException.create(httpResponse.getStatusText(), httpResponse.getStatusCode(), httpResponse.getStatusText(), httpResponse.getHeaders(), getBody(httpResponse), getCharset(httpResponse)); } }); return new ResponseMapGraphQlResponse((body != null) ? body : Collections.emptyMap()); } private static boolean isGraphQlResponse(ClientHttpResponse clientResponse) { return MediaTypes.APPLICATION_GRAPHQL_RESPONSE .isCompatibleWith(clientResponse.getHeaders().getContentType());
} private static byte[] getBody(HttpInputMessage message) { try { return FileCopyUtils.copyToByteArray(message.getBody()); } catch (IOException ignore) { } return new byte[0]; } private static @Nullable Charset getCharset(HttpMessage response) { HttpHeaders headers = response.getHeaders(); MediaType contentType = headers.getContentType(); return (contentType != null) ? contentType.getCharset() : null; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\HttpSyncGraphQlTransport.java
1
请完成以下Java代码
static class ActiveMQDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements ActiveMQConnectionDetails { private final ActiveMQClassicEnvironment environment; private final String brokerUrl; protected ActiveMQDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new ActiveMQClassicEnvironment(service.env()); this.brokerUrl = "tcp://" + service.host() + ":" + service.ports().get(ACTIVEMQ_PORT); } @Override public String getBrokerUrl() { return this.brokerUrl;
} @Override public @Nullable String getUser() { return this.environment.getUser(); } @Override public @Nullable String getPassword() { return this.environment.getPassword(); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\docker\compose\ActiveMQClassicDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public String getTenantIdLike() { return tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getActivePlanItemDefinitionId() { return activePlanItemDefinitionId; } public Set<String> getActivePlanItemDefinitionIds() { return activePlanItemDefinitionIds; } public String getInvolvedUser() { return involvedUser; } public IdentityLinkQueryObject getInvolvedUserIdentityLink() { return involvedUserIdentityLink; } public Set<String> getInvolvedGroups() { return involvedGroups; } public IdentityLinkQueryObject getInvolvedGroupIdentityLink() { return involvedGroupIdentityLink; } public boolean isIncludeCaseVariables() { return includeCaseVariables; } public Collection<String> getVariableNamesToInclude() { return variableNamesToInclude; } public List<HistoricCaseInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public String getDeploymentId() { return deploymentId;
} public List<String> getDeploymentIds() { return deploymentIds; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public boolean isNeedsCaseDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(HistoricCaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName()); } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) { this.safeCaseInstanceIds = safeCaseInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricCaseInstanceQueryImpl.java
1
请完成以下Java代码
public boolean checkRateLimit(LimitedApi api, TenantId tenantId) { return checkRateLimit(api, tenantId, tenantId); } @Override public boolean checkRateLimit(LimitedApi api, TenantId tenantId, Object level) { return checkRateLimit(api, tenantId, level, false); } @Override public boolean checkRateLimit(LimitedApi api, TenantId tenantId, Object level, boolean ignoreTenantNotFound) { if (tenantId.isSysTenantId()) { return true; } TenantProfile tenantProfile = tenantProfileProvider.get(tenantId); if (tenantProfile == null) { if (ignoreTenantNotFound) { return true; } else { throw new TenantProfileNotFoundException(tenantId); } } String rateLimitConfig = tenantProfile.getProfileConfiguration() .map(api::getLimitConfig).orElse(null); boolean success = checkRateLimit(api, level, rateLimitConfig); if (!success) { notificationRuleProcessor.process(RateLimitsTrigger.builder() .tenantId(tenantId) .api(api) .limitLevel(level instanceof EntityId ? (EntityId) level : tenantId) .limitLevelEntityName(null) .build()); } return success; } @Override public boolean checkRateLimit(LimitedApi api, Object level, String rateLimitConfig) { RateLimitKey key = new RateLimitKey(api, level); if (StringUtils.isEmpty(rateLimitConfig)) { rateLimits.invalidate(key); return true; } log.trace("[{}] Checking rate limit for {} ({})", level, api, rateLimitConfig);
TbRateLimits rateLimit = rateLimits.asMap().compute(key, (k, limit) -> { if (limit == null || !limit.getConfiguration().equals(rateLimitConfig)) { limit = new TbRateLimits(rateLimitConfig, api.isRefillRateLimitIntervally()); log.trace("[{}] Created new rate limit bucket for {} ({})", level, api, rateLimitConfig); } return limit; }); boolean success = rateLimit.tryConsume(); if (!success) { log.debug("[{}] Rate limit exceeded for {} ({})", level, api, rateLimitConfig); } return success; } @Override public void cleanUp(LimitedApi api, Object level) { RateLimitKey key = new RateLimitKey(api, level); rateLimits.invalidate(key); } @Data(staticConstructor = "of") private static class RateLimitKey { private final LimitedApi api; private final Object level; } }
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\limits\DefaultRateLimitService.java
1
请完成以下Java代码
public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public boolean isSkipSubprocesses() { return skipSubprocesses;
} public void setSkipSubprocesses(Boolean skipSubprocesses) { this.skipSubprocesses = skipSubprocesses; } public boolean isSkipIoMappings() { return skipIoMappings; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\batch\DeleteProcessInstancesDto.java
1
请完成以下Java代码
public <T> T copyToNew(final Class<T> modelClass) { final Object fromModel = getFrom(); final Properties ctx = InterfaceWrapperHelper.getCtx(fromModel); final T toModel = InterfaceWrapperHelper.create(ctx, modelClass, ITrx.TRXNAME_ThreadInherited); setTo(toModel); copy(); return toModel; } @Override public IModelCopyHelper setFrom(final Object fromModel) { this._fromModel = fromModel; this._fromModelAccessor = null; return this; } private final IModelInternalAccessor getFromAccessor() { if (_fromModelAccessor == null) { return InterfaceWrapperHelper.getModelInternalAccessor(getFrom()); } return _fromModelAccessor; } private Object getFrom() { Check.assumeNotNull(_fromModel, "_fromModel not null"); return _fromModel; } @Override public IModelCopyHelper setTo(final Object toModel) {
this._toModel = toModel; this._toModelAccessor = null; return this; } private final IModelInternalAccessor getToAccessor() { if (_toModelAccessor == null) { Check.assumeNotNull(_toModel, "_toModel not null"); _toModelAccessor = InterfaceWrapperHelper.getModelInternalAccessor(_toModel); } return _toModelAccessor; } public final boolean isSkipCalculatedColumns() { return _skipCalculatedColumns; } @Override public IModelCopyHelper setSkipCalculatedColumns(boolean skipCalculatedColumns) { this._skipCalculatedColumns = skipCalculatedColumns; return this; } @Override public IModelCopyHelper addTargetColumnNameToSkip(final String columnName) { targetColumnNamesToSkip.add(columnName); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\model\util\ModelCopyHelper.java
1
请完成以下Java代码
public String getResultVariable() { return resultVariable; } public void setResultVariable(String resultVariable) { this.resultVariable = resultVariable; } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public boolean isAutoStoreVariables() { return autoStoreVariables; } public void setAutoStoreVariables(boolean autoStoreVariables) { this.autoStoreVariables = autoStoreVariables; } public boolean isDoNotIncludeVariables() { return doNotIncludeVariables; } public void setDoNotIncludeVariables(boolean doNotIncludeVariables) { this.doNotIncludeVariables = doNotIncludeVariables; } @Override public List<IOParameter> getInParameters() { return inParameters; } @Override public void addInParameter(IOParameter inParameter) { if (inParameters == null) { inParameters = new ArrayList<>(); } inParameters.add(inParameter); }
@Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public ScriptTask clone() { ScriptTask clone = new ScriptTask(); clone.setValues(this); return clone; } public void setValues(ScriptTask otherElement) { super.setValues(otherElement); setScriptFormat(otherElement.getScriptFormat()); setScript(otherElement.getScript()); setResultVariable(otherElement.getResultVariable()); setSkipExpression(otherElement.getSkipExpression()); setAutoStoreVariables(otherElement.isAutoStoreVariables()); setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables()); inParameters = null; if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { inParameters = new ArrayList<>(); for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java
1
请完成以下Java代码
public boolean isAvailableForLocator(@NonNull final LocatorId locatorId) { if (!isAvailableForWarehouse(locatorId.getWarehouseId())) { return false; } final ImmutableSet<LocatorId> assignedLocatorIds = deviceConfig.getAssignedLocatorIds(); return assignedLocatorIds.isEmpty() || assignedLocatorIds.contains(locatorId); } public synchronized BigDecimal acquireValue() { logger.debug("This: {}, Device: {}; Request: {}", this, device, request); final ISingleValueResponse response = device.accessDevice(request); logger.debug("Device {}; Response: {}", device, response); return response.getSingleValue(); } public synchronized void beforeAcquireValue(@NonNull final Map<String, List<String>> parameters) { final Map<String, List<String>> runParameters = Stream.concat(parameters.entrySet().stream(), getDeviceConfigParams().entrySet().stream()) .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
for (final BeforeAcquireValueHook hook : beforeHooks) { hook.run(RunParameters.of(runParameters), device, request); } } public Optional<String> getConfigValue(@NonNull final String parameterName) { return deviceConfig.getDeviceConfigParamValue(parameterName); } @NonNull private Map<String, List<String>> getDeviceConfigParams() { return deviceConfig.getDeviceConfigParams() .entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> ImmutableList.of(entry.getValue()) )); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceAccessor.java
1
请完成以下Java代码
public Map<Method, IModelMethodInfo> createModelMethodInfos(final Class<?> clazz) { final Map<Method, IModelMethodInfo> modelMethodsInfo = new HashMap<>(); for (final Method method : clazz.getMethods()) { final IModelMethodInfo modelMethodInfo = createModelMethodInfo(method); modelMethodsInfo.put(method, modelMethodInfo); } return modelMethodsInfo; } /** * Creates {@link IModelMethodInfo} for given <code>method</code> * * @param method * @return method info; never return null */ public IModelMethodInfo createModelMethodInfo(final Method method) { String methodName = method.getName(); final Class<?>[] parameters = method.getParameterTypes(); final int parametersCount = parameters == null ? 0 : parameters.length; if (methodName.startsWith("set") && parametersCount == 1) { final String propertyName = methodName.substring(3); // method name without "set" prefix final Class<?> paramType = parameters[0]; if (InterfaceWrapperHelper.isModelInterface(paramType)) { final ModelSetterMethodInfo methodInfo = new ModelSetterMethodInfo(method, paramType, propertyName + "_ID"); return methodInfo; } else { final ValueSetterMethodInfo methodInfo = new ValueSetterMethodInfo(method, propertyName); return methodInfo; } } else if (methodName.startsWith("get") && (parametersCount == 0)) { String propertyName = methodName.substring(3); if (InterfaceWrapperHelper.isModelInterface(method.getReturnType())) { final String columnName = propertyName + "_ID"; final ModelGetterMethodInfo methodInfo = new ModelGetterMethodInfo(method, columnName);
return methodInfo; } else { final ValueGetterMethodInfo methodInfo = new ValueGetterMethodInfo(method, propertyName); return methodInfo; } } else if (methodName.startsWith("is") && (parametersCount == 0)) { final String propertyName = methodName.substring(2); final BooleanGetterMethodInfo methodInfo = new BooleanGetterMethodInfo(method, propertyName); return methodInfo; } else if (methodName.equals("equals") && parametersCount == 1) { final EqualsMethodInfo methodInfo = new EqualsMethodInfo(method); return methodInfo; } else { final InvokeParentMethodInfo methodInfo = new InvokeParentMethodInfo(method); return methodInfo; } } private static final String getTableNameOrNull(final Class<?> clazz) { try { final Field field = clazz.getField("Table_Name"); if (!field.isAccessible()) { field.setAccessible(true); } return (String)field.get(null); } catch (final Exception e) { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelClassIntrospector.java
1
请完成以下Java代码
public void setImplementationRef(String implementationRef) { this.implementationRef = implementationRef; } public String getInMessageRef() { return inMessageRef; } public void setInMessageRef(String inMessageRef) { this.inMessageRef = inMessageRef; } public String getOutMessageRef() { return outMessageRef; } public void setOutMessageRef(String outMessageRef) { this.outMessageRef = outMessageRef; } public List<String> getErrorMessageRef() { return errorMessageRef; } public void setErrorMessageRef(List<String> errorMessageRef) { this.errorMessageRef = errorMessageRef; }
@Override public Operation clone() { Operation clone = new Operation(); clone.setValues(this); return clone; } public void setValues(Operation otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setImplementationRef(otherElement.getImplementationRef()); setInMessageRef(otherElement.getInMessageRef()); setOutMessageRef(otherElement.getOutMessageRef()); errorMessageRef = new ArrayList<>(); if (otherElement.getErrorMessageRef() != null && !otherElement.getErrorMessageRef().isEmpty()) { errorMessageRef.addAll(otherElement.getErrorMessageRef()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\Operation.java
1
请完成以下Java代码
public class WelcomeApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(JacksonConfigurator.class); classes.add(JacksonJsonProvider.class); classes.add(RestExceptionHandler.class); classes.add(ExceptionHandler.class); addPluginResourceClasses(classes); return classes; }
private void addPluginResourceClasses(Set<Class<?>> classes) { List<WelcomePlugin> plugins = getPlugins(); for (WelcomePlugin plugin : plugins) { classes.addAll(plugin.getResourceClasses()); } } private List<WelcomePlugin> getPlugins() { return Welcome.getRuntimeDelegate().getAppPluginRegistry().getPlugins(); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\welcome\impl\web\WelcomeApplication.java
1
请完成以下Java代码
private IAllocationResult processCandidate_Material(final AllocCandidate candidate, final IAllocationRequest initialRequest, final IAllocationRequest requestActual) { final I_M_HU_Item vhuItem = candidate.getHuItem(); final I_M_HU_Item itemFirstNotPureVirtual = services.getFirstNotPureVirtualItem(vhuItem); final Quantity qtyTrx = AllocationUtils.getQuantity(requestActual, direction); final Object referencedModel = AllocationUtils.getReferencedModel(requestActual); final HUTransactionCandidate trx = HUTransactionCandidate.builder() .model(referencedModel) .huItem(itemFirstNotPureVirtual) .vhuItem(vhuItem) .productId(requestActual.getProductId()) .quantity(qtyTrx) .date(requestActual.getDate()) .build(); final BigDecimal qtyToAllocate = initialRequest.getQty(); final BigDecimal qtyAllocated = requestActual.getQty(); return AllocationUtils.createQtyAllocationResult( qtyToAllocate, qtyAllocated, ImmutableList.of(trx), // trxs ImmutableList.of()); // attributeTrxs }
private enum AllocCandidateType { MATERIAL, INCLUDED_HU } @Data @Builder private static class AllocCandidate { @NonNull private final AllocCandidateType type; @NonNull private final I_M_HU_Item huItem; @Nullable private final I_M_HU includedHU; @NonNull private final Quantity currentQty; private Quantity qtyToAllocate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\UniformAllocationStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public JsonSessionInfo login(@RequestBody @NonNull final JsonLoginRequest request) { try { loginService.login(request.getEmail(), request.getPassword()); return getSessionInfo(); } catch (final Exception ex) { return JsonSessionInfo.builder() .loggedIn(false) .loginError(ex.getLocalizedMessage()) .build(); } } @GetMapping("/logout") public void logout() { loginService.logout(); } @GetMapping("/resetUserPassword") public void resetUserPasswordRequest(@RequestParam("email") final String email) { final String passwordResetToken = loginService.generatePasswordResetKey(email); loginService.sendPasswordResetKey(email, passwordResetToken); } @GetMapping("/resetUserPasswordConfirm") public JsonPasswordResetResponse resetUserPasswordConfirm(@RequestParam("token") final String token) { final User user = loginService.resetPassword(token);
loginService.login(user); return JsonPasswordResetResponse.builder() .email(user.getEmail()) .language(user.getLanguageKeyOrDefault().getAsString()) .newPassword(user.getPassword()) .build(); } @PostMapping("/confirmDataEntry") public ConfirmDataEntryResponse confirmDataEntry() { final User user = loginService.getLoggedInUser(); userConfirmationService.confirmUserEntries(user); return ConfirmDataEntryResponse.builder() .countUnconfirmed(userConfirmationService.getCountUnconfirmed(user)) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\session\SessionRestController.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public AssignmentEnum getAssignment() { return assignment; } public void setAssignment(AssignmentEnum assignment) { this.assignment = assignment; } public AssignmentType getType() { return type; } public void setType(AssignmentType type) { this.type = type; } public AssignmentMode getMode() { return mode; } public void setMode(AssignmentMode mode) { this.mode = mode; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AssignmentDefinition that = (AssignmentDefinition) o; return Objects.equals(id, that.id) && assignment == that.assignment && type == that.type && mode == that.mode; } @Override public int hashCode() { return Objects.hash(id, assignment, type, mode); } @Override public String toString() { return ( "AssignmentDefinition{" + "id='" + id + '\'' + ", assignment=" + assignment + ", type=" + type + ", mode=" + mode + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\AssignmentDefinition.java
1
请在Spring Boot框架中完成以下Java代码
public void setKeyStoreType(String keyStoreType) { this.keyStoreType = keyStoreType; } public String getKeyStoreProvider() { return keyStoreProvider; } public void setKeyStoreProvider(String keyStoreProvider) { this.keyStoreProvider = keyStoreProvider; } public String getKeyStore() { return keyStore; } public void setKeyStore(String keyStore) { this.keyStore = keyStore; } public String getKeyPassword() { return keyPassword; } public void setKeyPassword(String keyPassword) { this.keyPassword = keyPassword; } public List<String> getTrustedX509Certificates() { return trustedX509Certificates; } public void setTrustedX509Certificates(List<String> trustedX509) { this.trustedX509Certificates = trustedX509; } public boolean isUseInsecureTrustManager() { return useInsecureTrustManager; } public void setUseInsecureTrustManager(boolean useInsecureTrustManager) { this.useInsecureTrustManager = useInsecureTrustManager; } public Duration getHandshakeTimeout() { return handshakeTimeout; } public void setHandshakeTimeout(Duration handshakeTimeout) { this.handshakeTimeout = handshakeTimeout; } public Duration getCloseNotifyFlushTimeout() { return closeNotifyFlushTimeout; } public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) { this.closeNotifyFlushTimeout = closeNotifyFlushTimeout; } public Duration getCloseNotifyReadTimeout() { return closeNotifyReadTimeout; } public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) { this.closeNotifyReadTimeout = closeNotifyReadTimeout;
} public String getSslBundle() { return sslBundle; } public void setSslBundle(String sslBundle) { this.sslBundle = sslBundle; } @Override public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout) .toString(); } } public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength; /** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() { return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请完成以下Java代码
public Mono<ArticleView> favoriteArticle(String slug, User currentUser) { return articleRepository.findBySlug(slug) .map(article -> { currentUser.favorite(article); return ArticleView.ofOwnArticle(article, currentUser); }); } public Mono<ArticleView> unfavoriteArticle(String slug, User currentUser) { return articleRepository.findBySlug(slug) .map(article -> { currentUser.unfavorite(article); return ArticleView.ofOwnArticle(article, currentUser); }); }
private ArticleView updateArticle(UpdateArticleRequest request, User currentUser, Article article) { if (!article.isAuthor(currentUser)) { throw new InvalidRequestException("Article", "only author can update article"); } ofNullable(request.getBody()) .ifPresent(article::setBody); ofNullable(request.getDescription()) .ifPresent(article::setDescription); ofNullable(request.getTitle()) .ifPresent(article::setTitle); return ArticleView.ofOwnArticle(article, currentUser); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\ArticleFacade.java
1
请完成以下Java代码
public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request) { return builder().updatingFrom(request).build(); } // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder
{ InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请完成以下Java代码
public class AstUnary extends AstRightValue { public interface Operator { public Object eval(Bindings bindings, ELContext context, AstNode node); } public abstract static class SimpleOperator implements Operator { public Object eval(Bindings bindings, ELContext context, AstNode node) { return apply(bindings, node.eval(bindings, context)); } protected abstract Object apply(TypeConverter converter, Object o); } public static final Operator EMPTY = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o) { return BooleanOperations.empty(converter, o); } @Override public String toString() { return "empty"; } }; public static final Operator NEG = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o) { return NumberOperations.neg(converter, o); } @Override public String toString() { return "-"; } }; public static final Operator NOT = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o) { return !converter.convert(o, Boolean.class); } @Override public String toString() { return "!"; } }; private final Operator operator; private final AstNode child; public AstUnary(AstNode child, Operator operator) { this.child = child; this.operator = operator; }
public Operator getOperator() { return operator; } @Override public Object eval(Bindings bindings, ELContext context) throws ELException { return operator.eval(bindings, context, child); } @Override public String toString() { return "'" + operator.toString() + "'"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(operator); b.append(' '); child.appendStructure(b, bindings); } public int getCardinality() { return 1; } public AstNode getChild(int i) { return i == 0 ? child : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstUnary.java
1
请在Spring Boot框架中完成以下Java代码
public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "dataSource") @Primary public DataSource dataSource() throws SQLException { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); // 设置分库策略 shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}")); // 设置规则适配的表 shardingRuleConfig.getBindingTableGroups().add("t_order"); // 设置分表策略 shardingRuleConfig.getTableRuleConfigs().add(orderTableRule()); shardingRuleConfig.setDefaultDataSourceName("ds0"); shardingRuleConfig.setDefaultTableShardingStrategyConfig(new NoneShardingStrategyConfiguration()); Properties properties = new Properties(); properties.setProperty("sql.show", "true"); return ShardingDataSourceFactory.createDataSource(dataSourceMap(), shardingRuleConfig, new ConcurrentHashMap<>(16), properties); } private TableRuleConfiguration orderTableRule() { TableRuleConfiguration tableRule = new TableRuleConfiguration(); // 设置逻辑表名 tableRule.setLogicTable("t_order"); // ds${0..1}.t_order_${0..2} 也可以写成 ds$->{0..1}.t_order_$->{0..1} tableRule.setActualDataNodes("ds${0..1}.t_order_${0..2}"); tableRule.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order_$->{order_id % 3}")); tableRule.setKeyGenerator(customKeyGenerator()); tableRule.setKeyGeneratorColumnName("order_id"); return tableRule;
} private Map<String, DataSource> dataSourceMap() { Map<String, DataSource> dataSourceMap = new HashMap<>(16); // 配置第一个数据源 HikariDataSource ds0 = new HikariDataSource(); ds0.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds0.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); ds0.setUsername("root"); ds0.setPassword("root"); // 配置第二个数据源 HikariDataSource ds1 = new HikariDataSource(); ds1.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds1.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo-2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); ds1.setUsername("root"); ds1.setPassword("root"); dataSourceMap.put("ds0", ds0); dataSourceMap.put("ds1", ds1); return dataSourceMap; } /** * 自定义主键生成器 */ private KeyGenerator customKeyGenerator() { return new CustomSnowflakeKeyGenerator(snowflake); } }
repos\spring-boot-demo-master\demo-sharding-jdbc\src\main\java\com\xkcoding\sharding\jdbc\config\DataSourceShardingConfig.java
2
请完成以下Java代码
public void setQtyPromised (java.math.BigDecimal QtyPromised) { set_ValueNoCheck (COLUMNNAME_QtyPromised, QtyPromised); } /** Get Zusagbar. @return Zusagbar */ @Override public java.math.BigDecimal getQtyPromised () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised); if (bd == null) { return Env.ZERO; } return bd; } /** Set Old Zusagbar. @param QtyPromised_Old Old Zusagbar */ @Override public void setQtyPromised_Old (java.math.BigDecimal QtyPromised_Old) { set_Value (COLUMNNAME_QtyPromised_Old, QtyPromised_Old); } /** Get Old Zusagbar. @return Old Zusagbar */ @Override public java.math.BigDecimal getQtyPromised_Old () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_Old); if (bd == null) { return Env.ZERO; } return bd; } /** Set Zusagbar (TU). @param QtyPromised_TU Zusagbar (TU) */ @Override public void setQtyPromised_TU (java.math.BigDecimal QtyPromised_TU) { set_ValueNoCheck (COLUMNNAME_QtyPromised_TU, QtyPromised_TU); } /** Get Zusagbar (TU). @return Zusagbar (TU) */ @Override
public java.math.BigDecimal getQtyPromised_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU); if (bd == null) { return Env.ZERO; } return bd; } /** Set Old Zusagbar (TU). @param QtyPromised_TU_Old Old Zusagbar (TU) */ @Override public void setQtyPromised_TU_Old (java.math.BigDecimal QtyPromised_TU_Old) { set_Value (COLUMNNAME_QtyPromised_TU_Old, QtyPromised_TU_Old); } /** Get Old Zusagbar (TU). @return Old Zusagbar (TU) */ @Override public java.math.BigDecimal getQtyPromised_TU_Old () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_Old); if (bd == null) { return Env.ZERO; } return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_QtyReport_Event.java
1
请完成以下Java代码
public double discountedPrice(double price) { return price - (price * discount); } public static int getMaxNumber(int[] numbers) { if (numbers.length == 0) { throw new IllegalArgumentException("Ensure array is not empty"); } int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } return max; }
public static int getMinNumber(int[] numbers) { if (numbers.length == 0) { throw new IllegalArgumentException("Ensure array is not empty"); } int min = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < min) { min = numbers[i]; } } return min; } }
repos\tutorials-master\core-java-modules\core-java-8-2\src\main\java\com\baeldung\helpervsutilityclasses\MyHelperClass.java
1
请完成以下Java代码
public int getM_DistributionListLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionListLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Minimum Quantity. @param MinQty Minimum quantity for the business partner */ public void setMinQty (BigDecimal MinQty) { set_Value (COLUMNNAME_MinQty, MinQty); } /** Get Minimum Quantity. @return Minimum quantity for the business partner */ public BigDecimal getMinQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty); if (bd == null) return Env.ZERO; return bd;
} /** Set Ratio. @param Ratio Relative Ratio for Distributions */ public void setRatio (BigDecimal Ratio) { set_Value (COLUMNNAME_Ratio, Ratio); } /** Get Ratio. @return Relative Ratio for Distributions */ public BigDecimal getRatio () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Ratio); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionListLine.java
1
请完成以下Java代码
public class PmsProductCategoryAttributeRelation implements Serializable { private Long id; private Long productCategoryId; private Long productAttributeId; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductCategoryId() { return productCategoryId; } public void setProductCategoryId(Long productCategoryId) { this.productCategoryId = productCategoryId; } public Long getProductAttributeId() {
return productAttributeId; } public void setProductAttributeId(Long productAttributeId) { this.productAttributeId = productAttributeId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", productAttributeId=").append(productAttributeId); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategoryAttributeRelation.java
1
请在Spring Boot框架中完成以下Java代码
public static String getnonceStr() { Random random = new Random(); StringBuilder nonceStrBuilder = new StringBuilder(); for (int i = 0; i < 31; i++) { nonceStrBuilder.append(random.nextInt(10)); } return nonceStrBuilder.toString(); } /** * 签名 * * @param paramMap * @param key * @return */ public static String getSign(SortedMap<String, Object> paramMap, String key) { StringBuilder signBuilder = new StringBuilder(); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { if (!"sign".equals(entry.getKey()) && !StringUtil.isEmpty(entry.getValue())) { signBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } } signBuilder.append("key=").append(key); logger.info("微信待签名参数字符串:{}", signBuilder.toString()); return MD5Util.encode(signBuilder.toString()).toUpperCase(); } /** * 转xml格式 *
* @param paramMap * @return */ private static String mapToXml(SortedMap<String, Object> paramMap) { StringBuilder dataBuilder = new StringBuilder("<xml>"); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { if (!StringUtil.isEmpty(entry.getValue())) { dataBuilder.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append("</").append(entry.getKey()).append(">"); } } dataBuilder.append("</xml>"); logger.info("Map转Xml结果:{}", dataBuilder.toString()); return dataBuilder.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\weixin\WeiXinPayUtil.java
2
请完成以下Java代码
public static void skipRequest(HttpServletRequest request) { request.setAttribute(SHOULD_NOT_FILTER, Boolean.TRUE); } /** * Specifies a {@link RequestMatcher} that is used to determine if CSRF protection * should be applied. If the {@link RequestMatcher} returns true for a given request, * then CSRF protection is applied. * * <p> * The default is to apply CSRF protection for any HTTP method other than GET, HEAD, * TRACE, OPTIONS. * </p> * @param requireCsrfProtectionMatcher the {@link RequestMatcher} used to determine if * CSRF protection should be applied. */ public void setRequireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher) { Assert.notNull(requireCsrfProtectionMatcher, "requireCsrfProtectionMatcher cannot be null"); this.requireCsrfProtectionMatcher = requireCsrfProtectionMatcher; } /** * Specifies a {@link AccessDeniedHandler} that should be used when CSRF protection * fails. * * <p> * The default is to use AccessDeniedHandlerImpl with no arguments. * </p> * @param accessDeniedHandler the {@link AccessDeniedHandler} to use */ public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) { Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null"); this.accessDeniedHandler = accessDeniedHandler; } /** * Specifies a {@link CsrfTokenRequestHandler} that is used to make the * {@link CsrfToken} available as a request attribute. * * <p> * The default is {@link XorCsrfTokenRequestAttributeHandler}. * </p> * @param requestHandler the {@link CsrfTokenRequestHandler} to use * @since 5.8 */ public void setRequestHandler(CsrfTokenRequestHandler requestHandler) { Assert.notNull(requestHandler, "requestHandler cannot be null"); this.requestHandler = requestHandler; } /** * Constant time comparison to prevent against timing attacks. * @param expected
* @param actual * @return */ private static boolean equalsConstantTime(String expected, @Nullable String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } private static final class DefaultRequiresCsrfMatcher implements RequestMatcher { private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS")); @Override public boolean matches(HttpServletRequest request) { return !this.allowedMethods.contains(request.getMethod()); } @Override public String toString() { return "IsNotHttpMethod " + this.allowedMethods; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfFilter.java
1
请完成以下Java代码
private boolean columnConstraint(int[][] board, int column) { boolean[] constraint = new boolean[BOARD_SIZE]; for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) { if (!checkConstraint(board, row, constraint, column)) { return false; } } return true; } private boolean rowConstraint(int[][] board, int row) { boolean[] constraint = new boolean[BOARD_SIZE]; for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) { if (!checkConstraint(board, row, constraint, column)) { return false;
} } return true; } private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) { if (board[row][column] != NO_VALUE) { if (!constraint[board[row][column] - 1]) { constraint[board[row][column] - 1] = true; } else { return false; } } return true; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\BacktrackingAlgorithm.java
1
请完成以下Java代码
private Set<String> extractTableNames(final CacheInvalidateMultiRequest multiRequest) { if (multiRequest.isResetAll()) { // not relevant for our lookups return ImmutableSet.of(); } return multiRequest.getRequests() .stream() .filter(request -> !request.isAll()) // not relevant for our lookups .map(CacheInvalidateRequest::getTableNameEffective) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } private void resetNow(final Set<String> tableNames) { if (tableNames.isEmpty()) {
return; } lookupDataSourceFactory.cacheInvalidateOnRecordsChanged(tableNames); } private static final class TableNamesToResetCollector { private final Set<String> tableNames = new HashSet<>(); public Set<String> toSet() { return ImmutableSet.copyOf(tableNames); } public void addTableNames(final Collection<String> tableNamesToAdd) { tableNames.addAll(tableNamesToAdd); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupCacheInvalidationDispatcher.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getOrderByRegisterTime() { return orderByRegisterTime; } public void setOrderByRegisterTime(Integer orderByRegisterTime) { this.orderByRegisterTime = orderByRegisterTime; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserQueryReq{" + "id='" + id + '\'' +
", username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", mail='" + mail + '\'' + ", registerTimeStart='" + registerTimeStart + '\'' + ", registerTimeEnd='" + registerTimeEnd + '\'' + ", userType=" + userType + ", userState=" + userState + ", roleId='" + roleId + '\'' + ", orderByRegisterTime=" + orderByRegisterTime + ", page=" + page + ", numPerPage=" + numPerPage + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\UserQueryReq.java
2
请完成以下Java代码
public void setStructuredRemittanceInfo (java.lang.String StructuredRemittanceInfo) { set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo); } /** Get StructuredRemittanceInfo. @return Structured Remittance Information */ @Override public java.lang.String getStructuredRemittanceInfo () { return (java.lang.String)get_Value(COLUMNNAME_StructuredRemittanceInfo); } /** Set Swift code. @param SwiftCode Swift Code or BIC */ @Override public void setSwiftCode (java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } /** Get Swift code. @return Swift Code or BIC */ @Override public java.lang.String getSwiftCode () { return (java.lang.String)get_Value(COLUMNNAME_SwiftCode); } @Override public void setIsGroupLine (final boolean IsGroupLine)
{ set_Value (COLUMNNAME_IsGroupLine, IsGroupLine); } @Override public boolean isGroupLine() { return get_ValueAsBoolean(COLUMNNAME_IsGroupLine); } @Override public void setNumberOfReferences (final int NumberOfReferences) { set_Value (COLUMNNAME_NumberOfReferences, NumberOfReferences); } @Override public int getNumberOfReferences() { return get_ValueAsInt(COLUMNNAME_NumberOfReferences); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line.java
1
请完成以下Java代码
public static GlobalQRCodeVersion ofString(final String string) { try { return ofInt(Integer.parseInt(string)); } catch (final NumberFormatException e) { throw Check.mkEx("Invalid global QR code version: `" + string + "`", e); } } private static final Interner<GlobalQRCodeVersion> interner = Interners.newStrongInterner(); private final int value; private GlobalQRCodeVersion(final int value) { this.value = value; }
@Override @Deprecated public String toString() { return String.valueOf(toJson()); } @JsonValue public int toJson() { return value; } public static boolean equals(@Nullable final GlobalQRCodeVersion o1, @Nullable final GlobalQRCodeVersion o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCodeVersion.java
1
请在Spring Boot框架中完成以下Java代码
public void generateMainReport(String reportName, OutputType output, HttpServletResponse response, HttpServletRequest request) { switch (output) { case HTML: generateHTMLReport(reports.get(reportName), response, request); break; case PDF: generatePDFReport(reports.get(reportName), response, request); break; default: throw new IllegalArgumentException("Output type not recognized:" + output); } } /** * Generate a report as HTML */ @SuppressWarnings("unchecked") private void generateHTMLReport(IReportRunnable report, HttpServletResponse response, HttpServletRequest request) { IRunAndRenderTask runAndRenderTask = birtEngine.createRunAndRenderTask(report); response.setContentType(birtEngine.getMIMEType("html")); IRenderOption options = new RenderOption(); HTMLRenderOption htmlOptions = new HTMLRenderOption(options); htmlOptions.setOutputFormat("html"); htmlOptions.setBaseImageURL("/" + reportsPath + imagesPath); htmlOptions.setImageDirectory(imageFolder); htmlOptions.setImageHandler(htmlImageHandler); runAndRenderTask.setRenderOption(htmlOptions); runAndRenderTask.getAppContext().put(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST, request); try { htmlOptions.setOutputStream(response.getOutputStream()); runAndRenderTask.run(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { runAndRenderTask.close(); }
} /** * Generate a report as PDF */ @SuppressWarnings("unchecked") private void generatePDFReport(IReportRunnable report, HttpServletResponse response, HttpServletRequest request) { IRunAndRenderTask runAndRenderTask = birtEngine.createRunAndRenderTask(report); response.setContentType(birtEngine.getMIMEType("pdf")); IRenderOption options = new RenderOption(); PDFRenderOption pdfRenderOption = new PDFRenderOption(options); pdfRenderOption.setOutputFormat("pdf"); runAndRenderTask.setRenderOption(pdfRenderOption); runAndRenderTask.getAppContext().put(EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT, request); try { pdfRenderOption.setOutputStream(response.getOutputStream()); runAndRenderTask.run(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { runAndRenderTask.close(); } } @Override public void destroy() { birtEngine.destroy(); Platform.shutdown(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-birt\src\main\java\com\baeldung\birt\engine\service\BirtReportService.java
2
请完成以下Java代码
public PPOrderRoutingActivity getLastActivity() { return getActivities() .stream() .filter(this::isFinalActivity) .findFirst() .orElseThrow(() -> new AdempiereException("No final activity found in " + this)); } private boolean isFinalActivity(final PPOrderRoutingActivity activity) { return getNextActivityCodes(activity).isEmpty(); } public ImmutableSet<ProductId> getProductIdsByActivityId(@NonNull final PPOrderRoutingActivityId activityId) { return getProducts() .stream() .filter(activityProduct -> activityProduct.getId() != null && PPOrderRoutingActivityId.equals(activityProduct.getId().getActivityId(), activityId)) .map(PPOrderRoutingProduct::getProductId) .collect(ImmutableSet.toImmutableSet()); } public void voidIt() { getActivities().forEach(PPOrderRoutingActivity::voidIt); } public void reportProgress(final PPOrderActivityProcessReport report)
{ getActivityById(report.getActivityId()).reportProgress(report); } public void completeActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).completeIt(); } public void closeActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).closeIt(); } public void uncloseActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).uncloseIt(); } @NonNull public RawMaterialsIssueStrategy getIssueStrategyForRawMaterialsActivity() { return activities.stream() .filter(activity -> activity.getType() == PPRoutingActivityType.RawMaterialsIssue) .findFirst() .map(PPOrderRoutingActivity::getRawMaterialsIssueStrategy) .orElse(RawMaterialsIssueStrategy.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRouting.java
1
请完成以下Java代码
public static FutureClearingAmountMap ofList(final List<FutureClearingAmount> list) { return !list.isEmpty() ? new FutureClearingAmountMap(list) : EMPTY; } public static Collector<FutureClearingAmount, ?, FutureClearingAmountMap> collect() { return GuavaCollectors.collectUsingListAccumulator(FutureClearingAmountMap::ofList); } @Nullable @VisibleForTesting static FutureClearingAmount extractFutureClearingAmount( @NonNull final SAPGLJournalLine sapGLJournalLine, @NonNull final CurrencyIdToCurrencyCodeConverter currencyCodeConverter) { final FAOpenItemTrxInfo openItemTrxInfo = sapGLJournalLine.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { return null; } if (!openItemTrxInfo.isClearing()) {
return null; } final Amount amount = sapGLJournalLine.getAmount() .negateIf(sapGLJournalLine.getPostingSign().isCredit()) .toAmount(currencyCodeConverter::getCurrencyCodeByCurrencyId); return FutureClearingAmount.builder() .key(openItemTrxInfo.getKey()) .amountSrc(amount) .build(); } public Optional<Amount> getAmountSrc(final FAOpenItemKey key) {return getByKey(key).map(FutureClearingAmount::getAmountSrc);} @NonNull private Optional<FutureClearingAmount> getByKey(final FAOpenItemKey key) {return Optional.ofNullable(byKey.get(key));} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\FutureClearingAmountMap.java
1
请完成以下Java代码
public ProcessEngineConfigurationImpl setAsyncExecutorDefaultTimerJobAcquireWaitTime(int asyncExecutorTimerJobAcquireWaitTime) { this.asyncExecutorDefaultTimerJobAcquireWaitTime = asyncExecutorTimerJobAcquireWaitTime; return this; } public int getAsyncExecutorDefaultAsyncJobAcquireWaitTime() { return asyncExecutorDefaultAsyncJobAcquireWaitTime; } public ProcessEngineConfigurationImpl setAsyncExecutorDefaultAsyncJobAcquireWaitTime(int asyncExecutorDefaultAsyncJobAcquireWaitTime) { this.asyncExecutorDefaultAsyncJobAcquireWaitTime = asyncExecutorDefaultAsyncJobAcquireWaitTime; return this; } public int getAsyncExecutorDefaultQueueSizeFullWaitTime() { return asyncExecutorDefaultQueueSizeFullWaitTime; } public ProcessEngineConfigurationImpl setAsyncExecutorDefaultQueueSizeFullWaitTime(int asyncExecutorDefaultQueueSizeFullWaitTime) { this.asyncExecutorDefaultQueueSizeFullWaitTime = asyncExecutorDefaultQueueSizeFullWaitTime; return this; } public String getAsyncExecutorLockOwner() { return asyncExecutorLockOwner; } public ProcessEngineConfigurationImpl setAsyncExecutorLockOwner(String asyncExecutorLockOwner) { this.asyncExecutorLockOwner = asyncExecutorLockOwner; return this; } public int getAsyncExecutorTimerLockTimeInMillis() { return asyncExecutorTimerLockTimeInMillis; } public ProcessEngineConfigurationImpl setAsyncExecutorTimerLockTimeInMillis(int asyncExecutorTimerLockTimeInMillis) { this.asyncExecutorTimerLockTimeInMillis = asyncExecutorTimerLockTimeInMillis; return this; }
public int getAsyncExecutorAsyncJobLockTimeInMillis() { return asyncExecutorAsyncJobLockTimeInMillis; } public ProcessEngineConfigurationImpl setAsyncExecutorAsyncJobLockTimeInMillis(int asyncExecutorAsyncJobLockTimeInMillis) { this.asyncExecutorAsyncJobLockTimeInMillis = asyncExecutorAsyncJobLockTimeInMillis; return this; } public int getAsyncExecutorLockRetryWaitTimeInMillis() { return asyncExecutorLockRetryWaitTimeInMillis; } public ProcessEngineConfigurationImpl setAsyncExecutorLockRetryWaitTimeInMillis(int asyncExecutorLockRetryWaitTimeInMillis) { this.asyncExecutorLockRetryWaitTimeInMillis = asyncExecutorLockRetryWaitTimeInMillis; return this; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } @Override
public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Author) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootUnproxyAProxy\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
private JsonHUConsolidationJob toJson(@NonNull final HUConsolidationJob job) { final RenderedAddressProvider renderedAddressProvider = documentLocationBL.newRenderedAddressProvider(); final String shipToAddress = renderedAddressProvider.getAddress(job.getShipToBPLocationId()); return JsonHUConsolidationJob.builder() .id(job.getId()) .shipToAddress(shipToAddress) .pickingSlots(toJsonHUConsolidationJobPickingSlots(job.getPickingSlotIds())) .currentTarget(JsonHUConsolidationTarget.ofNullable(job.getCurrentTarget())) .build(); } private ImmutableList<JsonHUConsolidationJobPickingSlot> toJsonHUConsolidationJobPickingSlots(final Set<PickingSlotId> pickingSlotIds) { if (pickingSlotIds.isEmpty())
{ return ImmutableList.of(); } final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions = pickingSlotService.getPickingSlotIdAndCaptions(pickingSlotIds); final PickingSlotQueuesSummary summary = pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(pickingSlotIds)); return pickingSlotIdAndCaptions.stream() .map(pickingSlotIdAndCaption -> JsonHUConsolidationJobPickingSlot.builder() .pickingSlotId(pickingSlotIdAndCaption.getPickingSlotId()) .pickingSlotQRCode(PickingSlotQRCode.ofPickingSlotIdAndCaption(pickingSlotIdAndCaption).toPrintableQRCode().toJsonDisplayableQRCode()) .countHUs(summary.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0)) .build()) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\HUConsolidateWFActivityHandler.java
1
请完成以下Java代码
public class AD_PrinterHW { private static final Logger logger = LogManager.getLogger(AD_PrinterHW.class); private final IPrintClientsBL printClientsBL = Services.get(IPrintClientsBL.class); private final IPrinterBL printerBL = Services.get(IPrinterBL.class); private final HardwarePrinterRepository hardwarePrinterRepository; @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void beforeSave(final I_AD_PrinterHW record, final ModelChangeType timing) { if (timing.isNew()) { setHostKey(record); } HardwarePrinterRepository.validateOnBeforeSave(record); } private void setHostKey(final I_AD_PrinterHW printerHW) { if (Check.isNotBlank(printerHW.getHostKey())) { return; // HostKey was already set, nothing to do } if (!Objects.equals(OutputType.Queue, OutputType.ofNullableCode(printerHW.getOutputType()))) { return; // no hostkey needed } final Properties ctx = InterfaceWrapperHelper.getCtx(printerHW); final String hostKey = printClientsBL.getHostKeyOrNull(ctx); if (Check.isBlank(hostKey)) { logger.debug("HostKey not found in context"); return; } // Finally, update the bean printerHW.setHostKey(hostKey); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteAttachedLines(final I_AD_PrinterHW printerHW) { final HardwarePrinterId hardwarePrinterId = HardwarePrinterId.ofRepoId(printerHW.getAD_PrinterHW_ID()); hardwarePrinterRepository.deleteCalibrations(hardwarePrinterId); hardwarePrinterRepository.deleteMediaTrays(hardwarePrinterId); hardwarePrinterRepository.deleteMediaSizes(hardwarePrinterId); } /** * Needed because we want to order by ConfigHostKey and "unspecified" shall always be last.
*/ @ModelChange( timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_AD_Printer_Config.COLUMNNAME_ConfigHostKey) public void trimBlankHostKeyToNull(@NonNull final I_AD_PrinterHW printerHW) { try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(printerHW)) { final String normalizedString = StringUtils.trimBlankToNull(printerHW.getHostKey()); printerHW.setHostKey(normalizedString); } } /** * This interceptor shall only fire if the given {@code printerTrayHW} was created with replication. * If it was created via the REST endpoint, then the business logic is called directly. */ @ModelChange(timings = ModelValidator.TYPE_AFTER_NEW_REPLICATION) public void createPrinterConfigIfNoneExists(final I_AD_PrinterHW printerHW) { printerBL.createConfigAndDefaultPrinterMatching(printerHW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_PrinterHW.java
1
请在Spring Boot框架中完成以下Java代码
abstract class HttpSender extends BaseHttpSender<URI, byte[]> { /** * Only use gzip compression on data which is bigger than this in bytes. */ private static final DataSize COMPRESSION_THRESHOLD = DataSize.ofKilobytes(1); HttpSender(Encoding encoding, Factory endpointSupplierFactory, String endpoint) { super(encoding, endpointSupplierFactory, endpoint); } @Override protected URI newEndpoint(String endpoint) { return URI.create(endpoint); } @Override protected byte[] newBody(List<byte[]> list) { return this.encoding.encode(list); } @Override protected void postSpans(URI endpoint, byte[] body) throws IOException { Map<String, String> headers = getDefaultHeaders(); if (needsCompression(body)) { body = compress(body); headers.put("Content-Encoding", "gzip"); } postSpans(endpoint, headers, body); } abstract void postSpans(URI endpoint, Map<String, String> headers, byte[] body) throws IOException; Map<String, String> getDefaultHeaders() { Map<String, String> headers = new LinkedHashMap<>(); headers.put("b3", "0"); headers.put("Content-Type", this.encoding.mediaType());
return headers; } private boolean needsCompression(byte[] body) { return body.length > COMPRESSION_THRESHOLD.toBytes(); } private byte[] compress(byte[] input) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); try (GZIPOutputStream gzip = new GZIPOutputStream(result)) { gzip.write(input); } return result.toByteArray(); } }
repos\spring-boot-4.0.1\module\spring-boot-zipkin\src\main\java\org\springframework\boot\zipkin\autoconfigure\HttpSender.java
2
请完成以下Java代码
public void execute() { CaseExecutionVariableCmd command = new CaseExecutionVariableCmd(this); executeCommand(command); } public void manualStart() { ManualStartCaseExecutionCmd command = new ManualStartCaseExecutionCmd(this); executeCommand(command); } public void disable() { DisableCaseExecutionCmd command = new DisableCaseExecutionCmd(this); executeCommand(command); } public void reenable() { ReenableCaseExecutionCmd command = new ReenableCaseExecutionCmd(this); executeCommand(command); } public void complete() { CompleteCaseExecutionCmd command = new CompleteCaseExecutionCmd(this); executeCommand(command); } public void close() { CloseCaseInstanceCmd command = new CloseCaseInstanceCmd(this); executeCommand(command); } public void terminate() { TerminateCaseExecutionCmd command = new TerminateCaseExecutionCmd(this); executeCommand(command); } protected void executeCommand(Command<?> command) { try { if(commandExecutor != null) { commandExecutor.execute(command); } else { command.execute(commandContext); }
} catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (CaseExecutionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (CaseDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (CaseIllegalStateTransitionException e) { throw new NotAllowedException(e.getMessage(), e); } } // getters //////////////////////////////////////////////////////////////////////////////// public String getCaseExecutionId() { return caseExecutionId; } public VariableMap getVariables() { return variables; } public VariableMap getVariablesLocal() { return variablesLocal; } public Collection<String> getVariableDeletions() { return variableDeletions; } public Collection<String> getVariableLocalDeletions() { return variableLocalDeletions; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseExecutionCommandBuilderImpl.java
1
请完成以下Java代码
public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getAuthorizationUserId() { return authorizationUserId; } public String getProcDefId() { return procDefId; } public String getEventSubscriptionName() { return eventSubscriptionName; }
public String getEventSubscriptionType() { return eventSubscriptionType; } public ProcessDefinitionQueryImpl startableByUser(String userId) { if (userId == null) { throw new ActivitiIllegalArgumentException("userId is null"); } this.authorizationUserId = userId; return this; } public ProcessDefinitionQuery startableByGroups(List<String> groupIds) { authorizationGroups = groupIds; return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessDefinitionQueryImpl.java
1
请完成以下Java代码
public void setResponseDetails (java.lang.String ResponseDetails) { set_ValueNoCheck (COLUMNNAME_ResponseDetails, ResponseDetails); } /** Get Antwort Details. @return Antwort Details */ @Override public java.lang.String getResponseDetails () { return (java.lang.String)get_Value(COLUMNNAME_ResponseDetails); } /** Set Transaktionsreferenz Kunde . @param TransactionCustomerId Transaktionsreferenz Kunde */ @Override public void setTransactionCustomerId (java.lang.String TransactionCustomerId) { set_ValueNoCheck (COLUMNNAME_TransactionCustomerId, TransactionCustomerId); } /** Get Transaktionsreferenz Kunde . @return Transaktionsreferenz Kunde */ @Override public java.lang.String getTransactionCustomerId () { return (java.lang.String)get_Value(COLUMNNAME_TransactionCustomerId); }
/** Set Transaktionsreferenz API. @param TransactionIdAPI Transaktionsreferenz API */ @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } /** Get Transaktionsreferenz API. @return Transaktionsreferenz API */ @Override public java.lang.String getTransactionIdAPI () { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\base\src\main\java-gen\de\metas\vertical\creditscore\base\model\X_CS_Transaction_Result.java
1
请完成以下Java代码
public static String computeFieldName(final AttributesIncludedTabFieldDescriptor includedTabField) { return includedTabField.getAttributeCode().getCode(); } private static AttributesIncludedTabDataField writeValueAsLocalDate(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withDateValue(documentField.getValueAs(LocalDate.class)); } private static AttributesIncludedTabDataField writeValueAsInteger(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withNumberValue(documentField.getValueAs(Integer.class)); } private static AttributesIncludedTabDataField writeValueAsBigDecimal(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withNumberValue(documentField.getValueAs(BigDecimal.class)); } private static AttributesIncludedTabDataField writeValueAsString(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField) { return dataField.withStringValue(documentField.getValueAs(String.class)); } private static AttributesIncludedTabDataField writeValueAsListItem(final AttributesIncludedTabDataField dataField, final IDocumentFieldView documentField) { final StringLookupValue lookupValue = documentField.getValueAs(StringLookupValue.class); final String valueString = lookupValue != null ? lookupValue.getIdAsString() : null; final AttributeValueId valueItemId = documentField.getDescriptor().getLookupDescriptor().get().cast(ASILookupDescriptor.class).getAttributeValueId(valueString); return dataField.withListValue(valueString, valueItemId); } public Object getValue(final @NonNull AttributesIncludedTabData data) {
return valueReader.readValue(data, attributeId); } public AttributesIncludedTabDataField updateData(final @NonNull AttributesIncludedTabDataField dataField, final IDocumentFieldView documentField) { return valueWriter.writeValue(dataField, documentField); } // // // // // @FunctionalInterface private interface ValueReader { Object readValue(AttributesIncludedTabData data, AttributeId attributeId); } @FunctionalInterface private interface ValueWriter { AttributesIncludedTabDataField writeValue(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabFieldBinding.java
1
请完成以下Java代码
public class PositiveOrNegative { enum Result { POSITIVE, NEGATIVE, ZERO } public static Result byOperator(Integer integer) { if (integer > 0) { return Result.POSITIVE; } else if (integer < 0) { return Result.NEGATIVE; } return Result.ZERO; } public static Result bySignum(Integer integer) { int result = Integer.signum(integer); if (result == 1) { return Result.POSITIVE;
} else if (result == -1) { return Result.NEGATIVE; } return Result.ZERO; } public static Result bySignum(Float floatNumber) { Float result = Math.signum(floatNumber); if (result.compareTo(1.0f) == 0) { return Result.POSITIVE; } else if (result.compareTo(-1.0f) == 0) { return Result.NEGATIVE; } return Result.ZERO; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\positivenegative\PositiveOrNegative.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-consumer-application cloud: # Spring Cloud Stream 配置项,对应 BindingServiceProperties 类 stream: # Binder 配置项,对应 BinderProperties Map # binders: # Binding 配置项,对应 BindingProperties Map bindings: demo01-input: destination: DEMO-TOPIC-01 # 目的地。这里使用 Kafka Topic content-type: application/json # 内容格式。这里使用 JSON group: demo01-consumer-group # 消费者分组 # Spring Cloud Stream Kafka 配置项 kafka: # Kafka Binder 配置项,对应 KafkaBinderConfigurationProperties 类 binder: brokers: 127.0.0.1:9092 # 指定 Kafka Broker 地址,可以设置多个,以逗号分隔 # Zipkin 配置项,对应 ZipkinProperties 类 zipkin: b
ase-url: http://127.0.0.1:9411 # Zipkin 服务的地址 # Spring Cloud Sleuth 配置项 sleuth: messaging: # Spring Cloud Sleuth 针对 kafka 组件的配置项kafka kafka: enabled: true # 是否开启 remote-service-name: kafka # 远程服务名,默认为 kafka server: port: ${random.int[10000,19999]} # 随机端口,方便启动多个消费者
repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-mq-kafka\labx-13-sc-stream-mq-kafka-consumer\src\main\resources\application.yml
2
请完成以下Java代码
public boolean isLongField() { // if (m_vo.displayType == DisplayType.String // || m_vo.displayType == DisplayType.Text // || m_vo.displayType == DisplayType.Memo // || m_vo.displayType == DisplayType.TextLong // || m_vo.displayType == DisplayType.Image) return displayLength >= MAXDISPLAY_LENGTH / 2; // return false; } // isLongField public int getSpanX() { return spanX; } public int getSpanY() { return spanY; } public static final class Builder { private int displayLength = 0; private int columnDisplayLength = 0; private boolean sameLine = false; private int spanX = 1; private int spanY = 1; private Builder() { super(); } public GridFieldLayoutConstraints build()
{ return new GridFieldLayoutConstraints(this); } public Builder setDisplayLength(final int displayLength) { this.displayLength = displayLength; return this; } public Builder setColumnDisplayLength(final int columnDisplayLength) { this.columnDisplayLength = columnDisplayLength; return this; } public Builder setSameLine(final boolean sameLine) { this.sameLine = sameLine; return this; } public Builder setSpanX(final int spanX) { this.spanX = spanX; return this; } public Builder setSpanY(final int spanY) { this.spanY = spanY; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldLayoutConstraints.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id private Long id; private String name; private String role; public User() { } public User(Long id, String name, String role) { this.id = id; this.name = name; this.role = role;
} public Long getId() { return id; } public String getName() { return name; } public String getRole() { return role; } }
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\persistencecontext\entity\User.java
2
请完成以下Java代码
public boolean load(String path) { try { BufferedReader br = new BufferedReader(new InputStreamReader(HanLP.Config.IOAdapter == null ? new FileInputStream(path) : HanLP.Config.IOAdapter.open(path), "UTF-8")); String line; while ((line = br.readLine()) != null) { Map.Entry<String, V> entry = onGenerateEntry(line); if (entry == null) continue; trie.put(entry.getKey(), entry.getValue()); } br.close(); } catch (Exception e) { Predefine.logger.warning("读取" + path + "失败" + e); return false; } return true; } /** * 查询一个单词 * * @param key * @return 单词对应的条目 */ public V get(String key) { return trie.get(key); } /** * 由参数构造一个词条 * * @param line * @return */ protected abstract Map.Entry<String, V> onGenerateEntry(String line); /** * 以我为主词典,合并一个副词典,我有的词条不会被副词典覆盖 * @param other 副词典 */ public void combine(SimpleDictionary<V> other) { if (other.trie == null) { Predefine.logger.warning("有个词典还没加载"); return; } for (Map.Entry<String, V> entry : other.trie.entrySet()) { if (trie.containsKey(entry.getKey())) continue; trie.put(entry.getKey(), entry.getValue()); } } /** * 获取键值对集合 * @return */ public Set<Map.Entry<String, V>> entrySet() { return trie.entrySet(); } /**
* 键集合 * @return */ public Set<String> keySet() { TreeSet<String> keySet = new TreeSet<String>(); for (Map.Entry<String, V> entry : entrySet()) { keySet.add(entry.getKey()); } return keySet; } /** * 过滤部分词条 * @param filter 过滤器 * @return 删除了多少条 */ public int remove(Filter filter) { int size = trie.size(); for (Map.Entry<String, V> entry : entrySet()) { if (filter.remove(entry)) { trie.remove(entry.getKey()); } } return size - trie.size(); } public interface Filter<V> { boolean remove(Map.Entry<String, V> entry); } /** * 向中加入单词 * @param key * @param value */ public void add(String key, V value) { trie.put(key, value); } public int size() { return trie.size(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SimpleDictionary.java
1
请完成以下Java代码
public void setWorkflowType (final java.lang.String WorkflowType) { set_Value (COLUMNNAME_WorkflowType, WorkflowType); } @Override public java.lang.String getWorkflowType() { return get_ValueAsString(COLUMNNAME_WorkflowType); } @Override public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() {
return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow.java
1
请完成以下Java代码
public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDiagramResourceName() { return diagramResourceName; } public void setDiagramResourceName(String diagramResourceName) { this.diagramResourceName = diagramResourceName; } public boolean hasStartFormKey() { return hasStartFormKey; } public boolean getHasStartFormKey() { return hasStartFormKey; } public void setStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } public void setHasStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } public boolean isGraphicalNotationDefined() { return isGraphicalNotationDefined; } public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) { this.isGraphicalNotationDefined = isGraphicalNotationDefined; } public int getSuspensionState() {
return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public IOSpecification getIoSpecification() { return ioSpecification; } public void setIoSpecification(IOSpecification ioSpecification) { this.ioSpecification = ioSpecification; } public String toString() { return "ProcessDefinitionEntity[" + id + "]"; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public Integer getAppVersion() { return this.appVersion; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java
1
请完成以下Java代码
protected CEditor getEditor() { if (_editor == null) { _editor = new CComboBox<>(); _editor.setRenderer(new ToStringListCellRenderer<Join>() { private static final long serialVersionUID = 1L; @Override protected String renderToString(Join value) { return getDisplayValue(value); } }); // make sure we are setting the model AFTER we set the renderer because else, // the value from combobox editor will not be the one that is returned by rendered _editor.setModel(new DefaultComboBoxModel<>(Join.values())); _editor.enableAutoCompletion(); } return _editor; }
@Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final String displayValue = getDisplayValue(value); return defaultRenderer.getTableCellRendererComponent(table, displayValue, isSelected, hasFocus, row, column); } private String getDisplayValue(final Object value) { if (value == null) { return null; } if (value instanceof Join) { return join2displayName.get(value); } else { return value.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindJoinCellEditor.java
1
请完成以下Java代码
@NonNull Set<String> getActiveProfiles(@NonNull Environment environment) { return environment != null ? toSet(environment.getActiveProfiles(), String.class) : Collections.emptySet(); } @NonNull Set<String> useDefaultProfilesIfEmpty(@NonNull Environment environment, @Nullable Set<String> activeProfiles) { Set<String> resolvedProfiles = CollectionUtils.nullSafeSet(activeProfiles).stream() .filter(StringUtils::hasText) .collect(Collectors.toSet()); if (resolvedProfiles.isEmpty()) { Set<String> defaultProfiles = environment != null ? toSet(environment.getDefaultProfiles(), String.class).stream() .filter(StringUtils::hasText) .collect(Collectors.toSet()) : Collections.emptySet(); if (isNotDefaultProfileOnlySet(defaultProfiles)) {
resolvedProfiles = defaultProfiles; } } return resolvedProfiles; } // The Set of configured Profiles cannot be null, empty or contain only the "default" Profile. boolean isNotDefaultProfileOnlySet(@Nullable Set<String> profiles) { return Objects.nonNull(profiles) && !profiles.isEmpty() && !Collections.singleton(RESERVED_DEFAULT_PROFILE_NAME).containsAll(profiles); } private static @NonNull <T> Set<T> toSet(@Nullable T[] array, @NonNull Class<T> type) { return CollectionUtils.asSet(ArrayUtils.nullSafeArray(array, type)); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\AbstractCacheDataImporterExporter.java
1
请完成以下Java代码
public void setC_BP_Group_Match_ID (final int C_BP_Group_Match_ID) { if (C_BP_Group_Match_ID < 1) set_Value (COLUMNNAME_C_BP_Group_Match_ID, null); else set_Value (COLUMNNAME_C_BP_Group_Match_ID, C_BP_Group_Match_ID); } @Override public int getC_BP_Group_Match_ID() { return get_ValueAsInt(COLUMNNAME_C_BP_Group_Match_ID); } @Override public de.metas.contracts.commission.model.I_C_LicenseFeeSettings getC_LicenseFeeSettings() { return get_ValueAsPO(COLUMNNAME_C_LicenseFeeSettings_ID, de.metas.contracts.commission.model.I_C_LicenseFeeSettings.class); } @Override public void setC_LicenseFeeSettings(final de.metas.contracts.commission.model.I_C_LicenseFeeSettings C_LicenseFeeSettings) { set_ValueFromPO(COLUMNNAME_C_LicenseFeeSettings_ID, de.metas.contracts.commission.model.I_C_LicenseFeeSettings.class, C_LicenseFeeSettings); } @Override public void setC_LicenseFeeSettings_ID (final int C_LicenseFeeSettings_ID) { if (C_LicenseFeeSettings_ID < 1) set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, null); else set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, C_LicenseFeeSettings_ID); } @Override public int getC_LicenseFeeSettings_ID() { return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID); } @Override public void setC_LicenseFeeSettingsLine_ID (final int C_LicenseFeeSettingsLine_ID) {
if (C_LicenseFeeSettingsLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, C_LicenseFeeSettingsLine_ID); } @Override public int getC_LicenseFeeSettingsLine_ID() { return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettingsLine_ID); } @Override public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints) { set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); } @Override public BigDecimal getPercentOfBasePoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettingsLine.java
1
请完成以下Java代码
public long findCleanableHistoricBatchesReportCountByCriteria(CleanableHistoricBatchReportImpl query, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); if (batchOperationsForHistoryCleanup.isEmpty()) { return (Long) getDbEntityManager().selectOne("selectOnlyFinishedBatchesReportEntitiesCount", query); } else { return (Long) getDbEntityManager().selectOne("selectFinishedBatchesReportEntitiesCount", query); } } public DbOperation deleteHistoricBatchesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricBatchEntity.class, "deleteHistoricBatchesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } public void addRemovalTimeById(String id, Date removalTime) {
CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricIncidentManager() .addRemovalTimeToHistoricIncidentsByBatchId(id, removalTime); commandContext.getHistoricJobLogManager() .addRemovalTimeToJobLogByBatchId(id, removalTime); Map<String, Object> parameters = new HashMap<>(); parameters.put("id", id); parameters.put("removalTime", removalTime); getDbEntityManager() .updatePreserveOrder(HistoricBatchEntity.class, "updateHistoricBatchRemovalTimeById", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricBatchManager.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtAuthorizationConfiguration { @Bean SecurityFilterChain customJwtSecurityChain(HttpSecurity http, JwtAuthorizationProperties props) throws Exception { // @formatter:off return http .authorizeHttpRequests( r -> r.anyRequest().authenticated()) .oauth2Login(oauth2 -> oauth2.userInfoEndpoint(ep -> ep.oidcUserService(customOidcUserService(props)))) .build(); // @formatter:on } private OAuth2UserService<OidcUserRequest, OidcUser> customOidcUserService(JwtAuthorizationProperties props) { final OidcUserService delegate = new OidcUserService(); final GroupsClaimMapper mapper = new GroupsClaimMapper( props.getAuthoritiesPrefix(),
props.getGroupsClaim(), props.getGroupToAuthorities()); return userRequest -> { OidcUser oidcUser = delegate.loadUser(userRequest); // Enrich standard authorities with groups Set<GrantedAuthority> mappedAuthorities = new HashSet<>(); mappedAuthorities.addAll(oidcUser.getAuthorities()); mappedAuthorities.addAll(mapper.mapAuthorities(oidcUser)); oidcUser = new NamedOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo(),oidcUser.getName()); return oidcUser; }; } }
repos\tutorials-master\spring-security-modules\spring-security-azuread\src\main\java\com\baeldung\security\azuread\config\JwtAuthorizationConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public List<SmsCoupon> list(Integer useStatus) { UmsMember member = memberService.getCurrentMember(); return couponHistoryDao.getCouponList(member.getId(),useStatus); } private BigDecimal calcTotalAmount(List<CartPromotionItem> cartItemList) { BigDecimal total = new BigDecimal("0"); for (CartPromotionItem item : cartItemList) { BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount()); total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity()))); } return total; } private BigDecimal calcTotalAmountByproductCategoryId(List<CartPromotionItem> cartItemList,List<Long> productCategoryIds) { BigDecimal total = new BigDecimal("0"); for (CartPromotionItem item : cartItemList) { if(productCategoryIds.contains(item.getProductCategoryId())){
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount()); total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity()))); } } return total; } private BigDecimal calcTotalAmountByProductId(List<CartPromotionItem> cartItemList,List<Long> productIds) { BigDecimal total = new BigDecimal("0"); for (CartPromotionItem item : cartItemList) { if(productIds.contains(item.getProductId())){ BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount()); total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity()))); } } return total; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberCouponServiceImpl.java
2
请完成以下Java代码
public String getStackTrace() { return stackTrace; } /** * Sets the value of the stackTrace property. * * @param value * allowed object is * {@link String } * */ public void setStackTrace(String value) { this.stackTrace = value; } /** * Gets the value of the beschreibung property. * * @return * possible object is * {@link String } * */ public String getBeschreibung() { return beschreibung; }
/** * Sets the value of the beschreibung property. * * @param value * allowed object is * {@link String } * */ public void setBeschreibung(String value) { this.beschreibung = value; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Fehlerbehandlung.java
1
请完成以下Java代码
public LogicExpressionBuilder setLeft(final ILogicExpression left) { this.left = left; return this; } public LogicExpressionBuilder setRight(final ILogicExpression right) { this.right = right; return this; } /** * Sets given <code>child</code> expression to * <ul> * <li>left, if left was not already set * <li>right, if right was not already set * </ul> * * @param child * @return this * @throws ExpressionCompileException if both left and right were already set */ public LogicExpressionBuilder addChild(final ILogicExpression child) { if (getLeft() == null) { setLeft(child); } else if (getRight() == null) { setRight(child); } else { throw new ExpressionCompileException("Cannot add " + child + " to " + this + " because both left and right are already filled");
} return this; } public LogicExpressionBuilder setOperator(final String operator) { this.operator = operator; return this; } public ILogicExpression getLeft() { return left; } public ILogicExpression getRight() { return right; } public String getOperator() { return operator; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpressionBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<? extends GrantedAuthority> getAuthorities() { return grantedAuthorities; } @Override public Object getCredentials() { return null; } @Override public Object getDetails() { return null; } @Override public Object getPrincipal() { return name; }
@Override public boolean isAuthenticated() { return isAuthenticated; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { this.isAuthenticated = isAuthenticated; } @Override public String getName() { return name; } }
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\AuthenticationImpl.java
2
请完成以下Java代码
default GraphQlClientInterceptor andThen(GraphQlClientInterceptor interceptor) { return new GraphQlClientInterceptor() { @Override public Mono<ClientGraphQlResponse> intercept(ClientGraphQlRequest request, Chain chain) { return GraphQlClientInterceptor.this.intercept( request, (nextRequest) -> interceptor.intercept(nextRequest, chain)); } @Override public Flux<ClientGraphQlResponse> interceptSubscription(ClientGraphQlRequest request, SubscriptionChain chain) { return GraphQlClientInterceptor.this.interceptSubscription( request, (nextRequest) -> interceptor.interceptSubscription(nextRequest, chain)); } }; } /** * Contract to delegate to the rest of a non-blocking execution chain. */ interface Chain { /** * Delegate to the rest of the chain to perform the request. * @param request the request to perform * @return {@code Mono} with the response * @see GraphQlClient.RequestSpec#execute() */ Mono<ClientGraphQlResponse> next(ClientGraphQlRequest request);
} /** * Contract for delegation of subscription requests to the rest of the chain. */ interface SubscriptionChain { /** * Delegate to the rest of the chain to perform the request. * @param request the request to perform * @return {@code Flux} with responses * @see GraphQlClient.RequestSpec#executeSubscription() */ Flux<ClientGraphQlResponse> next(ClientGraphQlRequest request); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\GraphQlClientInterceptor.java
1
请完成以下Java代码
public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); if (superExecutionId != null) { referenceIdAndClass.put(this.superExecutionId, ExecutionEntity.class); } if (parentId != null) { referenceIdAndClass.put(this.parentId, ExecutionEntity.class); } if (processInstanceId != null) { referenceIdAndClass.put(this.processInstanceId, ExecutionEntity.class); } if (processDefinitionId != null) { referenceIdAndClass.put(this.processDefinitionId, ProcessDefinitionEntity.class); } return referenceIdAndClass; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } @Override public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } @Override public String getCurrentActivityId() { return activityId; } @Override public String getCurrentActivityName() { return activityName; } @Override public FlowElement getBpmnModelElementInstance() { BpmnModelInstance bpmnModelInstance = getBpmnModelInstance(); if (bpmnModelInstance != null) { ModelElementInstance modelElementInstance = null; if (ExecutionListener.EVENTNAME_TAKE.equals(eventName)) { modelElementInstance = bpmnModelInstance.getModelElementById(transition.getId()); } else { modelElementInstance = bpmnModelInstance.getModelElementById(activityId); } try { return (FlowElement) modelElementInstance; } catch (ClassCastException e) { ModelElementType elementType = modelElementInstance.getElementType(); throw LOG.castModelInstanceException(modelElementInstance, "FlowElement", elementType.getTypeName(), elementType.getTypeNamespace(), e); } } else { return null; } } @Override
public BpmnModelInstance getBpmnModelInstance() { if (processDefinitionId != null) { return Context.getProcessEngineConfiguration().getDeploymentCache().findBpmnModelInstanceForProcessDefinition(processDefinitionId); } else { return null; } } @Override public ProcessEngineServices getProcessEngineServices() { return Context.getProcessEngineConfiguration().getProcessEngine(); } @Override public ProcessEngine getProcessEngine() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public String getProcessDefinitionTenantId() { return getProcessDefinition().getTenantId(); } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } @Override public String getProcessDefinitionKey() { return processDefinitionKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExecutionEntity.java
1
请完成以下Java代码
public Builder setBPartnerId(final BPartnerId bpartnerId) { this.bpartnerId = bpartnerId; return this; } private BPartnerId getBPartnerId() { return bpartnerId; } @Nullable private HUEditorRowAttributesProvider getAttributesProviderOrNull() { return attributesProvider; } public Builder setAttributesProvider(@Nullable final HUEditorRowAttributesProvider attributesProvider) { this.attributesProvider = attributesProvider; return this; } public Builder addIncludedRow(@NonNull final HUEditorRow includedRow) { if (includedRows == null) { includedRows = new ArrayList<>(); } includedRows.add(includedRow); return this; } private List<HUEditorRow> buildIncludedRows() { if (includedRows == null || includedRows.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(includedRows); } public Builder setReservedForOrderLine(@Nullable final OrderLineId orderLineId) { orderLineReservation = orderLineId; huReserved = orderLineId != null; return this; } public Builder setClearanceStatus(@Nullable final JSONLookupValue clearanceStatusLookupValue) {
clearanceStatus = clearanceStatusLookupValue; return this; } public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate) { this.customProcessApplyPredicate = processApplyPredicate; return this; } @Nullable private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate() { return this.customProcessApplyPredicate; } /** * @param currentRow the row that is currently constructed using this builder */ private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow) { final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder(); for (final HUEditorRow includedRow : buildIncludedRows()) { includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations()); } if (orderLineReservation != null) { includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow); } return includedOrderLineReservationsBuilder.build(); } } @lombok.Builder @lombok.Value public static class HUEditorRowHierarchy { @NonNull HUEditorRow cuRow; @Nullable HUEditorRow parentRow; @Nullable HUEditorRow topLevelRow; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java
1
请完成以下Java代码
private WorkpackageLogEntry createLogEntry(@NonNull final String msg, final Object... msgParameters) { final FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters); return WorkpackageLogEntry.builder() .message(msgAndAdIssueId.getFormattedMessage()) .adIssueId(msgAndAdIssueId.getAdIsueId().orElse(null)) .timestamp(SystemTime.asInstant()) .workpackageId(workpackageId) .adClientId(adClientId) .userId(userId) .build(); } @Override public void flush() { final List<WorkpackageLogEntry> logEntries = buffer; this.buffer = null;
if (logEntries == null || logEntries.isEmpty()) { return; } try { logsRepository.saveLogs(logEntries); } catch (final Exception ex) { // make sure flush never fails logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries.size(), logEntries, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageLoggable.java
1
请完成以下Java代码
protected String doIt() throws Exception { deactivateBPartnersAndRelatedEntries(); return MSG_OK; } private void deactivateBPartnersAndRelatedEntries() { final Instant now = SystemTime.asInstant(); final List<BPartnerId> partnerIdsToDeactivate = queryBL.createQueryBuilder(I_AD_OrgChange_History.class) .addCompareFilter(I_AD_OrgChange_History.COLUMNNAME_Date_OrgChange, CompareQueryFilter.Operator.LESS_OR_EQUAL, now) .andCollect(I_AD_OrgChange_History.COLUMNNAME_C_BPartner_From_ID, I_C_BPartner.class) .create() .idsAsSet(BPartnerId::ofRepoId) .asList(); partnerIdsToDeactivate.stream() .forEach( partnerId -> addLog("Business Partner {} was deactivated because it was moved to another organization.", partnerId)); if (Check.isEmpty(partnerIdsToDeactivate)) { // nothing to do return; } deactivateBankAccounts(partnerIdsToDeactivate, now); deactivateUsers(partnerIdsToDeactivate, now); deactivateLocations(partnerIdsToDeactivate, now); deactivatePartners(partnerIdsToDeactivate, now); } private void deactivateBankAccounts(final List<BPartnerId> partnerIds, final Instant date) { final ICompositeQueryUpdater<I_C_BP_BankAccount> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BP_BankAccount.class) .addSetColumnValue(I_C_BP_BankAccount.COLUMNNAME_IsActive, false); queryBL
.createQueryBuilder(I_C_BP_BankAccount.class) .addInArrayFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, partnerIds) .create() .update(queryUpdater); } private void deactivateUsers(final List<BPartnerId> partnerIds, final Instant date) { final ICompositeQueryUpdater<I_AD_User> queryUpdater = queryBL.createCompositeQueryUpdater(I_AD_User.class) .addSetColumnValue(I_AD_User.COLUMNNAME_IsActive, false); queryBL .createQueryBuilder(I_AD_User.class) .addInArrayFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, partnerIds) .create() .update(queryUpdater); } private void deactivateLocations(final List<BPartnerId> partnerIds, final Instant date) { final ICompositeQueryUpdater<I_C_BPartner_Location> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BPartner_Location.class) .addSetColumnValue(I_C_BPartner_Location.COLUMNNAME_IsActive, false); queryBL .createQueryBuilder(I_C_BPartner_Location.class) .addInArrayFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, partnerIds) .create() .update(queryUpdater); } private void deactivatePartners(final List<BPartnerId> partnerIds, final Instant date) { final ICompositeQueryUpdater<I_C_BPartner> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BPartner.class) .addSetColumnValue(I_C_BPartner.COLUMNNAME_IsActive, false); queryBL .createQueryBuilder(I_C_BPartner.class) .addInArrayFilter(I_C_BPartner.COLUMNNAME_C_BPartner_ID, partnerIds) .create() .update(queryUpdater); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\process\C_BPartner_DeactivateAfterOrgChange.java
1
请完成以下Java代码
private static final Boolean toConstantValueIfPossible(final ILogicExpression expr) { try { if (expr.isConstant()) { return expr.constantValue(); } if (!expr.getParameterNames().isEmpty()) { return null; } // Evaluate the expression now and replace it with a constant expression, but preserve the expression string. final Evaluatee ctx = null; // not needed final boolean value = expr.evaluate(ctx, OnVariableNotFound.Fail); return value; } catch (final Exception ex) { logger.warn("Failed evaluating {} to constant. Skipped.", expr, ex); return null; } } public LogicExpressionBuilder setLeft(final ILogicExpression left) { this.left = left; return this; } public LogicExpressionBuilder setRight(final ILogicExpression right) { this.right = right; return this; } /** * Sets given <code>child</code> expression to * <ul> * <li>left, if left was not already set * <li>right, if right was not already set * </ul> *
* @param child * @return this * @throws ExpressionCompileException if both left and right were already set */ public LogicExpressionBuilder addChild(final ILogicExpression child) { if (getLeft() == null) { setLeft(child); } else if (getRight() == null) { setRight(child); } else { throw new ExpressionCompileException("Cannot add " + child + " to " + this + " because both left and right are already filled"); } return this; } public LogicExpressionBuilder setOperator(final String operator) { this.operator = operator; return this; } public ILogicExpression getLeft() { return left; } public ILogicExpression getRight() { return right; } public String getOperator() { return operator; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpressionBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { @Id @GeneratedValue private long id; private String name; private String email; @Type(type = "org.hibernate.type.UUIDCharType") private UUID uuid; public Customer(String name, String email) { this.name = name; this.email = email; } public Customer(String name, String email, UUID uuid) { this.name = name; this.email = email; this.uuid = uuid; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public UUID getUuid() { return this.uuid; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-filtering\src\main\java\com\baeldung\entity\Customer.java
2
请完成以下Java代码
public void setAD_UserQuery_ID (int AD_UserQuery_ID) { if (AD_UserQuery_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UserQuery_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UserQuery_ID, Integer.valueOf(AD_UserQuery_ID)); } /** Get User Query. @return Saved User Query */ @Override public int getAD_UserQuery_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserQuery_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validierungscode. @param Code Validation Code */ @Override public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validierungscode. @return Validation Code */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Mandatory Parameters. @param IsManadatoryParams Mandatory Parameters */ @Override public void setIsManadatoryParams (boolean IsManadatoryParams) { set_Value (COLUMNNAME_IsManadatoryParams, Boolean.valueOf(IsManadatoryParams)); } /** Get Mandatory Parameters. @return Mandatory Parameters */ @Override public boolean isManadatoryParams () { Object oo = get_Value(COLUMNNAME_IsManadatoryParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo);
} return false; } /** Set Display All Parameters. @param IsShowAllParams Display All Parameters */ @Override public void setIsShowAllParams (boolean IsShowAllParams) { set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams)); } /** Get Display All Parameters. @return Display All Parameters */ @Override public boolean isShowAllParams () { Object oo = get_Value(COLUMNNAME_IsShowAllParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
1
请完成以下Java代码
public class BackwardsCompatiblePropertiesLoader implements EnvironmentPostProcessor, Ordered { public static final int DEFAULT_ORDER = ConfigDataEnvironmentPostProcessor.ORDER - 1; private static final PropertySourceFactory DEFAULT_PROPERTY_SOURCE_FACTORY = new DefaultPropertySourceFactory(); private final Logger logger = LoggerFactory.getLogger(getClass()); private static final String[] DEPRECATED_LOCATIONS = { "classpath:db.properties", "classpath:engine.properties" }; private int order = DEFAULT_ORDER; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { ResourceLoader resourceLoader = application.getResourceLoader(); if (resourceLoader == null) { resourceLoader = new DefaultResourceLoader(); } MutablePropertySources propertySources = environment.getPropertySources(); for (String location : DEPRECATED_LOCATIONS) { try { Resource resource = resourceLoader.getResource(location); PropertySource<?> propertySource = DEFAULT_PROPERTY_SOURCE_FACTORY.createPropertySource(null, new EncodedResource(resource)); if (propertySources.contains(propertySource.getName())) { propertySources.replace(propertySource.getName(), propertySource); } else { propertySources.addLast(propertySource);
} logger.warn("Using deprecated property source {} please switch to using Spring Boot externalized configuration", propertySource); } catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) { // We are always ignoring the deprecated resources. This is done in the same way as in the Spring ConfigurationClassParsers // Placeholders not resolvable or resource not found when trying to open it if (logger.isInfoEnabled()) { logger.info("Properties location [{}] not resolvable: {}", location, ex.getMessage()); } } catch (IOException ex) { throw new UncheckedIOException("Failed to create property source", ex); } } } @Override public int getOrder() { return order; } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\BackwardsCompatiblePropertiesLoader.java
1
请完成以下Java代码
public int getM_AttributeSetInstance_ID() { return ddOrderLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return ddOrderLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { values.setC_UOM_ID(uomId); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { ddOrderLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return ddOrderLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { ddOrderLine.setQtyEnteredTU(qtyPacks); values.setQtyTU(qtyPacks); } @Override public boolean isInDispute() {
// order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public void setC_BPartner_ID(final int partnerId) { // nothing } @Override public int getC_BPartner_ID() { return ddOrderLine.getDD_Order().getC_BPartner_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\lowlevel\model\DDOrderLineHUPackingAware.java
1
请完成以下Java代码
private Object makeEncryptable(Object propertySource) { return propertyConverter.makeEncryptable((PropertySource<?>) propertySource); } /** {@inheritDoc} */ @Override public Object invoke(MethodInvocation invocation) throws Throwable { String method = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); switch (method) { case "addFirst": envCopy.addFirst((PropertySource<?>) arguments[0]); return invocation.getMethod().invoke(invocation.getThis(), makeEncryptable(arguments[0])); case "addLast": envCopy.addLast((PropertySource<?>) arguments[0]); return invocation.getMethod().invoke(invocation.getThis(), makeEncryptable(arguments[0])); case "addBefore": envCopy.addBefore((String) arguments[0], (PropertySource<?>) arguments[1]); return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "addAfter": envCopy.addAfter((String) arguments[0], (PropertySource<?>) arguments[1]); return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1])); case "replace": envCopy.replace((String) arguments[0], (PropertySource<?>) arguments[1]); return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1])); case "remove": envCopy.remove((String) arguments[0]); return invocation.proceed(); default: return invocation.proceed(); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\aop\EncryptableMutablePropertySourcesInterceptor.java
1
请完成以下Java代码
public int getAD_AlertProcessorLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_AlertProcessorLog_ID); if (ii == null) return 0; return ii.intValue(); } /** Set BinaryData. @param BinaryData Binary Data */ public void setBinaryData (byte[] BinaryData) { set_Value (COLUMNNAME_BinaryData, BinaryData); } /** Get BinaryData. @return Binary Data */ public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** 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 Error. @param IsError An Error occured in the execution */ public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Error. @return An Error occured in the execution */ public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Reference. @param Reference Reference for this record */ public void setReference (String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference); } /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessorLog.java
1
请完成以下Java代码
public class VariableInstanceResourceImpl extends AbstractResourceProvider<VariableInstanceQuery, VariableInstance, VariableInstanceDto> implements VariableInstanceResource { public VariableInstanceResourceImpl(String variableId, ProcessEngine engine) { super(variableId, engine); } protected VariableInstanceQuery baseQuery() { return getEngine().getRuntimeService().createVariableInstanceQuery().variableId(getId()); } @Override protected Query<VariableInstanceQuery, VariableInstance> baseQueryForBinaryVariable() { return baseQuery().disableCustomObjectDeserialization(); } @Override protected Query<VariableInstanceQuery, VariableInstance> baseQueryForVariable(boolean deserializeObjectValue) { VariableInstanceQuery baseQuery = baseQuery(); // do not fetch byte arrays baseQuery.disableBinaryFetching(); if (!deserializeObjectValue) { baseQuery.disableCustomObjectDeserialization(); } return baseQuery; }
@Override protected TypedValue transformQueryResultIntoTypedValue(VariableInstance queryResult) { return queryResult.getTypedValue(); } @Override protected VariableInstanceDto transformToDto(VariableInstance queryResult) { return VariableInstanceDto.fromVariableInstance(queryResult); } @Override protected String getResourceNameForErrorMessage() { return "Variable instance"; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\VariableInstanceResourceImpl.java
1
请完成以下Java代码
public boolean isSelectionNone() { final Object selectedItem = getSelectedItem(); if (selectedItem == null) { return true; } else { return Check.isEmpty(selectedItem.toString(), true); } } @Override public E getSelectedItem() { final Object selectedItemObj = super.getSelectedItem(); @SuppressWarnings("unchecked") final E selectedItem = (E)selectedItemObj; return selectedItem; } /** * Enables auto completion (while user writes) on this combobox. * * @return combobox's auto-completion instance for further configurations */ public final ComboBoxAutoCompletion<E> enableAutoCompletion() { return ComboBoxAutoCompletion.enable(this); } /**
* Disable autocompletion on this combobox. * * If the autocompletion was not enabled, this method does nothing. */ public final void disableAutoCompletion() { ComboBoxAutoCompletion.disable(this); } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return JComboBoxCopyPasteSupportEditor.ofComponent(this); } } // CComboBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CComboBox.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { return modifyResponseBodyFilterFactory .apply(c -> c.setRewriteFunction(JsonNode.class, JsonNode.class, new Scrubber(config))); } public static class Config { private String fields; private String replacement; public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } } public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> { private final Pattern fields; private final String replacement; public Scrubber(Config config) { this.fields = Pattern.compile(config.getFields()); this.replacement = config.getReplacement(); } @Override public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) { return Mono.just(scrubRecursively(u)); } private JsonNode scrubRecursively(JsonNode u) { if ( !u.isContainerNode()) { return u; }
if ( u.isObject()) { ObjectNode node = (ObjectNode)u; node.fields().forEachRemaining((f) -> { if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) { f.setValue(TextNode.valueOf(replacement)); } else { f.setValue(scrubRecursively(f.getValue())); } }); } else if ( u.isArray()) { ArrayNode array = (ArrayNode)u; for ( int i = 0 ; i < array.size() ; i++ ) { array.set(i, scrubRecursively(array.get(i))); } } return u; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ScrubResponseGatewayFilterFactory.java
1
请完成以下Spring Boot application配置
spring: security: oauth2: authorizationserver: issuer: https://provider.com endpoint: authorization-uri: /authorize token-uri: /token jwk-set-uri: /jwks token-revocation-uri: /revoke token-introspection-uri: /introspect pushed-authorization-request-uri: /par oidc: logout-uri: /logout client-registration-uri: /register user-info-uri: /user client: messaging-client: registration: client-id: messaging-client client-secre
t: "{noop}secret" client-authentication-methods: - client_secret_basic authorization-grant-types: - client_credentials scopes: - message.read - message.write
repos\spring-boot-4.0.1\smoke-test\spring-boot-smoke-test-oauth2-authorization-server\src\main\resources\application.yml
2
请完成以下Java代码
private Properties createContext(final UserAuthToken token) { final IUserRolePermissions permissions = userRolePermissionsDAO.getUserRolePermissions(UserRolePermissionsKey.builder() .userId(token.getUserId()) .roleId(token.getRoleId()) .clientId(token.getClientId()) .date(SystemTime.asDayTimestamp()) .build()); final UserInfo userInfo = getUserInfo(token.getUserId()); final Properties ctx = Env.newTemporaryCtx(); Env.setContext(ctx, Env.CTXNAME_AD_Client_ID, permissions.getClientId().getRepoId()); Env.setContext(ctx, Env.CTXNAME_AD_Org_ID, OrgId.toRepoId(token.getOrgId())); Env.setContext(ctx, Env.CTXNAME_AD_User_ID, UserId.toRepoId(permissions.getUserId())); Env.setContext(ctx, Env.CTXNAME_AD_Role_ID, RoleId.toRepoId(permissions.getRoleId())); Env.setContext(ctx, Env.CTXNAME_AD_Language, userInfo.getAdLanguage()); return ctx; } public UserAuthToken getOrCreateNewToken(@NonNull final CreateUserAuthTokenRequest request) { return userAuthTokenRepo.getOrCreateNew(request); } private UserInfo getUserInfo(@NonNull final UserId userId) { return userInfoById.getOrLoad(userId, this::retrieveUserInfo); }
private UserInfo retrieveUserInfo(@NonNull final UserId userId) { final I_AD_User user = userDAO.getById(userId); return UserInfo.builder() .userId(userId) .adLanguage(StringUtils.trimBlankToOptional(user.getAD_Language()).orElseGet(Language::getBaseAD_Language)) .build(); } // // // @Value @Builder private static class UserInfo { @NonNull UserId userId; @NonNull String adLanguage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenService.java
1
请完成以下Java代码
public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getProbability() { return probability; } public void setProbability(Float probability) { this.probability = probability; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((count == null) ? 0 : count.hashCode()); result = prime * result + ((gender == null) ? 0 : gender.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((probability == null) ? 0 : probability.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameGenderEntity other = (NameGenderEntity) obj; if (count == null) { if (other.count != null) return false; } else if (!count.equals(other.count)) return false; if (gender == null) { if (other.gender != null)
return false; } else if (!gender.equals(other.gender)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (probability == null) { if (other.probability != null) return false; } else if (!probability.equals(other.probability)) return false; return true; } @Override public String toString() { return "NameGenderModel [count=" + count + ", gender=" + gender + ", name=" + name + ", probability=" + probability + "]"; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameGenderEntity.java
1
请完成以下Java代码
public void setAge(int age) { this.age = age; } public List<Book> getCheapBooks() { return cheapBooks; } public void setCheapBooks(List<Book> cheapBooks) { this.cheapBooks = cheapBooks; } public List<Book> getRestOfBooks() { return restOfBooks; } public void setRestOfBooks(List<Book> restOfBooks) {
this.restOfBooks = restOfBooks; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFilterAssociation\src\main\java\com\bookstore\entity\Author.java
1
请在Spring Boot框架中完成以下Java代码
public class JwksConfiguration { @Bean public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } @Bean public JWKSource<SecurityContext> jwkSource() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey) .privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build();
JWKSet jwkSet = new JWKSet(rsaKey); return new ImmutableJWKSet<>(jwkSet); } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); } return keyPair; } }
repos\tutorials-master\spring-security-modules\spring-security-pkce\pkce-auth-server\src\main\java\com\baeldung\security\pkce\authserver\conf\JwksConfiguration.java
2
请完成以下Java代码
public void setRemote_Client_ID (int Remote_Client_ID) { if (Remote_Client_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID)); } /** Get Remote Client. @return Remote Client to be used to replicate / synchronize data with. */ public int getRemote_Client_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Remote Organization. @param Remote_Org_ID Remote Organization to be used to replicate / synchronize data with. */ public void setRemote_Org_ID (int Remote_Org_ID) { if (Remote_Org_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID)); } /** Get Remote Organization. @return Remote Organization to be used to replicate / synchronize data with. */ public int getRemote_Org_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
1
请完成以下Java代码
private boolean shouldPerformMfa(@Nullable Authentication current, Authentication authenticationResult) { if (!this.mfaEnabled) { return false; } if (current == null || !current.isAuthenticated()) { return false; } if (!declaresToBuilder(authenticationResult)) { return false; } return current.getName().equals(authenticationResult.getName()); } private static boolean declaresToBuilder(Authentication authentication) { for (Method method : authentication.getClass().getDeclaredMethods()) { if (method.getName().equals("toBuilder") && method.getParameterTypes().length == 0) { return true; } } return false; } @Override protected String getAlreadyFilteredAttributeName() { String name = getFilterName(); if (name == null) { name = getClass().getName().concat("-" + System.identityHashCode(this)); } return name + ALREADY_FILTERED_SUFFIX; } private void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { this.securityContextHolderStrategy.clearContext(); this.failureHandler.onAuthenticationFailure(request, response, failed);
} private void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException { SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); this.successHandler.onAuthenticationSuccess(request, response, chain, authentication); } private @Nullable Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, ServletException { Authentication authentication = this.authenticationConverter.convert(request); if (authentication == null) { return null; } AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request); Authentication authenticationResult = authenticationManager.authenticate(authentication); if (authenticationResult == null) { throw new ServletException("AuthenticationManager should not return null Authentication object."); } return authenticationResult; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AuthenticationFilter.java
1