instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getId() { return name().toLowerCase(Locale.ENGLISH); } /** * Return the url prefixes of this driver. * @return the url prefixes */ protected Collection<String> getUrlPrefixes() { return Collections.singleton(name().toLowerCase(Locale.ENGLISH)); } protected boolean matchProductName(String productName) { return this.productName != null && this.productName.equalsIgnoreCase(productName); } /** * Return the driver class name. * @return the class name or {@code null} */ public @Nullable String getDriverClassName() { return this.driverClassName; } /** * Return the XA driver source class name. * @return the class name or {@code null} */ public @Nullable String getXaDataSourceClassName() { return this.xaDataSourceClassName; } /** * Return the validation query. * @return the validation query or {@code null} */ public @Nullable String getValidationQuery() { return this.validationQuery; } /** * Find a {@link DatabaseDriver} for the given URL. * @param url the JDBC URL * @return the database driver or {@link #UNKNOWN} if not found */ public static DatabaseDriver fromJdbcUrl(@Nullable String url) { if (StringUtils.hasLength(url)) { Assert.isTrue(url.startsWith("jdbc"), "'url' must start with \"jdbc\""); String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH); for (DatabaseDriver driver : values()) {
for (String urlPrefix : driver.getUrlPrefixes()) { String prefix = ":" + urlPrefix + ":"; if (driver != UNKNOWN && urlWithoutPrefix.startsWith(prefix)) { return driver; } } } } return UNKNOWN; } /** * Find a {@link DatabaseDriver} for the given product name. * @param productName product name * @return the database driver or {@link #UNKNOWN} if not found */ public static DatabaseDriver fromProductName(@Nullable String productName) { if (StringUtils.hasLength(productName)) { for (DatabaseDriver candidate : values()) { if (candidate.matchProductName(productName)) { return candidate; } } } return UNKNOWN; } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\DatabaseDriver.java
1
请完成以下Java代码
private ShipmentScheduleAndJobSchedulesCollection getShipmentScheduleAndJobSchedulesCollection() { ShipmentScheduleAndJobSchedulesCollection result = this._shipmentScheduleAndJobSchedulesCollection; if (result == null) { result = this._shipmentScheduleAndJobSchedulesCollection = retrieveShipmentScheduleAndJobSchedulesCollection(); } return result; } private ShipmentScheduleAndJobSchedulesCollection retrieveShipmentScheduleAndJobSchedulesCollection() { final boolean skipAlreadyProcessedItems = false; // yes, we want items whose queue packages were already processed! This is a workaround, but we need it that way. // Background: otherwise, after we did a partial delivery on a shipment schedule, we cannot deliver the rest, because the shipment schedule is already within a processed work package. // Note that it's the customer's declared responsibility to to verify the shipments // FIXME: find a better solution. If nothing else, then "split" the undelivered remainder of a partially delivered schedule off into a new schedule (we do that with ICs too). final TableRecordReferenceSet recordRefs = queueDAO.retrieveQueueElementRecordRefs(getQueueWorkPackageId(), skipAlreadyProcessedItems); final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds = recordRefs.getRecordIdsByTableName(I_M_ShipmentSchedule.Table_Name, ShipmentScheduleId::ofRepoId); final ImmutableSet<PickingJobScheduleId> jobScheduleIds = recordRefs.getRecordIdsByTableName(I_M_Picking_Job_Schedule.Table_Name, PickingJobScheduleId::ofRepoId); return pickingJobScheduleService.getShipmentScheduleAndJobSchedulesCollection(shipmentScheduleIds, jobScheduleIds); }
private Set<HuId> getOnlyLUIds() { final IParams parameters = getParameters(); return RepoIdAwares.ofCommaSeparatedSet( parameters.getParameterAsString(ShipmentScheduleWorkPackageParameters.PARAM_OnlyLUIds), HuId.class ); } private void closeSchedules() { final ShipmentScheduleAndJobSchedulesCollection schedules = getShipmentScheduleAndJobSchedulesCollection(); pickingJobScheduleService.markAsProcessed(schedules.getJobScheduleIds()); final HashSet<ShipmentScheduleId> shipmentScheduleIdsToClose = new HashSet<>(); shipmentScheduleIdsToClose.addAll(schedules.getShipmentScheduleIdsWithoutJobSchedules()); shipmentScheduleIdsToClose.addAll(pickingJobScheduleService.getShipmentScheduleIdsWithAllJobSchedulesProcessedOrMissing(schedules.getShipmentScheduleIdsWithJobSchedules())); shipmentScheduleBL.closeShipmentSchedules(shipmentScheduleIdsToClose); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\async\GenerateInOutFromShipmentSchedules.java
1
请完成以下Java代码
public void setPostal(final String postal) { this.postal = postal; this.postalSet = true; } public void setCity(final String city) { this.city = city; this.citySet = true; } public void setDistrict(final String district) { this.district = district; this.districtSet = true; } public void setRegion(final String region) { this.region = region; this.regionSet = true; } public void setCountryCode(final String countryCode) { this.countryCode = countryCode; this.countryCodeSet = true; } public void setGln(final String gln) { this.gln = gln; this.glnSet = true; } public void setShipTo(final Boolean shipTo) { this.shipTo = shipTo; this.shipToSet = true; } public void setShipToDefault(final Boolean shipToDefault) { this.shipToDefault = shipToDefault; this.shipToDefaultSet = true;
} public void setBillTo(final Boolean billTo) { this.billTo = billTo; this.billToSet = true; } public void setBillToDefault(final Boolean billToDefault) { this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestLocation.java
1
请完成以下Java代码
public WeightingSpecifications getDefault() { return getMap().getDefault(); } public WeightingSpecificationsMap getMap() { return cache.getOrLoad(0, this::retrieveMap); } private WeightingSpecificationsMap retrieveMap() { final ImmutableList<WeightingSpecifications> list = queryBL .createQueryBuilder(I_PP_Weighting_Spec.class) .addEqualsFilter(I_PP_Weighting_Spec.COLUMNNAME_AD_Client_ID, ClientId.METASFRESH) .addOnlyActiveRecordsFilter() .create()
.stream() .map(WeightingSpecificationsRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new WeightingSpecificationsMap(list); } public static WeightingSpecifications fromRecord(I_PP_Weighting_Spec record) { return WeightingSpecifications.builder() .id(WeightingSpecificationsId.ofRepoId(record.getPP_Weighting_Spec_ID())) .weightChecksRequired(record.getWeightChecksRequired()) .tolerance(Percent.of(record.getTolerance_Perc())) .uomId(UomId.ofRepoId(record.getC_UOM_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\spec\WeightingSpecificationsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public Attachment metadata(AttachmentMetadata metadata) { this.metadata = metadata; return this; } /** * Get metadata * @return metadata **/ @Schema(description = "") public AttachmentMetadata getMetadata() { return metadata; } public void setMetadata(AttachmentMetadata metadata) { this.metadata = metadata; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Attachment attachment = (Attachment) o; return Objects.equals(this._id, attachment._id) && Objects.equals(this.filename, attachment.filename) && Objects.equals(this.contentType, attachment.contentType) && Objects.equals(this.uploadDate, attachment.uploadDate) && Objects.equals(this.metadata, attachment.metadata);
} @Override public int hashCode() { return Objects.hash(_id, filename, contentType, uploadDate, metadata); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Attachment {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" filename: ").append(toIndentedString(filename)).append("\n"); sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); sb.append(" uploadDate: ").append(toIndentedString(uploadDate)).append("\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Attachment.java
2
请完成以下Java代码
private String getAuthorizationHeader(@NonNull final JsonShipperConfig config) { final String auth = config.getUsername() + ":" + config.getPassword(); return "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)); } private <T_Req> void logRequestAsJson(@NonNull final T_Req requestBody) { if (!logger.isTraceEnabled()) { return; } try { final String jsonRequest = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestBody); logger.trace("---- Sending nShift JSON Request ----\n{}", jsonRequest); } catch (final JsonProcessingException ex) { logger.trace("Could not serialize nShift request to JSON for logging", ex); } } private <T_Req> RuntimeException createApiException( @NonNull final T_Req request, @NonNull final HttpStatus statusCode, @NonNull final String responseBody) {
final StringBuilder sb = new StringBuilder(); sb.append("nShift API call failed with status code ").append(statusCode).append("\n"); sb.append("Additional information's:\n"); sb.append("Response body: ").append(responseBody).append("\n"); try { final String requestAsJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request); sb.append("nShiftRequest: ").append(requestAsJson).append("\n"); return new RuntimeException(sb.toString()); } catch (final JsonProcessingException ex) { logger.warn("Failed to serialize nShift request for exception details", ex); return new RuntimeException(sb.toString(), ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftRestClient.java
1
请完成以下Java代码
public I_C_Job getC_Job() throws RuntimeException { return (I_C_Job)MTable.get(getCtx(), I_C_Job.Table_Name) .getPO(getC_Job_ID(), get_TrxName()); } /** Set Position. @param C_Job_ID Job Position */ public void setC_Job_ID (int C_Job_ID) { if (C_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Job_ID, Integer.valueOf(C_Job_ID)); } /** Get Position. @return Job Position */ public int getC_Job_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getC_Job_ID())); } /** 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 Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom)
{ set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java
1
请完成以下Java代码
public static IPair<String, String> splitStreetAndHouseNumberOrNull(@Nullable final String streetAndNumber) { if (EmptyUtil.isBlank(streetAndNumber)) { return null; } final Pattern pattern = Pattern.compile(StringUtils.REGEXP_STREET_AND_NUMBER_SPLIT); final Matcher matcher = pattern.matcher(streetAndNumber); if (!matcher.matches()) { return null; } final String street = matcher.group(1); final String number = matcher.group(2); return ImmutablePair.of(trim(street), trim(number)); } public static String ident(@Nullable final String text, int tabs) { if (text == null || text.isEmpty() || tabs <= 0) { return text; } final String ident = repeat("\t", tabs); return ident + text.trim().replace("\n", "\n" + ident); } public static String repeat(@NonNull final String string, final int times) { if (string.isEmpty()) { return string; }
if (times <= 0) { return ""; } else if (times == 1) { return string; } else { final StringBuilder result = new StringBuilder(string.length() * times); for (int i = 0; i < times; i++) { result.append(string); } return result.toString(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\StringUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class NestedJobDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private JobLauncher jobLauncher; @Autowired private JobRepository jobRepository; @Autowired private PlatformTransactionManager platformTransactionManager; // 父任务 @Bean public Job parentJob() { return jobBuilderFactory.get("parentJob") .start(childJobOneStep()) .next(childJobTwoStep()) .build(); } // 将任务转换为特殊的步骤 private Step childJobOneStep() { return new JobStepBuilder(new StepBuilder("childJobOneStep")) .job(childJobOne()) .launcher(jobLauncher) .repository(jobRepository) .transactionManager(platformTransactionManager) .build(); } // 将任务转换为特殊的步骤 private Step childJobTwoStep() {
return new JobStepBuilder(new StepBuilder("childJobTwoStep")) .job(childJobTwo()) .launcher(jobLauncher) .repository(jobRepository) .transactionManager(platformTransactionManager) .build(); } // 子任务一 private Job childJobOne() { return jobBuilderFactory.get("childJobOne") .start( stepBuilderFactory.get("childJobOneStep") .tasklet((stepContribution, chunkContext) -> { System.out.println("子任务一执行步骤。。。"); return RepeatStatus.FINISHED; }).build() ).build(); } // 子任务二 private Job childJobTwo() { return jobBuilderFactory.get("childJobTwo") .start( stepBuilderFactory.get("childJobTwoStep") .tasklet((stepContribution, chunkContext) -> { System.out.println("子任务二执行步骤。。。"); return RepeatStatus.FINISHED; }).build() ).build(); } }
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\NestedJobDemo.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setErrorMsg (final @Nullable java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override public java.lang.String getErrorMsg() { return get_ValueAsString(COLUMNNAME_ErrorMsg); } @Override public void setEXP_ReplicationTrx_ID (final int EXP_ReplicationTrx_ID) { if (EXP_ReplicationTrx_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_ReplicationTrx_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_ReplicationTrx_ID, EXP_ReplicationTrx_ID); } @Override public int getEXP_ReplicationTrx_ID() { return get_ValueAsInt(COLUMNNAME_EXP_ReplicationTrx_ID); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); }
@Override public void setIsReplicationTrxFinished (final boolean IsReplicationTrxFinished) { set_Value (COLUMNNAME_IsReplicationTrxFinished, IsReplicationTrxFinished); } @Override public boolean isReplicationTrxFinished() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationTrxFinished); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrx.java
1
请在Spring Boot框架中完成以下Java代码
public ClassDiscriminatorMode getClassDiscriminatorMode() { return this.classDiscriminatorMode; } public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) { this.classDiscriminatorMode = classDiscriminatorMode; } public boolean isDecodeEnumsCaseInsensitive() { return this.decodeEnumsCaseInsensitive; } public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) { this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive; } public boolean isUseAlternativeNames() { return this.useAlternativeNames; } public void setUseAlternativeNames(boolean useAlternativeNames) { this.useAlternativeNames = useAlternativeNames; } public boolean isAllowTrailingComma() { return this.allowTrailingComma; } public void setAllowTrailingComma(boolean allowTrailingComma) { this.allowTrailingComma = allowTrailingComma; }
public boolean isAllowComments() { return this.allowComments; } public void setAllowComments(boolean allowComments) { this.allowComments = allowComments; } /** * Enum representing strategies for JSON property naming. The values correspond to * {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot * be directly referenced. */ public enum JsonNamingStrategy { /** * Snake case strategy. */ SNAKE_CASE, /** * Kebab case strategy. */ KEBAB_CASE } }
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
2
请完成以下Java代码
private static SessionFactory buildSessionFactory(String resource) { try { // Create the SessionFactory from hibernate-annotation.cfg.xml Configuration configuration = new Configuration(); configuration.addAnnotatedClass(WebSiteUser.class); configuration.addAnnotatedClass(Element.class); configuration.addAnnotatedClass(Reservation.class); configuration.addAnnotatedClass(Sale.class); configuration.addAnnotatedClass(Employee.class); configuration.addAnnotatedClass(Project.class); configuration.configure(resource); LOGGER.debug("Hibernate Annotation Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) .build(); LOGGER.debug("Hibernate Annotation serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return buildSessionFactory(DEFAULT_RESOURCE); } public static SessionFactory getSessionFactory(String resource) { return buildSessionFactory(resource); } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\manytomany\HibernateUtil.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } if (!securPharmService.hasConfig()) { return ProcessPreconditionsResolution.rejectWithInternalReason("No SecurPharm config"); } // // Retry makes sense only if the SecurPharm product has errors (i.e. was not acquired yet) final SecurPharmProductId productDataResultId = SecurPharmProductId.ofRepoId(context.getSingleSelectedRecordId()); final SecurPharmProduct product = securPharmService.getProductById(productDataResultId); if (!product.isError()) { ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final DataMatrixCode dataMatrix = getDataMatrix(); final HuId huId = getHuId(); securPharmService
.newHUScanner() // TODO: advice the scanner to update the existing SecurPharm product .scanAndUpdateHUAttributes(dataMatrix, huId); return MSG_OK; } private HuId getHuId() { final SecurPharmProductId productId = SecurPharmProductId.ofRepoId(getRecord_ID()); final SecurPharmProduct product = securPharmService.getProductById(productId); return product.getHuId(); } private final DataMatrixCode getDataMatrix() { return DataMatrixCode.ofString(dataMatrixString); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\process\M_Securpharm_Productdata_Result_Retry.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Issue Recommendation. @param R_IssueRecommendation_ID Recommendations how to fix an Issue */ public void setR_IssueRecommendation_ID (int R_IssueRecommendation_ID) { if (R_IssueRecommendation_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, Integer.valueOf(R_IssueRecommendation_ID)); } /** Get Issue Recommendation. @return Recommendations how to fix an Issue */ public int getR_IssueRecommendation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueRecommendation_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueRecommendation.java
1
请完成以下Java代码
public class ChannelEventTenantIdDetection { protected String fixedValue; protected String jsonPointerExpression; @JsonProperty("xPathExpression") protected String xPathExpression; protected String delegateExpression; public String getFixedValue() { return fixedValue; } public void setFixedValue(String fixedValue) { this.fixedValue = fixedValue; } public String getJsonPointerExpression() { return jsonPointerExpression; }
public void setJsonPointerExpression(String jsonPointerExpression) { this.jsonPointerExpression = jsonPointerExpression; } public String getxPathExpression() { return xPathExpression; } public void setxPathExpression(String xPathExpression) { this.xPathExpression = xPathExpression; } public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\ChannelEventTenantIdDetection.java
1
请在Spring Boot框架中完成以下Java代码
public class MachineRegistryController { private final Logger logger = LoggerFactory.getLogger(MachineRegistryController.class); @Autowired private AppManagement appManagement; @ResponseBody @RequestMapping("/machine") public Result<?> receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) { if (app == null) { app = MachineDiscovery.UNKNOWN_APP_NAME; } if (ip == null) { return Result.ofFail(-1, "ip can't be null"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } if (port == -1) { logger.info("Receive heartbeat from " + ip + " but port not set yet"); return Result.ofFail(-1, "your port not set yet"); } String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v;
version = version == null ? System.currentTimeMillis() : version; try { MachineInfo machineInfo = new MachineInfo(); machineInfo.setApp(app); machineInfo.setAppType(appType); machineInfo.setHostname(hostname); machineInfo.setIp(ip); machineInfo.setPort(port); machineInfo.setHeartbeatVersion(version); machineInfo.setLastHeartbeat(System.currentTimeMillis()); machineInfo.setVersion(sentinelVersion); appManagement.addMachine(machineInfo); return Result.ofSuccessMsg("success"); } catch (Exception e) { logger.error("Receive heartbeat error", e); return Result.ofFail(-1, e.getMessage()); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\MachineRegistryController.java
2
请完成以下Java代码
protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() { return getProcessEngineConfiguration().getProcessDefinitionInfoEntityManager(); } protected ModelEntityManager getModelEntityManager() { return getProcessEngineConfiguration().getModelEntityManager(); } protected ExecutionEntityManager getExecutionEntityManager() { return getProcessEngineConfiguration().getExecutionEntityManager(); } protected ActivityInstanceEntityManager getActivityInstanceEntityManager() { return getProcessEngineConfiguration().getActivityInstanceEntityManager(); } protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager(); }
protected HistoricDetailEntityManager getHistoricDetailEntityManager() { return getProcessEngineConfiguration().getHistoricDetailEntityManager(); } protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager(); } protected AttachmentEntityManager getAttachmentEntityManager() { return getProcessEngineConfiguration().getAttachmentEntityManager(); } protected CommentEntityManager getCommentEntityManager() { return getProcessEngineConfiguration().getCommentEntityManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\AbstractManager.java
1
请完成以下Java代码
public WarehouseId getOrgWarehouseId(@NonNull final OrgId orgId) { return getOrgInfoById(orgId).getWarehouseId(); } @Override public WarehouseId getOrgPOWarehouseId(@NonNull final OrgId orgId) { return getOrgInfoById(orgId).getPurchaseWarehouseId(); } @Override public WarehouseId getOrgDropshipWarehouseId(@NonNull final OrgId orgId) { return getOrgInfoById(orgId).getDropShipWarehouseId(); } @Override public I_AD_Org retrieveOrganizationByValue(final Properties ctx, final String value) { if (value == null) { return null; } final String valueFixed = value.trim(); return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_Org.class, ctx, ITrx.TRXNAME_None) .addEqualsFilter(I_AD_Org.COLUMNNAME_Value, valueFixed) .create() .setClient_ID() .firstOnly(I_AD_Org.class); } @Override public Optional<OrgId> retrieveOrgIdBy(@NonNull final OrgQuery orgQuery) { final IQueryBuilder<I_AD_Org> queryBuilder = createQueryBuilder(); final int orgId = queryBuilder .addEqualsFilter(I_AD_Org.COLUMNNAME_Value, orgQuery.getOrgValue()) .create() .setRequiredAccess(Access.READ) .firstIdOnly(); if (orgId < 0 && orgQuery.isFailIfNotExists()) { final String msg = StringUtils.formatMessage("Found no existing Org; Searched via value='{}'", orgQuery.getOrgValue()); throw new OrgIdNotFoundException(msg); } return Optional.ofNullable(OrgId.ofRepoIdOrNull(orgId)); } private IQueryBuilder<I_AD_Org> createQueryBuilder() { final IQueryBuilder<I_AD_Org> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Org.class); return queryBuilder.addOnlyActiveRecordsFilter(); } @Override public ZoneId getTimeZone(@NonNull final OrgId orgId) { if (!orgId.isRegular()) { return SystemTime.zoneId(); } final ZoneId timeZone = getOrgInfoById(orgId).getTimeZone(); return timeZone != null ? timeZone : SystemTime.zoneId(); } @Override public boolean isEUOneStopShop(@NonNull final OrgId orgId) { final I_AD_Org org = getById(orgId); if (org == null)
{ throw new AdempiereException("No Organization found for ID: " + orgId); } return org.isEUOneStopShop(); } @Override public UserGroupId getSupplierApprovalExpirationNotifyUserGroupID(final OrgId orgId) { return getOrgInfoById(orgId).getSupplierApprovalExpirationNotifyUserGroupID(); } @Override public UserGroupId getPartnerCreatedFromAnotherOrgNotifyUserGroupID(final OrgId orgId) { return getOrgInfoById(orgId).getPartnerCreatedFromAnotherOrgNotifyUserGroupID(); } @Override public String getOrgName(@NonNull final OrgId orgId) { return getById(orgId).getName(); } @Override public boolean isAutoInvoiceFlatrateTerm(@NonNull final OrgId orgId) { final OrgInfo orgInfo = getOrgInfoById(orgId); return orgInfo.isAutoInvoiceFlatrateTerms(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\impl\OrgDAO.java
1
请完成以下Java代码
public AsyncInlineCachingRegionConfigurer<T, ID> withQueueForwardedExpirationDestroyEvents() { this.forwardExpirationDestroy = true; return this; } /** * Builder method used to configure the maximum JVM Heap memory in megabytes used by the {@link AsyncEventQueue}. * * After the maximum memory threshold is reached then the AEQ overflows cache events to disk. * * Default to {@literal 100 MB}. * * @param maximumMemory {@link Integer} value specifying the maximum amount of memory in megabytes used by the AEQ * to capture cache events. * @return this {@link AsyncInlineCachingRegionConfigurer}. */ public AsyncInlineCachingRegionConfigurer<T, ID> withQueueMaxMemory(int maximumMemory) { this.maximumQueueMemory = maximumMemory; return this; } /** * Builder method used to configure the {@link AsyncEventQueue} order of processing for cache events when the AEQ * is serial and the AEQ is using multiple dispatcher threads. * * @param orderPolicy {@link GatewaySender} {@link OrderPolicy} used to determine the order of processing * for cache events when the AEQ is serial and uses multiple dispatcher threads. * @return this {@link AsyncInlineCachingRegionConfigurer}. * @see org.apache.geode.cache.wan.GatewaySender.OrderPolicy */ public AsyncInlineCachingRegionConfigurer<T, ID> withQueueOrderPolicy(
@Nullable GatewaySender.OrderPolicy orderPolicy) { this.orderPolicy = orderPolicy; return this; } /** * Builder method used to enable a single {@link AsyncEventQueue AEQ} attached to a {@link Region Region} * (possibly) hosted and distributed across the cache cluster to process cache events. * * Default is {@literal false}, or {@literal serial}. * * @return this {@link AsyncInlineCachingRegionConfigurer}. * @see #withParallelQueue() */ public AsyncInlineCachingRegionConfigurer<T, ID> withSerialQueue() { this.parallel = false; return this; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\AsyncInlineCachingRegionConfigurer.java
1
请完成以下Java代码
public class LieferavisAbfrageHistResponse { @XmlElement(name = "return", namespace = "", required = true) protected LieferavisAbfragenAntwort _return; /** * Gets the value of the return property. * * @return * possible object is * {@link LieferavisAbfragenAntwort } * */ public LieferavisAbfragenAntwort getReturn() { return _return;
} /** * Sets the value of the return property. * * @param value * allowed object is * {@link LieferavisAbfragenAntwort } * */ public void setReturn(LieferavisAbfragenAntwort value) { this._return = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfrageHistResponse.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper implements OAuth2ClientMapper { private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token"; private RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); @Override public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client auth2Client) { OAuth2MapperConfig config = auth2Client.getMapperConfig(); OAuth2User oauth2User = getOAuth2User(token, providerAccessToken, config.getCustom()); return getOrCreateSecurityUserFromOAuth2User(oauth2User, auth2Client); } private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) { if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) { restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword()); } if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) { restTemplateBuilder = restTemplateBuilder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken); }
RestTemplate restTemplate = restTemplateBuilder.build(); String request; try { request = JacksonUtil.getObjectMapperWithJavaTimeModule().writeValueAsString(token.getPrincipal()); } catch (JsonProcessingException e) { log.error("Can't convert principal to JSON string", e); throw new RuntimeException("Can't convert principal to JSON string", e); } try { return restTemplate.postForEntity(custom.getUrl(), request, OAuth2User.class).getBody(); } catch (Exception e) { log.error("There was an error during connection to custom mapper endpoint", e); throw new RuntimeException("Unable to login. Please contact your Administrator!"); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\CustomOAuth2ClientMapper.java
2
请完成以下Java代码
public org.compiere.model.I_M_Ingredients getParentElement() { return get_ValueAsPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class); } @Override public void setParentElement(final org.compiere.model.I_M_Ingredients ParentElement) { set_ValueFromPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class, ParentElement); } @Override public void setParentElement_ID (final int ParentElement_ID) { if (ParentElement_ID < 1) set_Value (COLUMNNAME_ParentElement_ID, null); else set_Value (COLUMNNAME_ParentElement_ID, ParentElement_ID); } @Override public int getParentElement_ID() { return get_ValueAsInt(COLUMNNAME_ParentElement_ID); } @Override public void setPrecision (final int Precision) { set_Value (COLUMNNAME_Precision, Precision); }
@Override public int getPrecision() { return get_ValueAsInt(COLUMNNAME_Precision); } @Override public void setQty (final @Nullable java.lang.String Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public java.lang.String getQty() { return get_ValueAsString(COLUMNNAME_Qty); } @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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Ingredients.java
1
请完成以下Java代码
public class DataLoaderObservationContext extends Observation.Context { private final DataLoader<?, ?> dataLoader; private final List<?> keys; private final BatchLoaderEnvironment environment; private List<?> result = List.of(); DataLoaderObservationContext(DataLoader<?, ?> dataLoader, List<?> keys, BatchLoaderEnvironment environment) { this.dataLoader = dataLoader; this.keys = keys; this.environment = environment; } /** * Return the {@link DataLoader} being used for the operation. */ public DataLoader<?, ?> getDataLoader() { return this.dataLoader; } /** * Return the keys for loading by the {@link org.dataloader.DataLoader}. */ public List<?> getKeys() { return this.keys;
} /** * Return the list of values resolved by the {@link org.dataloader.DataLoader}, * or an empty list if none were resolved. */ public List<?> getResult() { return this.result; } /** * Set the list of resolved values by the {@link org.dataloader.DataLoader}. * @param result the values resolved by the data loader */ public void setResult(List<?> result) { this.result = result; } /** * Return the {@link BatchLoaderEnvironment environment} given to the batch loading function. */ public BatchLoaderEnvironment getEnvironment() { return this.environment; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DataLoaderObservationContext.java
1
请完成以下Java代码
protected String doIt() { for (final String docTableName : docFactory.getDocTableNames()) { enqueueDocuments(docTableName); } return MSG_OK; } private void enqueueDocuments(final String docTableName) { final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(docTableName); final String sql = "SELECT " + keyColumnName + " FROM " + docTableName + " WHERE AD_Client_ID=" + getAD_Client_ID() + " AND Processed='Y' AND Posted='N' AND IsActive='Y'" + " ORDER BY Created"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); int countEnqueued = 0; while (rs.next()) { final int recordId = rs.getInt(keyColumnName); enqueueDocument(docTableName, recordId); countEnqueued++; } if (countEnqueued > 0) { addLog("{}: enqueued {} documents", docTableName, countEnqueued); } } catch (final SQLException ex) { addLog("{}: failed fetching IDs. Check log.", docTableName);
log.warn("Failed fetching IDs: \n SQL={}", sql, ex); } catch (final Exception ex) { addLog("{}: error: {}. Check log.", docTableName, ex.getLocalizedMessage()); log.warn("Error while processing {}", docTableName, ex); } finally { DB.close(rs, pstmt); } } private void enqueueDocument(final String tableName, final int recordId) { postingService.schedule( DocumentPostRequest.builder() .record(TableRecordReference.of(tableName, recordId)) // the document to be posted .clientId(getClientId()) .build() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\Documents_EnqueueNotPosted.java
1
请完成以下Java代码
public class User { @Nullable private String id; @Nullable @Unwrapped(onEmpty = OnEmpty.USE_NULL) private UserName userName; /* * The prefix allows to unwrap multiple properties of the same type assigning them a unique prefix. * In this case the `Email.email` will be stored as `primary_email`. */ @Nullable @Unwrapped(onEmpty = OnEmpty.USE_NULL, prefix = "primary_") private Email email; User() { } public User(String id, UserName userName, Email email) { this.id = id; this.userName = userName; this.email = email; } User(String id, String userName, String email) { this(id, new UserName(userName), new Email(email)); } public String getId() { return id; } public void setId(String id) { this.id = id; } public UserName getUserName() { return userName; } public Email getEmail() { return email; } public void setUserName(@Nullable UserName userName) { this.userName = userName; } public void setEmail(@Nullable Email email) {
this.email = email; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; var user = (User) o; return Objects.equals(id, user.id) && Objects.equals(userName, user.userName) && Objects.equals(email, user.email); } @Override public int hashCode() { return Objects.hash(id, userName, email); } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", userName=" + userName + ", email=" + email + '}'; } }
repos\spring-data-examples-main\mongodb\example\src\main\java\example\springdata\mongodb\unwrapping\User.java
1
请完成以下Java代码
class DocLine_GLJournal extends DocLine<Doc_GLJournal> { @Getter private final int groupNo; @Getter @Setter private AcctSchemaId acctSchemaId; @Getter @Setter private BigDecimal fixedCurrencyRate; @Getter private Account account; @Nullable @Setter private ProductId productId; @Nullable @Setter private OrderId salesOrderId; @Nullable @Getter @Setter private LocatorId locatorId; DocLine_GLJournal(@NonNull final I_GL_JournalLine glJournalLine, @NonNull final Doc_GLJournal doc) { super(InterfaceWrapperHelper.getPO(glJournalLine), doc); groupNo = glJournalLine.getGL_JournalLine_Group(); fixedCurrencyRate = glJournalLine.getCurrencyRate(); } final void setAccount(@NonNull final I_C_ValidCombination acct) { setAccount(Account.ofId(AccountId.ofRepoId(acct.getC_ValidCombination_ID())));
} final void setAccount(@NonNull final Account account) { this.account = account; } @Override @Nullable public ProductId getProductId() {return productId;} @Nullable @Override protected OrderId getSalesOrderId() {return salesOrderId;} @Override public int getM_Locator_ID() {return LocatorId.toRepoId(getLocatorId());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_GLJournal.java
1
请在Spring Boot框架中完成以下Java代码
public static List toList() { BankCodeEnum[] ary = BankCodeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("name", ary[i].name()); map.put("desc", ary[i].getDesc()); list.add(map); } return list; } /** * 取枚举的json字符串 *
* @return */ public static String getJsonStr() { BankCodeEnum[] enums = BankCodeEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (BankCodeEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BankCodeEnum.java
2
请完成以下Java代码
public PageData<MobileApp> findMobileAppsByTenantId(TenantId tenantId, PlatformType platformType, PageLink pageLink) { log.trace("Executing findMobileAppInfosByTenantId [{}]", tenantId); return mobileAppDao.findByTenantId(tenantId, platformType, pageLink); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findMobileAppById(tenantId, new MobileAppId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(mobileAppDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteMobileAppById(tenantId, (MobileAppId) id); } @Override public MobileApp findByBundleIdAndPlatformType(TenantId tenantId, MobileAppBundleId mobileAppBundleId, PlatformType platformType) { log.trace("Executing findAndroidQrConfig, tenantId [{}], mobileAppBundleId [{}]", tenantId, mobileAppBundleId); return mobileAppDao.findByBundleIdAndPlatformType(tenantId, mobileAppBundleId, platformType); }
@Override public MobileApp findMobileAppByPkgNameAndPlatformType(String pkgName, PlatformType platformType) { log.trace("Executing findMobileAppByPkgNameAndPlatformType, pkgName [{}], platform [{}]", pkgName, platformType); Validator.checkNotNull(platformType, PLATFORM_TYPE_IS_REQUIRED); return mobileAppDao.findByPkgNameAndPlatformType(TenantId.SYS_TENANT_ID, pkgName, platformType); } @Override public void deleteByTenantId(TenantId tenantId) { log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId); mobileAppDao.deleteByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.MOBILE_APP; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppServiceImpl.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { getLeave(); } private static void getLeave() throws NoLeaveGrantedException { try { howIsTeamLead(); } catch (TeamLeadUpsetException e) { throw new NoLeaveGrantedException("Leave not sanctioned.", e); } } private static void howIsTeamLead() throws TeamLeadUpsetException { try { howIsManager(); } catch (ManagerUpsetException e) { throw new TeamLeadUpsetException("Team lead is not in good mood", e);
} } private static void howIsManager() throws ManagerUpsetException { try { howIsGirlFriendOfManager(); } catch (GirlFriendOfManagerUpsetException e) { throw new ManagerUpsetException("Manager is in bad mood", e); } } private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException { throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood"); } }
repos\tutorials-master\core-java-modules\core-java-exceptions-5\src\main\java\com\baeldung\exceptions\chainedexception\LogWithChain.java
1
请完成以下Java代码
private Step step() { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(multiFileItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> multiFileItemReader() { MultiResourceItemReader<TestData> reader = new MultiResourceItemReader<>(); reader.setDelegate(fileItemReader()); // 设置文件读取代理,方法可以使用前面文件读取中的例子 Resource[] resources = new Resource[]{ new ClassPathResource("file1"), new ClassPathResource("file2") }; reader.setResources(resources); // 设置多文件源 return reader; } private FlatFileItemReader<TestData> fileItemReader() { FlatFileItemReader<TestData> reader = new FlatFileItemReader<>(); reader.setLinesToSkip(1); // 忽略第一行 // AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取, // 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符 DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); // 设置属姓名,类似于表头 tokenizer.setNames("id", "field1", "field2", "field3");
// 将每行数据转换为TestData对象 DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>(); mapper.setLineTokenizer(tokenizer); // 设置映射方式 mapper.setFieldSetMapper(fieldSet -> { TestData data = new TestData(); data.setId(fieldSet.readInt("id")); data.setField1(fieldSet.readString("field1")); data.setField2(fieldSet.readString("field2")); data.setField3(fieldSet.readString("field3")); return data; }); reader.setLineMapper(mapper); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\MultiFileIteamReaderDemo.java
1
请完成以下Java代码
public static class Background { private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; } } @JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) public static class RequestResult { private int requestCode; public int getRequestCode() { return requestCode; } public void setRequestCode(int requestCode) { this.requestCode = requestCode; } } @JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) public static class ResponseResult { private int resultCode; public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } } private Fonts fonts; private Background background; @JsonProperty("RequestResult")
private RequestResult requestResult; @JsonProperty("ResponseResult") private ResponseResult responseResult; public Fonts getFonts() { return fonts; } public void setFonts(Fonts fonts) { this.fonts = fonts; } public Background getBackground() { return background; } public void setBackground(Background background) { this.background = background; } public RequestResult getRequestResult() { return requestResult; } public void setRequestResult(RequestResult requestResult) { this.requestResult = requestResult; } public ResponseResult getResponseResult() { return responseResult; } public void setResponseResult(ResponseResult responseResult) { this.responseResult = responseResult; } }
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\ini\MyConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getConnectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) { this.connectionAcquisitionTimeout = connectionAcquisitionTimeout; } } public static class Security { /** * Whether the driver should use encrypted traffic. */ private boolean encrypted; /** * Trust strategy to use. */ private TrustStrategy trustStrategy = TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES; /** * Path to the file that holds the trusted certificates. */ private @Nullable File certFile; /** * Whether hostname verification is required. */ private boolean hostnameVerificationEnabled = true; public boolean isEncrypted() { return this.encrypted; } public void setEncrypted(boolean encrypted) { this.encrypted = encrypted; } public TrustStrategy getTrustStrategy() { return this.trustStrategy; } public void setTrustStrategy(TrustStrategy trustStrategy) { this.trustStrategy = trustStrategy; } public @Nullable File getCertFile() { return this.certFile;
} public void setCertFile(@Nullable File certFile) { this.certFile = certFile; } public boolean isHostnameVerificationEnabled() { return this.hostnameVerificationEnabled; } public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) { this.hostnameVerificationEnabled = hostnameVerificationEnabled; } public enum TrustStrategy { /** * Trust all certificates. */ TRUST_ALL_CERTIFICATES, /** * Trust certificates that are signed by a trusted certificate. */ TRUST_CUSTOM_CA_SIGNED_CERTIFICATES, /** * Trust certificates that can be verified through the local system store. */ TRUST_SYSTEM_CA_SIGNED_CERTIFICATES } } }
repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java
2
请完成以下Java代码
public List<String> getDependsOnColumnNames() { return Collections.emptyList(); } @Override public Set<String> getValuePropagationKeyColumnNames(final Info_Column infoColumn) { return Collections.singleton(InfoProductQtyController.COLUMNNAME_M_Product_ID); } @Override public Object gridConvertAfterLoad(final Info_Column infoColumn, final int rowIndexModel, final int rowRecordId, final Object data) { return data; } @Override public int getParameterCount() { return 0; } @Override public String getLabel(final int index) { return null; } @Override public Object getParameterComponent(final int index) { return null; } @Override public Object getParameterToComponent(final int index) { return null; } @Override public Object getParameterValue(final int index, final boolean returnValueTo) { return null; } @Override public String[] getWhereClauses(final List<Object> params) { return new String[0]; } @Override public String getText() { return null; } @Override public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders) { for (final Map.Entry<Integer, Integer> e : recordId2asi.entrySet()) { final Integer recordId = e.getKey(); if (recordId == null || recordId <= 0) { continue; }
final Integer asiId = e.getValue(); if (asiId == null || asiId <= 0) { continue; } final OrderLineProductASIGridRowBuilder productQtyBuilder = new OrderLineProductASIGridRowBuilder(); productQtyBuilder.setSource(recordId, asiId); builders.addGridTabRowBuilder(recordId, productQtyBuilder); } } @Override public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel) { final VPAttributeContext attributeContext = new VPAttributeContext(rowIndexModel); editor.putClientProperty(IVPAttributeContext.ATTR_NAME, attributeContext); // nothing } @Override public String getProductCombinations() { // nothing to do return null; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductASIController.java
1
请完成以下Java代码
public static String combine(String... termArray) { StringBuilder sbSentence = new StringBuilder(); for (String word : termArray) { sbSentence.append(word); } return sbSentence.toString(); } public static String join(Iterable<? extends CharSequence> s, String delimiter) { Iterator<? extends CharSequence> iter = s.iterator(); if (!iter.hasNext()) return ""; StringBuilder buffer = new StringBuilder(iter.next()); while (iter.hasNext()) buffer.append(delimiter).append(iter.next()); return buffer.toString(); } public static String combine(Sentence sentence) { StringBuilder sb = new StringBuilder(sentence.wordList.size() * 3);
for (IWord word : sentence.wordList) { sb.append(word.getValue()); } return sb.toString(); } public static String combine(List<Word> wordList) { StringBuilder sb = new StringBuilder(wordList.size() * 3); for (IWord word : wordList) { sb.append(word.getValue()); } return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\TextUtility.java
1
请完成以下Java代码
public void onQtyChanges(final I_PMM_PurchaseCandidate_OrderLine alloc) { throw new AdempiereException("Changing quantities is not allowed: " + alloc); } @VisibleForTesting public static PMMBalanceChangeEvent createPMMBalanceChangeEvent(final I_PMM_PurchaseCandidate_OrderLine alloc, final boolean isReversal) { final I_PMM_PurchaseCandidate candidate = alloc.getPMM_PurchaseCandidate(); final BigDecimal qtyOrdered = isReversal ? alloc.getQtyOrdered().negate() : alloc.getQtyOrdered(); final BigDecimal qtyOrderedTU = isReversal ? alloc.getQtyOrdered_TU().negate() : alloc.getQtyOrdered_TU(); final PMMBalanceChangeEvent event = PMMBalanceChangeEvent.builder() .setC_BPartner_ID(candidate.getC_BPartner_ID()) .setM_Product_ID(candidate.getM_Product_ID())
.setM_AttributeSetInstance_ID(candidate.getM_AttributeSetInstance_ID()) .setM_HU_PI_Item_Product_ID(Services.get(IPMMPurchaseCandidateBL.class).getM_HU_PI_Item_Product_Effective_ID(candidate)) .setC_Flatrate_DataEntry_ID(candidate.getC_Flatrate_DataEntry_ID()) // .setDate(candidate.getDatePromised()) // .setQtyOrdered(qtyOrdered, qtyOrderedTU) // .build(); logger.trace("Created {} for {}, isReversal={}", event, alloc, isReversal); return event; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\interceptor\PMM_PurchaseCandidate_OrderLine.java
1
请完成以下Java代码
public List<JsonWindowsHealthCheckResponse.Entry> getCollectedErrors() { return ImmutableList.copyOf(errors); } public int getCollectedErrorsCount() { return errors.size(); } public void setCurrentWindow(@NonNull final AdWindowId windowId) { setCurrentWindow(windowId, null); } public void setCurrentWindow(@NonNull final DocumentEntityDescriptor entityDescriptor) { setCurrentWindow(entityDescriptor.getWindowId().toAdWindowId(), entityDescriptor.getCaption().translate(adLanguage)); } public void setCurrentWindow(@NonNull final AdWindowId windowId, @Nullable final String windowName) { this.currentWindowId = windowId; this._currentWindowName = windowName; } public void clearCurrentWindow() { this.currentWindowId = null; this._currentWindowName = null; } @Nullable public String getCurrentWindowName() { if (this._currentWindowName == null && this.currentWindowId != null) { this._currentWindowName = adWindowDAO.retrieveWindowName(currentWindowId).translate(adLanguage); } return this._currentWindowName; }
public void collectError(@NonNull final String errorMessage) { errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(WindowId.of(currentWindowId)) .windowName(getCurrentWindowName()) .errorMessage(errorMessage) .build()); } public void collectError(@NonNull final Throwable exception) { errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(WindowId.of(currentWindowId)) .windowName(getCurrentWindowName()) .error(JsonErrors.ofThrowable(exception, adLanguage)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ErrorsCollector.java
1
请完成以下Java代码
private BigDecimal getAttributeValueAsBigDecimal(final String attributeCode, final BigDecimal defaultValue) { if (asiAware == null) { return defaultValue; } final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiAware.getM_AttributeSetInstance_ID()); if (asiId == null) { return defaultValue; } final ImmutableAttributeSet asi = asiBL.getImmutableAttributeSetById(asiId); if (!asi.hasAttribute(attributeCode)) { return defaultValue; } final BigDecimal value = asi.getValueAsBigDecimal(attributeCode); return value != null ? value : defaultValue; } private List<I_PP_Product_BOMLine> getBOMLines() { final I_PP_Product_BOM bom = getBOMIfEligible(); if (bom == null) { return ImmutableList.of(); } return bomsRepo.retrieveLines(bom); } private I_PP_Product_BOM getBOMIfEligible() { final I_M_Product bomProduct = productsRepo.getById(bomProductId); if (!bomProduct.isBOM()) { return null; } return bomsRepo.getDefaultBOMByProductId(bomProductId) .filter(this::isEligible)
.orElse(null); } private boolean isEligible(final I_PP_Product_BOM bom) { final BOMType bomType = BOMType.ofNullableCode(bom.getBOMType()); return BOMType.MakeToOrder.equals(bomType); } // // // --- // // public static class BOMPriceCalculatorBuilder { public Optional<BOMPrices> calculate() { return build().calculate(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\BOMPriceCalculator.java
1
请完成以下Java代码
public Function<ISeq<SpringsteenRecord>, Double> fitness() { return SpringsteenRecords -> { double cost = SpringsteenRecords.stream() .mapToDouble(r -> r.price) .sum(); int uniqueSongCount = SpringsteenRecords.stream() .flatMap(r -> r.songs.stream()) .collect(Collectors.toSet()) .size(); double pricePerUniqueSong = cost / uniqueSongCount; return pricePerUniqueSong <= maxPricePerUniqueSong ? uniqueSongCount : 0.0; }; } @Override public Codec<ISeq<SpringsteenRecord>, BitGene> codec() { return codecs.ofSubSet(records); } public static void main(String[] args) { double maxPricePerUniqueSong = 2.5; SpringsteenProblem springsteen = new SpringsteenProblem( ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")), new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")), new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))), maxPricePerUniqueSong);
Engine<BitGene, Double> engine = Engine.builder(springsteen) .build(); ISeq<SpringsteenRecord> result = springsteen.codec() .decoder() .apply(engine.stream() .limit(10) .collect(EvolutionResult.toBestGenotype())); double cost = result.stream() .mapToDouble(r -> r.price) .sum(); int uniqueSongCount = result.stream() .flatMap(r -> r.songs.stream()) .collect(Collectors.toSet()) .size(); double pricePerUniqueSong = cost / uniqueSongCount; System.out.println("Overall cost: " + cost); System.out.println("Unique songs: " + uniqueSongCount); System.out.println("Cost per song: " + pricePerUniqueSong); System.out.println("Records: " + result.map(r -> r.name) .toString(", ")); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\jenetics\SpringsteenProblem.java
1
请完成以下Java代码
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 application配置
spring: application: name: mall-search profiles: active: dev #默认为开发环境 mvc: pathmatch: matching-strategy: ant_path_matcher server: port: 8081 mybatis: ma
pper-locations: - classpath:dao/*.xml - classpath*:com/**/mapper/*.xml
repos\mall-master\mall-search\src\main\resources\application.yml
2
请完成以下Java代码
public void setEan(final String ean) { this.ean = ean; this.eanSet = true; } public void setGtin(final String gtin) { this.gtin = gtin; this.gtinSet = true; } public void setDescription(final String description) { this.description = description; this.descriptionSet = true; } public void setDiscontinued(final Boolean discontinued) { this.discontinued = discontinued; this.discontinuedSet = true; } public void setDiscontinuedFrom(final LocalDate discontinuedFrom) { this.discontinuedFrom = discontinuedFrom; this.discontinuedFromSet = true; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setStocked(final Boolean stocked) {
this.stocked = stocked; this.stockedSet = true; } public void setProductCategoryIdentifier(final String productCategoryIdentifier) { this.productCategoryIdentifier = productCategoryIdentifier; this.productCategoryIdentifierSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; } public void setBpartnerProductItems(final List<JsonRequestBPartnerProductUpsert> bpartnerProductItems) { this.bpartnerProductItems = bpartnerProductItems; } public void setProductTaxCategories(final List<JsonRequestProductTaxCategoryUpsert> productTaxCategories) { this.productTaxCategories = productTaxCategories; } public void setUomConversions(final List<JsonRequestUOMConversionUpsert> uomConversions) { this.uomConversions = uomConversions; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProduct.java
1
请完成以下Java代码
public T[] getFilteredObject() { // Recreate an array of same type and filter the removed objects. int originalSize = this.list.length; int sizeOfResultingList = originalSize - this.removeList.size(); T[] filtered = (T[]) Array.newInstance(this.list.getClass().getComponentType(), sizeOfResultingList); for (int i = 0, j = 0; i < this.list.length; i++) { T object = this.list[i]; if (!this.removeList.contains(object)) { filtered[j] = object; j++; } } logger.debug(LogMessage.of(() -> "Original array contained " + originalSize + " elements; now contains " + sizeOfResultingList + " elements")); return filtered; } @Override public Iterator<T> iterator() { return new ArrayFiltererIterator(); } @Override public void remove(T object) { this.removeList.add(object); } /** * Iterator for {@link ArrayFilterer} elements. */ private class ArrayFiltererIterator implements Iterator<T> { private int index = 0; @Override
public boolean hasNext() { return this.index < ArrayFilterer.this.list.length; } @Override public T next() { if (hasNext()) { return ArrayFilterer.this.list[this.index++]; } throw new NoSuchElementException(); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\afterinvocation\ArrayFilterer.java
1
请完成以下Java代码
private String getProduct(JdbcTemplate jdbcTemplate) { return jdbcTemplate.execute((ConnectionCallback<String>) this::getProduct); } private String getProduct(Connection connection) throws SQLException { return connection.getMetaData().getDatabaseProductName(); } private Boolean isConnectionValid(JdbcTemplate jdbcTemplate) { return jdbcTemplate.execute((ConnectionCallback<Boolean>) this::isConnectionValid); } private Boolean isConnectionValid(Connection connection) throws SQLException { return connection.isValid(0); } /** * Set the {@link DataSource} to use. * @param dataSource the data source */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); } /** * Set a specific validation query to use to validate a connection. If none is set, a * validation based on {@link Connection#isValid(int)} is used. * @param query the validation query to use */ public void setQuery(String query) { this.query = query; } /** * Return the validation query or {@code null}. * @return the query */
public @Nullable String getQuery() { return this.query; } /** * {@link RowMapper} that expects and returns results from a single column. */ private static final class SingleColumnRowMapper implements RowMapper<Object> { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columns = metaData.getColumnCount(); if (columns != 1) { throw new IncorrectResultSetColumnCountException(1, columns); } Object result = JdbcUtils.getResultSetValue(rs, 1); Assert.state(result != null, "'result' must not be null"); return result; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\health\DataSourceHealthIndicator.java
1
请完成以下Java代码
public void write(PrintWriter writer) throws IOException { for (GitIgnoreSection section : this.sections) { section.write(writer); } } public void addSection(GitIgnoreSection section) { GitIgnoreSection existingSection = getSection(section.name); Assert.state(existingSection == null, () -> "Section with name '%s' already exists".formatted(section.name)); this.sections.add(section); } /** * Adds a section if it doesn't already exist. * @param sectionName the name of the section * @return the newly added section or the existing one */ public GitIgnoreSection addSectionIfAbsent(String sectionName) { GitIgnoreSection section = getSection(sectionName); if (section != null) { return section; } section = new GitIgnoreSection(sectionName); addSection(section); return section; } public GitIgnoreSection getSection(String sectionName) { if ("general".equalsIgnoreCase(sectionName)) { return this.general; } else { return this.sections.stream() .filter((section) -> section.name != null && section.name.equalsIgnoreCase(sectionName)) .findAny() .orElse(null); } } public boolean isEmpty() { return this.sections.stream().allMatch((section) -> section.items.isEmpty()); } public GitIgnoreSection getGeneral() { return this.general; } public GitIgnoreSection getSts() { return this.sts; }
public GitIgnoreSection getIntellijIdea() { return this.intellijIdea; } public GitIgnoreSection getNetBeans() { return this.netBeans; } public GitIgnoreSection getVscode() { return this.vscode; } /** * Representation of a section of a {@code .gitignore} file. */ public static class GitIgnoreSection implements Section { private final String name; private final LinkedList<String> items; public GitIgnoreSection(String name) { this.name = name; this.items = new LinkedList<>(); } public void add(String... items) { this.items.addAll(Arrays.asList(items)); } public LinkedList<String> getItems() { return this.items; } @Override public void write(PrintWriter writer) { if (!this.items.isEmpty()) { if (this.name != null) { writer.println(); writer.println(String.format("### %s ###", this.name)); } this.items.forEach(writer::println); } } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitIgnore.java
1
请在Spring Boot框架中完成以下Java代码
public R update(@Valid @RequestBody Region region) { return R.status(regionService.updateById(region)); } /** * 新增或修改 行政区划表 */ @PostMapping("/submit") @ApiOperationSupport(order = 7) @Operation(summary = "新增或修改", description = "传入region") public R submit(@Valid @RequestBody Region region) { return R.status(regionService.submit(region)); } /** * 删除 行政区划表 */ @PostMapping("/remove") @ApiOperationSupport(order = 8) @Operation(summary = "删除", description = "传入主键") public R remove(@Parameter(description = "主键", required = true) @RequestParam String id) {
return R.status(regionService.removeRegion(id)); } /** * 行政区划下拉数据源 */ @GetMapping("/select") @ApiOperationSupport(order = 9) @Operation(summary = "下拉数据源", description = "传入tenant") public R<List<Region>> select(@RequestParam(required = false, defaultValue = "00") String code) { List<Region> list = regionService.list(Wrappers.<Region>query().lambda().eq(Region::getParentCode, code)); return R.data(list); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RegionController.java
2
请完成以下Java代码
public <T> T execute(CommandConfig config, Command<T> command) { long waitTime = waitTimeInMs; int failedAttempts = 0; do { if (failedAttempts > 0) { log.info("Waiting for {}ms before retrying the command.", waitTime); waitBeforeRetry(waitTime); waitTime *= waitIncreaseFactor; } try { // try to execute the command return next.execute(config, command); } catch (ActivitiOptimisticLockingException e) { log.info("Caught optimistic locking exception: " + e); } failedAttempts++; } while (failedAttempts <= numOfRetries); throw new ActivitiException( numOfRetries + " retries failed with ActivitiOptimisticLockingException. Giving up." ); } protected void waitBeforeRetry(long waitTime) { try { Thread.sleep(waitTime); } catch (InterruptedException e) { log.debug("I am interrupted while waiting for a retry."); } } public void setNumOfRetries(int numOfRetries) { this.numOfRetries = numOfRetries; }
public void setWaitIncreaseFactor(int waitIncreaseFactor) { this.waitIncreaseFactor = waitIncreaseFactor; } public void setWaitTimeInMs(int waitTimeInMs) { this.waitTimeInMs = waitTimeInMs; } public int getNumOfRetries() { return numOfRetries; } public int getWaitIncreaseFactor() { return waitIncreaseFactor; } public int getWaitTimeInMs() { return waitTimeInMs; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\RetryInterceptor.java
1
请完成以下Java代码
public String getExtensionId() { return "credProtect"; } @Override public CredProtect getInput() { return this.input; } public static class CredProtect implements Serializable { @Serial private static final long serialVersionUID = 109597301115842688L; private final ProtectionPolicy credProtectionPolicy; private final boolean enforceCredentialProtectionPolicy; public CredProtect(ProtectionPolicy credProtectionPolicy, boolean enforceCredentialProtectionPolicy) { this.enforceCredentialProtectionPolicy = enforceCredentialProtectionPolicy; this.credProtectionPolicy = credProtectionPolicy; } public boolean isEnforceCredentialProtectionPolicy() { return this.enforceCredentialProtectionPolicy;
} public ProtectionPolicy getCredProtectionPolicy() { return this.credProtectionPolicy; } public enum ProtectionPolicy { USER_VERIFICATION_OPTIONAL, USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST, USER_VERIFICATION_REQUIRED } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\CredProtectAuthenticationExtensionsClientInput.java
1
请完成以下Java代码
public void add(String word) { word = reverse(word); trie.put(word, word.length()); } public void addAll(String total) { for (int i = 0; i < total.length(); ++i) { add(String.valueOf(total.charAt(i))); } } public void addAll(String[] total) { for (String single : total) { add(single); } } /** * 查找是否有该后缀 * @param suffix * @return */ public int get(String suffix) { suffix = reverse(suffix); Integer length = trie.get(suffix); if (length == null) return 0; return length; } /** * 词语是否以该词典中的某个单词结尾 * @param word * @return */ public boolean endsWith(String word) { word = reverse(word); return trie.commonPrefixSearchWithValue(word).size() > 0; }
/** * 获取最长的后缀 * @param word * @return */ public int getLongestSuffixLength(String word) { word = reverse(word); LinkedList<Map.Entry<String, Integer>> suffixList = trie.commonPrefixSearchWithValue(word); if (suffixList.size() == 0) return 0; return suffixList.getLast().getValue(); } private static String reverse(String word) { return new StringBuilder(word).reverse().toString(); } /** * 键值对 * @return */ public Set<Map.Entry<String, Integer>> entrySet() { Set<Map.Entry<String, Integer>> treeSet = new LinkedHashSet<Map.Entry<String, Integer>>(); for (Map.Entry<String, Integer> entry : trie.entrySet()) { treeSet.add(new AbstractMap.SimpleEntry<String, Integer>(reverse(entry.getKey()), entry.getValue())); } return treeSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SuffixDictionary.java
1
请完成以下Java代码
public Iterable<OidcSessionInformation> removeSessionInformation(OidcLogoutToken token) { List<String> audience = token.getAudience(); String issuer = token.getIssuer().toString(); String subject = token.getSubject(); String providerSessionId = token.getSessionId(); Predicate<OidcSessionInformation> matcher = (providerSessionId != null) ? sessionIdMatcher(audience, issuer, providerSessionId) : subjectMatcher(audience, issuer, subject); if (this.logger.isTraceEnabled()) { String message = "Looking up sessions by issuer [%s] and %s [%s]"; if (providerSessionId != null) { this.logger.trace(String.format(message, issuer, LogoutTokenClaimNames.SID, providerSessionId)); } else { this.logger.trace(String.format(message, issuer, LogoutTokenClaimNames.SUB, subject)); } } int size = this.sessions.size(); Set<OidcSessionInformation> infos = new HashSet<>(); this.sessions.values().removeIf((info) -> { boolean result = matcher.test(info); if (result) { infos.add(info); } return result; }); if (infos.isEmpty()) { this.logger.debug("Failed to remove any sessions since none matched"); } else if (this.logger.isTraceEnabled()) { String message = "Found and removed %d session(s) from mapping of %d session(s)"; this.logger.trace(String.format(message, infos.size(), size)); } return infos; }
private static Predicate<OidcSessionInformation> sessionIdMatcher(List<String> audience, String issuer, String sessionId) { return (session) -> { List<String> thatAudience = session.getPrincipal().getAudience(); String thatIssuer = session.getPrincipal().getIssuer().toString(); String thatSessionId = session.getPrincipal().getClaimAsString(LogoutTokenClaimNames.SID); if (thatAudience == null) { return false; } return !Collections.disjoint(audience, thatAudience) && issuer.equals(thatIssuer) && sessionId.equals(thatSessionId); }; } private static Predicate<OidcSessionInformation> subjectMatcher(List<String> audience, String issuer, String subject) { return (session) -> { List<String> thatAudience = session.getPrincipal().getAudience(); String thatIssuer = session.getPrincipal().getIssuer().toString(); String thatSubject = session.getPrincipal().getSubject(); if (thatAudience == null) { return false; } return !Collections.disjoint(audience, thatAudience) && issuer.equals(thatIssuer) && subject.equals(thatSubject); }; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\session\InMemoryOidcSessionRegistry.java
1
请完成以下Java代码
protected List<CaseSentryPartImpl> findSentry(String sentryId) { List<CaseSentryPartImpl> result = new ArrayList<CaseSentryPartImpl>(); for (CaseSentryPartImpl sentryPart : getCaseSentryParts()) { if (sentryPart.getSentryId().equals(sentryId)) { result.add(sentryPart); } } return result; } protected void addSentryPart(CmmnSentryPart sentryPart) { getCaseSentryParts().add((CaseSentryPartImpl) sentryPart); } protected CmmnSentryPart newSentryPart() { return new CaseSentryPartImpl(); } // new case executions //////////////////////////////////////////////////////////// protected CaseExecutionImpl createCaseExecution(CmmnActivity activity) { CaseExecutionImpl child = newCaseExecution(); // set activity to execute child.setActivity(activity); // handle child/parent-relation child.setParent(this); getCaseExecutionsInternal().add(child); // set case instance child.setCaseInstance(getCaseInstance()); // set case definition child.setCaseDefinition(getCaseDefinition()); return child; } protected CaseExecutionImpl newCaseExecution() { return new CaseExecutionImpl(); } // variables ////////////////////////////////////////////////////////////// protected VariableStore<CoreVariableInstance> getVariableStore() { return (VariableStore) variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; }
@Override protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); } // toString ///////////////////////////////////////////////////////////////// public String toString() { if (isCaseInstanceExecution()) { return "CaseInstance[" + getToStringIdentity() + "]"; } else { return "CmmnExecution["+getToStringIdentity() + "]"; } } protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } public String getId() { return String.valueOf(System.identityHashCode(this)); } public ProcessEngineServices getProcessEngineServices() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public ProcessEngine getProcessEngine() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public CmmnElement getCmmnModelElementInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } public CmmnModelInstance getCmmnModelInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java
1
请完成以下Java代码
public void init(FilterConfig filterConfig) throws ServletException { String tempExcludes = filterConfig.getInitParameter("excludes"); String tempEnabled = filterConfig.getInitParameter("enabled"); if (StringUtils.isNotEmpty(tempExcludes)) { String[] url = tempExcludes.split(","); for (int i = 0; url != null && i < url.length; i++) { excludes.add(url[i]); } } if (StringUtils.isNotEmpty(tempEnabled)) { enabled = Boolean.valueOf(tempEnabled); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (handleExcludeURL(req, resp)) { chain.doFilter(request, response); return; } XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(xssRequest, response); } private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
if (!enabled) { return true; } if (excludes == null || excludes.isEmpty()) { return false; } String url = request.getServletPath(); for (String pattern : excludes) { Pattern p = Pattern.compile("^" + pattern); Matcher m = p.matcher(url); if (m.find()) { return true; } } return false; } @Override public void destroy() { } }
repos\springboot-demo-master\xss\src\main\java\com\et\filter\XssFilter.java
1
请在Spring Boot框架中完成以下Java代码
public boolean schedule(Runnable runnable, boolean isLongRunning) { if(isLongRunning) { return scheduleLongRunningWork(runnable); } else { return scheduleShortRunningWork(runnable); } } protected boolean scheduleShortRunningWork(Runnable runnable) { ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue(); try { managedQueueExecutorService.executeBlocking(runnable); return true; } catch (InterruptedException e) { // the the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (Exception e) { // we must be able to schedule this log.log(Level.WARNING, "Cannot schedule long running work.", e); } return false; } protected boolean scheduleLongRunningWork(Runnable runnable) { final ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue();
boolean rejected = false; try { // wait for 2 seconds for the job to be accepted by the pool. managedQueueExecutorService.executeBlocking(runnable, 2, TimeUnit.SECONDS); } catch (InterruptedException e) { // the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (ExecutionTimedOutException e) { rejected = true; } catch (RejectedExecutionException e) { rejected = true; } catch (Exception e) { // if it fails for some other reason, log a warning message long now = System.currentTimeMillis(); // only log every 60 seconds to prevent log flooding if((now-lastWarningLogged) >= (60*1000)) { log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e); } else { log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e); } } return !rejected; } public InjectedValue<ManagedQueueExecutorService> getManagedQueueInjector() { return managedQueueInjector; } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java
2
请完成以下Java代码
public static DistributionFacetIdsCollection ofCollection(final Collection<DistributionFacetId> collection) { return !collection.isEmpty() ? new DistributionFacetIdsCollection(ImmutableSet.copyOf(collection)) : EMPTY; } @Override @NonNull public Iterator<DistributionFacetId> iterator() {return set.iterator();} public boolean isEmpty() {return set.isEmpty();} public Set<WarehouseId> getWarehouseFromIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_FROM, DistributionFacetId::getWarehouseId);} public Set<WarehouseId> getWarehouseToIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_TO, DistributionFacetId::getWarehouseId);} public Set<OrderId> getSalesOrderIds() {return getValues(DistributionFacetGroupType.SALES_ORDER, DistributionFacetId::getSalesOrderId);} public Set<PPOrderId> getManufacturingOrderIds() {return getValues(DistributionFacetGroupType.MANUFACTURING_ORDER_NO, DistributionFacetId::getManufacturingOrderId);} public Set<LocalDate> getDatesPromised() {return getValues(DistributionFacetGroupType.DATE_PROMISED, DistributionFacetId::getDatePromised);} public Set<ProductId> getProductIds() {return getValues(DistributionFacetGroupType.PRODUCT, DistributionFacetId::getProductId);} public Set<Quantity> getQuantities() {return getValues(DistributionFacetGroupType.QUANTITY, DistributionFacetId::getQty);}
public Set<ResourceId> getPlantIds() {return getValues(DistributionFacetGroupType.PLANT_RESOURCE_ID, DistributionFacetId::getPlantId);} public <T> Set<T> getValues(DistributionFacetGroupType groupType, Function<DistributionFacetId, T> valueExtractor) { if (set.isEmpty()) { return ImmutableSet.of(); } return set.stream() .filter(facetId -> facetId.getGroup().equals(groupType)) .map(valueExtractor) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetIdsCollection.java
1
请完成以下Java代码
public class GetPotentialStarterUsersCmd implements Command<List<User>>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; public GetPotentialStarterUsersCmd(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public List<User> execute(CommandContext commandContext) { ProcessDefinitionEntity processDefinition = CommandContextUtil.getProcessDefinitionEntityManager(commandContext).findById(processDefinitionId); if (processDefinition == null) { throw new FlowableObjectNotFoundException("Cannot find process definition with id " + processDefinitionId, ProcessDefinition.class); } IdentityService identityService = CommandContextUtil.getProcessEngineConfiguration(commandContext).getIdentityService(); List<String> userIds = new ArrayList<>(); List<IdentityLink> identityLinks = (List) processDefinition.getIdentityLinks(); for (IdentityLink identityLink : identityLinks) {
if (identityLink.getUserId() != null && identityLink.getUserId().length() > 0) { if (!userIds.contains(identityLink.getUserId())) { userIds.add(identityLink.getUserId()); } } } if (userIds.size() > 0) { return identityService.createUserQuery().userIds(userIds).list(); } else { return new ArrayList<>(); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetPotentialStarterUsersCmd.java
1
请在Spring Boot框架中完成以下Java代码
private static Optional<AdWindowId> extractAdWindowId(final I_AD_Preference adPreference) { return AdWindowId.optionalOfRepoId(adPreference.getAD_Window_ID()); } private Optional<AdWindowId> adWindowIdOptional; private final Map<String, IUserValuePreference> name2value = new HashMap<>(); private UserValuePreferencesBuilder() { super(); } public UserValuePreferences build() { if (isEmpty()) { return UserValuePreferences.EMPTY; } return new UserValuePreferences(this); } public boolean isEmpty() { return name2value.isEmpty(); } public UserValuePreferencesBuilder add(final I_AD_Preference adPreference) { final Optional<AdWindowId> currentWindowId = extractAdWindowId(adPreference); if (isEmpty()) { adWindowIdOptional = currentWindowId; } else if (!adWindowIdOptional.equals(currentWindowId)) { throw new IllegalArgumentException("Preference " + adPreference + "'s AD_Window_ID=" + currentWindowId + " is not matching builder's AD_Window_ID=" + adWindowIdOptional); } final String attributeName = adPreference.getAttribute();
final String attributeValue = adPreference.getValue(); name2value.put(attributeName, UserValuePreference.of(adWindowIdOptional, attributeName, attributeValue)); return this; } public UserValuePreferencesBuilder addAll(final UserValuePreferencesBuilder fromBuilder) { if (fromBuilder == null || fromBuilder.isEmpty()) { return this; } if (!isEmpty() && !adWindowIdOptional.equals(fromBuilder.adWindowIdOptional)) { throw new IllegalArgumentException("Builder " + fromBuilder + "'s AD_Window_ID=" + fromBuilder.adWindowIdOptional + " is not matching builder's AD_Window_ID=" + adWindowIdOptional); } name2value.putAll(fromBuilder.name2value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ValuePreferenceBL.java
2
请在Spring Boot框架中完成以下Java代码
public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context1 = new SpringApplicationBuilder(DemoApplication.class) .web(WebApplicationType.NONE) .profiles("java7") .run(args); // 返回 IOC 容器,使用注解配置,传入配置类 ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class); System.out.println("容器创建完毕"); // User user = context.getBean(User.class); // System.out.println(user); // 查看 User 这个类在 Spring 容器中叫啥玩意 // String[] beanNames = context.getBeanNamesForType(User.class); // Arrays.stream(beanNames).forEach(System.out::println); // 查看基于注解的 IOC容器中所有组件名称 String[] beanNames = context.getBeanDefinitionNames(); Arrays.stream(beanNames).forEach(System.out::println); // 组件的作用域 // Object user1 = context.getBean("user"); // Object user2 = context.getBean("user");
// System.out.println(user1 == user2); // 测试懒加载 // Object user1 = context.getBean("user"); // Object user2 = context.getBean("user"); // 测试 Profile CalculateService service = context1.getBean(CalculateService.class); System.out.println("求合结果: " + service.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); // FactoryBean测试 Object cherry = context.getBean("cherryFactoryBean"); System.out.println(cherry.getClass()); Object cherryFactoryBean = context.getBean("&cherryFactoryBean"); System.out.println(cherryFactoryBean.getClass()); } }
repos\SpringAll-master\50.Spring-Regist-Bean\src\main\java\cc\mrbird\DemoApplication.java
2
请完成以下Java代码
protected void mapSearchResultToUser(SearchResult result, UserEntity user) throws NamingException { if (ldapConfigurator.getUserIdAttribute() != null) { user.setId(result.getAttributes().get(ldapConfigurator.getUserIdAttribute()).get().toString()); } if (ldapConfigurator.getUserFirstNameAttribute() != null) { try { user.setFirstName(result.getAttributes().get(ldapConfigurator.getUserFirstNameAttribute()).get().toString()); } catch (NullPointerException e) { user.setFirstName(""); } } if (ldapConfigurator.getUserLastNameAttribute() != null) { try { user.setLastName(result.getAttributes().get(ldapConfigurator.getUserLastNameAttribute()).get().toString()); } catch (NullPointerException e) { user.setLastName(""); }
} if (ldapConfigurator.getUserEmailAttribute() != null) { try { user.setEmail(result.getAttributes().get(ldapConfigurator.getUserEmailAttribute()).get().toString()); } catch (NullPointerException e) { user.setEmail(""); } } } protected SearchControls createSearchControls() { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit()); return searchControls; } }
repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\impl\LDAPUserQueryImpl.java
1
请完成以下Java代码
public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Line.java
1
请完成以下Java代码
public static ResponseBo error() { return error(1, "操作失败"); } public static ResponseBo error(String msg) { return error(500, msg); } public static ResponseBo error(int code, String msg) { ResponseBo ResponseBo = new ResponseBo(); ResponseBo.put("code", code); ResponseBo.put("msg", msg); return ResponseBo; } public static ResponseBo ok(String msg) { ResponseBo ResponseBo = new ResponseBo(); ResponseBo.put("msg", msg); return ResponseBo;
} public static ResponseBo ok(Map<String, Object> map) { ResponseBo ResponseBo = new ResponseBo(); ResponseBo.putAll(map); return ResponseBo; } public static ResponseBo ok() { return new ResponseBo(); } @Override public ResponseBo put(String key, Object value) { super.put(key, value); return this; } }
repos\SpringAll-master\11.Spring-Boot-Shiro-Authentication\src\main\java\com\springboot\pojo\ResponseBo.java
1
请完成以下Java代码
public class UserWithMixin { private Long id; private String name; public UserWithMixin(Long id, String name) { this.id = id; this.name = name; } public UserWithMixin() { } public String getName() { return name;
} public Long getId() { return id; } /** * Mixin interface that is used to hide sensitive information */ public interface PublicMixin { @JsonIgnore Long getId(); } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\dynamicignore\UserWithMixin.java
1
请完成以下Java代码
public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsBoolean(defaultValue) : defaultValue; } @Override public boolean getParameter_ToAsBool(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); if (processInfoParameter == null) { return false; } return processInfoParameter.getParameter_ToAsBoolean(); } @Override public final Timestamp getParameterAsTimestamp(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsTimestamp() : null; } @Override public LocalDate getParameterAsLocalDate(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsLocalDate() : null; } @Override public ZonedDateTime getParameterAsZonedDateTime(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsZonedDateTime() : null; } @Override public Instant getParameterAsInstant(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameterAsInstant() : null; } @Override public Timestamp getParameter_ToAsTimestamp(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameter_ToAsTimestamp() : null; } @Override public LocalDate getParameter_ToAsLocalDate(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameter_ToAsLocalDate() : null; } @Override public ZonedDateTime getParameter_ToAsZonedDateTime(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameter_ToAsZonedDateTime() : null; } /** * Returns an immutable collection of the wrapped process parameter names. */ @Override public Collection<String> getParameterNames() { return ImmutableSet.copyOf(getParametersMap().keySet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessParams.java
1
请完成以下Java代码
private static void printResult(FindIterable<Document> documents) { MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void main(String args[]) { setUp(); equalsOperator(); notEqualOperator(); greaterThanOperator();
lessThanOperator(); inOperator(); notInOperator(); andOperator(); orOperator(); existsOperator(); regexOperator(); } }
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\filter\FilterOperation.java
1
请完成以下Java代码
private void handleUnavailableDefinition(String simpleName, Set<String> unavailableDefinitions) { final String errorMessage = String.format("Invalid %s: %s", simpleName, unavailableDefinitions); log.warn(errorMessage); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errorMessage); } private void handleError(String errorMessage) { log.warn(errorMessage); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errorMessage); } private boolean isAvailable(FilterDefinition filterDefinition) { return GatewayFilters.stream() .anyMatch(gatewayFilterFactory -> filterDefinition.getName().equals(gatewayFilterFactory.name())); } private boolean isAvailable(PredicateDefinition predicateDefinition) { return routePredicates.stream() .anyMatch(routePredicate -> predicateDefinition.getName().equals(routePredicate.name())); } @DeleteMapping("/routes/{id}")
public Mono<ResponseEntity<Object>> delete(@PathVariable String id) { return this.routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> { publisher.publishEvent(new RouteDeletedEvent(this, id)); return Mono.just(ResponseEntity.ok().build()); })).onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build())); } @GetMapping("/routes/{id}/combinedfilters") public Mono<HashMap<String, Object>> combinedfilters(@PathVariable String id) { // TODO: missing global filters return this.routeLocator.getRoutes() .filter(route -> route.getId().equals(id)) .reduce(new HashMap<>(), this::putItem); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\actuate\AbstractGatewayControllerEndpoint.java
1
请完成以下Java代码
private IView createViewWithFilter(final DocumentFilter filter) { final WindowId windowId = getWindowId(); return viewsRepo.createView(CreateViewRequest.builder(windowId) .setFilters(DocumentFilterList.of(filter)) .build()); } @NonNull private WindowId getWindowId() { return WindowId.of(getProcessInfo().getAdWindowId().getRepoId()); } @NonNull private DocumentFilter createAreaSearchFilter(final I_C_Location location) { final DocumentEntityDescriptor entityDescriptor = documentCollection.getDocumentEntityDescriptor(getWindowId()); final GeoLocationDocumentQuery query = createGeoLocationQuery(location); return geoLocationDocumentService.createDocumentFilter(entityDescriptor, query); } private GeoLocationDocumentQuery createGeoLocationQuery(final I_C_Location location) { final CountryId countryId = CountryId.ofRepoId(location.getC_Country_ID()); final ITranslatableString countryName = countriesRepo.getCountryNameById(countryId); return GeoLocationDocumentQuery.builder() .country(IntegerLookupValue.of(countryId, countryName))
.address1(location.getAddress1()) .city(location.getCity()) .postal(location.getPostal()) .distanceInKm(distanceInKm) .visitorsAddress(visitorsAddress) .build(); } private I_C_Location getSelectedLocationOrFirstAvailable() { final Set<Integer> bpLocationIds = getSelectedIncludedRecordIds(I_C_BPartner_Location.class); if (!bpLocationIds.isEmpty()) { // retrieve the selected location final LocationId locationId = bpartnersRepo.getBPartnerLocationAndCaptureIdInTrx(BPartnerLocationId.ofRepoId(getRecord_ID(), bpLocationIds.iterator().next())).getLocationCaptureId(); return locationsRepo.getById(locationId); } else { // retrieve the first bpartner location available final List<I_C_BPartner_Location> partnerLocations = bpartnersRepo.retrieveBPartnerLocations(BPartnerId.ofRepoId(getRecord_ID())); if (!partnerLocations.isEmpty()) { return locationsRepo.getById(LocationId.ofRepoId(partnerLocations.get(0).getC_Location_ID())); } } throw new AdempiereException("@NotFound@ @C_Location_ID@"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\location\geocoding\process\C_BPartner_Window_AreaSearchProcess.java
1
请完成以下Spring Boot application配置
server: port: 8086 spring: security: oauth2: resourceserver: opaquetoken: introspection-uri: http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/token/introspect client-id: quotes-client client-secret: 0e082231-a70d-48e8-b8a5-fbfb743041b6 cloud: gateway:
redis: enabled: false routes: - id: quotes uri: http://localhost:8085 predicates: - Path=/quotes/**
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\resources\application-resource-server.yml
2
请完成以下Java代码
public void setIsPurchased (final boolean IsPurchased) { set_Value (COLUMNNAME_IsPurchased, IsPurchased); } @Override public boolean isPurchased() { return get_ValueAsBoolean(COLUMNNAME_IsPurchased); } @Override public void setIsSold (final boolean IsSold) { set_Value (COLUMNNAME_IsSold, IsSold); } @Override public boolean isSold() { return get_ValueAsBoolean(COLUMNNAME_IsSold); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable) { set_Value (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_Value (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities_Summary.java
1
请在Spring Boot框架中完成以下Java代码
public class ConditionalUnitType { @XmlValue protected BigDecimal value; @XmlAttribute(name = "Unit", namespace = "http://erpel.at/schemas/1p0/documents") protected String unit; /** * Gets the value of the value property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; }
/** * The type of unit. ERPEL recommends the use of code list UN/ECE recommendation 20. Note, that ERPEL supports both representations for piece: PCE and C62. A list of valid codes may be found under https://docs.ecosio.com/files/Measure_Unit_Qualifiers_6411.pdf * * @return * possible object is * {@link String } * */ public String getUnit() { return unit; } /** * Sets the value of the unit property. * * @param value * allowed object is * {@link String } * */ public void setUnit(String value) { this.unit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ConditionalUnitType.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_AD_UI_Column getAD_UI_Column() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_UI_Column_ID, org.compiere.model.I_AD_UI_Column.class); } @Override public void setAD_UI_Column(org.compiere.model.I_AD_UI_Column AD_UI_Column) { set_ValueFromPO(COLUMNNAME_AD_UI_Column_ID, org.compiere.model.I_AD_UI_Column.class, AD_UI_Column); } /** Set UI Column. @param AD_UI_Column_ID UI Column */ @Override public void setAD_UI_Column_ID (int AD_UI_Column_ID) { if (AD_UI_Column_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_Column_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_Column_ID, Integer.valueOf(AD_UI_Column_ID)); } /** Get UI Column. @return UI Column */ @Override public int getAD_UI_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Column_ID); if (ii == null) return 0; return ii.intValue(); } /** Set UI Element Group. @param AD_UI_ElementGroup_ID UI Element Group */ @Override public void setAD_UI_ElementGroup_ID (int AD_UI_ElementGroup_ID) { if (AD_UI_ElementGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_ElementGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_ElementGroup_ID, Integer.valueOf(AD_UI_ElementGroup_ID)); } /** Get UI Element Group. @return UI Element Group */ @Override public int getAD_UI_ElementGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_ElementGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity
*/ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set UI Style. @param UIStyle UI Style */ @Override public void setUIStyle (java.lang.String UIStyle) { set_Value (COLUMNNAME_UIStyle, UIStyle); } /** Get UI Style. @return UI Style */ @Override public java.lang.String getUIStyle () { return (java.lang.String)get_Value(COLUMNNAME_UIStyle); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementGroup.java
1
请完成以下Java代码
private CommissionPoints getCommissionPoints(@NonNull final I_C_OrderLine orderLine, final boolean isTaxIncluded) { if (orderLine.getQtyOrdered().signum() == 0) { return CommissionPoints.ZERO; } final Tax taxRecord = taxDAO.getTaxById(orderLine.getC_Tax_ID()); final CurrencyPrecision precision = orderLineBL.extractPricePrecision(orderLine); final Quantity orderedQtyPriceUOM = getOrderedQtyInPriceUOM(orderLine); final BigDecimal priceForOrderedQty = orderedQtyPriceUOM.toBigDecimal().multiply(orderLine.getPriceActual()); final BigDecimal taxAdjustedAmount = taxRecord.calculateBaseAmt( priceForOrderedQty, isTaxIncluded, precision.toInt()); return CommissionPoints.of(taxAdjustedAmount); }
private boolean hasTheRightStatus(@NonNull final DocStatus orderDocStatus) { return orderDocStatus.isCompleted() || orderDocStatus.isInProgress() || orderDocStatus.isClosed(); } @NonNull private Quantity getOrderedQtyInPriceUOM(@NonNull final I_C_OrderLine orderLine) { final UomId stockUOMId = UomId.ofRepoId(orderLine.getC_UOM_ID()); final UomId priceUOMId = UomId.ofRepoIdOrNull(orderLine.getPrice_UOM_ID()); final Quantity orderedQtyStock = Quantity.of(orderLine.getQtyOrdered(), uomDao.getById(stockUOMId)); return priceUOMId != null ? uomConversionService.convertQuantityTo(orderedQtyStock, ProductId.ofRepoId(orderLine.getM_Product_ID()), priceUOMId) : orderedQtyStock; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\commissiontrigger\mediatedorder\MediatedOrderFactory.java
1
请完成以下Java代码
public class IdentityLinkDto { protected String userId; protected String groupId; protected String type; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getType() { return type; } public void setType(String type) { this.type = type;
} public static IdentityLinkDto fromIdentityLink(IdentityLink identityLink) { IdentityLinkDto dto = new IdentityLinkDto(); dto.userId = identityLink.getUserId(); dto.groupId = identityLink.getGroupId(); dto.type = identityLink.getType(); return dto; } public void validate() { if (userId != null && groupId != null) { throw new InvalidRequestException(Status.BAD_REQUEST, "Identity Link requires userId or groupId, but not both."); } if (userId == null && groupId == null) { throw new InvalidRequestException(Status.BAD_REQUEST, "Identity Link requires userId or groupId."); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\IdentityLinkDto.java
1
请完成以下Java代码
public void postAfterCommit(@NonNull final DocumentPostMultiRequest requests) { trxManager.accumulateAndProcessAfterCommit( "DocumentPostRequests.toPostNow", requests.toSet(), this::postNow ); } private void postNow(@NonNull final List<DocumentPostRequest> requests) { requests.forEach(this::postNow); } private void postNow(@NonNull final DocumentPostRequest request) { // TODO check Profiles.isProfileActive(Profiles.PROFILE_AccountingService) ... maybe not // TODO check if disabled? maybe not.... logger.debug("Posting directly: {}", this); final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, request.getClientId()); try (final IAutoCloseable ignored = Env.switchContext(ctx)) { final List<AcctSchema> acctSchemas = acctSchemaDAO.getAllByClient(request.getClientId()); final Doc<?> doc = acctDocRegistryHolder.get().get(acctSchemas, request.getRecord()); doc.post(request.isForce(), true);
documentPostingLogServiceHolder.get().logPostingOK(request); } catch (final Exception ex) { final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex); documentPostingLogServiceHolder.get().logPostingError(request, metasfreshException); if (request.getOnErrorNotifyUserId() != null) { userNotificationsHolder.get().notifyPostingError(request.getOnErrorNotifyUserId(), request.getRecord(), metasfreshException); } } } // // // ---------- // // }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\impl\PostingService.java
1
请完成以下Java代码
public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setIsSplitWhenDifference (final boolean IsSplitWhenDifference) { set_Value (COLUMNNAME_IsSplitWhenDifference, IsSplitWhenDifference); } @Override public boolean isSplitWhenDifference() { return get_ValueAsBoolean(COLUMNNAME_IsSplitWhenDifference); } @Override public org.compiere.model.I_AD_Sequence getLotNo_Sequence() { return get_ValueAsPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setLotNo_Sequence(final org.compiere.model.I_AD_Sequence LotNo_Sequence) { set_ValueFromPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, LotNo_Sequence); } @Override public void setLotNo_Sequence_ID (final int LotNo_Sequence_ID) { if (LotNo_Sequence_ID < 1) set_Value (COLUMNNAME_LotNo_Sequence_ID, null); else set_Value (COLUMNNAME_LotNo_Sequence_ID, LotNo_Sequence_ID); } @Override public int getLotNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_LotNo_Sequence_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintName (final java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName);
} @Override public java.lang.String getPrintName() { return get_ValueAsString(COLUMNNAME_PrintName); } @Override public org.compiere.model.I_R_RequestType getR_RequestType() { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); } @Override public void setR_RequestType_ID (final int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID); } @Override public int getR_RequestType_ID() { return get_ValueAsInt(COLUMNNAME_R_RequestType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
1
请完成以下Java代码
public Import newInstance(ModelTypeInstanceContext instanceContext) { return new ImportImpl(instanceContext); } }); namespaceAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAMESPACE) .required() .build(); locationAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_LOCATION) .required() .build(); importTypeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPORT_TYPE) .required() .build(); typeBuilder.build(); } public ImportImpl(ModelTypeInstanceContext context) { super(context); } public String getNamespace() { return namespaceAttribute.getValue(this); } public void setNamespace(String namespace) {
namespaceAttribute.setValue(this, namespace); } public String getLocation() { return locationAttribute.getValue(this); } public void setLocation(String location) { locationAttribute.setValue(this, location); } public String getImportType() { return importTypeAttribute.getValue(this); } public void setImportType(String importType) { importTypeAttribute.setValue(this, importType); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ImportImpl.java
1
请完成以下Java代码
public void setGrowth(Integer growth) { this.growth = growth; } public Integer getIntergration() { return intergration; } public void setIntergration(Integer intergration) { this.intergration = intergration; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type;
} @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(", name=").append(name); sb.append(", growth=").append(growth); sb.append(", intergration=").append(intergration); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTask.java
1
请完成以下Java代码
public java.sql.Timestamp getLastEndTime() { return get_ValueAsTimestamp(COLUMNNAME_LastEndTime); } @Override public void setLastStartTime (final @Nullable java.sql.Timestamp LastStartTime) { set_Value (COLUMNNAME_LastStartTime, LastStartTime); } @Override public java.sql.Timestamp getLastStartTime() { return get_ValueAsTimestamp(COLUMNNAME_LastStartTime); } @Override public void setLockedAt (final @Nullable java.sql.Timestamp LockedAt) { set_Value (COLUMNNAME_LockedAt, LockedAt); } @Override public java.sql.Timestamp getLockedAt() { return get_ValueAsTimestamp(COLUMNNAME_LockedAt); } /** * Priority AD_Reference_ID=154 * Reference name: _PriorityRule */ public static final int PRIORITY_AD_Reference_ID=154; /** High = 3 */ public static final String PRIORITY_High = "3"; /** Medium = 5 */ public static final String PRIORITY_Medium = "5"; /** Low = 7 */ public static final String PRIORITY_Low = "7"; /** Urgent = 1 */ public static final String PRIORITY_Urgent = "1"; /** Minor = 9 */ public static final String PRIORITY_Minor = "9"; @Override public void setPriority (final java.lang.String Priority) { set_Value (COLUMNNAME_Priority, Priority); } @Override public java.lang.String getPriority() { return get_ValueAsString(COLUMNNAME_Priority); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); }
@Override public void setSkippedAt (final @Nullable java.sql.Timestamp SkippedAt) { set_Value (COLUMNNAME_SkippedAt, SkippedAt); } @Override public java.sql.Timestamp getSkippedAt() { return get_ValueAsTimestamp(COLUMNNAME_SkippedAt); } @Override public void setSkipped_Count (final int Skipped_Count) { set_Value (COLUMNNAME_Skipped_Count, Skipped_Count); } @Override public int getSkipped_Count() { return get_ValueAsInt(COLUMNNAME_Skipped_Count); } @Override public void setSkipped_First_Time (final @Nullable java.sql.Timestamp Skipped_First_Time) { set_Value (COLUMNNAME_Skipped_First_Time, Skipped_First_Time); } @Override public java.sql.Timestamp getSkipped_First_Time() { return get_ValueAsTimestamp(COLUMNNAME_Skipped_First_Time); } @Override public void setSkipped_Last_Reason (final @Nullable java.lang.String Skipped_Last_Reason) { set_Value (COLUMNNAME_Skipped_Last_Reason, Skipped_Last_Reason); } @Override public java.lang.String getSkipped_Last_Reason() { return get_ValueAsString(COLUMNNAME_Skipped_Last_Reason); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage.java
1
请完成以下Java代码
public class OracleUcpDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata<PoolDataSource> { public OracleUcpDataSourcePoolMetadata(PoolDataSource dataSource) { super(dataSource); } @Override public @Nullable Integer getActive() { try { return getDataSource().getBorrowedConnectionsCount(); } catch (SQLException ex) { return null; } } @Override public @Nullable Integer getIdle() { try { return getDataSource().getAvailableConnectionsCount(); } catch (SQLException ex) { return null; } } @Override public @Nullable Integer getMax() { return getDataSource().getMaxPoolSize(); }
@Override public @Nullable Integer getMin() { return getDataSource().getMinPoolSize(); } @Override public @Nullable String getValidationQuery() { return getDataSource().getSQLForValidateConnection(); } @Override public @Nullable Boolean getDefaultAutoCommit() { String autoCommit = getDataSource().getConnectionProperty("autoCommit"); return StringUtils.hasText(autoCommit) ? Boolean.valueOf(autoCommit) : null; } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\OracleUcpDataSourcePoolMetadata.java
1
请完成以下Java代码
public String getSuperCaseInstanceId() { return superCaseInstanceId; } public void setSuperCaseInstanceId(String superCaseInstanceId) { this.superCaseInstanceId = superCaseInstanceId; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRestartedProcessInstanceId() { return restartedProcessInstanceId; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId) { this.restartedProcessInstanceId = restartedProcessInstanceId;
} @Override public String toString() { return this.getClass().getSimpleName() + "[businessKey=" + businessKey + ", startUserId=" + startUserId + ", superProcessInstanceId=" + superProcessInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", superCaseInstanceId=" + superCaseInstanceId + ", deleteReason=" + deleteReason + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", removalTime=" + removalTime + ", endActivityId=" + endActivityId + ", startActivityId=" + startActivityId + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", tenantId=" + tenantId + ", restartedProcessInstanceId=" + restartedProcessInstanceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java
1
请完成以下Java代码
public boolean isReadWrite() { return super.isEditable(); } // isReadWrite /** * Set Background based on editable / mandatory / error * @param error if true, set background to error color, otherwise mandatory/editable */ @Override public void setBackground (boolean error) { if (error) setBackground(AdempierePLAF.getFieldBackground_Error()); else if (!isReadWrite()) setBackground(AdempierePLAF.getFieldBackground_Inactive()); else if (m_mandatory) setBackground(AdempierePLAF.getFieldBackground_Mandatory()); else setBackground(AdempierePLAF.getFieldBackground_Normal()); } // setBackground /** * Set Background * @param bg */ @Override public void setBackground (Color bg) { if (bg.equals(getBackground())) return; super.setBackground(bg); } // setBackground /** * Set Editor to value * @param value value of the editor */
@Override public void setValue (Object value) { if (value == null) setText(""); else setText(value.toString()); } // setValue /** * Return Editor value * @return current value */ @Override public Object getValue() { return new String(super.getPassword()); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return new String(super.getPassword()); } // getDisplay }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPassword.java
1
请完成以下Java代码
public ScriptTask newInstance(ModelTypeInstanceContext instanceContext) { return new ScriptTaskImpl(instanceContext); } }); scriptFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SCRIPT_FORMAT) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); scriptChild = sequenceBuilder.element(Script.class) .build(); /** camunda extensions */ camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE) .namespace(CAMUNDA_NS) .build(); camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public ScriptTaskImpl(ModelTypeInstanceContext context) { super(context); } @Override public ScriptTaskBuilder builder() { return new ScriptTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getScriptFormat() { return scriptFormatAttribute.getValue(this); } public void setScriptFormat(String scriptFormat) { scriptFormatAttribute.setValue(this, scriptFormat);
} public Script getScript() { return scriptChild.getChild(this); } public void setScript(Script script) { scriptChild.setChild(this, script); } /** camunda extensions */ public String getCamundaResultVariable() { return camundaResultVariableAttribute.getValue(this); } public void setCamundaResultVariable(String camundaResultVariable) { camundaResultVariableAttribute.setValue(this, camundaResultVariable); } public String getCamundaResource() { return camundaResourceAttribute.getValue(this); } public void setCamundaResource(String camundaResource) { camundaResourceAttribute.setValue(this, camundaResource); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ScriptTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
private class InactiveSourceChecker implements BindHandler { private final @Nullable ConfigDataActivationContext activationContext; InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) { this.activationContext = activationContext; } @Override public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) { for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) { if (!contributor.isActive(this.activationContext)) { InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name); } } return result; } }
/** * Binder options that can be used with * {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}. */ enum BinderOption { /** * Throw an exception if an inactive contributor contains a bound value. */ FAIL_ON_BIND_TO_INACTIVE_SOURCE } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java
2
请完成以下Java代码
public class AtmRequestContext extends ContextBase { int totalAmountToBeWithdrawn; int noOfHundredsDispensed; int noOfFiftiesDispensed; int noOfTensDispensed; int amountLeftToBeWithdrawn; public int getTotalAmountToBeWithdrawn() { return totalAmountToBeWithdrawn; } public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) { this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn; } public int getNoOfHundredsDispensed() { return noOfHundredsDispensed; } public void setNoOfHundredsDispensed(int noOfHundredsDispensed) { this.noOfHundredsDispensed = noOfHundredsDispensed; } public int getNoOfFiftiesDispensed() { return noOfFiftiesDispensed; } public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) { this.noOfFiftiesDispensed = noOfFiftiesDispensed;
} public int getNoOfTensDispensed() { return noOfTensDispensed; } public void setNoOfTensDispensed(int noOfTensDispensed) { this.noOfTensDispensed = noOfTensDispensed; } public int getAmountLeftToBeWithdrawn() { return amountLeftToBeWithdrawn; } public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) { this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn; } }
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\chain\AtmRequestContext.java
1
请在Spring Boot框架中完成以下Java代码
public class C_Order { private final RepairSalesOrderService salesOrderService; public C_Order( @NonNull final RepairSalesOrderService salesOrderService) { this.salesOrderService = salesOrderService; } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void beforeDelete(final I_C_Order order) { salesOrderService.extractSalesProposalInfo(order).ifPresent(salesOrderService::unlinkProposalFromProject); } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void afterComplete(final I_C_Order order) { salesOrderService.extractSalesOrderInfo(order).ifPresent(salesOrderService::transferVHUsFromProjectToSalesOrderLine); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE, ModelValidator.TIMING_BEFORE_VOID, ModelValidator.TIMING_BEFORE_REVERSECORRECT }) public void beforeVoid( @NonNull final I_C_Order order, @NonNull final DocTimingType timing) { final RepairSalesProposalInfo proposal = salesOrderService.extractSalesProposalInfo(order).orElse(null); if (proposal != null) { beforeVoid_Proposal(proposal, timing);
} else { salesOrderService.extractSalesOrderInfo(order).ifPresent(this::beforeVoid_SalesOrder); } } private void beforeVoid_Proposal( @NonNull final RepairSalesProposalInfo proposal, @NonNull final DocTimingType timing) { if (timing.isVoid() || timing.isReverse()) { salesOrderService.unlinkProposalFromProject(proposal); } } private void beforeVoid_SalesOrder(@NonNull final RepairSalesOrderInfo salesOrder) { salesOrderService.transferVHUsFromSalesOrderToProject(salesOrder); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\sales_order\interceptor\C_Order.java
2
请完成以下Java代码
public class WorkPackageLockHelper { private static final Logger logger = LogManager.getLogger(WorkPackageLockHelper.class); public static boolean unlockNoFail(final I_C_Queue_WorkPackage workPackage) { try { unlock(workPackage); return true; } catch (final Exception e) { logger.warn("Got exception while unlocking " + workPackage, e); return false; } } private static void unlock(final I_C_Queue_WorkPackage workPackage)
{ try { final boolean success = Services.get(ILockManager.class).unlock(workPackage); if (!success) { throw new UnlockFailedException("Cannot unlock"); } } catch (final Exception e) { throw UnlockFailedException.wrapIfNeeded(e) .setParameter("Workpackage", workPackage); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\WorkPackageLockHelper.java
1
请完成以下Java代码
public String getValue() { return value; } /** * Gets code. * * @return the code */ public int getCode() { return code; } /** * Find by name. * * @param name the name * @return the month if found else <code>Optional.empty()</code> */ public static Optional<Month> findByName(String name) { return Arrays.stream(values()).filter(month -> month.name().equalsIgnoreCase(name)).findFirst(); } /**
* Find by code. * * @param code the code * @return the month if found else <code>Optional.empty()</code> */ public static Optional<Month> findByCode(int code) { return Arrays.stream(values()).filter(month -> month.getCode() == code).findFirst(); } /** * Finds month by value. * * @param value value * @return month if value is valid * @throws IllegalArgumentException if month not found for given value */ public static Month findByValue(String value) { return Arrays.stream(values()).filter(month -> month.getValue().equalsIgnoreCase(value)).findFirst().orElseThrow(IllegalArgumentException::new); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\enums\Month.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentReportResult { @NonNull @Builder.Default DocumentReportFlavor flavor = DocumentReportFlavor.PRINT; @Nullable ReportResultData reportResultData; @Nullable TableRecordReference documentRef; @Nullable AdProcessId reportProcessId; @Nullable PInstanceId reportPInstanceId; @Nullable BPartnerId bpartnerId; @Nullable Language language; @NonNull @Builder.Default PrintCopies copies = PrintCopies.ONE; @Nullable ArchiveResult lastArchive; @Nullable
Integer asyncBatchId; @Nullable String poReference; @Nullable public String getFilename() { return reportResultData != null ? reportResultData.getReportFilename() : null; } public boolean isNoData() { return reportResultData == null || reportResultData.isEmpty(); } @NonNull public Optional<Resource> getReportData() { if (reportResultData == null) { return Optional.empty(); } return Optional.of(reportResultData.getReportData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportResult.java
2
请完成以下Java代码
public EventDefinitionEntity getMostRecentVersionOfEventDefinition(EventDefinitionEntity eventDefinition) { String key = eventDefinition.getKey(); String tenantId = eventDefinition.getTenantId(); EventDefinitionEntityManager eventDefinitionEntityManager = CommandContextUtil.getEventRegistryConfiguration().getEventDefinitionEntityManager(); EventDefinitionEntity existingDefinition = null; if (tenantId != null && !tenantId.equals(EventRegistryEngineConfiguration.NO_TENANT_ID)) { existingDefinition = eventDefinitionEntityManager.findLatestEventDefinitionByKeyAndTenantId(key, tenantId); } else { existingDefinition = eventDefinitionEntityManager.findLatestEventDefinitionByKey(key); } return existingDefinition; } /** * Gets the persisted version of the already-deployed event definition. */ public EventDefinitionEntity getPersistedInstanceOfEventDefinition(EventDefinitionEntity eventDefinition) { String deploymentId = eventDefinition.getDeploymentId(); if (StringUtils.isEmpty(eventDefinition.getDeploymentId())) { throw new FlowableIllegalArgumentException("Provided event definition must have a deployment id.");
} EventDefinitionEntityManager eventDefinitionEntityManager = CommandContextUtil.getEventRegistryConfiguration().getEventDefinitionEntityManager(); EventDefinitionEntity persistedEventDefinition = null; if (eventDefinition.getTenantId() == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(eventDefinition.getTenantId())) { persistedEventDefinition = eventDefinitionEntityManager.findEventDefinitionByDeploymentAndKey(deploymentId, eventDefinition.getKey()); } else { persistedEventDefinition = eventDefinitionEntityManager.findEventDefinitionByDeploymentAndKeyAndTenantId(deploymentId, eventDefinition.getKey(), eventDefinition.getTenantId()); } return persistedEventDefinition; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\EventDefinitionDeploymentHelper.java
1
请完成以下Java代码
public ComponentDescriptorId getId() { return super.getId(); } @Schema(description = "Timestamp of the descriptor creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComponentDescriptor that = (ComponentDescriptor) o; if (type != that.type) return false; if (scope != that.scope) return false; if (!Objects.equals(name, that.name)) return false; if (!Objects.equals(actions, that.actions)) return false;
if (!Objects.equals(configurationDescriptor, that.configurationDescriptor)) return false; if (configurationVersion != that.configurationVersion) return false; if (clusteringMode != that.clusteringMode) return false; if (hasQueueName != that.isHasQueueName()) return false; return Objects.equals(clazz, that.clazz); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (scope != null ? scope.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (clazz != null ? clazz.hashCode() : 0); result = 31 * result + (actions != null ? actions.hashCode() : 0); result = 31 * result + (clusteringMode != null ? clusteringMode.hashCode() : 0); result = 31 * result + (hasQueueName ? 1 : 0); return result; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\plugin\ComponentDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public Object getValue(final Object po, final String columnName) { doChecks(po, columnName); if (MiscUtils.asPO(po).get_ColumnIndex(columnName) != -1) { return MiscUtils.asPO(po).get_Value(columnName); } // TODO throw an Exception return null; } private void doChecks(final Object po, final String columnName) { if (columnName == null) { throw new NullPointerException("columnName"); } if (po == null) { throw new NullPointerException("po"); } } /** * If the table of the given PO has a column with the given name, the PO's value is set to the given value. * * This method can be used to access non-standard columns that are not present in every ADempiere database. * * @param po * @param columnName * @param value * may be <code>null</code> */ @Override public void setValue(final Object po, final String columnName, final Object value) { if (columnName == null) { throw new NullPointerException("columnName"); }
if (MiscUtils.asPO(po).get_ColumnIndex(columnName) != -1) { MiscUtils.asPO(po).set_ValueOfColumn(columnName, value); } else { // TODO throw an Exception return; } } @Override public void copyValue(final Object source, final Object dest, final String columnName) { setValue(dest, columnName, getValue(source, columnName)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\misc\service\impl\POService.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_Year[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Calendar getC_Calendar() throws RuntimeException { return (I_C_Calendar)MTable.get(getCtx(), I_C_Calendar.Table_Name) .getPO(getC_Calendar_ID(), get_TrxName()); } /** Set Calendar. @param C_Calendar_ID Accounting Calendar Name */ public void setC_Calendar_ID (int C_Calendar_ID) { if (C_Calendar_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, Integer.valueOf(C_Calendar_ID)); } /** Get Calendar. @return Accounting Calendar Name */ public int getC_Calendar_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Calendar_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Year. @param C_Year_ID Calendar Year */ public void setC_Year_ID (int C_Year_ID) { if (C_Year_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Year_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID)); } /** Get Year. @return Calendar Year */ public int getC_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description
Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Year. @param FiscalYear The Fiscal Year */ public void setFiscalYear (String FiscalYear) { set_Value (COLUMNNAME_FiscalYear, FiscalYear); } /** Get Year. @return The Fiscal Year */ public String getFiscalYear () { return (String)get_Value(COLUMNNAME_FiscalYear); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getFiscalYear()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Year.java
1
请在Spring Boot框架中完成以下Java代码
private ArtemisMode deduceMode() { if (this.properties.getEmbedded().isEnabled() && isEmbeddedJmsClassPresent()) { return ArtemisMode.EMBEDDED; } return ArtemisMode.NATIVE; } private boolean isEmbeddedJmsClassPresent() { for (String embeddedJmsClass : EMBEDDED_JMS_CLASSES) { if (ClassUtils.isPresent(embeddedJmsClass, null)) { return true; } } return false; } private <T extends ActiveMQConnectionFactory> T createEmbeddedConnectionFactory( Function<ServerLocator, T> factoryCreator) throws Exception { try { TransportConfiguration transportConfiguration = new TransportConfiguration( InVMConnectorFactory.class.getName(), this.properties.getEmbedded().generateTransportParameters()); ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(transportConfiguration); return factoryCreator.apply(serverLocator); }
catch (NoClassDefFoundError ex) { throw new IllegalStateException("Unable to create InVM " + "Artemis connection, ensure that artemis-jms-server.jar is in the classpath", ex); } } private <T extends ActiveMQConnectionFactory> T createNativeConnectionFactory(Function<String, T> factoryCreator) { T connectionFactory = newNativeConnectionFactory(factoryCreator); String user = this.connectionDetails.getUser(); if (StringUtils.hasText(user)) { connectionFactory.setUser(user); connectionFactory.setPassword(this.connectionDetails.getPassword()); } return connectionFactory; } private <T extends ActiveMQConnectionFactory> T newNativeConnectionFactory(Function<String, T> factoryCreator) { String brokerUrl = StringUtils.hasText(this.connectionDetails.getBrokerUrl()) ? this.connectionDetails.getBrokerUrl() : DEFAULT_BROKER_URL; return factoryCreator.apply(brokerUrl); } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisConnectionFactoryFactory.java
2
请完成以下Java代码
public final class DeviceAccessorsList { static DeviceAccessorsList of(final List<DeviceAccessor> deviceAccessors, final String warningMessage) { final String warningMessageNorm = StringUtils.trimBlankToNull(warningMessage); if (deviceAccessors.isEmpty() && warningMessage == null) { return EMPTY; } return new DeviceAccessorsList(deviceAccessors, warningMessageNorm); } public static Collector<DeviceAccessor, ?, DeviceAccessorsList> collect() { return GuavaCollectors.collectUsingListAccumulator(list -> of(list, null)); } static final DeviceAccessorsList EMPTY = new DeviceAccessorsList(); @NonNull private final ImmutableList<DeviceAccessor> list; @NonNull private final ImmutableMap<DeviceId, DeviceAccessor> byId; @NonNull private final Optional<String> warningMessage; private DeviceAccessorsList(@NonNull final List<DeviceAccessor> list, @Nullable final String warningMessage) { this.list = ImmutableList.copyOf(list); this.byId = Maps.uniqueIndex(list, DeviceAccessor::getId); this.warningMessage = StringUtils.trimBlankToOptional(warningMessage); } /** * empty/null constructor */ private DeviceAccessorsList() { this.list = ImmutableList.of(); this.byId = ImmutableMap.of(); this.warningMessage = Optional.empty(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("warningMessage", warningMessage) .addValue(list.isEmpty() ? null : list)
.toString(); } public Stream<DeviceAccessor> stream() { return list.stream(); } public Stream<DeviceAccessor> stream(final WarehouseId warehouseId) { return stream().filter(deviceAccessor -> deviceAccessor.isAvailableForWarehouse(warehouseId)); } @NonNull public Stream<DeviceAccessor> streamForLocator(final LocatorId locatorId) { return stream().filter(deviceAccessor -> deviceAccessor.isAvailableForLocator(locatorId)); } public DeviceAccessor getByIdOrNull(final DeviceId id) { return byId.get(id); } /** * Convenient (fluent) method to consume the warningMessage if any. */ public void consumeWarningMessageIfAny(final Consumer<String> warningMessageConsumer) { warningMessage.ifPresent(warningMessageConsumer); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceAccessorsList.java
1
请在Spring Boot框架中完成以下Java代码
public Stream<ConditionAndOutcome> stream() { return StreamSupport.stream(spliterator(), false); } @Override public Iterator<ConditionAndOutcome> iterator() { return Collections.unmodifiableSet(this.outcomes).iterator(); } } /** * Provides access to a single {@link Condition} and {@link ConditionOutcome}. */ public static class ConditionAndOutcome { private final Condition condition; private final ConditionOutcome outcome; public ConditionAndOutcome(Condition condition, ConditionOutcome outcome) { this.condition = condition; this.outcome = outcome; } public Condition getCondition() { return this.condition; } public ConditionOutcome getOutcome() { return this.outcome; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ConditionAndOutcome other = (ConditionAndOutcome) obj; return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass())
&& ObjectUtils.nullSafeEquals(this.outcome, other.outcome)); } @Override public int hashCode() { return this.condition.getClass().hashCode() * 31 + this.outcome.hashCode(); } @Override public String toString() { return this.condition.getClass() + " " + this.outcome; } } private static final class AncestorsMatchedCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { throw new UnsupportedOperationException(); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionEvaluationReport.java
2
请完成以下Java代码
public Account getTaxCreditOrExpense(@NonNull final AcctSchema as) { return accountProvider.getTaxAccount(as.getId(), taxId, TaxAcctType.getAPTaxType(salesTax)); } @NonNull public Account getTaxDueAcct(@NonNull final AcctSchema as) { return accountProvider.getTaxAccount(as.getId(), taxId, TaxAcctType.TaxDue); } public int getC_Tax_ID() {return taxId.getRepoId();} public String getDescription() {return taxName + " " + taxBaseAmt;} public void addIncludedTax(final BigDecimal amt) { includedTaxAmt = includedTaxAmt.add(amt); }
/** * @return tax amount - included tax amount */ public BigDecimal getIncludedTaxDifference() { return taxAmt.subtract(includedTaxAmt); } /** * Included Tax differs from tax amount * * @return true if difference */ public boolean isIncludedTaxDifference() {return getIncludedTaxDifference().signum() != 0;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTax.java
1
请完成以下Java代码
public void delayEvents() { m_propertyChangeListeners.blockEvents(); } /** * Fire all enqueued events (if any) and disable events delaying. * * @see #delayEvents(). */ public void releaseDelayedEvents() { m_propertyChangeListeners.releaseEvents(); } @Override public boolean isRecordCopyingMode() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.isDataNewCopy(); } @Override public boolean isRecordCopyingModeIncludingDetails() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.getTableModel().isCopyWithDetails(); } @Override public void fireDataStatusEEvent(final String AD_Message, final String info, final boolean isError) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: AD_Message={}, info={}, isError={}", this, AD_Message, info, isError); return; } gridTab.fireDataStatusEEvent(AD_Message, info, isError); } @Override public void fireDataStatusEEvent(final ValueNamePair errorLog)
{ final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: errorLog={}", this, errorLog); return; } gridTab.fireDataStatusEEvent(errorLog); } @Override public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id) { throw new UnsupportedOperationException(); } @Override public ICalloutRecord getCalloutRecord() { final GridTab gridTab = getGridTab(); Check.assumeNotNull(gridTab, "gridTab not null"); return gridTab; } @Override public int getContextAsInt(String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridField.java
1
请完成以下Java代码
public static String formatDate(long value, DateFormat threadLocalformat) { String cachedDate = null; Long longValue = value; try { cachedDate = formatCache.get(longValue); } catch (Exception ex) { } if (cachedDate != null) { return cachedDate; } String newDate; Date dateValue = new Date(value); if (threadLocalformat != null) { newDate = threadLocalformat.format(dateValue); synchronized (formatCache) { updateCache(formatCache, longValue, newDate); } } else { synchronized (formatCache) { newDate = format.format(dateValue); updateCache(formatCache, longValue, newDate); } } return newDate; } /** * Gets the current date in HTTP format. * @return Current date in HTTP format */ public static @Nullable String getCurrentDate() { long now = System.currentTimeMillis(); if ((now - currentDateGenerated) > 1000) { synchronized (format) { if ((now - currentDateGenerated) > 1000) { currentDateGenerated = now; currentDate = format.format(new Date(now)); } } } return currentDate; } /** * Parses date with given formatters. * @param value The string to parse * @param formats Array of formats to use * @return Parsed date (or <code>null</code> if no formatter mached) */ private static @Nullable Long internalParseDate(String value, DateFormat[] formats) { Date date = null; for (int i = 0; (date == null) && (i < formats.length); i++) { try { date = formats[i].parse(value); } catch (ParseException ex) { } } if (date == null) { return null; } return date.getTime(); } /**
* Tries to parse the given date as an HTTP date. If local format list is not * <code>null</code>, it's used instead. * @param value The string to parse * @param threadLocalformats Array of formats to use for parsing. If <code>null</code> * , HTTP formats are used. * @return Parsed date (or -1 if error occurred) */ public static long parseDate(String value, DateFormat[] threadLocalformats) { Long cachedDate = null; try { cachedDate = parseCache.get(value); } catch (Exception ex) { } if (cachedDate != null) { return cachedDate; } Long date; if (threadLocalformats != null) { date = internalParseDate(value, threadLocalformats); synchronized (parseCache) { updateCache(parseCache, value, date); } } else { synchronized (parseCache) { date = internalParseDate(value, formats); updateCache(parseCache, value, date); } } return (date != null) ? date : -1L; } /** * Updates cache. * @param cache Cache to be updated * @param key Key to be updated * @param value New value */ @SuppressWarnings("unchecked") private static void updateCache(HashMap cache, Object key, @Nullable Object value) { if (value == null) { return; } if (cache.size() > 1000) { cache.clear(); } cache.put(key, value); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\FastHttpDateFormat.java
1
请完成以下Java代码
public void setFormatType (final java.lang.String FormatType) { set_Value (COLUMNNAME_FormatType, FormatType); } @Override public java.lang.String getFormatType() { return get_ValueAsString(COLUMNNAME_FormatType); } @Override public void setIsManualImport (final boolean IsManualImport) { set_Value (COLUMNNAME_IsManualImport, IsManualImport); } @Override public boolean isManualImport() { return get_ValueAsBoolean(COLUMNNAME_IsManualImport); } @Override public void setIsMultiLine (final boolean IsMultiLine) { set_Value (COLUMNNAME_IsMultiLine, IsMultiLine); } @Override public boolean isMultiLine() { return get_ValueAsBoolean(COLUMNNAME_IsMultiLine); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSkipFirstNRows (final int SkipFirstNRows) { set_Value (COLUMNNAME_SkipFirstNRows, SkipFirstNRows); } @Override public int getSkipFirstNRows() { return get_ValueAsInt(COLUMNNAME_SkipFirstNRows); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat.java
1
请完成以下Java代码
private void checkCancellation(final CommandContext commandContext) { for (final AbstractProcessInstanceModificationCommand instruction : builder.getModificationOperations()) { if (instruction instanceof ActivityCancellationCmd && ((ActivityCancellationCmd) instruction).cancelCurrentActiveActivityInstances) { ActivityInstance activityInstanceTree = commandContext.runWithoutAuthorization( new GetActivityInstanceCmd(((ActivityCancellationCmd) instruction).processInstanceId)); ((ActivityCancellationCmd) instruction).setActivityInstanceTreeToCancel(activityInstanceTree); } } } protected void ensureProcessInstanceExist(String processInstanceId, ExecutionEntity processInstance) { if (processInstance == null) { throw LOG.processInstanceDoesNotExist(processInstanceId); } } protected String getLogEntryOperation() { return UserOperationLogEntry.OPERATION_TYPE_MODIFY_PROCESS_INSTANCE; } protected void checkUpdateProcessInstance(ExecutionEntity execution, CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessInstance(execution); } }
protected void checkDeleteProcessInstance(ExecutionEntity execution, CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkDeleteProcessInstance(execution); } } protected void deletePropagate(ExecutionEntity processInstance, String deleteReason, boolean skipCustomListeners, boolean skipIoMappings, boolean externallyTerminated) { ExecutionEntity topmostDeletableExecution = processInstance; ExecutionEntity parentScopeExecution = (ExecutionEntity) topmostDeletableExecution.getParentScopeExecution(true); while (parentScopeExecution != null && (parentScopeExecution.getNonEventScopeExecutions().size() <= 1)) { topmostDeletableExecution = parentScopeExecution; parentScopeExecution = (ExecutionEntity) topmostDeletableExecution.getParentScopeExecution(true); } topmostDeletableExecution.deleteCascade(deleteReason, skipCustomListeners, skipIoMappings, externallyTerminated, false); ModificationUtil.handleChildRemovalInScope(topmostDeletableExecution); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ModifyProcessInstanceCmd.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Employee other = (Employee) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } 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 Long getSalary() { return salary; } public void setSalary(Long salary) { this.salary = salary; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\model\Employee.java
1
请完成以下Spring Boot application配置
spring: application.name: client-service cloud: kubernetes: reload: enabled: true discovery: enabled: true all-namespaces: false primary-port-name: "default-http" discovery-server-url: "http://myapp-discoveryserver" include-not-ready-addresses: true server.port: 8080 management: e
ndpoint: restart: enabled: true health: enabled: true info: enabled: true ribbon: http: client: enabled: true
repos\tutorials-master\spring-cloud-modules\spring-cloud-kubernetes\kubernetes-guide\client-service\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class Article { @Id private int id; private String title; @Enumerated(EnumType.ORDINAL) private Status status; @Enumerated(EnumType.STRING) private Type type; @Basic private int priorityValue; @Transient private Priority priority; private Category category; public Article() { } @PostLoad void fillTransient() { if (priorityValue > 0) { this.priority = Priority.of(priorityValue); } } @PrePersist void fillPersistent() { if (priority != null) { this.priorityValue = priority.getPriority(); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) {
this.title = title; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Priority getPriority() { return priority; } public void setPriority(Priority priority) { this.priority = priority; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\enums\Article.java
2