instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public Department add(@RequestBody Department department) { LOGGER.info("Department add: {}", department); return repository.add(department); } @GetMapping("/{id}") public Department findById(@PathVariable("id") Long id) { LOGGER.info("Department find: id={}", id); return repository.findById(id); } @GetMapping("/") public List<Department> findAll() { LOGGER.info("Department find"); return repository.findAll(); }
@GetMapping("/organization/{organizationId}") public List<Department> findByOrganization(@PathVariable("organizationId") Long organizationId) { LOGGER.info("Department find: organizationId={}", organizationId); return repository.findByOrganization(organizationId); } @GetMapping("/organization/{organizationId}/with-employees") public List<Department> findByOrganizationWithEmployees(@PathVariable("organizationId") Long organizationId) { LOGGER.info("Department find with employees: organizationId={}", organizationId); List<Department> departments = repository.findByOrganization(organizationId); departments.forEach(d -> d.setEmployees(employeeClient.findByDepartment(d.getId()))); return departments; } }
repos\sample-spring-microservices-new-master\department-service\src\main\java\pl\piomin\services\department\controller\DepartmentController.java
2
请在Spring Boot框架中完成以下Java代码
private List<I_M_HU> extractToTopLevelHUs(@NonNull final ImmutableSet<HUIdAndQRCode> huIdAndQRCodeList) { final Set<HuId> topLevelHUIds = newHUTransformService().extractToTopLevel(huIdAndQRCodeList); return huService.getByIds(topLevelHUIds); } private static ImmutableSet<HUIdAndQRCode> extractHuIdAndQRCodes(final @NonNull List<PickingJobStepPickedToHU> pickedToHUs) { return pickedToHUs.stream() .map(PickingJobStepPickedToHU::getActualPickedHU) .map(HUInfo::toHUIdAndQRCode) .collect(ImmutableSet.toImmutableSet()); } private void changeHUStatusFromPickedToActive(final Collection<I_M_HU> topLevelHUs) { topLevelHUs.forEach(this::changeHUStatusFromPickedToActive); } private void changeHUStatusFromPickedToActive(final I_M_HU topLevelHU) { if (X_M_HU.HUSTATUS_Picked.equals(topLevelHU.getHUStatus())) { huService.setHUStatusActive(topLevelHU); } } private HUTransformService newHUTransformService() { return HUTransformService.builder() .huQRCodesService(huService.getHuQRCodesService()) .build(); } @NonNull private PickingJob reinitializePickingTargetIfDestroyed(final PickingJob pickingJob) { if (isLineLevelPickTarget(pickingJob)) { return pickingJob.withLuPickingTarget(lineId, this::reinitializeLUPickingTarget); } else { return pickingJob.withLuPickingTarget(null, this::reinitializeLUPickingTarget); }
} private boolean isLineLevelPickTarget(final PickingJob pickingJob) {return pickingJob.isLineLevelPickTarget();} @Nullable private LUPickingTarget reinitializeLUPickingTarget(@Nullable final LUPickingTarget luPickingTarget) { if (luPickingTarget == null) { return null; } final HuId luId = luPickingTarget.getLuId(); if (luId == null) { return luPickingTarget; } final I_M_HU lu = huService.getById(luId); if (!huService.isDestroyedOrEmptyStorage(lu)) { return luPickingTarget; } final HuPackingInstructionsIdAndCaption luPI = huService.getEffectivePackingInstructionsIdAndCaption(lu); return LUPickingTarget.ofPackingInstructions(luPI); } // // // @Value @Builder private static class StepUnpickInstructions { @NonNull PickingJobStepId stepId; @NonNull PickingJobStepPickFromKey pickFromKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobUnPickCommand.java
2
请在Spring Boot框架中完成以下Java代码
public Result<?> delete(@RequestParam(name = "id") String id) { if (sysTableWhiteListService.deleteByIds(id)) { return Result.OK("删除成功!"); } else { return Result.error("删除失败!"); } } /** * 批量删除 * * @param ids * @return */ @AutoLog(value = "系统表白名单-批量删除") @Operation(summary = "系统表白名单-批量删除") // @RequiresRoles("admin") @RequiresPermissions("system:tableWhite:deleteBatch") @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) { if (sysTableWhiteListService.deleteByIds(ids)) { return Result.OK("批量删除成功!"); } else {
return Result.error("批量删除失败!"); } } /** * 通过id查询 * * @param id * @return */ @AutoLog(value = "系统表白名单-通过id查询") @Operation(summary = "系统表白名单-通过id查询") // @RequiresRoles("admin") @RequiresPermissions("system:tableWhite:queryById") @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { SysTableWhiteList sysTableWhiteList = sysTableWhiteListService.getById(id); return Result.OK(sysTableWhiteList); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysTableWhiteListController.java
2
请完成以下Java代码
private Optional<String> getRuestplatz(@NonNull final Context pickingJob) { final BPartnerLocationId deliveryLocationId = pickingJob.getDeliveryLocationId(); if (deliveryLocationId == null) { return Optional.empty(); } return ruestplatzCache.computeIfAbsent(deliveryLocationId, this::retrieveRuestplatz); } private Optional<String> retrieveRuestplatz(final BPartnerLocationId deliveryLocationId) { return extractRuestplatz(bpartnerService.getBPartnerLocationByIdEvenInactive(deliveryLocationId)); } private static Optional<String> extractRuestplatz(@Nullable final I_C_BPartner_Location location) { return Optional.ofNullable(location) .map(I_C_BPartner_Location::getSetup_Place_No) .map(StringUtils::trimBlankToNull); } @Nullable private String getHandoverAddress(@NonNull final Context pickingJob, @Nullable AddressDisplaySequence displaySequence) { final BPartnerLocationId bpLocationId = pickingJob.getHandoverLocationIdWithFallback(); return bpLocationId != null ? renderedAddressProvider.getAddress(bpLocationId, displaySequence) : null;
} @Nullable private String getDeliveryAddress(@NonNull final Context context, @Nullable AddressDisplaySequence displaySequence) { final BPartnerLocationId bpLocationId = context.getDeliveryLocationId(); return bpLocationId != null ? renderedAddressProvider.getAddress(bpLocationId, displaySequence) : null; } @Value @Builder private static class Context { @Nullable String salesOrderDocumentNo; @Nullable String customerName; @Nullable ZonedDateTime preparationDate; @Nullable BPartnerLocationId deliveryLocationId; @Nullable BPartnerLocationId handoverLocationId; @Nullable ITranslatableString productName; @Nullable Quantity qtyToDeliver; @Nullable public BPartnerLocationId getHandoverLocationIdWithFallback() { return handoverLocationId != null ? handoverLocationId : deliveryLocationId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\DisplayValueProvider.java
1
请完成以下Java代码
private void createUpdateInterestArea(final I_I_BPartner importRecord) { final int interestAreaId = importRecord.getR_InterestArea_ID(); if (interestAreaId <= 0) { return; } final int adUserId = importRecord.getAD_User_ID(); if (adUserId <= 0) { return; } final MContactInterest ci = MContactInterest.get(getCtx(), interestAreaId, adUserId, true, // active ITrx.TRXNAME_ThreadInherited); ci.save(); // don't subscribe or re-activate } @Override public Class<I_I_BPartner> getImportModelClass() { return I_I_BPartner.class; } @Override public String getImportTableName() { return I_I_BPartner.Table_Name; }
@Override protected String getImportOrderBySql() { // gody: 20070113 - Order so the same values are consecutive. return I_I_BPartner.COLUMNNAME_BPValue + ", " + I_I_BPartner.COLUMNNAME_GlobalId + ", " + I_I_BPartner.COLUMNNAME_I_BPartner_ID; } @Override protected String getTargetTableName() { return I_C_BPartner.Table_Name; } @Override public I_I_BPartner retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { return new X_I_BPartner(ctx, rs, ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public Result index() { return Results.html(); } public Result userJson() { HashMap<String, String> userMap = userService.getUserMap(); logger.info(userMap); return Results.json().render(userMap); } public Result helloWorld(Context context) { Optional<String> language = Optional.of("fr"); String helloMsg = msg.get("helloMsg", language).get(); return Results.text().render(helloMsg); } public Result showFlashMsg(FlashScope flashScope) { flashScope.success("Success message"); flashScope.error("Error message"); return Results.redirect("/home"); } public Result home() { return Results.html(); } public Result createUser() { return Results.html(); } @UnitOfWork
public Result fetchUsers() { EntityManager entityManager = entityManagerProvider.get(); Query q = entityManager.createQuery("SELECT x FROM User x"); List<User> users = (List<User>) q.getResultList(); return Results.json().render(users); } @Transactional public Result insertUser(FlashScope flashScope, @JSR303Validation User user, Validation validation) { logger.info("Inserting User : " +user); if (validation.getViolations().size() > 0) { flashScope.error("Validation Error: User can't be created"); } else { EntityManager entityManager = entityManagerProvider.get(); entityManager.persist(user); entityManager.flush(); flashScope.success("User '" + user + "' is created successfully"); } return Results.redirect("/home"); } }
repos\tutorials-master\web-modules\ninja\src\main\java\controllers\ApplicationController.java
2
请完成以下Java代码
public ConsumerFactory<String, Greeting> greetingConsumerFactory() { Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.GROUP_ID_CONFIG, "greeting"); return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(Greeting.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Greeting> greetingKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Greeting> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(greetingConsumerFactory()); return factory; } @Bean public RecordMessageConverter multiTypeConverter() { StringJsonMessageConverter converter = new StringJsonMessageConverter(); DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper(); typeMapper.setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence.TYPE_ID); typeMapper.addTrustedPackages("com.baeldung.spring.kafka"); Map<String, Class<?>> mappings = new HashMap<>(); mappings.put("greeting", Greeting.class); mappings.put("farewell", Farewell.class); typeMapper.setIdClassMapping(mappings); converter.setTypeMapper(typeMapper); return converter;
} @Bean public ConsumerFactory<String, Object> multiTypeConsumerFactory() { HashMap<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Object> multiTypeKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(multiTypeConsumerFactory()); factory.setRecordMessageConverter(multiTypeConverter()); return factory; } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\spring\kafka\KafkaConsumerConfig.java
1
请在Spring Boot框架中完成以下Java代码
public boolean matchesFilter(DeviceActivityTrigger trigger, DeviceActivityNotificationRuleTriggerConfig triggerConfig) { DeviceEvent event = trigger.isActive() ? DeviceEvent.ACTIVE : DeviceEvent.INACTIVE; if (!triggerConfig.getNotifyOn().contains(event)) { return false; } DeviceId deviceId = trigger.getDeviceId(); if (CollectionUtils.isNotEmpty(triggerConfig.getDevices())) { return triggerConfig.getDevices().contains(deviceId.getId()); } else if (CollectionUtils.isNotEmpty(triggerConfig.getDeviceProfiles())) { DeviceProfile deviceProfile = deviceProfileCache.get(TenantId.SYS_TENANT_ID, deviceId); return deviceProfile != null && triggerConfig.getDeviceProfiles().contains(deviceProfile.getUuidId()); } else { return true; } } @Override public RuleOriginatedNotificationInfo constructNotificationInfo(DeviceActivityTrigger trigger) {
return DeviceActivityNotificationInfo.builder() .eventType(trigger.isActive() ? "active" : "inactive") .deviceId(trigger.getDeviceId().getId()) .deviceName(trigger.getDeviceName()) .deviceType(trigger.getDeviceType()) .deviceLabel(trigger.getDeviceLabel()) .deviceCustomerId(trigger.getCustomerId()) .build(); } @Override public NotificationRuleTriggerType getTriggerType() { return NotificationRuleTriggerType.DEVICE_ACTIVITY; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\DeviceActivityTriggerProcessor.java
2
请完成以下Java代码
public boolean isClusterMode() { return clusterMode; } public void setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; } public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip;
} public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请完成以下Java代码
public static ShipmentScheduleAndJobScheduleId ofShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId) { return of(shipmentScheduleId, null); } @Override @Deprecated public String toString() {return toJsonString();} @JsonValue public String toJsonString() { return jobScheduleId != null ? shipmentScheduleId.getRepoId() + "_" + jobScheduleId.getRepoId() : "" + shipmentScheduleId.getRepoId(); } @JsonCreator public static ShipmentScheduleAndJobScheduleId ofJsonString(@NonNull final String json) { try { final int idx = json.indexOf("_"); if (idx > 0) { return of( ShipmentScheduleId.ofRepoId(Integer.parseInt(json.substring(0, idx))), PickingJobScheduleId.ofRepoId(Integer.parseInt(json.substring(idx + 1))) ); } else { return of( ShipmentScheduleId.ofRepoId(Integer.parseInt(json)), null ); }
} catch (Exception ex) { throw new AdempiereException("Invalid JSON: " + json, ex); } } public TableRecordReference toTableRecordReference() { return jobScheduleId != null ? jobScheduleId.toTableRecordReference() : shipmentScheduleId.toTableRecordReference(); } public boolean isJobSchedule() {return jobScheduleId != null;} @Override public int compareTo(@NotNull final ShipmentScheduleAndJobScheduleId other) { return this.toJsonString().compareTo(other.toJsonString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\ShipmentScheduleAndJobScheduleId.java
1
请在Spring Boot框架中完成以下Java代码
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> { private Logger logger = LoggerFactory.getLogger(getClass()); @Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.UNPAID) .states(EnumSet.allOf(States.class)); } @Override public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception { transitions .withExternal() .source(States.UNPAID).target(States.WAITING_FOR_RECEIVE) .event(Events.PAY) .and() .withExternal() .source(States.WAITING_FOR_RECEIVE).target(States.DONE) .event(Events.RECEIVE); } // @Override // public void configure(StateMachineConfigurationConfigurer<States, Events> config) // throws Exception { // config // .withConfiguration() // .listener(listener()); // } // // @Bean // public StateMachineListener<States, Events> listener() { // return new StateMachineListenerAdapter<States, Events>() { // // @Override // public void transition(Transition<States, Events> transition) { // if(transition.getTarget().getId() == States.UNPAID) { // logger.info("订单创建,待支付"); // return;
// } // // if(transition.getSource().getId() == States.UNPAID // && transition.getTarget().getId() == States.WAITING_FOR_RECEIVE) { // logger.info("用户完成支付,待收货"); // return; // } // // if(transition.getSource().getId() == States.WAITING_FOR_RECEIVE // && transition.getTarget().getId() == States.DONE) { // logger.info("用户已收货,订单完成"); // return; // } // } // // }; // } }
repos\SpringBoot-Learning-master\1.x\Chapter6-1-1\src\main\java\com\didispace\StateMachineConfig.java
2
请完成以下Java代码
public class RequestMappingConditionsDescription { private final List<MediaTypeExpressionDescription> consumes; private final List<NameValueExpressionDescription> headers; private final Set<RequestMethod> methods; private final List<NameValueExpressionDescription> params; private final Set<String> patterns; private final List<MediaTypeExpressionDescription> produces; RequestMappingConditionsDescription(RequestMappingInfo requestMapping) { this.consumes = requestMapping.getConsumesCondition() .getExpressions() .stream() .map(MediaTypeExpressionDescription::new) .toList(); this.headers = requestMapping.getHeadersCondition() .getExpressions() .stream() .map(NameValueExpressionDescription::new) .toList(); this.methods = requestMapping.getMethodsCondition().getMethods(); this.params = requestMapping.getParamsCondition() .getExpressions() .stream() .map(NameValueExpressionDescription::new) .toList(); this.patterns = requestMapping.getPatternsCondition() .getPatterns() .stream() .map(PathPattern::getPatternString) .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); this.produces = requestMapping.getProducesCondition() .getExpressions() .stream() .map(MediaTypeExpressionDescription::new) .toList(); } public List<MediaTypeExpressionDescription> getConsumes() { return this.consumes; } public List<NameValueExpressionDescription> getHeaders() { return this.headers; } public Set<RequestMethod> getMethods() { return this.methods; } public List<NameValueExpressionDescription> getParams() { return this.params; } public Set<String> getPatterns() { return this.patterns; } public List<MediaTypeExpressionDescription> getProduces() { return this.produces; } /** * A description of a {@link MediaTypeExpression} in a request mapping condition.
*/ public static class MediaTypeExpressionDescription { private final String mediaType; private final boolean negated; MediaTypeExpressionDescription(MediaTypeExpression expression) { this.mediaType = expression.getMediaType().toString(); this.negated = expression.isNegated(); } public String getMediaType() { return this.mediaType; } public boolean isNegated() { return this.negated; } } /** * A description of a {@link NameValueExpression} in a request mapping condition. */ public static class NameValueExpressionDescription { private final String name; private final @Nullable Object value; private final boolean negated; NameValueExpressionDescription(NameValueExpression<?> expression) { this.name = expression.getName(); this.value = expression.getValue(); this.negated = expression.isNegated(); } public String getName() { return this.name; } public @Nullable Object getValue() { return this.value; } public boolean isNegated() { return this.negated; } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\RequestMappingConditionsDescription.java
1
请完成以下Java代码
private static final class ExcludingVariablesEvaluatee implements Evaluatee { private final Evaluatee parent; private final String excludeVariableName; private ExcludingVariablesEvaluatee(final Evaluatee parent, final String excludeVariableName) { super(); this.parent = parent; this.excludeVariableName = excludeVariableName; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("excludeVariableName", excludeVariableName) .add("parent", parent) .toString(); } @Nullable @Override public <T> T get_ValueAsObject(final String variableName) { if (excludeVariableName.equals(variableName)) { return null; } return parent.get_ValueAsObject(variableName); } @Nullable @Override public String get_ValueAsString(final String variableName) { if (excludeVariableName.equals(variableName)) { return null; } return parent.get_ValueAsString(variableName); } @Override public Optional<Object> get_ValueIfExists(final @NonNull String variableName, final @NonNull Class<?> targetType) { if (excludeVariableName.equals(variableName)) { return Optional.empty(); } return parent.get_ValueIfExists(variableName, targetType); } } @ToString private static class RangeAwareParamsAsEvaluatee implements Evaluatee2 { private final IRangeAwareParams params;
private RangeAwareParamsAsEvaluatee(@NonNull final IRangeAwareParams params) { this.params = params; } @Override public boolean has_Variable(final String variableName) { return params.hasParameter(variableName); } @SuppressWarnings("unchecked") @Override public <T> T get_ValueAsObject(final String variableName) { return (T)params.getParameterAsObject(variableName); } @Override public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue) { final BigDecimal value = params.getParameterAsBigDecimal(variableName); return value != null ? value : defaultValue; } @Override public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED) { return params.getParameterAsBool(variableName); } @Override public Date get_ValueAsDate(final String variableName, final Date defaultValue) { final Timestamp value = params.getParameterAsTimestamp(variableName); return value != null ? value : defaultValue; } @Override public Integer get_ValueAsInt(final String variableName, final Integer defaultValue) { final int defaultValueInt = defaultValue != null ? defaultValue : 0; return params.getParameterAsInt(variableName, defaultValueInt); } @Override public String get_ValueAsString(final String variableName) { return params.getParameterAsString(variableName); } @Override public String get_ValueOldAsString(final String variableName) { return get_ValueAsString(variableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java
1
请完成以下Java代码
final class PPOrderLinesViewData { @Getter private final ITranslatableString description; @Getter private final PPOrderPlanningStatus planningStatus; private final ImmutableList<PPOrderLineRow> topLevelRows; @Getter private final PPOrderLineRow finishedGoodRow; @Getter private final ViewHeaderProperties headerProperties; /** * All records (included ones too) indexed by DocumentId */ private final ImmutableMap<DocumentId, PPOrderLineRow> allRowsById; @Builder private PPOrderLinesViewData( @NonNull final ITranslatableString description, @NonNull final PPOrderPlanningStatus planningStatus, @NonNull final PPOrderLineRow finishedGoodRow, @NonNull final List<PPOrderLineRow> bomLineRows, @NonNull final List<PPOrderLineRow> sourceHURows, @NonNull final ViewHeaderProperties headerProperties) { this.description = description; this.planningStatus = planningStatus; this.finishedGoodRow = finishedGoodRow; this.headerProperties = headerProperties; this.topLevelRows = ImmutableList.<PPOrderLineRow>builder() .add(finishedGoodRow) .addAll(bomLineRows) .addAll(sourceHURows) .build(); allRowsById = buildRecordsByIdMap(this.topLevelRows); } private static ImmutableMap<DocumentId, PPOrderLineRow> buildRecordsByIdMap(@NonNull final List<PPOrderLineRow> rows) { if (rows.isEmpty()) { return ImmutableMap.of(); } final ImmutableMap.Builder<DocumentId, PPOrderLineRow> rowsById = ImmutableMap.builder(); rows.forEach(row -> indexByIdRecursively(rowsById, row)); return rowsById.build(); } private static void indexByIdRecursively( @NonNull final ImmutableMap.Builder<DocumentId, PPOrderLineRow> collector, @NonNull final PPOrderLineRow row) { collector.put(row.getRowId().toDocumentId(), row); row.getIncludedRows().forEach(includedRow -> indexByIdRecursively(collector, includedRow)); } public PPOrderLineRow getById(@NonNull final PPOrderLineRowId rowId) { final DocumentId documentId = rowId.toDocumentId(); final PPOrderLineRow row = allRowsById.get(documentId); if (row == null) { throw new EntityNotFoundException("No document found for rowId=" + rowId); } return row;
} public Stream<PPOrderLineRow> streamByIds(@NonNull final DocumentIdsSelection documentIds) { if (documentIds == null || documentIds.isEmpty()) { return Stream.empty(); } else if (documentIds.isAll()) { return topLevelRows.stream(); } else { return documentIds.stream() .distinct() .map(allRowsById::get) .filter(Objects::nonNull); } } public Stream<PPOrderLineRow> stream() { return topLevelRows.stream(); } public long size() { return topLevelRows.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesViewData.java
1
请在Spring Boot框架中完成以下Java代码
private static ClientRegistration.Builder getBuilder(ParserContext parserContext, ClientRegistration.Builder builder, Map<String, String> provider) { getOptionalIfNotEmpty(parserContext, provider.get(ATT_AUTHORIZATION_URI)).ifPresent(builder::authorizationUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_TOKEN_URI)).ifPresent(builder::tokenUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_URI)).ifPresent(builder::userInfoUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_AUTHENTICATION_METHOD)) .map(AuthenticationMethod::new) .ifPresent(builder::userInfoAuthenticationMethod); getOptionalIfNotEmpty(parserContext, provider.get(ATT_JWK_SET_URI)).ifPresent(builder::jwkSetUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_USER_NAME_ATTRIBUTE)) .ifPresent(builder::userNameAttributeName); return builder; } private static Optional<String> getOptionalIfNotEmpty(ParserContext parserContext, String str) { return Optional.ofNullable(str) .filter((s) -> !s.isEmpty()) .map(parserContext.getReaderContext().getEnvironment()::resolvePlaceholders); } private static CommonOAuth2Provider getCommonProvider(String providerId) { try { String value = providerId.trim(); if (value.isEmpty()) { return null; } try { return CommonOAuth2Provider.valueOf(value); } catch (Exception ex) { return findEnum(value); } } catch (Exception ex) { return null; }
} private static CommonOAuth2Provider findEnum(String value) { String name = getCanonicalName(value); for (CommonOAuth2Provider candidate : EnumSet.allOf(CommonOAuth2Provider.class)) { String candidateName = getCanonicalName(candidate.name()); if (name.equals(candidateName)) { return candidate; } } throw new IllegalArgumentException( "No enum constant " + CommonOAuth2Provider.class.getCanonicalName() + "." + value); } private static String getCanonicalName(String name) { StringBuilder canonicalName = new StringBuilder(name.length()); name.chars() .filter(Character::isLetterOrDigit) .map(Character::toLowerCase) .forEach((c) -> canonicalName.append((char) c)); return canonicalName.toString(); } private static String getErrorMessage(String configuredProviderId, String registrationId) { return (configuredProviderId != null) ? "Unknown provider ID '" + configuredProviderId + "'" : "Provider ID must be specified for client registration '" + registrationId + "'"; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\oauth2\client\ClientRegistrationsBeanDefinitionParser.java
2
请完成以下Java代码
private final boolean hasType(final QualityInspectionLineType type) { return type2index.containsKey(type); } /** * Remove from given lines those which their type is not specified in our list. * * NOTE: we assume the list is read-write. * * @param lines */ public void filter(final List<IQualityInspectionLine> lines) { for (final Iterator<IQualityInspectionLine> it = lines.iterator(); it.hasNext();) { final IQualityInspectionLine line = it.next(); final QualityInspectionLineType type = line.getQualityInspectionLineType(); if (!hasType(type)) { it.remove(); } } } /** * Sort given lines with this comparator. * * NOTE: we assume the list is read-write. * * @param lines */ public void sort(final List<IQualityInspectionLine> lines) {
Collections.sort(lines, this); } /** * Remove from given lines those which their type is not specified in our list. Then sort the result. * * NOTE: we assume the list is read-write. * * @param lines */ public void filterAndSort(final List<IQualityInspectionLine> lines) { filter(lines); sort(lines); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\QualityInspectionLineByTypeComparator.java
1
请完成以下Java代码
public class Fact_Acct_OpenLinkedFacts_GridView extends ViewBasedProcessTemplate implements IProcessPrecondition { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); }
@Override protected String doIt() throws Exception { final IViewRow singleSelectedRow = getSingleSelectedRow(); final DocumentId factAcctId = singleSelectedRow.getId(); final ProcessExecutionResult result = getResult(); new Fact_Acct_OpenLinkedFacts_ProcessHelper().openLinkedFactAccounts(factAcctId.toInt(), result); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\Fact_Acct_OpenLinkedFacts_GridView.java
1
请完成以下Java代码
public static class Expanded extends Jar { @Override public String getLauncherClassName() { return "org.springframework.boot.loader.launch.PropertiesLauncher"; } } /** * No layout. */ public static class None extends Jar { @Override public @Nullable String getLauncherClassName() { return null; } @Override public boolean isExecutable() { return false; } } /** * Executable WAR layout. */ public static class War implements Layout { private static final Map<LibraryScope, String> SCOPE_LOCATION; static { Map<LibraryScope, String> locations = new HashMap<>(); locations.put(LibraryScope.COMPILE, "WEB-INF/lib/"); locations.put(LibraryScope.CUSTOM, "WEB-INF/lib/"); locations.put(LibraryScope.RUNTIME, "WEB-INF/lib/"); locations.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/");
SCOPE_LOCATION = Collections.unmodifiableMap(locations); } @Override public String getLauncherClassName() { return "org.springframework.boot.loader.launch.WarLauncher"; } @Override public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) { return SCOPE_LOCATION.get(scope); } @Override public String getClassesLocation() { return "WEB-INF/classes/"; } @Override public String getClasspathIndexFileLocation() { return "WEB-INF/classpath.idx"; } @Override public String getLayersIndexFileLocation() { return "WEB-INF/layers.idx"; } @Override public boolean isExecutable() { return true; } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java
1
请完成以下Java代码
private ProductProposalPrice createPrice(@NonNull final ProductId productId, @NonNull final Amount priceListPrice) { final ProductProposalCampaignPrice campaignPrice = campaignPriceProvider.getCampaignPrice(productId).orElse(null); return ProductProposalPrice.builder() .priceListPrice(priceListPrice) .campaignPrice(campaignPrice) .build(); } private ProductsProposalRow createRow(final ProductsProposalRowAddRequest request) { return ProductsProposalRow.builder() .id(nextRowIdSequence.nextDocumentId()) .product(request.getProduct()) .asiDescription(request.getAsiDescription()) .asiId(request.getAsiId()) .price(createPrice(request.getProductId(), request.getPriceListPrice())) .packingMaterialId(request.getPackingMaterialId()) .packingDescription(request.getPackingDescription()) .lastShipmentDays(request.getLastShipmentDays()) .copiedFromProductPriceId(request.getCopiedFromProductPriceId()) .build() .withExistingOrderLine(bestMatchingProductPriceIdToOrderLine.get(request.getCopiedFromProductPriceId())); } private synchronized void addRow(final ProductsProposalRow row) { rowIdsOrderedAndFiltered.add(0, row.getId()); // add first rowIdsOrdered.add(0, row.getId()); // add first rowsById.put(row.getId(), row); } public synchronized void removeRowsByIds(@NonNull final Set<DocumentId> rowIds) { rowIdsOrderedAndFiltered.removeAll(rowIds); rowIdsOrdered.removeAll(rowIds); rowIds.forEach(rowsById::remove);
} public synchronized ProductsProposalViewFilter getFilter() { return filter; } public synchronized void filter(@NonNull final ProductsProposalViewFilter filter) { if (Objects.equals(this.filter, filter)) { return; } this.filter = filter; rowIdsOrderedAndFiltered = rowIdsOrdered .stream() .filter(rowId -> rowsById.get(rowId).isMatching(filter)) .collect(Collectors.toCollection(ArrayList::new)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowsData.java
1
请在Spring Boot框架中完成以下Java代码
public class CreateEDIDesadvPackRequest { @NonNull OrgId orgId; @NonNull EDIDesadvId ediDesadvId; /** * A value <=0 means that the repo shall pick the proper seqNo */ @NonNull Integer seqNo; @NonNull String sscc18; /** * true means the SSCC was just created on-the-fly. false means it's coming from a HU's SSCC-Attribute. */ @NonNull Boolean isManualIpaSSCC;
@Nullable HuId huId; @Nullable PackagingCodeId huPackagingCodeID; @Nullable String gtinPackingMaterial; @NonNull @Singular List<CreateEDIDesadvPackItemRequest> createEDIDesadvPackItemRequests; }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\CreateEDIDesadvPackRequest.java
2
请完成以下Java代码
public static final class Builder { private final String name; private String returnType; private int modifiers; private Object value; private boolean initialized; private Builder(String name) { this.name = name; } /** * Sets the modifiers. * @param modifiers the modifiers * @return this for method chaining */ public Builder modifiers(int modifiers) { this.modifiers = modifiers; return this; } /** * Sets the value. * @param value the value * @return this for method chaining */ public Builder value(Object value) { this.value = value; this.initialized = true; return this;
} /** * Sets the return type. * @param returnType the return type * @return this for method chaining */ public JavaFieldDeclaration returning(String returnType) { this.returnType = returnType; return new JavaFieldDeclaration(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaFieldDeclaration.java
1
请完成以下Java代码
public class Application { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); System.out.println(result1); int result2 = numbers.stream().reduce(0, Integer::sum); System.out.println(result2); List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); System.out.println(result3); String result4 = letters.stream().reduce("", String::concat);
System.out.println(result4); String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); System.out.println(result5); List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35)); int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); System.out.println(result6); String result7 = letters.parallelStream().reduce("", String::concat); System.out.println(result7); int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); System.out.println(result8); } }
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\reduce\application\Application.java
1
请完成以下Java代码
public void setAD_BusinessRule_Trigger_ID (final int AD_BusinessRule_Trigger_ID) { if (AD_BusinessRule_Trigger_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, AD_BusinessRule_Trigger_ID); } @Override public int getAD_BusinessRule_Trigger_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID); } @Override public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_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 setProcessingTag (final @Nullable java.lang.String ProcessingTag) { set_Value (COLUMNNAME_ProcessingTag, ProcessingTag); } @Override public java.lang.String getProcessingTag()
{ return get_ValueAsString(COLUMNNAME_ProcessingTag); } @Override public void setSource_Record_ID (final int Source_Record_ID) { if (Source_Record_ID < 1) set_ValueNoCheck (COLUMNNAME_Source_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Source_Record_ID, Source_Record_ID); } @Override public int getSource_Record_ID() { return get_ValueAsInt(COLUMNNAME_Source_Record_ID); } @Override public void setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_Source_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_Source_Table_ID, Source_Table_ID); } @Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setTriggering_User_ID (final int Triggering_User_ID) { if (Triggering_User_ID < 1) set_Value (COLUMNNAME_Triggering_User_ID, null); else set_Value (COLUMNNAME_Triggering_User_ID, Triggering_User_ID); } @Override public int getTriggering_User_ID() { return get_ValueAsInt(COLUMNNAME_Triggering_User_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Event.java
1
请在Spring Boot框架中完成以下Java代码
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public ShiroRealm shiroRealm(){ ShiroRealm shiroRealm = new ShiroRealm(); return shiroRealm; } /** * cookie对象 * @return */ public SimpleCookie rememberMeCookie() { // 设置cookie名称,对应login.html页面的<input type="checkbox" name="rememberMe"/> SimpleCookie cookie = new SimpleCookie("rememberMe"); // 设置cookie的过期时间,单位为秒,这里为一天 cookie.setMaxAge(86400);
return cookie; } /** * cookie管理对象 * @return */ public CookieRememberMeManager rememberMeManager() { CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); // rememberMe cookie加密的密钥 cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag==")); return cookieRememberMeManager; } }
repos\SpringAll-master\12.Spring-Boot-Shiro-RememberMe\src\main\java\com\springboot\config\ShiroConfig.java
2
请完成以下Java代码
public void receiveMessage(@NonNull @Payload final RequestToMetasfresh requestToMetasfresh) { rabbitLogger.log(RabbitMQAuditEntry.builder() .queueName(Constants.QUEUE_NAME_PW_TO_MF) .direction(RabbitMQDirection.IN) .content(requestToMetasfresh) .eventUUID(requestToMetasfresh.getEventId()) .host(NetUtils.getLocalHost()) .build()); invokeServerSyncBL(requestToMetasfresh); } private void invokeServerSyncBL(@NonNull final RequestToMetasfresh requestToMetasfresh) { final IServerSyncBL serverSyncBL = Services.get(IServerSyncBL.class); if (requestToMetasfresh instanceof PutWeeklySupplyRequest) { serverSyncBL.reportWeekSupply((PutWeeklySupplyRequest)requestToMetasfresh); } else if (requestToMetasfresh instanceof PutProductSuppliesRequest) { serverSyncBL.reportProductSupplies((PutProductSuppliesRequest)requestToMetasfresh); } else if (requestToMetasfresh instanceof PutRfQChangeRequest) { serverSyncBL.reportRfQChanges((PutRfQChangeRequest)requestToMetasfresh); } else if (requestToMetasfresh instanceof GetAllBPartnersRequest) { final List<SyncBPartner> allBPartners = serverSyncBL.getAllBPartners(); senderToProcurementWebUI.send(PutBPartnersRequest.builder() .bpartners(allBPartners) .relatedEventId(requestToMetasfresh.getEventId()) .build()); } else if (requestToMetasfresh instanceof GetAllProductsRequest) { final List<SyncProduct> allProducts = serverSyncBL.getAllProducts(); senderToProcurementWebUI.send(PutProductsRequest.builder() .products(allProducts) .relatedEventId(requestToMetasfresh.getEventId()) .build());
} else if (requestToMetasfresh instanceof GetInfoMessageRequest) { final String infoMessage = serverSyncBL.getInfoMessage(); senderToProcurementWebUI.send(PutInfoMessageRequest.builder() .message(infoMessage) .relatedEventId(requestToMetasfresh.getEventId()) .build()); } else if (requestToMetasfresh instanceof PutUserChangedRequest) { serverSyncBL.reportUserChanged((PutUserChangedRequest)requestToMetasfresh); } else { throw new AdempiereException("Unsupported type " + requestToMetasfresh.getClass().getName()) .appendParametersToMessage() .setParameter("requestToMetasfresh", requestToMetasfresh); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rabbitmq\ReceiverFromProcurementWeb.java
1
请完成以下Java代码
public void setC_DataImport_ID (int C_DataImport_ID) { if (C_DataImport_ID < 1) set_Value (COLUMNNAME_C_DataImport_ID, null); else set_Value (COLUMNNAME_C_DataImport_ID, Integer.valueOf(C_DataImport_ID)); } /** Get Data import. @return Data import */ @Override public int getC_DataImport_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Import-Fehlermeldung. @param I_ErrorMsg Meldungen, die durch den Importprozess generiert wurden */ @Override public void setI_ErrorMsg (java.lang.String I_ErrorMsg) { set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg); } /** Get Import-Fehlermeldung. @return Meldungen, die durch den Importprozess generiert wurden */ @Override public java.lang.String getI_ErrorMsg () { return (java.lang.String)get_Value(COLUMNNAME_I_ErrorMsg); } /** * I_IsImported AD_Reference_ID=540745 * Reference name: I_IsImported */ public static final int I_ISIMPORTED_AD_Reference_ID=540745; /** NotImported = N */ public static final String I_ISIMPORTED_NotImported = "N"; /** Imported = Y */ public static final String I_ISIMPORTED_Imported = "Y"; /** ImportFailed = E */ public static final String I_ISIMPORTED_ImportFailed = "E"; /** Set Importiert. @param I_IsImported Ist dieser Import verarbeitet worden? */ @Override public void setI_IsImported (java.lang.String I_IsImported) { set_Value (COLUMNNAME_I_IsImported, I_IsImported); } /** Get Importiert.
@return Ist dieser Import verarbeitet worden? */ @Override public java.lang.String getI_IsImported () { return (java.lang.String)get_Value(COLUMNNAME_I_IsImported); } /** Set Import Pharma BPartners. @param I_Pharma_BPartner_ID Import Pharma BPartners */ @Override public void setI_Pharma_BPartner_ID (int I_Pharma_BPartner_ID) { if (I_Pharma_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_I_Pharma_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_I_Pharma_BPartner_ID, Integer.valueOf(I_Pharma_BPartner_ID)); } /** Get Import Pharma BPartners. @return Import Pharma BPartners */ @Override public int getI_Pharma_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_Pharma_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_BPartner.java
1
请在Spring Boot框架中完成以下Java代码
public boolean insertJobEntity(JobEntity timerJobEntity) { return doInsert(timerJobEntity, true); } @Override public void insert(JobEntity jobEntity, boolean fireCreateEvent) { doInsert(jobEntity, fireCreateEvent); } protected boolean doInsert(JobEntity jobEntity, boolean fireCreateEvent) { if (serviceConfiguration.getInternalJobManager() != null) { boolean handledJob = serviceConfiguration.getInternalJobManager().handleJobInsert(jobEntity); if (!handledJob) { return false; } } jobEntity.setCreateTime(getClock().getCurrentTime()); if (jobEntity.getCorrelationId() == null) { jobEntity.setCorrelationId(serviceConfiguration.getIdGenerator().getNextId()); } super.insert(jobEntity, fireCreateEvent); return true; } @Override public JobEntity findJobByCorrelationId(String correlationId) { return dataManager.findJobByCorrelationId(correlationId); } @Override public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery) { return dataManager.findJobsByQueryCriteria(jobQuery); }
@Override public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) { return dataManager.findJobCountByQueryCriteria(jobQuery); } @Override public void delete(JobEntity jobEntity) { delete(jobEntity, false); deleteByteArrayRef(jobEntity.getExceptionByteArrayRef()); deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef()); // Send event FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity), serviceConfiguration.getEngineName()); } } @Override public void delete(JobEntity entity, boolean fireDeleteEvent) { if (serviceConfiguration.getInternalJobManager() != null) { serviceConfiguration.getInternalJobManager().handleJobDelete(entity); } super.delete(entity, fireDeleteEvent); } @Override public void deleteJobsByExecutionId(String executionId) { dataManager.deleteJobsByExecutionId(executionId); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\JobEntityManagerImpl.java
2
请完成以下Java代码
public int getC_AcctSchema_ID() { return C_AcctSchema_ID; } public int getC_Tax_ID() { return C_Tax_ID; } public boolean isSOTrx() { return isSOTrx; } public Date getDate() { return (Date)date.clone(); } public static final class Builder { private Integer C_AcctSchema_ID; private Integer C_Tax_ID; private Boolean isSOTrx; private Date date; private Builder() { super(); } public VATCodeMatchingRequest build() { return new VATCodeMatchingRequest(this); } public Builder setC_AcctSchema_ID(final int C_AcctSchema_ID) { this.C_AcctSchema_ID = C_AcctSchema_ID; return this; }
public Builder setC_Tax_ID(final int C_Tax_ID) { this.C_Tax_ID = C_Tax_ID; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { this.isSOTrx = isSOTrx; return this; } public Builder setDate(final Date date) { this.date = date; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\vatcode\VATCodeMatchingRequest.java
1
请完成以下Java代码
public HUReceiptScheduleReportExecutor withWindowNo(final int windowNo) { this.windowNo = windowNo; return this; } public void executeHUReport() { final I_C_OrderLine orderLine = receiptSchedule.getC_OrderLine(); // // service final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); // // Get Process from SysConfig final int reportProcessId = sysConfigBL.getIntValue(SYSCONFIG_ReceiptScheduleHUPOSJasper_Process, -1, // default receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID()); Check.errorIf(reportProcessId <= 0, "Report SysConfig value not set for for {}", SYSCONFIG_ReceiptScheduleHUPOSJasper_Process); // // get number of copies from SysConfig (default=1) final PrintCopies copies = PrintCopies.ofInt(sysConfigBL.getIntValue(SYSCONFIG_ReceiptScheduleHUPOSJasper_Copies, 1, // default receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID())); final Properties ctx = InterfaceWrapperHelper.getCtx(receiptSchedule); Check.assumeNotNull(orderLine, "orderLine not null");
final int orderLineId = orderLine.getC_OrderLine_ID(); final I_C_Order order = orderLine.getC_Order(); final Language bpartnerLaguage = Services.get(IBPartnerBL.class).getLanguage(ctx, order.getC_BPartner_ID()); // // Create ProcessInfo ProcessInfo.builder() .setCtx(ctx) .setAD_Process_ID(reportProcessId) .setProcessCalledFrom(ProcessCalledFrom.WebUI) // .setAD_PInstance_ID() // NO AD_PInstance => we want a new instance .setRecord(I_C_OrderLine.Table_Name, orderLineId) .setWindowNo(windowNo) .setReportLanguage(bpartnerLaguage) .addParameter(PARA_C_Orderline_ID, orderLineId) .addParameter(PARA_AD_Table_ID, InterfaceWrapperHelper.getTableId(I_C_OrderLine.class)) .addParameter(IMassPrintingService.PARAM_PrintCopies, copies.toInt()) // // Execute report in a new AD_PInstance .buildAndPrepareExecution() .onErrorThrowException() .executeSync(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\HUReceiptScheduleReportExecutor.java
1
请完成以下Java代码
public String getName() { return this.name; } @Override public String getContextualName(DataFetcherObservationContext context) { return "graphql field " + context.getEnvironment().getField().getName(); } @Override public KeyValues getLowCardinalityKeyValues(DataFetcherObservationContext context) { return KeyValues.of(outcome(context), fieldName(context), errorType(context)); } protected KeyValue outcome(DataFetcherObservationContext context) { if (context.getError() != null) { return OUTCOME_ERROR; } return OUTCOME_SUCCESS; } protected KeyValue fieldName(DataFetcherObservationContext context) { return KeyValue.of(DataFetcherLowCardinalityKeyNames.FIELD_NAME, context.getEnvironment().getField().getName()); }
protected KeyValue errorType(DataFetcherObservationContext context) { if (context.getError() != null) { return KeyValue.of(DataFetcherLowCardinalityKeyNames.ERROR_TYPE, context.getError().getClass().getSimpleName()); } return ERROR_TYPE_NONE; } @Override public KeyValues getHighCardinalityKeyValues(DataFetcherObservationContext context) { return KeyValues.of(fieldPath(context)); } protected KeyValue fieldPath(DataFetcherObservationContext context) { return KeyValue.of(GraphQlObservationDocumentation.DataFetcherHighCardinalityKeyNames.FIELD_PATH, context.getEnvironment().getExecutionStepInfo().getPath().toString()); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultDataFetcherObservationConvention.java
1
请在Spring Boot框架中完成以下Java代码
public List<Doctor> getNewAndUpdatedDoctors(String albertaApiKey, String updatedAfter) throws ApiException { ApiResponse<List<Doctor>> resp = getNewAndUpdatedDoctorsWithHttpInfo(albertaApiKey, updatedAfter); return resp.getData(); } /** * Daten der neuen und geänderten Ärzte abrufen * Szenario - das WaWi fragt bei Alberta nach, wie ob es neue oder geänderte Ärzte gibt * @param albertaApiKey (required) * @param updatedAfter 2021-02-21T09:30:00.000Z (im UTC-Format) (required) * @return ApiResponse&lt;List&lt;Doctor&gt;&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<List<Doctor>> getNewAndUpdatedDoctorsWithHttpInfo(String albertaApiKey, String updatedAfter) throws ApiException { com.squareup.okhttp.Call call = getNewAndUpdatedDoctorsValidateBeforeCall(albertaApiKey, updatedAfter, null, null); Type localVarReturnType = new TypeToken<List<Doctor>>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Daten der neuen und geänderten Ärzte abrufen (asynchronously) * Szenario - das WaWi fragt bei Alberta nach, wie ob es neue oder geänderte Ärzte gibt * @param albertaApiKey (required) * @param updatedAfter 2021-02-21T09:30:00.000Z (im UTC-Format) (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getNewAndUpdatedDoctorsAsync(String albertaApiKey, String updatedAfter, final ApiCallback<List<Doctor>> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override
public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getNewAndUpdatedDoctorsValidateBeforeCall(albertaApiKey, updatedAfter, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<List<Doctor>>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\DoctorApi.java
2
请完成以下Java代码
public Children getChildren() { return childrenChild.getChild(this); } public void setChildren(Children children) { childrenChild.setChild(this, children); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItem.class, CMMN_ELEMENT_CASE_FILE_ITEM) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<CaseFileItem>() { public CaseFileItem newInstance(ModelTypeInstanceContext instanceContext) { return new CaseFileItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); multiplicityAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_MULTIPLICITY, MultiplicityEnum.class) .defaultValue(MultiplicityEnum.Unspecified) .build();
definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .qNameAttributeReference(CaseFileItemDefinition.class) .build(); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .namespace(CMMN10_NS) .idAttributeReference(CaseFileItem.class) .build(); sourceRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); targetRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); SequenceBuilder sequence = typeBuilder.sequence(); childrenChild = sequence.element(Children.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemImpl.java
1
请完成以下Java代码
protected HistoricIncidentEventEntity loadIncidentEvent(Incident incident) { String incidentId = incident.getId(); HistoricIncidentEventEntity cachedEntity = findInCache(HistoricIncidentEventEntity.class, incidentId); if(cachedEntity != null) { return cachedEntity; } else { return newIncidentEventEntity(incident); } } protected HistoricBatchEntity loadBatchEntity(BatchEntity batch) { String batchId = batch.getId(); HistoricBatchEntity cachedEntity = findInCache(HistoricBatchEntity.class, batchId); if(cachedEntity != null) { return cachedEntity; } else { return newBatchEventEntity(batch); } }
/** find a cached entity by primary key */ protected <T extends HistoryEvent> T findInCache(Class<T> type, String id) { return Context.getCommandContext() .getDbEntityManager() .getCachedEntity(type, id); } @Override protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) { CommandContext commandContext = Context.getCommandContext(); ProcessDefinitionEntity entity = null; if(commandContext != null) { entity = commandContext .getDbEntityManager() .getCachedEntity(ProcessDefinitionEntity.class, processDefinitionId); } return (entity != null) ? entity : super.getProcessDefinitionEntity(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\CacheAwareHistoryEventProducer.java
1
请完成以下Java代码
private TableCellRenderer createTableCellRenderer(final TableColumnInfo columnMetaInfo) { if (columnMetaInfo.isSelectionColumn()) { return new SelectionColumnCellRenderer(); } final int displayTypeToUse = columnMetaInfo.getDisplayType(DisplayType.String); return new AnnotatedTableCellRenderer(displayTypeToUse); } private TableCellEditor createTableCellEditor(final TableColumnInfo columnMetaInfo) { if (columnMetaInfo.isSelectionColumn()) { return new SelectionColumnCellEditor(); } return new AnnotatedTableCellEditor(columnMetaInfo); } /** * Synchronize changes from {@link TableColumnInfo} to {@link TableColumnExt}. * * @author tsa * */ private static final class TableColumnInfo2TableColumnExtSynchronizer implements PropertyChangeListener { private final WeakReference<TableColumnExt> columnExtRef; private boolean running = false; public TableColumnInfo2TableColumnExtSynchronizer(final TableColumnExt columnExt) { super(); columnExtRef = new WeakReference<>(columnExt); } private TableColumnExt getTableColumnExt() { return columnExtRef.getValue(); } @Override public void propertyChange(final PropertyChangeEvent evt) { // Avoid recursion if (running) { return; }
running = true; try { final TableColumnInfo columnMetaInfo = (TableColumnInfo)evt.getSource(); final TableColumnExt columnExt = getTableColumnExt(); if (columnExt == null) { // ColumnExt reference expired: // * remove this listener because there is no point to have this listener invoked in future // * exit quickly because there is nothing to do columnMetaInfo.removePropertyChangeListener(this); return; } updateColumnExtFromMetaInfo(columnExt, columnMetaInfo); } finally { running = false; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableColumnFactory.java
1
请完成以下Java代码
public void setCategoryName(String categoryName) { this.categoryName = categoryName == null ? null : categoryName.trim(); } public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", categoryId=").append(categoryId); sb.append(", categoryName=").append(categoryName); sb.append(", isDeleted=").append(isDeleted); sb.append(", createTime=").append(createTime); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsCategory.java
1
请完成以下Java代码
public int getC_BP_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_Group_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null);
else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_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_CM_AccessListBPGroup.java
1
请完成以下Java代码
private ITrxListenerManager getTrxListenerManager(final boolean create) { if (trxListenerManager != null) { return trxListenerManager; } if (create) { trxListenerManager = new TrxListenerManager(getTrxName()); return trxListenerManager; } return NullTrxListenerManager.instance; } @Override public ITrxListenerManager getTrxListenerManager() { return getTrxListenerManager(true); // create=true } @Override public final ITrxManager getTrxManager() { return trxManager; } private Map<String, Object> getPropertiesMap() { if (_properties == null) { synchronized (this) { if (_properties == null) { _properties = new ConcurrentHashMap<>(); } } } return _properties; } private Map<String, Object> getPropertiesMapOrNull() { synchronized (this) { return _properties; } } @Nullable @Override public final <T> T setProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); // Handle null value case if (value == null) { final Map<String, Object> properties = getPropertiesMapOrNull(); if (properties == null) { return null; } @SuppressWarnings("unchecked") final T valueOld = (T)properties.remove(name); return valueOld; } else { @SuppressWarnings("unchecked") final T valueOld = (T)getPropertiesMap().put(name, value); return valueOld; } } @Override public final <T> T getProperty(final String name) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().get(name);
return value; } @Override public <T> T getProperty(final String name, final Supplier<T> valueInitializer) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.get()); return value; } @Override public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.apply(this)); return value; } @Override public <T> T setAndGetProperty(@NonNull final String name, @NonNull final Function<T, T> valueRemappingFunction) { final BiFunction<? super String, ? super Object, ?> remappingFunction = (propertyName, oldValue) -> { @SuppressWarnings("unchecked") final T oldValueCasted = (T)oldValue; return valueRemappingFunction.apply(oldValueCasted); }; @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().compute(name, remappingFunction); return value; } protected final void setDebugConnectionBackendId(final String debugConnectionBackendId) { this.debugConnectionBackendId = debugConnectionBackendId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrx.java
1
请完成以下Java代码
public String getEncodedResponseToken() { if (!hasResponseToken()) { throw new IllegalStateException("Unauthenticated or no response token"); } return Base64.getEncoder().encodeToString(this.ticketValidation.responseToken()); } /** * Unwraps an encrypted message using the gss context * @param data the data * @param offset data offset * @param length data length * @return the decrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] decrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException { return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() { public byte[] run() throws Exception { final GSSContext context = getTicketValidation().getGssContext(); return context.unwrap(data, offset, length, new MessageProp(true)); } }); } /** * Unwraps an encrypted message using the gss context * @param data the data * @return the decrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] decrypt(final byte[] data) throws PrivilegedActionException { return decrypt(data, 0, data.length); } /**
* Wraps an message using the gss context * @param data the data * @param offset data offset * @param length data length * @return the encrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] encrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException { return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() { public byte[] run() throws Exception { final GSSContext context = getTicketValidation().getGssContext(); return context.wrap(data, offset, length, new MessageProp(true)); } }); } /** * Wraps an message using the gss context * @param data the data * @return the encrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] encrypt(final byte[] data) throws PrivilegedActionException { return encrypt(data, 0, data.length); } @Override public JaasSubjectHolder getJaasSubjectHolder() { return this.jaasSubjectHolder; } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceRequestToken.java
1
请在Spring Boot框架中完成以下Java代码
private void onNotificationsSubUpdate(String targetServiceId, EntityId entityId, NotificationsSubscriptionUpdate subscriptionUpdate) { if (serviceId.equals(targetServiceId)) { log.trace("[{}] Forwarding to local service: {}", entityId, subscriptionUpdate); localSubscriptionService.onNotificationUpdate(entityId, subscriptionUpdate, TbCallback.EMPTY); } else { sendCoreNotification(targetServiceId, entityId, TbSubscriptionUtils.notificationsSubUpdateToProto(entityId, subscriptionUpdate)); } } private static <T extends KvEntry> List<T> getSubList(List<T> ts, Set<String> keys) { List<T> update = null; for (T entry : ts) { if (keys.contains(entry.getKey())) { if (update == null) { update = new ArrayList<>(ts.size()); } update.add(entry); }
} return update; } private TbEntityUpdatesInfo getEntityUpdatesInfo(EntityId entityId) { return entityUpdates.computeIfAbsent(entityId, id -> new TbEntityUpdatesInfo(initTs)); } private void cleanupEntityUpdates() { initTs = System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1); int sizeBeforeCleanup = entityUpdates.size(); entityUpdates.entrySet().removeIf(kv -> { var v = kv.getValue(); return initTs > v.attributesUpdateTs && initTs > v.timeSeriesUpdateTs; }); log.info("Removed {} old entity update records.", entityUpdates.size() - sizeBeforeCleanup); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\DefaultSubscriptionManagerService.java
2
请在Spring Boot框架中完成以下Java代码
public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientNoteMapping patientNoteMapping = (PatientNoteMapping) o; return Objects.equals(this._id, patientNoteMapping._id) && Objects.equals(this.updatedAt, patientNoteMapping.updatedAt); } @Override public int hashCode() { return Objects.hash(_id, updatedAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientNoteMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).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-patient-api\src\main\java\io\swagger\client\model\PatientNoteMapping.java
2
请完成以下Java代码
public User save(@NonNull final User user) { final I_AD_User userRecord; if (user.getId() == null) { userRecord = newInstance(I_AD_User.class); } else { userRecord = load(user.getId().getRepoId(), I_AD_User.class); } userRecord.setC_BPartner_ID(BPartnerId.toRepoId(user.getBpartnerId())); userRecord.setName(user.getName()); userRecord.setFirstname(user.getFirstName()); userRecord.setLastname(user.getLastName()); userRecord.setBirthday(TimeUtil.asTimestamp(user.getBirthday())); userRecord.setEMail(user.getEmailAddress()); userRecord.setAD_Language(Language.asLanguageStringOrNull(user.getUserLanguage()));
saveRecord(userRecord); return user .toBuilder() .id(UserId.ofRepoId(userRecord.getAD_User_ID())) .build(); } @NonNull public Optional<UserId> getDefaultDunningContact(@NonNull final BPartnerId bPartnerId) { return queryBL.createQueryBuilder(I_AD_User.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, bPartnerId) .addEqualsFilter(I_AD_User.COLUMNNAME_IsDunningContact, true) .create() .firstIdOnlyOptional(UserId::ofRepoIdOrNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserRepository.java
1
请完成以下Java代码
public class RSocketGraphQlResponse extends DefaultExecutionGraphQlResponse { /** * Create an instance that wraps the given {@link ExecutionGraphQlResponse}. * @param response the response to wrap */ public RSocketGraphQlResponse(ExecutionGraphQlResponse response) { super(response); } private RSocketGraphQlResponse(RSocketGraphQlResponse original, ExecutionResult executionResult) { super(original.getExecutionInput(), executionResult); } /** * Transform the underlying {@link ExecutionResult} through a {@link Builder} * and return a new instance with the modified values. * @param consumer callback to transform the result * @return the new response instance with the mutated {@code ExecutionResult} */ public RSocketGraphQlResponse transform(Consumer<Builder> consumer) { Builder builder = new Builder(this); consumer.accept(builder); return builder.build(); } /** * Builder to transform a {@link RSocketGraphQlResponse}.
*/ public static final class Builder extends DefaultExecutionGraphQlResponse.Builder<Builder, RSocketGraphQlResponse> { private Builder(RSocketGraphQlResponse original) { super(original); } @Override protected RSocketGraphQlResponse build(RSocketGraphQlResponse original, ExecutionResult newResult) { return new RSocketGraphQlResponse(original, newResult); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\RSocketGraphQlResponse.java
1
请完成以下Java代码
public class SetEventDefinitionCategoryCmd implements Command<Void> { protected String eventDefinitionId; protected String category; public SetEventDefinitionCategoryCmd(String eventDefinitionId, String category) { this.eventDefinitionId = eventDefinitionId; this.category = category; } @Override public Void execute(CommandContext commandContext) { if (eventDefinitionId == null) { throw new FlowableIllegalArgumentException("Event definition id is null"); } EventDefinitionEntity eventDefinition = CommandContextUtil.getEventDefinitionEntityManager(commandContext).findById(eventDefinitionId); if (eventDefinition == null) { throw new FlowableObjectNotFoundException("No event definition found for id = '" + eventDefinitionId + "'"); } // Update category eventDefinition.setCategory(category); // Remove form from cache, it will be refetch later DeploymentCache<EventDefinitionCacheEntry> eventDefinitionCache = CommandContextUtil.getEventRegistryConfiguration().getEventDefinitionCache(); if (eventDefinitionCache != null) { eventDefinitionCache.remove(eventDefinitionId); } CommandContextUtil.getEventDefinitionEntityManager(commandContext).update(eventDefinition); return null; }
public String getEventDefinitionId() { return eventDefinitionId; } public void setEventDefinitionId(String eventDefinitionId) { this.eventDefinitionId = eventDefinitionId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\cmd\SetEventDefinitionCategoryCmd.java
1
请完成以下Java代码
public Map<Object, Integer> getHotItems() { return hotItems; } public void setHotItems(Map<Object, Integer> hotItems) { this.hotItems = hotItems; } public boolean isClusterMode() { return clusterMode; } public void setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; } public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() {
return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringbootRabbitmqApplication { final static String queueName = "spring-boot"; @Bean Queue queue() { return new Queue(queueName, false); } @Bean TopicExchange exchange() { return new TopicExchange("spring-boot-exchange"); } @Bean Binding binding(Queue queue, TopicExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(queueName); } @Bean SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory); container.setQueueNames(queueName); container.setMessageListener(listenerAdapter); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } public static void main(String[] args) { SpringApplication.run(SpringbootRabbitmqApplication.class, args); } }
repos\SpringBootLearning-master\springboot-rabbitmq\src\main\java\com\forezp\SpringbootRabbitmqApplication.java
2
请完成以下Java代码
public void onNodeInserted(PO po) { for (ITreeListener listener : listeners) { listener.onNodeInserted(po); } } @Override public void onNodeDeleted(PO po) { for (ITreeListener listener : listeners) { listener.onNodeDeleted(po); }
} @Override public void onParentChanged(int AD_Table_ID, int nodeId, int newParentId, int oldParentId, String trxName) { if (newParentId == oldParentId) return; for (ITreeListener listener : listeners) { listener.onParentChanged(AD_Table_ID, nodeId, newParentId, oldParentId, trxName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\TreeListenerSupport.java
1
请完成以下Java代码
public WindowId getWindowId() { return PickingConstants.WINDOWID_PackageableView; } @Override public Set<DocumentId> findAffectedRowIds( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend, @NonNull IView view) { final Set<ShipmentScheduleId> shipmentScheduleIds = extractShipmentScheduleIds(recordRefs); if (shipmentScheduleIds.isEmpty()) { return ImmutableSet.of(); } final SqlViewKeyColumnNamesMap keyColumnNamesMap = SqlViewKeyColumnNamesMap.ofIntKeyField(I_M_Packageable_V.COLUMNNAME_M_ShipmentSchedule_ID); return SqlViewRowIdsOrderedSelectionFactory.retrieveRowIdsForLineIds( keyColumnNamesMap, view.getViewId(), ShipmentScheduleId.toIntSet(shipmentScheduleIds)); } private Set<ShipmentScheduleId> extractShipmentScheduleIds(final TableRecordReferenceSet recordRefs) { if (recordRefs.isEmpty()) { return ImmutableSet.of(); } final Set<ShipmentScheduleId> shipmentScheduleIds = new HashSet<>(); final Set<PickingCandidateId> pickingCandidateIds = new HashSet<>(); for (TableRecordReference recordRef : recordRefs)
{ final String tableName = recordRef.getTableName(); if (I_M_ShipmentSchedule.Table_Name.equals(tableName)) { shipmentScheduleIds.add(ShipmentScheduleId.ofRepoId(recordRef.getRecord_ID())); } else if (I_M_Picking_Candidate.Table_Name.equals(tableName)) { pickingCandidateIds.add(PickingCandidateId.ofRepoId(recordRef.getRecord_ID())); } } if (!pickingCandidateIds.isEmpty()) { shipmentScheduleIds.addAll(pickingCandidateRepository.getShipmentScheduleIdsByPickingCandidateIds(pickingCandidateIds)); } return shipmentScheduleIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\PickingTerminalViewInvalidationAdvisor.java
1
请完成以下Java代码
public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public String getIncidentId() {
return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public static List<Term> segment(String text) { List<Term> termList = new LinkedList<Term>(); for (String sentence : SentencesUtil.toSentenceList(text)) { termList.addAll(segSentence(sentence)); } return termList; } /** * 分词 * * @param text 文本 * @return 分词结果 */ public static List<Term> segment(char[] text) { return segment(CharTable.convert(text)); } /** * 切分为句子形式 * * @param text 文本 * @return 句子列表 */ public static List<List<Term>> seg2sentence(String text) { List<List<Term>> resultList = new LinkedList<List<Term>>(); { for (String sentence : SentencesUtil.toSentenceList(text)) { resultList.add(segment(sentence)); }
} return resultList; } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) { return SEGMENT.seg2sentence(text, shortest); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\TraditionalChineseTokenizer.java
1
请完成以下Java代码
public class DeleteTaskCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected Collection<String> taskIds; protected boolean cascade; protected String deleteReason; protected boolean cancel; public DeleteTaskCmd(String taskId, String deleteReason, boolean cascade) { this(taskId, deleteReason, cascade, false); } public DeleteTaskCmd(String taskId, String deleteReason, boolean cascade, boolean cancel) { this.taskId = taskId; this.cascade = cascade; this.deleteReason = deleteReason; this.cancel = cancel; } public DeleteTaskCmd(Collection<String> taskIds, String deleteReason, boolean cascade) { this(taskIds, deleteReason, cascade, false); } public DeleteTaskCmd(Collection<String> taskIds, String deleteReason, boolean cascade, boolean cancel) { this.taskIds = taskIds; this.cascade = cascade; this.deleteReason = deleteReason; this.cancel = cancel; } public Void execute(CommandContext commandContext) { if (taskId != null) { deleteTask(commandContext, taskId);
} else if (taskIds != null) { for (String taskId : taskIds) { deleteTask(commandContext, taskId); } } else { throw new ActivitiIllegalArgumentException("taskId and taskIds are null"); } return null; } protected void deleteTask(CommandContext commandContext, String taskId) { commandContext.getTaskEntityManager().deleteTask(taskId, deleteReason, cascade, cancel); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteTaskCmd.java
1
请完成以下Java代码
public class FileValueSerializer extends AbstractTypedValueSerializer<FileValue> { /** * The numbers values we encoded in textfield two. */ protected static final int NR_OF_VALUES_IN_TEXTFIELD2 = 2; /** * The separator to be able to store encoding and mimetype inside the same * text field. Please be aware that the separator only works when it is a * character that is not allowed in the first component. */ protected static final String MIMETYPE_ENCODING_SEPARATOR = "#"; public FileValueSerializer() { super(ValueType.FILE); } @Override public void writeValue(FileValue value, ValueFields valueFields) { byte[] data = ((FileValueImpl) value).getByteArray(); valueFields.setByteArrayValue(data); valueFields.setTextValue(value.getFilename()); if (value.getMimeType() == null && value.getEncoding() != null) { valueFields.setTextValue2(MIMETYPE_ENCODING_SEPARATOR + value.getEncoding()); } else if (value.getMimeType() != null && value.getEncoding() == null) { valueFields.setTextValue2(value.getMimeType() + MIMETYPE_ENCODING_SEPARATOR); } else if (value.getMimeType() != null && value.getEncoding() != null) { valueFields.setTextValue2(value.getMimeType() + MIMETYPE_ENCODING_SEPARATOR + value.getEncoding()); } } @Override public FileValue convertToTypedValue(UntypedValueImpl untypedValue) { throw new UnsupportedOperationException("Currently no automatic conversation from UntypedValue to FileValue"); } @Override public FileValue readValue(ValueFields valueFields, boolean deserializeValue, boolean asTransientValue) { String fileName = valueFields.getTextValue(); if (fileName == null) { // ensure file name is not null fileName = ""; } FileValueBuilder builder = Variables.fileValue(fileName); if (valueFields.getByteArrayValue() != null) { builder.file(valueFields.getByteArrayValue()); }
// to ensure the same array size all the time if (valueFields.getTextValue2() != null) { String[] split = Arrays.copyOf(valueFields.getTextValue2().split(MIMETYPE_ENCODING_SEPARATOR, NR_OF_VALUES_IN_TEXTFIELD2), NR_OF_VALUES_IN_TEXTFIELD2); String mimeType = returnNullIfEmptyString(split[0]); String encoding = returnNullIfEmptyString(split[1]); builder.mimeType(mimeType); builder.encoding(encoding); } builder.setTransient(asTransientValue); return builder.create(); } protected String returnNullIfEmptyString(String s) { if (s.isEmpty()) { return null; } return s; } @Override public String getName() { return valueType.getName(); } @Override protected boolean canWriteValue(TypedValue value) { if (value == null || value.getType() == null) { // untyped value return false; } return value.getType().getName().equals(getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\FileValueSerializer.java
1
请完成以下Java代码
public void setA_Registration_ID (int A_Registration_ID) { if (A_Registration_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Registration_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Registration_ID, Integer.valueOf(A_Registration_ID)); } /** Get Registration. @return User Asset Registration */ public int getA_Registration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Registration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); }
/** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationValue.java
1
请在Spring Boot框架中完成以下Java代码
public static class Insert { /** * Insert the version into a header with the given name. */ private @Nullable String header; /** * Insert the version into a query parameter with the given name. */ private @Nullable String queryParameter; /** * Insert the version into a path segment at the given index. */ private @Nullable Integer pathSegment; /** * Insert the version into a media type parameter with the given name. */ private @Nullable String mediaTypeParameter; public @Nullable String getHeader() { return this.header; } public void setHeader(@Nullable String header) { this.header = header; }
public @Nullable String getQueryParameter() { return this.queryParameter; } public void setQueryParameter(@Nullable String queryParameter) { this.queryParameter = queryParameter; } public @Nullable Integer getPathSegment() { return this.pathSegment; } public void setPathSegment(@Nullable Integer pathSegment) { this.pathSegment = pathSegment; } public @Nullable String getMediaTypeParameter() { return this.mediaTypeParameter; } public void setMediaTypeParameter(@Nullable String mediaTypeParameter) { this.mediaTypeParameter = mediaTypeParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\ApiversionProperties.java
2
请完成以下Java代码
private void checkIfSerializable(Object object) { if (Objects.isNull(object)) { throw new JsonSerializationException("Can't serialize a null object"); } Class<?> clazz = object.getClass(); if (!clazz.isAnnotationPresent(JsonSerializable.class)) { throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable"); } } private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> clazz = object.getClass(); for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(Init.class)) { method.setAccessible(true); method.invoke(object); } } } private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass(); Map<String, String> jsonElementsMap = new HashMap<>(); for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); if (field.isAnnotationPresent(JsonElement.class)) { jsonElementsMap.put(getKey(field), (String) field.get(object)); } } String jsonString = jsonElementsMap.entrySet() .stream() .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"") .collect(Collectors.joining(",")); return "{" + jsonString + "}"; } private String getKey(Field field) { String value = field.getAnnotation(JsonElement.class) .key(); return value.isEmpty() ? field.getName() : value; } }
repos\tutorials-master\core-java-modules\core-java-annotations\src\main\java\com\baeldung\customannotations\ObjectToJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public void setType(String type) { this.type = type; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Override public void setUserId(String userId) { this.userId = userId; } @Override public void setData(String data) { this.data = data; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getIdPrefix() { // id prefix is empty because sequence is used instead of id prefix return ""; } @Override public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public long getLogNumber() { return logNumber; } @Override public String getType() { return type; } @Override public String getTaskId() { return taskId;
} @Override public Date getTimeStamp() { return timeStamp; } @Override public String getUserId() { return userId; } @Override public String getData() { return data; } @Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")"; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java
2
请完成以下Java代码
public class JsonObjectMapperHolder { private static final Logger logger = LoggerFactory.getLogger(JsonObjectMapperHolder.class); public static ObjectMapper sharedJsonObjectMapper() { return sharedJsonObjectMapper.get(); } @VisibleForTesting public static void resetSharedJsonObjectMapper() { sharedJsonObjectMapper.forget(); } private static final ExtendedMemorizingSupplier<ObjectMapper> sharedJsonObjectMapper = ExtendedMemorizingSupplier.of(JsonObjectMapperHolder::newJsonObjectMapper); public static ObjectMapper newJsonObjectMapper() { // important to register the jackson-datatype-jsr310 module which we have in our pom and // which is needed to serialize/deserialize java.time.Instant Check.assumeNotNull(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule.class, ""); // just to get a compile error if not present final ObjectMapper objectMapper = new ObjectMapper() .findAndRegisterModules() .registerModule(new GuavaModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .enable(MapperFeature.USE_ANNOTATIONS); logger.info("Created a new JSON ObjectMapper: {} \nRegistered modules: {}", objectMapper, objectMapper.getRegisteredModuleIds()); return objectMapper; } @Nullable public static String toJson(@Nullable final Object object) { if (object == null) { return null; } try { return sharedJsonObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw Check.mkEx("Failed converting object to JSON: " + object, e); } } @Nullable public static <T> T fromJson(@Nullable final String json, @NonNull final Class<T> valueType) { if (json == null) { return null;
} return fromJsonNonNull(json, valueType); } @NonNull public static <T> T fromJsonNonNull(@NonNull final String json, @NonNull final Class<T> valueType) { try { return sharedJsonObjectMapper().readValue(json, valueType); } catch (final JsonProcessingException e) { throw Check.mkEx("Failed converting JSON to " + valueType.getSimpleName() + ": `" + json + "`", e); } } @NonNull public static String toJsonNonNull(@NonNull final Object object) { try { return sharedJsonObjectMapper().writeValueAsString(object); } catch (final JsonProcessingException e) { throw Check.mkEx("Failed converting object to JSON: " + object, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\JsonObjectMapperHolder.java
1
请完成以下Java代码
public void unlockContact() { setLocked(false); set_Value(COLUMNNAME_LockedBy, null); setLockedDate(null); } public boolean isExpired() { if (!isLocked()) return true; Timestamp dateExpire = TimeUtil.addMinutes(getLockedDate(), LOCK_EXPIRE_MIN); Timestamp now = new Timestamp(System.currentTimeMillis()); return dateExpire.before(now); } public void expireLock() { if (isLocked() && isExpired()) unlockContact();
} @Override public String toString() { String bundleName = DB.getSQLValueString(get_TrxName(), "SELECT "+I_R_Group.COLUMNNAME_Name+" FROM "+I_R_Group.Table_Name +" WHERE "+I_R_Group.COLUMNNAME_R_Group_ID+"=?", getR_Group_ID()); String bpName = DB.getSQLValueString(get_TrxName(), "SELECT "+I_C_BPartner.COLUMNNAME_Value+"||'_'||"+I_C_BPartner.COLUMNNAME_Name +" FROM "+I_C_BPartner.Table_Name +" WHERE "+I_C_BPartner.COLUMNNAME_C_BPartner_ID+"=?", getC_BPartner_ID()); return bundleName+"/"+bpName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\model\MRGroupProspect.java
1
请完成以下Java代码
public class OrderLineCountryAware implements ICountryAware { public static final ICountryAwareFactory factory = model -> { final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class); final ICountryAware countryAware = new OrderLineCountryAware(orderLine); return countryAware; }; private final I_C_OrderLine orderLine; private OrderLineCountryAware(final I_C_OrderLine orderLine) { super(); Check.assumeNotNull(orderLine, "Order line not null"); this.orderLine = orderLine; } @Override public int getAD_Client_ID() { return orderLine.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return orderLine.getAD_Org_ID(); } @Override public boolean isSOTrx() { final I_C_Order order = getOrder(); return order.isSOTrx(); } @Override public I_C_Country getC_Country()
{ final I_C_Order order = getOrder(); final BPartnerLocationAndCaptureId bpLocationId = OrderDocumentLocationAdapterFactory .locationAdapter(order) .getBPartnerLocationAndCaptureIdIfExists() .orElse(null); if (bpLocationId == null) { return null; } final CountryId countryId = Services.get(IBPartnerBL.class).getCountryId(bpLocationId); return Services.get(ICountryDAO.class).getById(countryId); } private I_C_Order getOrder() { final I_C_Order order = orderLine.getC_Order(); if (order == null) { throw new AdempiereException("Order not set for" + orderLine); } return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\OrderLineCountryAware.java
1
请完成以下Java代码
public String getUrl() { return url; } /** * Sets the value of the url property. * * @param value * allowed object is * {@link String } * */ public void setUrl(String value) { this.url = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link String } * */ public String getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link String } * */ public void setTitle(String value) { this.title = value; } /** * Gets the value of the filename property. * * @return * possible object is * {@link String } * */ public String getFilename() { return filename; } /**
* Sets the value of the filename property. * * @param value * allowed object is * {@link String } * */ public void setFilename(String value) { this.filename = value; } /** * Gets the value of the mimeType property. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\DocumentType.java
1
请完成以下Java代码
public class ConvListVal { private Integer age; private Double average; private Date myDate; private String name; private String surname; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getAverage() { return average; } public void setAverage(Double average) { this.average = average; } public Date getMyDate() { return myDate; } public void setMyDate(Date myDate) {
this.myDate = myDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\convListVal\ConvListVal.java
1
请完成以下Java代码
public void removeDataSource(Object key) { dataSources.remove(key); } public Connection getConnection() throws SQLException { return getCurrentDataSource().getConnection(); } public Connection getConnection(String username, String password) throws SQLException { return getCurrentDataSource().getConnection(username, password); } protected DataSource getCurrentDataSource() { String tenantId = tenantInfoHolder.getCurrentTenantId(); DataSource dataSource = dataSources.get(tenantId); if (dataSource == null) { throw new ActivitiException("Could not find a dataSource for tenant " + tenantId); } return dataSource; } public int getLoginTimeout() throws SQLException { return 0; // Default } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; } throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName());
} public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } public Map<Object, DataSource> getDataSources() { return dataSources; } public void setDataSources(Map<Object, DataSource> dataSources) { this.dataSources = dataSources; } // Unsupported ////////////////////////////////////////////////////////// public PrintWriter getLogWriter() throws SQLException { throw new UnsupportedOperationException(); } public void setLogWriter(PrintWriter out) throws SQLException { throw new UnsupportedOperationException(); } public void setLoginTimeout(int seconds) throws SQLException { throw new UnsupportedOperationException(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\multitenant\TenantAwareDataSource.java
1
请完成以下Java代码
public int getAD_Table_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) { return 0; } return ii.intValue(); } @Override public de.metas.dlm.model.I_DLM_Partition getDLM_Partition() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DLM_Partition_ID, de.metas.dlm.model.I_DLM_Partition.class); } @Override public void setDLM_Partition(final de.metas.dlm.model.I_DLM_Partition DLM_Partition) { set_ValueFromPO(COLUMNNAME_DLM_Partition_ID, de.metas.dlm.model.I_DLM_Partition.class, DLM_Partition); } /** * Set Partition. * * @param DLM_Partition_ID Partition */ @Override public void setDLM_Partition_ID(final int DLM_Partition_ID) { if (DLM_Partition_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, Integer.valueOf(DLM_Partition_ID)); } } /** * Get Partition. * * @return Partition */ @Override public int getDLM_Partition_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Partitionierungswarteschlange. * * @param DLM_Partition_Workqueue_ID Partitionierungswarteschlange */ @Override public void setDLM_Partition_Workqueue_ID(final int DLM_Partition_Workqueue_ID) { if (DLM_Partition_Workqueue_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Workqueue_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Workqueue_ID, Integer.valueOf(DLM_Partition_Workqueue_ID)); } } /** * Get Partitionierungswarteschlange. * * @return Partitionierungswarteschlange */ @Override public int getDLM_Partition_Workqueue_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Workqueue_ID); if (ii == null) { return 0; } return ii.intValue();
} /** * Set Datensatz-ID. * * @param Record_ID * Direct internal record ID */ @Override public void setRecord_ID(final int Record_ID) { if (Record_ID < 0) { set_Value(COLUMNNAME_Record_ID, null); } else { set_Value(COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } } /** * Get Datensatz-ID. * * @return Direct internal record ID */ @Override public int getRecord_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override public void setTableName(final java.lang.String TableName) { throw new IllegalArgumentException("TableName is virtual column"); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Workqueue.java
1
请完成以下Java代码
public String[] getExecutionIds() { return executionIds; } public String[] getProcessInstanceIds() { return processInstanceIds; } public String[] getCaseExecutionIds() { return caseExecutionIds; } public String[] getCaseInstanceIds() { return caseInstanceIds; }
public String[] getTaskIds() { return taskIds; } public String[] getBatchIds() { return batchIds; } public String[] getVariableScopeIds() { return variableScopeIds; } public String[] getActivityInstanceIds() { return activityInstanceIds; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableInstanceQueryImpl.java
1
请完成以下Java代码
public class SepaUtils { /** * coming from the SEPA specifications https://www.sepaforcorporates.com/sepa-implementation/valid-xml-characters-sepa-payments/ */ private static final Pattern SEPA_COMPLIANT_PATTERN = Pattern.compile( "([a-zA-Z0-9.,;:'\\+\\-/()\\*\\[\\]{}\\\\`´~ ]|[!\"#%&<>÷=@_$£]|[àáâäçèéêëìíîïñòóôöùúûüýßÀÁÂÄÇÈÉÊËÌÍÎÏÒÓÔÖÙÚÛÜÑ])*"); private static Map<String, String> SEPA_REPLACEMENT_MAP = new HashMap<>(); static { SEPA_REPLACEMENT_MAP.put("’", "'"); SEPA_REPLACEMENT_MAP.put("“", "\""); SEPA_REPLACEMENT_MAP.put("INVALID_CHAR", "_"); // Define replacement for any non-compliant character } /** * Cleans a given input string, replacing non-compliant SEPA characters with their respective * mapped values, or an underscore for unsupported characters. * * @param input the string to sanitize * @return the sanitized SEPA-compliant string */ @Nullable public static String replaceForbiddenChars(@Nullable final String input) { if (input == null) { return null; } // Apply specific replacements from SEPA_REPLACEMENT_MAP String sanitizedText = input; for (Map.Entry<String, String> entry : SEPA_REPLACEMENT_MAP.entrySet()) { if (!entry.getKey().equals("INVALID_CHAR"))
{ // Exclude INVALID_CHAR replacement here sanitizedText = sanitizedText.replace(entry.getKey(), entry.getValue()); } } // Use SEPA_COMPLIANT_PATTERN to retain only compliant characters StringBuilder compliantText = new StringBuilder(); for (int i = 0; i < sanitizedText.length(); i++) { String currentChar = String.valueOf(sanitizedText.charAt(i)); if (SEPA_COMPLIANT_PATTERN.matcher(currentChar).matches()) { compliantText.append(currentChar); } else { // Use the map's value for invalid characters (underscore) compliantText.append(SEPA_REPLACEMENT_MAP.get("INVALID_CHAR")); } } return compliantText.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\SepaUtils.java
1
请完成以下Java代码
public void setAD_Process_ID (final int AD_Process_ID) { if (AD_Process_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Process_ID, AD_Process_ID); } @Override public int getAD_Process_ID() { return get_ValueAsInt(COLUMNNAME_AD_Process_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHelp (final java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated);
} @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Trl.java
1
请完成以下Java代码
public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } public Map<String, String> getClothes() { return clothes; } public void setClothes(Map<String, String> clothes) { this.clothes = clothes; } public List<Person> getFriends() { return friends; } public void setFriends(List<Person> friends) { this.friends = friends;
} @Override public String toString() { StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age=" + age + ", birthday=" + birthday + ", hobbies=" + hobbies + ", clothes=" + clothes + "]\n"); if (friends != null) { str.append("Friends:\n"); for (Person f : friends) { str.append("\t").append(f); } } return str.toString(); } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\model\Person.java
1
请完成以下Java代码
public boolean isInternalUseInventory(final I_M_InventoryLine inventoryLine) { /* * TODO: need to add M_Inventory.IsInternalUseInventory flag * see FR [ 1879029 ] Added IsInternalUseInventory flag to M_Inventory table * MInventory parent = getParent(); * return parent != null && parent.isInternalUseInventory(); */ return inventoryLine.getQtyInternalUse().signum() != 0; } @Override public boolean isSOTrx(final I_M_InventoryLine inventoryLine) { return getMovementQty(inventoryLine).signum() < 0; } @Override public void assignToInventoryCounters(final List<I_M_InventoryLine> inventoryLines, final int numberOfCounters) { final Map<Integer, List<I_M_InventoryLine>> linesToLocators = new HashMap<>(); GuavaCollectors.groupByAndStream(inventoryLines.stream(), I_M_InventoryLine::getM_Locator_ID) .forEach( inventoryLinesPerLocator -> linesToLocators.put(inventoryLinesPerLocator.get(0).getM_Locator_ID(), inventoryLinesPerLocator)); final List<Integer> locatorIds = linesToLocators .keySet() .stream() .sorted() .collect(ImmutableList.toImmutableList()); int i = 0; for (int locatorId : locatorIds) { if (i == numberOfCounters) { i = 0; } final char counterIdentifier = (char)('A' + i); assignInventoryLinesToCounterIdentifiers(linesToLocators.get(locatorId), counterIdentifier); i++; } } private void assignInventoryLinesToCounterIdentifiers(final List<I_M_InventoryLine> list, final char counterIdentifier) { list.forEach(inventoryLine -> { inventoryLine.setAssignedTo(Character.toString(counterIdentifier)); save(inventoryLine); });
} @Override public void setDefaultInternalChargeId(final I_M_InventoryLine inventoryLine) { final int defaultChargeId = getDefaultInternalChargeId(); inventoryLine.setC_Charge_ID(defaultChargeId); } @Override public void markInventoryLinesAsCounted(@NonNull final InventoryId inventoryId) { inventoryDAO.retrieveLinesForInventoryId(inventoryId) .forEach(this::markInventoryLineAsCounted); } private void markInventoryLineAsCounted(final I_M_InventoryLine inventoryLine) { inventoryLine.setIsCounted(true); save(inventoryLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\impl\InventoryBL.java
1
请完成以下Java代码
private void init() { this.var = null; this.scopeSpecified = false; this.scope = PageContext.PAGE_SCOPE; } public void setVar(String var) { this.var = var; } public void setProperty(String operation) { this.property = operation; } public void setScope(String scope) { this.scope = TagUtils.getScope(scope); this.scopeSpecified = true; } public void setPageContext(PageContext pageContext) { super.setPageContext(pageContext); ServletContext servletContext = pageContext.getServletContext(); ApplicationContext context = SecurityWebApplicationContextUtils .findRequiredWebApplicationContext(servletContext); String[] names = context.getBeanNamesForType(SecurityContextHolderStrategy.class); if (names.length == 1) { SecurityContextHolderStrategy strategy = context.getBean(SecurityContextHolderStrategy.class); this.securityContextHolderStrategy = strategy; } } @Override public int doStartTag() throws JspException { return super.doStartTag(); } @Override public int doEndTag() throws JspException { Object result = null; // determine the value by... if (this.property != null) { SecurityContext context = this.securityContextHolderStrategy.getContext(); if ((context == null) || !(context instanceof SecurityContext) || (context.getAuthentication() == null)) { return Tag.EVAL_PAGE; } Authentication auth = context.getAuthentication(); if (auth.getPrincipal() == null) { return Tag.EVAL_PAGE; } try { BeanWrapperImpl wrapper = new BeanWrapperImpl(auth); result = wrapper.getPropertyValue(this.property); } catch (BeansException ex) { throw new JspException(ex); } } if (this.var != null) { /* * Store the result, letting an IllegalArgumentException propagate back if the * scope is invalid (e.g., if an attempt is made to store something in the * session without any HttpSession existing). */
if (result != null) { this.pageContext.setAttribute(this.var, result, this.scope); } else { if (this.scopeSpecified) { this.pageContext.removeAttribute(this.var, this.scope); } else { this.pageContext.removeAttribute(this.var); } } } else { if (this.htmlEscape) { writeMessage(TextEscapeUtils.escapeEntities(String.valueOf(result))); } else { writeMessage(String.valueOf(result)); } } return EVAL_PAGE; } protected void writeMessage(String msg) throws JspException { try { this.pageContext.getOut().write(String.valueOf(msg)); } catch (IOException ioe) { throw new JspException(ioe); } } /** * Set HTML escaping for this tag, as boolean value. */ public void setHtmlEscape(String htmlEscape) { this.htmlEscape = Boolean.parseBoolean(htmlEscape); } /** * Return the HTML escaping setting for this tag, or the default setting if not * overridden. */ protected boolean isHtmlEscape() { return this.htmlEscape; } }
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AuthenticationTag.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final InventoryService inventoryService; public MainApplication(InventoryService inventoryService) { this.inventoryService = inventoryService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public OptimisticConcurrencyControlAspect optimisticConcurrencyControlAspect() { return new OptimisticConcurrencyControlAspect(); }
@Bean public ApplicationRunner init() { return args -> { ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(inventoryService); // Thread.sleep(2000); -> adding a sleep here will break the transactions concurrency executor.execute(inventoryService); executor.shutdown(); try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootRetryVersionedOptimisticLockingTT\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public void setQtyOrdered(BigDecimal QtyOrdered) { final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID()); if (QtyOrdered != null && productId != null) { final UOMPrecision precision = Services.get(IProductBL.class).getUOMPrecision(productId); QtyOrdered = precision.round(QtyOrdered); } super.setQtyOrdered(QtyOrdered); } // setQtyOrdered @Override protected boolean beforeSave(boolean newRecord) { if (newRecord && getParent().isComplete()) { throw new AdempiereException("@ParentComplete@ @DD_OrderLine_ID@"); } // Get Defaults from Parent /* * if (getC_BPartner_ID() == 0 || getC_BPartner_Location_ID() == 0 * || getM_Warehouse_ID() == 0) * setOrder (getParent()); */ // if (m_M_PriceList_ID == 0) // setHeaderInfo(getParent()); // R/O Check - Product/Warehouse Change if (!newRecord && (is_ValueChanged("M_Product_ID") || is_ValueChanged("M_Locator_ID") || is_ValueChanged("M_LocatorTo_ID"))) { if (!canChangeWarehouse()) { throw new AdempiereException("Changing product/locator is not allowed"); } } // Product Changed // Charge if (getC_Charge_ID() != 0 && getM_Product_ID() != 0) setM_Product_ID(0); // No Product if (getM_Product_ID() == 0) setM_AttributeSetInstance_ID(0); // Product // UOM if (getC_UOM_ID() == 0 && (getM_Product_ID() != 0 || getC_Charge_ID() != 0)) { int C_UOM_ID = MUOM.getDefault_UOM_ID(getCtx()); if (C_UOM_ID > 0) setC_UOM_ID(C_UOM_ID); } // Qty Precision if (newRecord || is_ValueChanged(COLUMNNAME_QtyEntered)) setQtyEntered(getQtyEntered()); if (newRecord || is_ValueChanged(COLUMNNAME_QtyOrdered)) setQtyOrdered(getQtyOrdered()); // FreightAmt Not used if (BigDecimal.ZERO.compareTo(getFreightAmt()) != 0) setFreightAmt(BigDecimal.ZERO);
// Get Line No if (getLine() == 0) { String sql = "SELECT COALESCE(MAX(Line),0)+10 FROM DD_OrderLine WHERE DD_Order_ID=?"; int ii = DB.getSQLValue(get_TrxName(), sql, getDD_Order_ID()); setLine(ii); } return true; } // beforeSave /** * Before Delete * * @return true if it can be deleted */ @Override protected boolean beforeDelete() { // R/O Check - Something delivered. etc. if (getQtyDelivered().signum() != 0) { throw new AdempiereException("@QtyDelivered@: " + getQtyDelivered()); } if (getQtyReserved().signum() != 0) { // For PO should be On Order throw new AdempiereException("@QtyReserved@: " + getQtyReserved()); } return true; } // beforeDelete } // MDDOrderLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\model\MDDOrderLine.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPosted (final boolean Posted) { set_ValueNoCheck (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); }
@Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setQty (final BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInUOM (final @Nullable BigDecimal QtyInUOM) { set_Value (COLUMNNAME_QtyInUOM, QtyInUOM); } @Override public BigDecimal getQtyInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInUOM); return bd != null ? bd : BigDecimal.ZERO; } /** * Type AD_Reference_ID=541716 * Reference name: M_MatchInv_Type */ public static final int TYPE_AD_Reference_ID=541716; /** Material = M */ public static final String TYPE_Material = "M"; /** Cost = C */ public static final String TYPE_Cost = "C"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchInv.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultTbCustomerService extends AbstractTbEntityService implements TbCustomerService { @Override public Customer save(Customer customer, SecurityUser user) throws Exception { return save(customer, NameConflictStrategy.DEFAULT, user); } @Override public Customer save(Customer customer, NameConflictStrategy nameConflictStrategy, SecurityUser user) throws Exception { ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = customer.getTenantId(); try { Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer, nameConflictStrategy)); autoCommit(user, savedCustomer.getId()); logEntityActionService.logEntityAction(tenantId, savedCustomer.getId(), savedCustomer, null, actionType, user); return savedCustomer; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.CUSTOMER), customer, actionType, user, e); throw e; } }
@Override public void delete(Customer customer, User user) { ActionType actionType = ActionType.DELETED; TenantId tenantId = customer.getTenantId(); CustomerId customerId = customer.getId(); try { customerService.deleteCustomer(tenantId, customerId); logEntityActionService.logEntityAction(tenantId, customer.getId(), customer, customerId, actionType, user, customerId.toString()); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.CUSTOMER), actionType, user, e, customerId.toString()); throw e; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\customer\DefaultTbCustomerService.java
2
请在Spring Boot框架中完成以下Java代码
public class FilterProperties { @NotNull private @Nullable String name; private Map<String, String> args = new LinkedHashMap<>(); public FilterProperties() { } public FilterProperties(String text) { int eqIdx = text.indexOf('='); if (eqIdx <= 0) { setName(text); return; } setName(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ","); for (int i = 0; i < args.length; i++) { this.args.put(NameUtils.generateName(i), args[i]); } } public @Nullable String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getArgs() { return args; } public void setArgs(Map<String, String> args) { this.args = args; } public void addArg(String key, String value) { this.args.put(key, value); } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterProperties that = (FilterProperties) o; return Objects.equals(name, that.name) && Objects.equals(args, that.args); } @Override public int hashCode() { return Objects.hash(name, args); } @Override public String toString() { final StringBuilder sb = new StringBuilder("FilterDefinition{"); sb.append("name='").append(name).append('\''); sb.append(", args=").append(args); sb.append('}'); return sb.toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\FilterProperties.java
2
请完成以下Java代码
public class Association extends Artifact { protected AssociationDirection associationDirection = AssociationDirection.NONE; protected String sourceRef; protected String targetRef; public AssociationDirection getAssociationDirection() { return associationDirection; } public void setAssociationDirection(AssociationDirection associationDirection) { this.associationDirection = associationDirection; } public String getSourceRef() { return sourceRef; } public void setSourceRef(String sourceRef) { this.sourceRef = sourceRef; } public String getTargetRef() { return targetRef; } public void setTargetRef(String targetRef) { this.targetRef = targetRef; }
public Association clone() { Association clone = new Association(); clone.setValues(this); return clone; } public void setValues(Association otherElement) { super.setValues(otherElement); setSourceRef(otherElement.getSourceRef()); setTargetRef(otherElement.getTargetRef()); if (otherElement.getAssociationDirection() != null) { setAssociationDirection(otherElement.getAssociationDirection()); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Association.java
1
请完成以下Java代码
protected @Nullable String getUnstructuredRemittanceInfo(final @NonNull String delimiter) { final RemittanceInformation5 rmtInf = entryDtls.getRmtInf(); if(rmtInf == null) { return null; } return String.join(delimiter, rmtInf.getUstrd()); } @Override protected @NonNull String getLineDescription(final @NonNull String delimiter) { return entryDtls.getAddtlTxInf(); }
@Nullable @Override public String getCcy() { return entryDtls.getAmtDtls().getInstdAmt().getAmt().getCcy(); } /** * @return true if this is a "credit" line (i.e. we get money) */ @Override public boolean isCRDT() { final TransactionParty2 party = entryDtls.getRltdPties(); return party.getCdtr() != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\TransactionDtls2Wrapper.java
1
请完成以下Java代码
private List<TextSegment> loadJsonDocuments(String resourcePath, int maxTokensPerChunk, int overlapTokens) throws IOException { InputStream inputStream = ArticlesRepository.class.getClassLoader().getResourceAsStream(resourcePath); if (inputStream == null) { throw new FileNotFoundException("Resource not found: " + resourcePath); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); int batchSize = 500; List<Document> batch = new ArrayList<>(); List<TextSegment> textSegments = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { JsonNode jsonNode = objectMapper.readTree(line); String title = jsonNode.path("title").asText(null); String body = jsonNode.path("body").asText(null); JsonNode metadataNode = jsonNode.path("metadata"); if (body != null) { addDocumentToBatch(title, body, metadataNode, batch); if (batch.size() >= batchSize) { textSegments.addAll(splitIntoChunks(batch, maxTokensPerChunk, overlapTokens)); batch.clear(); } } } if (!batch.isEmpty()) { textSegments.addAll(splitIntoChunks(batch, maxTokensPerChunk, overlapTokens)); } return textSegments; } private void addDocumentToBatch(String title, String body, JsonNode metadataNode, List<Document> batch) { String text = (title != null ? title + "\n\n" + body : body);
Metadata metadata = new Metadata(); if (metadataNode != null && metadataNode.isObject()) { Iterator<String> fieldNames = metadataNode.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); metadata.put(fieldName, metadataNode.path(fieldName).asText()); } } Document document = Document.from(text, metadata); batch.add(document); } private List<TextSegment> splitIntoChunks(List<Document> documents, int maxTokensPerChunk, int overlapTokens) { OpenAiTokenizer tokenizer = new OpenAiTokenizer(OpenAiEmbeddingModelName.TEXT_EMBEDDING_3_SMALL); DocumentSplitter splitter = DocumentSplitters.recursive( maxTokensPerChunk, overlapTokens, tokenizer ); List<TextSegment> allSegments = new ArrayList<>(); for (Document document : documents) { List<TextSegment> segments = splitter.split(document); allSegments.addAll(segments); } return allSegments; } }
repos\tutorials-master\libraries-llms-2\src\main\java\com\baeldung\chatbot\mongodb\repositories\ArticlesRepository.java
1
请完成以下Java代码
private ConcurrentMessageListenerContainer<String, String> createContainer( ConcurrentKafkaListenerContainerFactory<String, String> factory, String topic, String group) { ConcurrentMessageListenerContainer<String, String> container = factory.createContainer(topic); container.getContainerProperties().setMessageListener(new MyListener()); container.getContainerProperties().setGroupId(group); container.setBeanName(group); container.start(); return container; } // end::create[] @Bean public KafkaAdmin.NewTopics topics() { return new KafkaAdmin.NewTopics( TopicBuilder.name("topic1") .partitions(10) .replicas(1) .build(), TopicBuilder.name("topic2") .partitions(10) .replicas(1) .build(),
TopicBuilder.name("topic3") .partitions(10) .replicas(1) .build()); } // tag::pojoBean[] @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) MyPojo pojo(String id, String topic) { return new MyPojo(id, topic); } //end::pojoBean[] }
repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\dynamic\Application.java
1
请完成以下Java代码
public java.lang.String getPrintServiceTray() { return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions)); } @Override public boolean isStatus_Print_Job_Instructions() { return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions); }
@Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } @Override public void setWP_IsError (boolean WP_IsError) { set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError)); } @Override public boolean isWP_IsError() { return get_ValueAsBoolean(COLUMNNAME_WP_IsError); } @Override public void setWP_IsProcessed (boolean WP_IsProcessed) { set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed)); } @Override public boolean isWP_IsProcessed() { return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java
1
请完成以下Java代码
public int getC_OLCand_AlbertaTherapyType_ID() { return get_ValueAsInt(COLUMNNAME_C_OLCand_AlbertaTherapyType_ID); } @Override public void setC_OLCand_ID (final int C_OLCand_ID) { if (C_OLCand_ID < 1) set_Value (COLUMNNAME_C_OLCand_ID, null); else set_Value (COLUMNNAME_C_OLCand_ID, C_OLCand_ID); } @Override public int getC_OLCand_ID() {
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID); } @Override public void setTherapyType (final java.lang.String TherapyType) { set_Value (COLUMNNAME_TherapyType, TherapyType); } @Override public java.lang.String getTherapyType() { return get_ValueAsString(COLUMNNAME_TherapyType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaTherapyType.java
1
请在Spring Boot框架中完成以下Java代码
public VATType getVAT() { return vat; } /** * Sets the value of the vat property. * * @param value * allowed object is * {@link VATType } * */ public void setVAT(VATType value) { this.vat = value; } /** * Used to provide information about other tax.Gets the value of the otherTax property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the otherTax property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOtherTax().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OtherTaxType } * * */ public List<OtherTaxType> getOtherTax() { if (otherTax == null) { otherTax = new ArrayList<OtherTaxType>(); } return this.otherTax;
} /** * Gets the value of the taxExtension property. * * @return * possible object is * {@link TaxExtensionType } * */ public TaxExtensionType getTaxExtension() { return taxExtension; } /** * Sets the value of the taxExtension property. * * @param value * allowed object is * {@link TaxExtensionType } * */ public void setTaxExtension(TaxExtensionType value) { this.taxExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\TaxType.java
2
请完成以下Java代码
public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID) { if (M_HU_PI_Item_Product_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Item_Product_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID); } @Override public int getM_HU_PI_Item_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class); } @Override public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Version_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { throw new IllegalArgumentException ("M_Product_Category_ID is virtual column"); } @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) { throw new IllegalArgumentException ("M_Product_ID is virtual column"); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSerialNo (final @Nullable java.lang.String SerialNo) { throw new IllegalArgumentException ("SerialNo is virtual column"); } @Override public java.lang.String getSerialNo() { return get_ValueAsString(COLUMNNAME_SerialNo); } @Override public void setServiceContract (final @Nullable java.lang.String ServiceContract) { throw new IllegalArgumentException ("ServiceContract is virtual column"); } @Override public java.lang.String getServiceContract() { return get_ValueAsString(COLUMNNAME_ServiceContract); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (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_M_HU.java
1
请在Spring Boot框架中完成以下Java代码
public boolean excludeUnlistedClasses() { return false; } @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.UNSPECIFIED; } @Override public ValidationMode getValidationMode() { return ValidationMode.AUTO; } public Properties getProperties() { return properties; } @Override public String getPersistenceXMLSchemaVersion() { return JPA_VERSION; }
@Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public void addTransformer(ClassTransformer transformer) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ClassLoader getNewTempClassLoader() { return null; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java
2
请在Spring Boot框架中完成以下Java代码
private static ImmutableSet<HUIdAndQRCode> extractHuIdAndQRCodes(final @NonNull List<PickingJobStepPickedToHU> pickedToHUs) { return pickedToHUs.stream() .map(PickingJobStepPickedToHU::getActualPickedHU) .map(HUInfo::toHUIdAndQRCode) .collect(ImmutableSet.toImmutableSet()); } private void changeHUStatusFromPickedToActive(final Collection<I_M_HU> topLevelHUs) { topLevelHUs.forEach(this::changeHUStatusFromPickedToActive); } private void changeHUStatusFromPickedToActive(final I_M_HU topLevelHU) { if (X_M_HU.HUSTATUS_Picked.equals(topLevelHU.getHUStatus())) { huService.setHUStatusActive(topLevelHU); } } private HUTransformService newHUTransformService() { return HUTransformService.builder() .huQRCodesService(huService.getHuQRCodesService()) .build(); } @NonNull private PickingJob reinitializePickingTargetIfDestroyed(final PickingJob pickingJob) { if (isLineLevelPickTarget(pickingJob)) { return pickingJob.withLuPickingTarget(lineId, this::reinitializeLUPickingTarget); } else { return pickingJob.withLuPickingTarget(null, this::reinitializeLUPickingTarget); } }
private boolean isLineLevelPickTarget(final PickingJob pickingJob) {return pickingJob.isLineLevelPickTarget();} @Nullable private LUPickingTarget reinitializeLUPickingTarget(@Nullable final LUPickingTarget luPickingTarget) { if (luPickingTarget == null) { return null; } final HuId luId = luPickingTarget.getLuId(); if (luId == null) { return luPickingTarget; } final I_M_HU lu = huService.getById(luId); if (!huService.isDestroyedOrEmptyStorage(lu)) { return luPickingTarget; } final HuPackingInstructionsIdAndCaption luPI = huService.getEffectivePackingInstructionsIdAndCaption(lu); return LUPickingTarget.ofPackingInstructions(luPI); } // // // @Value @Builder private static class StepUnpickInstructions { @NonNull PickingJobStepId stepId; @NonNull PickingJobStepPickFromKey pickFromKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobUnPickCommand.java
2
请完成以下Java代码
private static String buildUserFullname(final org.compiere.model.I_AD_User user) { final StringBuilder fullname = new StringBuilder(); final String firstname = StringUtils.trimBlankToNull(user.getFirstname()); if (firstname != null) { fullname.append(firstname); } final String lastname = StringUtils.trimBlankToNull(user.getLastname()); if (lastname != null) { if (fullname.length() > 0) { fullname.append(" "); } fullname.append(lastname); } if (fullname.length() <= 0) { final String login = StringUtils.trimBlankToNull(user.getLogin()); if (login != null) // shall not happen to be empty { fullname.append(login); } } if (fullname.length() <= 0) { fullname.append(user.getAD_User_ID()); } return fullname.toString(); } private static ClientId getClientId( @NonNull final Login loginService, @NonNull final UserId userId, @NonNull final RoleId roleId) { final Set<ClientId> clientIds = loginService.getAvailableClients(roleId, userId); if (clientIds == null || clientIds.isEmpty()) { throw new AdempiereException("User is not assigned to an AD_Client"); } else if (clientIds.size() != 1) { throw new AdempiereException("User is assigned to more than one AD_Client"); } else { return clientIds.iterator().next(); } } private static OrgId getOrgId(final Login loginService, final UserId userId, final RoleId roleId, final ClientId clientId) { final Set<OrgId> orgIds = loginService.getAvailableOrgs(roleId, userId, clientId); final OrgId orgId; if (orgIds == null || orgIds.isEmpty()) { throw new AdempiereException("User is not assigned to an AD_Org"); } else if (orgIds.size() != 1) { // if there are more Orgs, we are going with organization "*" orgId = OrgId.ANY; } else { orgId = orgIds.iterator().next(); } return orgId; }
private Role getRoleToLogin(LoginAuthenticateResponse response) { final ImmutableList<Role> roles = response.getAvailableRoles(); if (roles.isEmpty()) { throw new AdempiereException("User has no role assigned"); } else if (roles.size() == 1) { return roles.get(0); } else { final ArrayList<Role> nonSysAdminRoles = new ArrayList<>(); for (final Role role : roles) { if (role.isSystem()) { continue; } nonSysAdminRoles.add(role); } if (nonSysAdminRoles.size() == 1) { return nonSysAdminRoles.get(0); } else { throw new AdempiereException("Multiple roles are not supported. Make sure user has only one role assigned"); } } } @NonNull private static Login getLoginService() { final LoginContext loginCtx = new LoginContext(Env.newTemporaryCtx()); loginCtx.setWebui(true); return new Login(loginCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\authentication\AuthenticationRestController.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(value); } public void insert(int value) { insert(this, value); } private void insert(TreeNode currentNode, final int value) { if (currentNode.left == null && value < currentNode.value) { currentNode.left = new TreeNode(value); return; } if (currentNode.right == null && value > currentNode.value) { currentNode.right = new TreeNode(value); return; } if (value > currentNode.value) { insert(currentNode.right, value); } if (value < currentNode.value) { insert(currentNode.left, value); } } public TreeNode parent(int target) throws NoSuchElementException { return parent(this, new TreeNode(target)); } private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException { if (target.equals(current) || current == null) { throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " + "The target is not in the tree or the target is the topmost root node.", target.value)); } if (target.equals(current.left) || target.equals(current.right)) { return current;
} return parent(target.value < current.value ? current.left : current.right, target); } public TreeNode iterativeParent(int target) { return iterativeParent(this, new TreeNode(target)); } private TreeNode iterativeParent(TreeNode current, TreeNode target) { Deque<TreeNode> parentCandidates = new LinkedList<>(); String notFoundMessage = format("No parent node found for 'target.value=%s' " + "The target is not in the tree or the target is the topmost root node.", target.value); if (target.equals(current)) { throw new NoSuchElementException(notFoundMessage); } while (current != null || !parentCandidates.isEmpty()) { while (current != null) { parentCandidates.addFirst(current); current = current.left; } current = parentCandidates.pollFirst(); if (target.equals(current.left) || target.equals(current.right)) { return current; } current = current.right; } throw new NoSuchElementException(notFoundMessage); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\parentnodebinarytree\TreeNode.java
1
请完成以下Java代码
public final class JacksonUtils { private static final boolean JDK8_MODULE_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.datatype.jdk8.Jdk8Module", null); private static final boolean PARAMETER_NAMES_MODULE_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.module.paramnames.ParameterNamesModule", null); private static final boolean JAVA_TIME_MODULE_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule", null); private static final boolean JODA_MODULE_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.datatype.joda.JodaModule", null); private static final boolean KOTLIN_MODULE_PRESENT = ClassUtils.isPresent("kotlin.Unit", null) && ClassUtils.isPresent("com.fasterxml.jackson.module.kotlin.KotlinModule", null); /** * Factory for {@link ObjectMapper} instances with registered well-known modules * and disabled {@link MapperFeature#DEFAULT_VIEW_INCLUSION} and * {@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} features. * @return the {@link ObjectMapper} instance. */ public static ObjectMapper enhancedObjectMapper() { ObjectMapper objectMapper = JsonMapper.builder() .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .build(); registerWellKnownModulesIfAvailable(objectMapper); return objectMapper; } private static void registerWellKnownModulesIfAvailable(ObjectMapper objectMapper) { if (JDK8_MODULE_PRESENT) { objectMapper.registerModule(Jdk8ModuleProvider.MODULE); } if (PARAMETER_NAMES_MODULE_PRESENT) { objectMapper.registerModule(ParameterNamesProvider.MODULE); } if (JAVA_TIME_MODULE_PRESENT) { objectMapper.registerModule(JavaTimeModuleProvider.MODULE); } if (JODA_MODULE_PRESENT) { objectMapper.registerModule(JodaModuleProvider.MODULE); } if (KOTLIN_MODULE_PRESENT) { objectMapper.registerModule(KotlinModuleProvider.MODULE); }
} private JacksonUtils() { } private static final class Jdk8ModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.datatype.jdk8.Jdk8Module(); } private static final class ParameterNamesProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.module.paramnames.ParameterNamesModule(); } private static final class JavaTimeModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule(); } private static final class JodaModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.datatype.joda.JodaModule(); } private static final class KotlinModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.module.kotlin.KotlinModule.Builder().build(); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\JacksonUtils.java
1
请完成以下Java代码
public class TalentMQMessage implements Serializable { /** * TalentId : a848030e-b09b-4c93-a10e-37e8cc956621 * CallbackData : * CallbackQueue : */ private String TalentId; private String CallbackData; private String CallbackQueue; public String getTalentId() { return TalentId; } public void setTalentId(String TalentId) { this.TalentId = TalentId; } public String getCallbackData() { return CallbackData; } public void setCallbackData(String CallbackData) { this.CallbackData = CallbackData; }
public String getCallbackQueue() { return CallbackQueue; } public void setCallbackQueue(String CallbackQueue) { this.CallbackQueue = CallbackQueue; } @Override public String toString() { return "TalentMQMessage{" + "TalentId='" + TalentId + '\'' + ", CallbackData='" + CallbackData + '\'' + ", CallbackQueue='" + CallbackQueue + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-activemq\src\main\java\com\mq\model\TalentMQMessage.java
1
请完成以下Java代码
static int bruteForce(int n) { int count = 0; int limit = (int)Math.pow(10, n); for (int num = 0; num < limit; num++) { if (hasUniqueDigits(num)) { count++; } } return count; } static boolean hasUniqueDigits(int num) { String str = Integer.toString(num); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) { return false; } } } return true; } static int combinatorial(int n) { if (n == 0) return 1; int result = 10; int current = 9; int available = 9; for (int i = 2; i <= n; i++) {
current *= available; result += current; available--; } return result; } static int dp(int n) { if (n == 0) return 1; int result = 10; int current = 9; int available = 9; for (int i = 2; i <= n; i++) { current *= available; result += current; available--; } return result; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\uniquedigitcounter\UniqueDigitCounter.java
1
请完成以下Java代码
public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Line No. @return Unique line for this document */ public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set BOM Line. @param M_Product_BOM_ID BOM Line */ public void setM_Product_BOM_ID (int M_Product_BOM_ID) { if (M_Product_BOM_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_BOM_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_BOM_ID, Integer.valueOf(M_Product_BOM_ID)); } /** Get BOM Line. @return BOM Line */ public int getM_Product_BOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_BOM_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_ProductBOM() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_ProductBOM_ID(), get_TrxName()); } /** Set BOM Product. @param M_ProductBOM_ID Bill of Material Component Product */ public void setM_ProductBOM_ID (int M_ProductBOM_ID) { if (M_ProductBOM_ID < 1) set_Value (COLUMNNAME_M_ProductBOM_ID, null); else
set_Value (COLUMNNAME_M_ProductBOM_ID, Integer.valueOf(M_ProductBOM_ID)); } /** Get BOM Product. @return Bill of Material Component Product */ public int getM_ProductBOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductBOM_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(getM_ProductBOM_ID())); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_BOM.java
1
请完成以下Java代码
public final class ExpressionJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private final Log logger = LogFactory.getLog(getClass()); private String authorityPrefix = "SCOPE_"; private final Expression authoritiesClaimExpression; /** * Constructs a {@link ExpressionJwtGrantedAuthoritiesConverter} using the provided * {@code authoritiesClaimExpression}. * @param authoritiesClaimExpression The token claim SpEL Expression to map * authorities from. */ public ExpressionJwtGrantedAuthoritiesConverter(Expression authoritiesClaimExpression) { Assert.notNull(authoritiesClaimExpression, "authoritiesClaimExpression must not be null"); this.authoritiesClaimExpression = authoritiesClaimExpression; } /** * Sets the prefix to use for {@link GrantedAuthority authorities} mapped by this * converter. Defaults to {@code "SCOPE_"}. * @param authorityPrefix The authority prefix */ public void setAuthorityPrefix(String authorityPrefix) { Assert.notNull(authorityPrefix, "authorityPrefix cannot be null"); this.authorityPrefix = authorityPrefix; } /** * Extract {@link GrantedAuthority}s from the given {@link Jwt}. * @param jwt The {@link Jwt} token * @return The {@link GrantedAuthority authorities} read from the token scopes */ @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority)); } return grantedAuthorities; } private Collection<String> getAuthorities(Jwt jwt) { Object authorities; try { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for authorities with expression. expression=%s", this.authoritiesClaimExpression.getExpressionString())); } authorities = this.authoritiesClaimExpression.getValue(jwt.getClaims(), Collection.class);
if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Found authorities with expression. authorities=%s", authorities)); } } catch (ExpressionException ee) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Failed to evaluate expression. error=%s", ee.getMessage())); } authorities = Collections.emptyList(); } if (authorities != null) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\ExpressionJwtGrantedAuthoritiesConverter.java
1
请完成以下Java代码
public static CookieCsrfTokenRepository withHttpOnlyFalse() { CookieCsrfTokenRepository result = new CookieCsrfTokenRepository(); result.cookieHttpOnly = false; return result; } private String createNewToken() { return UUID.randomUUID().toString(); } private Cookie mapToCookie(ResponseCookie responseCookie) { Cookie cookie = new Cookie(responseCookie.getName(), responseCookie.getValue()); cookie.setSecure(responseCookie.isSecure()); cookie.setPath(responseCookie.getPath()); cookie.setMaxAge((int) responseCookie.getMaxAge().getSeconds()); cookie.setHttpOnly(responseCookie.isHttpOnly()); if (StringUtils.hasLength(responseCookie.getDomain())) { cookie.setDomain(responseCookie.getDomain()); } if (StringUtils.hasText(responseCookie.getSameSite())) { cookie.setAttribute("SameSite", responseCookie.getSameSite());
} return cookie; } /** * Set the path that the Cookie will be created with. This will override the default * functionality which uses the request context as the path. * @param path the path to use */ public void setCookiePath(String path) { this.cookiePath = path; } /** * Get the path that the CSRF cookie will be set to. * @return the path to be used. */ public @Nullable String getCookiePath() { return this.cookiePath; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CookieCsrfTokenRepository.java
1
请完成以下Java代码
public ArrayKey getValidationKey() { return validationKey; } @Override public boolean hasInactiveValues() { return this.hasInactiveValues; } @Override public boolean isAllLoaded() { return allLoaded; } @Override public boolean isDirty() { return wasInterrupted; } private final String normalizeKey(final Object key) { return key == null ? null : key.toString(); } @Override public boolean containsKey(Object key) { final String keyStr = normalizeKey(key); return values.containsKey(keyStr); } @Override public NamePair getByKey(Object key) {
final String keyStr = normalizeKey(key); return values.get(keyStr); } @Override public Collection<NamePair> getValues() { return values.values(); } @Override public int size() { return values.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MLookupLoader.java
1
请完成以下Java代码
public void setHUStorageASIKey (final @Nullable java.lang.String HUStorageASIKey) { set_ValueNoCheck (COLUMNNAME_HUStorageASIKey, HUStorageASIKey); } @Override public java.lang.String getHUStorageASIKey() { return get_ValueAsString(COLUMNNAME_HUStorageASIKey); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Locator_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_ValueNoCheck (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_ValueNoCheck (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_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); 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_RV_M_HU_Storage_InvoiceHistory.java
1
请完成以下Java代码
public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { if (returnedObject == null) { logger.debug("Return object is null, skipping"); return null; } for (ConfigAttribute attr : config) { if (!this.supports(attr)) { continue; } // Need to process the Collection for this invocation Filterer filterer = getFilterer(returnedObject); // Locate unauthorised Collection elements for (Object domainObject : filterer) { // Ignore nulls or entries which aren't instances of the configured domain // object class if (domainObject == null || !getProcessDomainObjectClass().isAssignableFrom(domainObject.getClass())) { continue; } if (!hasPermission(authentication, domainObject)) { filterer.remove(domainObject);
logger.debug(LogMessage.of(() -> "Principal is NOT authorised for element: " + domainObject)); } } return filterer.getFilteredObject(); } return returnedObject; } private Filterer getFilterer(Object returnedObject) { if (returnedObject instanceof Collection) { return new CollectionFilterer((Collection) returnedObject); } if (returnedObject.getClass().isArray()) { return new ArrayFilterer((Object[]) returnedObject); } throw new AuthorizationServiceException("A Collection or an array (or null) was required as the " + "returnedObject, but the returnedObject was: " + returnedObject); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationCollectionFilteringProvider.java
1
请完成以下Java代码
public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public boolean isCmmnEnabled() { return cmmnEnabled; } public void setCmmnEnabled(boolean cmmnEnabled) { this.cmmnEnabled = cmmnEnabled; } public boolean isDmnEnabled() { return dmnEnabled; } public void setDmnEnabled(boolean dmnEnabled) { this.dmnEnabled = dmnEnabled; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix;
} public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSessionFactory.java
1
请完成以下Java代码
protected void createSnapshotsByParentIds(final Set<Integer> huIds) { Check.assumeNotEmpty(huIds, "huIds not empty"); query(I_M_HU_Storage.class) .addInArrayOrAllFilter(I_M_HU_Storage.COLUMN_M_HU_ID, huIds) .create() .insertDirectlyInto(I_M_HU_Storage_Snapshot.class) .mapCommonColumns() .mapColumnToConstant(I_M_HU_Storage_Snapshot.COLUMNNAME_Snapshot_UUID, getSnapshotId()) .execute(); } @Override protected Map<Integer, I_M_HU_Storage_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU model) { return query(I_M_HU_Storage_Snapshot.class) .addEqualsFilter(I_M_HU_Storage_Snapshot.COLUMN_M_HU_ID, model.getM_HU_ID()) .addEqualsFilter(I_M_HU_Storage_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId()) .create() .map(I_M_HU_Storage_Snapshot.class, snapshot2ModelIdFunction); } @Override protected final Map<Integer, I_M_HU_Storage> retrieveModelsByParent(final I_M_HU hu) { return query(I_M_HU_Storage.class) .addEqualsFilter(I_M_HU_Storage.COLUMN_M_HU_ID, hu.getM_HU_ID()) .create() .mapById(I_M_HU_Storage.class); } @Override protected I_M_HU_Storage_Snapshot retrieveModelSnapshot(final I_M_HU_Storage model) { throw new UnsupportedOperationException(); }
@Override protected void restoreModelWhenSnapshotIsMissing(final I_M_HU_Storage model) { model.setQty(BigDecimal.ZERO); } @Override protected int getModelId(final I_M_HU_Storage_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_Storage_ID(); } @Override protected I_M_HU_Storage getModel(final I_M_HU_Storage_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_Storage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Storage_SnapshotHandler.java
1
请完成以下Java代码
public List<CreateAttributeInstanceReq> toCreateAttributeInstanceReqList(@NonNull final Collection<JsonAttributeInstance> jsonAttributeInstances) { return jsonAttributeInstances.stream() .map(this::toCreateAttributeInstanceReq) .collect(ImmutableList.toImmutableList()); } private CreateAttributeInstanceReq toCreateAttributeInstanceReq(@NonNull final JsonAttributeInstance jsonAttributeInstance) { return CreateAttributeInstanceReq.builder() .attributeCode(AttributeCode.ofString(jsonAttributeInstance.getAttributeCode())) .value(extractAttributeValueObject(jsonAttributeInstance)) .build(); } private Object extractAttributeValueObject(@NonNull final JsonAttributeInstance attributeInstance) { final I_M_Attribute attribute = attributeDAO.retrieveAttributeByValue(attributeInstance.getAttributeCode());
final AttributeValueType targetAttributeType = AttributeValueType.ofCode(attribute.getAttributeValueType()); switch (targetAttributeType) { case DATE: return attributeInstance.getValueDate(); case NUMBER: return attributeInstance.getValueNumber(); case STRING: case LIST: return attributeInstance.getValueStr(); default: throw new IllegalArgumentException("@NotSupported@ @AttributeValueType@=" + targetAttributeType + ", @M_Attribute_ID@=" + attribute.getM_Attribute_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\AttributeSetHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalReferenceLookupProcessor implements Processor { @Override public void process(final Exchange exchange) { final List<Order> orders = exchange.getIn().getBody(ArrayOfOrders.class); if (CollectionUtils.isEmpty(orders)) { return; //nothing to do } final DoctorApi doctorApi = ProcessorHelper.getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_DOCTOR_API, DoctorApi.class); final PharmacyApi pharmacyApi = ProcessorHelper.getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_ALBERTA_PHARMACY_API, PharmacyApi.class); final JsonExternalReferenceLookupRequest externalReferenceLookupRequest = buildESRLookupRequest(orders, exchange, pharmacyApi, doctorApi) .orElse(null); exchange.getIn().setBody(externalReferenceLookupRequest); } @NonNull private Optional<JsonExternalReferenceLookupRequest> buildESRLookupRequest( @NonNull final List<Order> orders, @NonNull final Exchange exchange, @NonNull final PharmacyApi pharmacyApi, @NonNull final DoctorApi doctorApi) { final Map<String, Object> externalBPId2Api = new HashMap<>(); orders.forEach(order -> { if (!StringUtils.isEmpty(order.getDoctorId())) { externalBPId2Api.put(order.getDoctorId(), doctorApi); }
if (!StringUtils.isEmpty(order.getPharmacyId())) { externalBPId2Api.put(order.getPharmacyId(), pharmacyApi); } }); if (externalBPId2Api.isEmpty()) { return Optional.empty(); } exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_EXTERNAL_BP_IDENTIFIER_TO_API, externalBPId2Api); final JsonExternalReferenceLookupRequest.JsonExternalReferenceLookupRequestBuilder jsonExternalReferenceLookupRequest = JsonExternalReferenceLookupRequest.builder() .systemName(JsonExternalSystemName.of(GetPatientsRouteConstants.ALBERTA_SYSTEM_NAME)); externalBPId2Api.keySet().stream() .map(this::getBPartnerLookupItem) .forEach(jsonExternalReferenceLookupRequest::item); return Optional.of(jsonExternalReferenceLookupRequest.build()); } @NonNull private JsonExternalReferenceLookupItem getBPartnerLookupItem(@NonNull final String externalId) { return JsonExternalReferenceLookupItem.builder() .type(GetPatientsRouteConstants.ESR_TYPE_BPARTNER) .id(externalId) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\ExternalReferenceLookupProcessor.java
2
请完成以下Java代码
private void constructFailureStates() { Queue<State> queue = new LinkedBlockingDeque<State>(); // 第一步,将深度为1的节点的failure设为根节点 for (State depthOneState : this.rootState.getStates()) { depthOneState.setFailure(this.rootState); queue.add(depthOneState); } this.failureStatesConstructed = true; // 第二步,为深度 > 1 的节点建立failure表,这是一个bfs while (!queue.isEmpty()) { State currentState = queue.remove(); for (Character transition : currentState.getTransitions()) { State targetState = currentState.nextState(transition); queue.add(targetState); State traceFailureState = currentState.failure(); while (traceFailureState.nextState(transition) == null) { traceFailureState = traceFailureState.failure(); } State newFailureState = traceFailureState.nextState(transition); targetState.setFailure(newFailureState); targetState.addEmit(newFailureState.emit()); } } } public void dfs(IWalker walker) { checkForConstructedFailureStates(); dfs(rootState, "", walker); } private void dfs(State currentState, String path, IWalker walker) { walker.meet(path, currentState); for (Character transition : currentState.getTransitions()) { State targetState = currentState.nextState(transition); dfs(targetState, path + transition, walker); } } public static interface IWalker { /** * 遇到了一个节点 * @param path * @param state */ void meet(String path, State state); } /** * 保存匹配结果 * * @param position 当前位置,也就是匹配到的模式串的结束位置+1 * @param currentState 当前状态 * @param collectedEmits 保存位置 */ private static void storeEmits(int position, State currentState, List<Emit> collectedEmits) { Collection<String> emits = currentState.emit();
if (emits != null && !emits.isEmpty()) { for (String emit : emits) { collectedEmits.add(new Emit(position - emit.length() + 1, position, emit)); } } } /** * 文本是否包含任何模式 * * @param text 待匹配的文本 * @return 文本包含模式時回傳true */ public boolean hasKeyword(String text) { checkForConstructedFailureStates(); State currentState = this.rootState; for (int i = 0; i < text.length(); ++i) { State nextState = getState(currentState, text.charAt(i)); if (nextState != null && nextState != currentState && nextState.emit().size() != 0) { return true; } currentState = nextState; } return false; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\trie\Trie.java
1
请在Spring Boot框架中完成以下Java代码
public class UserRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); public User getByIdInTrx(@NonNull final UserId userId) { final I_AD_User userRecord = load(userId.getRepoId(), I_AD_User.class); Check.assumeNotNull(userRecord, "UserRecord not null"); return ofRecord(userRecord); } public User ofRecord(@NonNull final I_AD_User userRecord) { final IUserBL userBL = Services.get(IUserBL.class); final IBPartnerBL bPartnerBL = Services.get(IBPartnerBL.class); final Language userLanguage = Language.asLanguage(userRecord.getAD_Language()); final Language bpartnerLanguage = bPartnerBL.getLanguageForModel(userRecord).orElse(null); final Language language = userBL.getUserLanguage(userRecord); return User.builder() .bpartnerId(BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID())) .id(UserId.ofRepoId(userRecord.getAD_User_ID())) .externalId(ExternalId.ofOrNull(userRecord.getExternalId())) .name(userRecord.getName()) .firstName(userRecord.getFirstname()) .lastName(userRecord.getLastname()) .birthday(TimeUtil.asLocalDate(userRecord.getBirthday())) .emailAddress(userRecord.getEMail()) .userLanguage(userLanguage) .bPartnerLanguage(bpartnerLanguage) .language(language) .isInvoiceEmailEnabled(OptionalBoolean.ofNullableString(userRecord.getIsInvoiceEmailEnabled())) .build(); } public User save(@NonNull final User user) {
final I_AD_User userRecord; if (user.getId() == null) { userRecord = newInstance(I_AD_User.class); } else { userRecord = load(user.getId().getRepoId(), I_AD_User.class); } userRecord.setC_BPartner_ID(BPartnerId.toRepoId(user.getBpartnerId())); userRecord.setName(user.getName()); userRecord.setFirstname(user.getFirstName()); userRecord.setLastname(user.getLastName()); userRecord.setBirthday(TimeUtil.asTimestamp(user.getBirthday())); userRecord.setEMail(user.getEmailAddress()); userRecord.setAD_Language(Language.asLanguageStringOrNull(user.getUserLanguage())); saveRecord(userRecord); return user .toBuilder() .id(UserId.ofRepoId(userRecord.getAD_User_ID())) .build(); } @NonNull public Optional<UserId> getDefaultDunningContact(@NonNull final BPartnerId bPartnerId) { return queryBL.createQueryBuilder(I_AD_User.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, bPartnerId) .addEqualsFilter(I_AD_User.COLUMNNAME_IsDunningContact, true) .create() .firstIdOnlyOptional(UserId::ofRepoIdOrNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserRepository.java
2