instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { return acceptIfEligibleOrder(context) .and(() -> acceptIfOrderLinesNotInGroup(context)); } @Override protected String doIt() { final List<I_C_OrderLine> selectedOrderLines = getSelectedOrderLines(); Check.assumeNotEmpty(selectedOrderLines, "selectedOrderLines is not empty"); final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = extractOrderLineIdsByGroupTemplate(selectedOrderLines); if (orderLineIdsByGroupTemplate.isEmpty()) { throw new AdempiereException("Nothing to group"); // TODO trl } final List<Group> groups = orderLineIdsByGroupTemplate.asMap() .entrySet() .stream() .map(e -> createGroup(e.getKey(), e.getValue())) .collect(ImmutableList.toImmutableList()); final OrderId orderId = OrderGroupRepository.extractOrderIdFromGroups(groups); groupsRepo.renumberOrderLinesForOrderId(orderId); return MSG_OK; } private ListMultimap<GroupTemplate, OrderLineId> extractOrderLineIdsByGroupTemplate(final List<I_C_OrderLine> orderLines) { final List<I_C_OrderLine> orderLinesSorted = orderLines.stream() .sorted(Comparator.comparing(I_C_OrderLine::getLine)) .collect(ImmutableList.toImmutableList()); final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = LinkedListMultimap.create(); for (final I_C_OrderLine orderLine : orderLinesSorted) { final GroupTemplate groupTemplate = extractGroupTemplate(orderLine); if (groupTemplate == null) { continue; }
orderLineIdsByGroupTemplate.put(groupTemplate, OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())); } return orderLineIdsByGroupTemplate; } @Nullable private GroupTemplate extractGroupTemplate(final I_C_OrderLine orderLine) { final ProductId productId = ProductId.ofRepoIdOrNull(orderLine.getM_Product_ID()); if (productId == null) { return null; } final IProductDAO productsRepo = Services.get(IProductDAO.class); final ProductCategoryId productCategoryId = productsRepo.retrieveProductCategoryByProductId(productId); final I_M_Product_Category productCategory = productsRepo.getProductCategoryById(productCategoryId, I_M_Product_Category.class); final GroupTemplateId groupTemplateId = GroupTemplateId.ofRepoIdOrNull(productCategory.getC_CompensationGroup_Schema_ID()); if (groupTemplateId == null) { return null; } return groupTemplateRepo.getById(groupTemplateId); } private Group createGroup(final GroupTemplate groupTemplate, final Collection<OrderLineId> orderLineIds) { return groupsRepo.prepareNewGroup() .groupTemplate(groupTemplate) .createGroup(orderLineIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\C_Order_CreateCompensationMultiGroups.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "simpleApp") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @ApiModelProperty(example = "This is an app for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ApiModelProperty(example = "1") public int getVersion() { return version; } public void setVersion(int version) { this.version = version; }
@ApiModelProperty(example = "SimpleSourceName") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "818e4703-f1d2-11e6-8549-acde48001121") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDefinitionResponse.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } final UserId loggedUserId = getLoggedUserId(); final UserId userId = UserId.ofRepoId(context.getSingleSelectedRecordId()); if (UserId.equals(userId, loggedUserId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("for logged in user we use a different process"); } if (user2FAService.isDisabled(userId))
{ return ProcessPreconditionsResolution.rejectWithInternalReason("Already disabled"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final UserId userId = UserId.ofRepoId(getRecord_ID()); user2FAService.disable(userId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\process\AD_User_Disable2FA_Admin.java
1
请在Spring Boot框架中完成以下Java代码
public void index() { try { view("products", Product.findAll()); render().contentType("application/json"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void create() { try { Map payload = mapper.readValue(getRequestString(), Map.class); Product p = new Product(); p.fromMap(payload); p.saveIt(); view("message", "Successfully saved product id " + p.get("id"), "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void update() { try { Map payload = mapper.readValue(getRequestString(), Map.class); String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } p.fromMap(payload); p.saveIt(); view("message", "Successfully updated product id " + id, "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void show() { try { String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } view("product", p); render("_product"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } }
public void destroy() { try { String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } p.delete(); view("message", "Successfully deleted product id " + id, "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } @Override protected String getContentType() { return "application/json"; } @Override protected String getLayout() { return null; } }
repos\tutorials-master\web-modules\java-lite\src\main\java\app\controllers\ProductsController.java
2
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getAuthor() { return author; }
public void setAuthor(String address) { this.author = address; } public String getSynopsis() { return synopsis; } public void setSynopsis(String synopsis) { this.synopsis = synopsis; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\java\com\baeldung\spring\data\jpa\optionalfields\Book.java
1
请在Spring Boot框架中完成以下Java代码
private static FTSJoinColumn.ValueType getValueTypeByClass(@NonNull final Class<?> valueClass) { if (int.class.equals(valueClass) || Integer.class.equals(valueClass)) { return FTSJoinColumn.ValueType.INTEGER; } else if (String.class.equals(valueClass)) { return FTSJoinColumn.ValueType.STRING; } else { throw new AdempiereException("Cannot determine " + FTSJoinColumn.ValueType.class + " for `" + valueClass + "`"); } } @ToString private static class FTSFilterDescriptorsMap { private final ImmutableMap<String, FTSFilterDescriptor> descriptorsByTargetTableName; private final ImmutableMap<FTSFilterDescriptorId, FTSFilterDescriptor> descriptorsById; private FTSFilterDescriptorsMap(@NonNull final List<FTSFilterDescriptor> descriptors) { descriptorsByTargetTableName = Maps.uniqueIndex(descriptors, FTSFilterDescriptor::getTargetTableName); descriptorsById = Maps.uniqueIndex(descriptors, FTSFilterDescriptor::getId); } public Optional<FTSFilterDescriptor> getByTargetTableName(@NonNull final String targetTableName) { return Optional.ofNullable(descriptorsByTargetTableName.get(targetTableName)); } public FTSFilterDescriptor getById(final FTSFilterDescriptorId id) { final FTSFilterDescriptor filter = descriptorsById.get(id); if (filter == null) { throw new AdempiereException("No filter found for " + id); } return filter; } } @ToString
private static class AvailableSelectionKeyColumnNames { private final ArrayList<String> availableIntKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_IntKeys); private final ArrayList<String> availableStringKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_StringKeys); public String reserveNext(@NonNull final FTSJoinColumn.ValueType valueType) { final ArrayList<String> availableKeys; if (valueType == FTSJoinColumn.ValueType.INTEGER) { availableKeys = availableIntKeys; } else if (valueType == FTSJoinColumn.ValueType.STRING) { availableKeys = availableStringKeys; } else { availableKeys = new ArrayList<>(); } if (availableKeys.isEmpty()) { throw new AdempiereException("No more available key columns left for valueType=" + valueType + " in " + this); } return availableKeys.remove(0); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSFilterDescriptorRepository.java
2
请在Spring Boot框架中完成以下Java代码
public Result<ClusterAppAssignResultVO> apiAssignAllClusterServersOfApp(@PathVariable String app, @RequestBody ClusterAppFullAssignRequest assignRequest) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app cannot be null or empty"); } if (assignRequest == null || assignRequest.getClusterMap() == null || assignRequest.getRemainingList() == null) { return Result.ofFail(-1, "bad request body"); } try { return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, assignRequest.getClusterMap(), assignRequest.getRemainingList())); } catch (Throwable throwable) { logger.error("Error when assigning full cluster servers for app: " + app, throwable); return Result.ofFail(-1, throwable.getMessage()); } } @PostMapping("/single_server/{app}") public Result<ClusterAppAssignResultVO> apiAssignSingleClusterServersOfApp(@PathVariable String app, @RequestBody ClusterAppSingleServerAssignRequest assignRequest) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app cannot be null or empty"); } if (assignRequest == null || assignRequest.getClusterMap() == null) { return Result.ofFail(-1, "bad request body"); } try { return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, Collections.singletonList(assignRequest.getClusterMap()), assignRequest.getRemainingList())); } catch (Throwable throwable) {
logger.error("Error when assigning single cluster servers for app: " + app, throwable); return Result.ofFail(-1, throwable.getMessage()); } } @PostMapping("/unbind_server/{app}") public Result<ClusterAppAssignResultVO> apiUnbindClusterServersOfApp(@PathVariable String app, @RequestBody Set<String> machineIds) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app cannot be null or empty"); } if (machineIds == null || machineIds.isEmpty()) { return Result.ofFail(-1, "bad request body"); } try { return Result.ofSuccess(clusterAssignService.unbindClusterServers(app, machineIds)); } catch (Throwable throwable) { logger.error("Error when unbinding cluster server {} for app <{}>", machineIds, app, throwable); return Result.ofFail(-1, throwable.getMessage()); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\cluster\ClusterAssignController.java
2
请在Spring Boot框架中完成以下Java代码
public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */ public void setCountry(String value) { this.country = value; } /** * Details about the contact person at the delivery point. * * @return * possible object is * {@link ContactType } * */ public ContactType getContact() {
return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link ContactType } * */ public void setContact(ContactType value) { this.contact = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DeliveryPointDetails.java
2
请完成以下Java代码
public Timestamp getFirstDayOfYear(final I_C_Year year) { final I_C_Period period = Services.get(ICalendarDAO.class).retrieveFirstPeriodOfTheYear(year); final Timestamp firstDay = period.getStartDate(); return firstDay; } @Override public void checkCorrectCalendar(final I_C_Calendar calendar) { Check.errorUnless(isCalendarNoOverlaps(calendar), "{} has overlaps", calendar); Check.errorUnless(isCalendarNoGaps(calendar), "{} has gaps", calendar); final List<I_C_Year> years = Services.get(ICalendarDAO.class).retrieveYearsOfCalendar(calendar); for (final I_C_Year year : years) { Check.errorUnless(isLengthOneYear(year), "{} doesn't have the length 1 year", year); } } private List<I_C_Period> getPeriodsOfCalendar(final I_C_Calendar calendar) { final Properties ctx = InterfaceWrapperHelper.getCtx(calendar); final String trxName = InterfaceWrapperHelper.getTrxName(calendar); final List<I_C_Year> years = Services.get(ICalendarDAO.class).retrieveYearsOfCalendar(calendar); final List<I_C_Period> periodsOfCalendar = new ArrayList<>(); for (final I_C_Year year : years) { final List<I_C_Period> periodsOfYear = Services.get(ICalendarDAO.class).retrievePeriods(ctx, year, trxName); periodsOfCalendar.addAll(periodsOfYear); } Collections.sort(periodsOfCalendar, new AccessorComparator<I_C_Period, Timestamp>( new ComparableComparator<Timestamp>(), new TypedAccessor<Timestamp>() {
@Override public Timestamp getValue(final Object o) { return ((I_C_Period)o).getStartDate(); } })); return periodsOfCalendar; } @Override public boolean isStandardPeriod(final I_C_Period period) { return X_C_Period.PERIODTYPE_StandardCalendarPeriod.equals(period.getPeriodType()); } // isStandardPeriod @Override public IBusinessDayMatcher createBusinessDayMatcherExcluding(final Set<DayOfWeek> excludeWeekendDays) { // TODO: consider I_C_NonBusinessDay and compose the matchers using CompositeBusinessDayMatcher return ExcludeWeekendBusinessDayMatcher.builder() .excludeWeekendDays(excludeWeekendDays) .build(); } @Override @NonNull public CalendarId getOrgCalendarOrDefault(final @NonNull OrgId orgId) { final OrgInfo orgInfo = orgDAO.getOrgInfoByIdInTrx(orgId); if (orgInfo.getCalendarId() != null) { return orgInfo.getCalendarId(); } final I_C_Calendar calendar = calendarDAO.getDefaultCalendar(orgId); return CalendarId.ofRepoId(calendar.getC_Calendar_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\CalendarBL.java
1
请完成以下Java代码
public class GatewayDelegatingRouterFunction<T extends ServerResponse> implements RouterFunction<T> { private final RouterFunction<T> delegate; private final String routeId; public GatewayDelegatingRouterFunction(RouterFunction<T> delegate, String routeId) { this.delegate = delegate; this.routeId = routeId; } @Override public Optional<HandlerFunction<T>> route(ServerRequest request) { // Don't use MvcUtils.putAttribute() as it is prior to init of gateway attrs request.attributes().put(MvcUtils.GATEWAY_ROUTE_ID_ATTR, routeId); request.attributes().computeIfAbsent(MvcUtils.GATEWAY_ATTRIBUTES_ATTR, s -> new HashMap<String, Object>()); Optional<HandlerFunction<T>> handlerFunction = delegate.route(request);
request.attributes().remove(MvcUtils.GATEWAY_ROUTE_ID_ATTR); return handlerFunction; } @Override public void accept(RouterFunctions.Visitor visitor) { delegate.accept(visitor); } @Override public String toString() { return String.format("RouterFunction routeId=%s delegate=%s", routeId, delegate); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayDelegatingRouterFunction.java
1
请完成以下Java代码
public void setPP_Plant_ID (int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, Integer.valueOf(PP_Plant_ID)); } /** Get Produktionsstätte. @return Produktionsstätte */ @Override public int getPP_Plant_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Plant_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.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Order_MFGWarehouse_Report.java
1
请在Spring Boot框架中完成以下Java代码
public class DecisionResponse { private String id; private String category; private String name; private String key; private String description; private int version; private String resourceName; private String deploymentId; private String tenantId; private String url; public DecisionResponse(DmnDecision decision) { this.id = decision.getId(); this.category = decision.getCategory(); this.name = decision.getName(); this.key = decision.getKey(); this.description = decision.getDescription(); this.version = decision.getVersion(); this.resourceName = decision.getResourceName(); this.deploymentId = decision.getDeploymentId(); this.tenantId = decision.getTenantId(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DecisionResponse.java
2
请完成以下Java代码
public Rating findRatingById(Long ratingId) { return ratingRepository.findById(ratingId) .orElseThrow(() -> new RatingNotFoundException("Rating not found. ID: " + ratingId)); } public Rating findCachedRatingById(Long ratingId, Exception exception) { return cacheRepository.findCachedRatingById(ratingId); } @Transactional(propagation = Propagation.REQUIRED) public Rating createRating(Rating rating) { Rating newRating = new Rating(); newRating.setBookId(rating.getBookId()); newRating.setStars(rating.getStars()); Rating persisted = ratingRepository.save(newRating); cacheRepository.createRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public void deleteRating(Long ratingId) { ratingRepository.deleteById(ratingId); cacheRepository.deleteRating(ratingId); } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Map<String, String> updates, Long ratingId) { final Rating rating = findRatingById(ratingId); updates.keySet() .forEach(key -> { switch (key) { case "stars": rating.setStars(Integer.parseInt(updates.get(key)));
break; } }); Rating persisted = ratingRepository.save(rating); cacheRepository.updateRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Rating rating, Long ratingId) { Preconditions.checkNotNull(rating); Preconditions.checkState(rating.getId() == ratingId); Preconditions.checkNotNull(ratingRepository.findById(ratingId)); return ratingRepository.save(rating); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingService.java
1
请完成以下Java代码
private static final ImmutableSetMultimap<BPartnerId, DocumentId> extractBPartnerIds(final ViewResult rows, final GeoLocationDocumentDescriptor descriptor) { final String locationColumnName = descriptor.getLocationColumnName(); final ImmutableSetMultimap.Builder<BPartnerId, DocumentId> rowIdsByBPartnerRepoId = ImmutableSetMultimap.builder(); for (final IViewRow row : rows.getPage()) { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(row.getFieldValueAsInt(locationColumnName, -1)); if (bpartnerId == null) { continue; } final DocumentId rowId = row.getId(); rowIdsByBPartnerRepoId.put(bpartnerId, rowId); } return rowIdsByBPartnerRepoId.build(); } private List<JsonViewRowGeoLocation> retrieveGeoLocationsForBPartnerId(final ImmutableSetMultimap<BPartnerId, DocumentId> rowIdsByBPartnerId) { if (rowIdsByBPartnerId.isEmpty()) { return ImmutableList.of(); } final List<JsonViewRowGeoLocation> result = new ArrayList<>(); final ImmutableSet<BPartnerId> bpartnerIds = rowIdsByBPartnerId.keySet(); for (final GeographicalCoordinatesWithBPartnerLocationId bplCoordinates : bpartnersRepo.getGeoCoordinatesByBPartnerIds(bpartnerIds)) {
final BPartnerId bpartnerId = bplCoordinates.getBPartnerId(); final ImmutableSet<DocumentId> rowIds = rowIdsByBPartnerId.get(bpartnerId); if (rowIds.isEmpty()) { // shall not happen logger.warn("Ignored unexpected bpartnerId={}. We have no rows for it.", bpartnerId); continue; } final GeographicalCoordinates coordinate = bplCoordinates.getCoordinate(); for (final DocumentId rowId : rowIds) { result.add(JsonViewRowGeoLocation.builder() .rowId(rowId) .latitude(coordinate.getLatitude()) .longitude(coordinate.getLongitude()) .build()); } } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\geo_location\ViewGeoLocationsRestController.java
1
请完成以下Java代码
public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp; } @Override public String toString() { return "UserDetail{" + "id=" + id + ", userId=" + userId + ", age=" + age + ", realName='" + realName + '\'' + ", status='" + status + '\'' + ", hobby='" + hobby + '\'' + ", introduction='" + introduction + '\'' + ", lastLoginIp='" + lastLoginIp + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\model\UserDetail.java
1
请完成以下Java代码
public String getButtonLink() { return getButtonConfigProperty("link"); } @JsonIgnore public void setButtonLink(String buttonLink) { getButtonConfig().ifPresent(buttonConfig -> { buttonConfig.set("link", new TextNode(buttonLink)); }); } private String getButtonConfigProperty(String property) { return getButtonConfig() .map(buttonConfig -> buttonConfig.get(property)) .filter(JsonNode::isTextual) .map(JsonNode::asText).orElse(null); }
private Optional<ObjectNode> getButtonConfig() { return Optional.ofNullable(additionalConfig) .map(config -> config.get("actionButtonConfig")).filter(JsonNode::isObject) .map(config -> (ObjectNode) config); } @Override public NotificationDeliveryMethod getMethod() { return NotificationDeliveryMethod.WEB; } @Override public WebDeliveryMethodNotificationTemplate copy() { return new WebDeliveryMethodNotificationTemplate(this); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\template\WebDeliveryMethodNotificationTemplate.java
1
请完成以下Java代码
private ViewRowIdsOrderedSelections computeOrderBySelectionIfAbsent( @NonNull final ViewRowIdsOrderedSelections selections, @Nullable final DocumentQueryOrderByList orderBys) { return selections.withOrderBysSelectionIfAbsent( orderBys, this::createSelectionFromSelection); } private ViewRowIdsOrderedSelection createSelectionFromSelection( @NonNull final ViewRowIdsOrderedSelection fromSelection, @Nullable final DocumentQueryOrderByList orderBys) { final ViewEvaluationCtx viewEvaluationCtx = getViewEvaluationCtx(); final SqlDocumentFilterConverterContext filterConverterContext = SqlDocumentFilterConverterContext.builder() .userRolePermissionsKey(viewEvaluationCtx.getPermissionsKey()) .build(); return viewDataRepository.createOrderedSelectionFromSelection( viewEvaluationCtx, fromSelection, DocumentFilterList.EMPTY, orderBys, filterConverterContext);
} public Set<DocumentId> retainExistingRowIds(@NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } return viewDataRepository.retrieveRowIdsMatchingFilters( viewId, DocumentFilterList.EMPTY, rowIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelectionsHolder.java
1
请完成以下Java代码
public Boolean isChrgInclInd() { return chrgInclInd; } /** * Sets the value of the chrgInclInd property. * * @param value * allowed object is * {@link Boolean } * */ public void setChrgInclInd(Boolean value) { this.chrgInclInd = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link ChargeType3Choice } * */ public ChargeType3Choice getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link ChargeType3Choice } * */ public void setTp(ChargeType3Choice value) { this.tp = value; } /** * Gets the value of the rate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setRate(BigDecimal value) { this.rate = value; } /** * Gets the value of the br property. * * @return * possible object is * {@link ChargeBearerType1Code } * */ public ChargeBearerType1Code getBr() { return br; } /**
* Sets the value of the br property. * * @param value * allowed object is * {@link ChargeBearerType1Code } * */ public void setBr(ChargeBearerType1Code value) { this.br = value; } /** * Gets the value of the agt property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public BranchAndFinancialInstitutionIdentification5 getAgt() { return agt; } /** * Sets the value of the agt property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public void setAgt(BranchAndFinancialInstitutionIdentification5 value) { this.agt = value; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxCharges2 } * */ public TaxCharges2 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxCharges2 } * */ public void setTax(TaxCharges2 value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\ChargesRecord2.java
1
请完成以下Java代码
public long getQueueSize() { return queueSize; } @Override public void incrementQueueSize() { queueSize++; } @Override public void decrementQueueSize() { queueSize--;
} @Override public long getCountSkipped() { return countSkipped; } @Override public void incrementCountSkipped() { countSkipped++; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorStatistics.java
1
请完成以下Java代码
public class SchemaLogEntryEntity implements SchemaLogEntry, DbEntity, Serializable { private static final long serialVersionUID = 1L; protected String id; protected Date timestamp; protected String version; public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } // persistent object methods //////////////////////////////////////////////// @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id;
} @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("id", this.id); persistentState.put("timestamp", this.timestamp); persistentState.put("version", this.version); return persistentState; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", timestamp=" + timestamp + ", version=" + version + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\SchemaLogEntryEntity.java
1
请完成以下Java代码
public int getKeyAsInt() { Integer keyAsInt = this.keyAsInt; if (keyAsInt == null) { keyAsInt = this.keyAsInt = Integer.parseInt(getKey()); } return keyAsInt; } public IntegerLookupValue toIntegerLookupValue() { return IntegerLookupValue.builder() .id(getKeyAsInt()) .displayName(TranslatableStrings.constant(getCaption())) .attributes(getAttributes()) .active(isActive()) .build(); }
public StringLookupValue toStringLookupValue() { return StringLookupValue.builder() .id(getKey()) .displayName(TranslatableStrings.constant(getCaption())) .attributes(getAttributes()) .active(isActive()) .validationInformation(null) // NOTE: converting back from JSON is not supported nor needed atm .build(); } private boolean isActive() { return active == null || active; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONLookupValue.java
1
请完成以下Java代码
public String toString() { return new StringBuilder("MachineInfo {") .append("app='").append(app).append('\'') .append(",appType='").append(appType).append('\'') .append(", hostname='").append(hostname).append('\'') .append(", ip='").append(ip).append('\'') .append(", port=").append(port) .append(", heartbeatVersion=").append(heartbeatVersion) .append(", lastHeartbeat=").append(lastHeartbeat) .append(", version='").append(version).append('\'') .append(", healthy=").append(isHealthy()) .append('}').toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MachineInfo)) { return false; } MachineInfo that = (MachineInfo)o; return Objects.equals(app, that.app) &&
Objects.equals(ip, that.ip) && Objects.equals(port, that.port); } @Override public int hashCode() { return Objects.hash(app, ip, port); } /** * Information for log * * @return */ public String toLogString() { return app + "|" + ip + "|" + port + "|" + version; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\MachineInfo.java
1
请完成以下Java代码
default String getEmail() { return this.getClaimAsString(StandardClaimNames.EMAIL); } /** * Returns {@code true} if the user's e-mail address has been verified * {@code (email_verified)}, otherwise {@code false}. * @return {@code true} if the user's e-mail address has been verified, otherwise * {@code false} */ default Boolean getEmailVerified() { return this.getClaimAsBoolean(StandardClaimNames.EMAIL_VERIFIED); } /** * Returns the user's gender {@code (gender)}. * @return the user's gender */ default String getGender() { return this.getClaimAsString(StandardClaimNames.GENDER); } /** * Returns the user's birth date {@code (birthdate)}. * @return the user's birth date */ default String getBirthdate() { return this.getClaimAsString(StandardClaimNames.BIRTHDATE); } /** * Returns the user's time zone {@code (zoneinfo)}. * @return the user's time zone */ default String getZoneInfo() { return this.getClaimAsString(StandardClaimNames.ZONEINFO); } /** * Returns the user's locale {@code (locale)}. * @return the user's locale */ default String getLocale() { return this.getClaimAsString(StandardClaimNames.LOCALE); } /** * Returns the user's preferred phone number {@code (phone_number)}. * @return the user's preferred phone number */ default String getPhoneNumber() { return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER); } /**
* Returns {@code true} if the user's phone number has been verified * {@code (phone_number_verified)}, otherwise {@code false}. * @return {@code true} if the user's phone number has been verified, otherwise * {@code false} */ default Boolean getPhoneNumberVerified() { return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED); } /** * Returns the user's preferred postal address {@code (address)}. * @return the user's preferred postal address */ default AddressStandardClaim getAddress() { Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS); return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build() : new DefaultAddressStandardClaim.Builder().build()); } /** * Returns the time the user's information was last updated {@code (updated_at)}. * @return the time the user's information was last updated */ default Instant getUpdatedAt() { return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public User(int id, String name, String email, LocalDateTime createdAt) { this.id = id; this.name = name; this.email = email; this.createdAt = createdAt; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\hateoasvsswagger\model\User.java
1
请完成以下Java代码
public B contentType(String contentType) { return header(JoseHeaderNames.CTY, contentType); } /** * Sets the critical header that indicates which extensions to the JWS/JWE/JWA * specifications are being used that MUST be understood and processed. * @param name the critical header name * @param value the critical header value * @return the {@link AbstractBuilder} */ @SuppressWarnings("unchecked") public B criticalHeader(String name, Object value) { header(name, value); getHeaders().computeIfAbsent(JoseHeaderNames.CRIT, (k) -> new HashSet<String>()); ((Set<String>) getHeaders().get(JoseHeaderNames.CRIT)).add(name); return getThis(); } /** * Sets the header. * @param name the header name * @param value the header value * @return the {@link AbstractBuilder} */ public B header(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.headers.put(name, value); return getThis(); } /** * A {@code Consumer} to be provided access to the headers allowing the ability to * add, replace, or remove. * @param headersConsumer a {@code Consumer} of the headers * @return the {@link AbstractBuilder} */ public B headers(Consumer<Map<String, Object>> headersConsumer) { headersConsumer.accept(this.headers); return getThis();
} /** * Builds a new {@link JoseHeader}. * @return a {@link JoseHeader} */ public abstract T build(); private static URL convertAsURL(String header, String value) { URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class); Assert.notNull(convertedValue, () -> "Unable to convert header '" + header + "' of type '" + value.getClass() + "' to URL."); return convertedValue; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JoseHeader.java
1
请完成以下Java代码
public class PrintingQueueProcessingInfo { /** * -- GETTER -- * Return the<code>AD_User_ID</code>s to be used for printing.<br> * Notes: * <ul> * <li>the IDs are always ordered by their value * <li>the list is never empty because that would mean "nothing to print" and therefore there would be no queue source instance to start with. * </ul> */ private final List<UserId> AD_User_ToPrint_IDs; /** * -- GETTER -- * The user who shall be the printjob's AD_User_ID/contact */ private final UserId AD_User_PrintJob_ID; /** * -- GETTER -- * Returns true if we want the system to create printjob instructions with a dedicated hostKey. * That means that even if the job is created for a certain user, it can only be printed by that user if his/her client connects with the particular key. */ private final boolean createWithSpecificHostKey; public PrintingQueueProcessingInfo(
final UserId aD_User_PrintJob_ID, final ImmutableList<UserId> aD_User_ToPrint_IDs, final boolean createWithSpecificHostKey) { this.AD_User_PrintJob_ID = aD_User_PrintJob_ID; this.AD_User_ToPrint_IDs = ImmutableList.<UserId> copyOf(aD_User_ToPrint_IDs); this.createWithSpecificHostKey = createWithSpecificHostKey; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\PrintingQueueProcessingInfo.java
1
请完成以下Java代码
private I_MSV3_BestellungAntwortPosition createRecord(@NonNull final OrderResponsePackageItem responseItem) { final I_MSV3_BestellungAntwortPosition record = newInstanceOutOfTrx(I_MSV3_BestellungAntwortPosition.class); record.setAD_Org_ID(orgId.getRepoId()); record.setMSV3_BestellLiefervorgabe(responseItem.getDeliverySpecifications().getV2SoapCode().value()); record.setMSV3_BestellMenge(responseItem.getQty().getValueAsInt()); record.setMSV3_BestellPzn(responseItem.getPzn().getValueAsString()); record.setC_PurchaseCandidate_ID(MSV3PurchaseCandidateId.toRepoId(responseItem.getPurchaseCandidateId())); final I_MSV3_Substitution substitutionRecord = Msv3SubstitutionDataPersister.newInstanceWithOrgId(orgId) .storeSubstitutionOrNull(responseItem.getSubstitution()); record.setMSV3_BestellungSubstitution(substitutionRecord); return record; } private I_MSV3_BestellungAnteil createRecord(@NonNull final OrderResponsePackageItemPart anteil) { final I_MSV3_BestellungAnteil bestellungAnteilRecord = newInstanceOutOfTrx(I_MSV3_BestellungAnteil.class); bestellungAnteilRecord.setAD_Org_ID(orgId.getRepoId());
Optional.ofNullable(anteil.getDefectReason()) .map(OrderDefectReason::value) .ifPresent(bestellungAnteilRecord::setMSV3_Grund); bestellungAnteilRecord.setMSV3_Lieferzeitpunkt(TimeUtil.asTimestamp(anteil.getDeliveryDate())); bestellungAnteilRecord.setMSV3_Menge(anteil.getQty().getValueAsInt()); bestellungAnteilRecord.setMSV3_Tourabweichung(anteil.isTourDeviation()); bestellungAnteilRecord.setMSV3_Typ(Type.getValueOrNull(anteil.getType())); return bestellungAnteilRecord; } public MSV3OrderResponsePackageItemPartRepoIds getResponseItemPartRepoIds() { return responseItemPartRepoIds.copyAsImmutable(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\purchaseOrder\MSV3PurchaseOrderResponsePersister.java
1
请完成以下Java代码
public String getNote () { return (String)get_Value(COLUMNNAME_Note); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */
public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_C_DunningRunEntry.java
1
请在Spring Boot框架中完成以下Java代码
public class C_BPartner_Location_QuickInput { private final ILocationDAO locationDAO = Services.get(ILocationDAO.class); private final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); private final BPartnerQuickInputRepository repo; public C_BPartner_Location_QuickInput(final BPartnerQuickInputRepository repo) { this.repo = repo; } @PostConstruct void postConstruct() { final IProgramaticCalloutProvider programmaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programmaticCalloutProvider.registerAnnotatedCallout(this); } @CalloutMethod(columnNames = I_C_BPartner_Location_QuickInput.COLUMNNAME_C_Location_ID) public void onLocationChanged(@NonNull final I_C_BPartner_Location_QuickInput record) { final LocationId id = LocationId.ofRepoIdOrNull(record.getC_Location_ID()); if (id == null) { return; } final I_C_Location locationRecord = locationDAO.getById(id); if (locationRecord == null) { // location not yet created. Nothing to do yet return; } final POInfo poInfo = POInfo.getPOInfo(I_C_BPartner_Location_QuickInput.Table_Name); // gh12157: Please, keep in sync with org.compiere.model.MBPartnerLocation.beforeSave final String name = MakeUniqueLocationNameCommand.builder() .name(record.getName())
.address(locationRecord) .companyName(getCompanyNameOrNull(record)) .existingNames(repo.getOtherLocationNames(record.getC_BPartner_QuickInput_ID(), record.getC_BPartner_Location_QuickInput_ID())) .maxLength(poInfo.getFieldLength(I_C_BPartner_Location_QuickInput.COLUMNNAME_Name)) .build() .execute(); record.setName(name); } @Nullable private String getCompanyNameOrNull(@NonNull final I_C_BPartner_Location_QuickInput record) { final BPartnerQuickInputId bpartnerQuickInputId = BPartnerQuickInputId.ofRepoIdOrNull(record.getC_BPartner_QuickInput_ID()); if (bpartnerQuickInputId != null) { final I_C_BPartner_QuickInput bpartnerQuickInputRecord = repo.getById(bpartnerQuickInputId); return bpartnerQuickInputRecord.getCompanyname(); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\callout\C_BPartner_Location_QuickInput.java
2
请在Spring Boot框架中完成以下Java代码
public class C_Project_StartRepairOrder extends ServiceOrRepairProjectBasedProcess implements IProcessPrecondition { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { final List<ServiceRepairProjectTask> tasks = getSelectedTasks(context) .stream() .filter(this::isEligible) .collect(ImmutableList.toImmutableList()); if (tasks.isEmpty()) { return ProcessPreconditionsResolution.rejectWithInternalReason("no eligible tasks found"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final List<ServiceRepairProjectTask> tasks = getSelectedTasks() .stream() .filter(this::isEligible) .collect(ImmutableList.toImmutableList());
if (tasks.isEmpty()) { throw new AdempiereException("@NoSelection@"); } projectService.createRepairOrders(tasks); return MSG_OK; } private boolean isEligible(@NonNull final ServiceRepairProjectTask task) { return ServiceRepairProjectTaskType.REPAIR_ORDER.equals(task.getType()) && ServiceRepairProjectTaskStatus.NOT_STARTED.equals(task.getStatus()) && task.getRepairOrderId() == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\C_Project_StartRepairOrder.java
2
请完成以下Java代码
/* package */class OrderLinePackingMaterialDocumentLine extends AbstractPackingMaterialDocumentLine { private final I_C_OrderLine orderLine; public OrderLinePackingMaterialDocumentLine(@NonNull final org.compiere.model.I_C_OrderLine orderLine) { this.orderLine = InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class); Check.assume(this.orderLine.isPackagingMaterial(), "Orderline shall have PackingMaterial flag set: {}", this.orderLine); } public I_C_OrderLine getC_OrderLine() { return orderLine; } @Override public ProductId getProductId() { return ProductId.ofRepoId(orderLine.getM_Product_ID()); } private I_C_UOM getUOM() { return Services.get(IUOMDAO.class).getById(orderLine.getC_UOM_ID()); } /** * @returns QtyOrdered of the wrapped order line */
@Override public BigDecimal getQty() { return orderLine.getQtyOrdered(); } /** * Sets both QtyOrdered and QtyEntered of the wrapped order line. * * @param qtyOrdered ordered quantity in stock UOM, which is also converted to qtyEntered. */ @Override protected void setQty(final BigDecimal qtyOrdered) { orderLine.setQtyOrdered(qtyOrdered); final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class); final Quantity qtyInStockUOM = Quantitys.of(qtyOrdered, ProductId.ofRepoId(orderLine.getM_Product_ID())); final Quantity qtyEntered = orderLineBL.convertQtyToUOM(qtyInStockUOM, orderLine); orderLine.setQtyEntered(qtyEntered.toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\OrderLinePackingMaterialDocumentLine.java
1
请完成以下Java代码
public IdentityLinkQueryObject getInvolvedUserIdentityLink() { return involvedUserIdentityLink; } public IdentityLinkQueryObject getInvolvedGroupIdentityLink() { return involvedGroupIdentityLink; } public Set<String> getInvolvedGroups() { return involvedGroups; } public boolean isIncludeCaseVariables() { return includeCaseVariables; } public Collection<String> getVariableNamesToInclude() { return variableNamesToInclude; } public boolean isNeedsCaseDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(CaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName()); }
public List<CaseInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) { this.safeCaseInstanceIds = safeCaseInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceQueryImpl.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Set<Book> getBooks() { return books; } public void setBooks(Set<Book> books) { this.books = books; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Author) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCloneEntity\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (!this.requestMatcher.matches(request)) { chain.doFilter(request, response); return; } this.requestCache.saveRequest(request, response); HttpSession session = request.getSession(true); session.setAttribute(CAS_GATEWAY_AUTHENTICATION_ATTR, true); String urlEncodedService = WebUtils.constructServiceUrl(request, response, this.serviceProperties.getService(), null, this.serviceProperties.getServiceParameter(), this.serviceProperties.getArtifactParameter(), true); String redirectUrl = CommonUtils.constructRedirectUrl(this.casLoginUrl, this.serviceProperties.getServiceParameter(), urlEncodedService, false, true); this.redirectStrategy.sendRedirect(request, response, redirectUrl); } /** * Sets the {@link RequestMatcher} used to trigger this filter. Defaults to * {@link CasGatewayResolverRequestMatcher}. * @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } /** * Sets the {@link RequestCache} used to store the current request to be replayed * after redirect from the CAS server. Defaults to {@link HttpSessionRequestCache}. * @param requestCache the {@link RequestCache} to use */ public void setRequestCache(RequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasGatewayAuthenticationRedirectFilter.java
1
请完成以下Java代码
private BooleanWithReason checkValid() { boolean valid = true; final StringBuilder notValidReasonCollector = new StringBuilder(); // From final EMailAddress from = getFrom(); if (!isValidAddress(from)) { final String errmsg = "No From address"; if (notValidReasonCollector.length() > 0) { notValidReasonCollector.append("; "); } notValidReasonCollector.append(errmsg); valid = false; } // To final List<InternetAddress> toList = getTos(); if (toList.isEmpty()) { final String errmsg = "No To addresses"; if (notValidReasonCollector.length() > 0) { notValidReasonCollector.append("; "); } notValidReasonCollector.append(errmsg); valid = false; } else { for (final InternetAddress to : toList) { if (!isValidAddress(to)) { final String errmsg = "To address is invalid (" + to + ")"; if (notValidReasonCollector.length() > 0) { notValidReasonCollector.append("; "); } notValidReasonCollector.append(errmsg); valid = false; } } } // Subject final String subject = getSubject(); if (Check.isEmpty(subject, true)) { final String errmsg = "Subject is empty"; if (notValidReasonCollector.length() > 0) { notValidReasonCollector.append("; "); } notValidReasonCollector.append(errmsg); valid = false; } return valid ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause(notValidReasonCollector.toString()); } private static boolean isValidAddress(final EMailAddress emailAddress) { if (emailAddress == null) {
return false; } try { return isValidAddress(emailAddress.toInternetAddress()); } catch (final AddressException e) { return false; } } private static boolean isValidAddress(final InternetAddress emailAddress) { if (emailAddress == null) { return false; } final String addressStr = emailAddress.getAddress(); return addressStr != null && !addressStr.isEmpty() && addressStr.indexOf(' ') < 0; } /** * @return attachments array or empty array. This method will never return null. */ public List<EMailAttachment> getAttachments() { return ImmutableList.copyOf(_attachments); } /** * Do send the mail to the respective mail address, even if the {@code DebugMailTo} SysConfig is set. */ public void forceRealEmailRecipients() { _forceRealEmailRecipients = true; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("to", _to) .add("cc", _cc.isEmpty() ? null : _cc) .add("bcc", _bcc.isEmpty() ? null : _bcc) .add("replyTo", _replyTo) .add("subject", _subject) .add("attachments", _attachments.isEmpty() ? null : _attachments) .add("mailbox", _mailbox) .toString(); } } // EMail
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMail.java
1
请完成以下Java代码
public void setPostal (String Postal) { set_Value (COLUMNNAME_Postal, Postal); } /** Get ZIP. @return Postal code */ public String getPostal () { return (String)get_Value(COLUMNNAME_Postal); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getPostal()); }
/** Set ZIP To. @param Postal_To Postal code to */ public void setPostal_To (String Postal_To) { set_Value (COLUMNNAME_Postal_To, Postal_To); } /** Get ZIP To. @return Postal code to */ public String getPostal_To () { return (String)get_Value(COLUMNNAME_Postal_To); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxPostal.java
1
请在Spring Boot框架中完成以下Java代码
private void buildToStringProperty(StringBuilder string, String property, Object value) { if (value != null) { string.append(" ").append(property).append(":").append(value); } } @Override public int compareTo(ItemMetadata o) { return getName().compareTo(o.getName()); } public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) { return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null); } public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType, String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description, defaultValue, deprecation); } public static String newItemMetadataPrefix(String prefix, String suffix) { return prefix.toLowerCase(Locale.ENGLISH) + ConventionUtils.toDashedCase(suffix); } /** * The item type. */
public enum ItemType { /** * Group item type. */ GROUP, /** * Property item type. */ PROPERTY } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemMetadata.java
2
请完成以下Java代码
public Balance negateAndInvert() { return new Balance(this.credit.negate(), this.debit.negate()); } public Balance negateAndInvertIf(final boolean condition) { return condition ? negateAndInvert() : this; } public Balance toSingleSide() { final Money min = debit.min(credit); if (min.isZero()) { return this; } return new Balance(this.debit.subtract(min), this.credit.subtract(min)); } public Balance computeDiffToBalance() { final Money diff = toMoney(); if (isReversal()) { return diff.signum() < 0 ? ofCredit(diff) : ofDebit(diff.negate()); } else { return diff.signum() < 0 ? ofDebit(diff.negate()) : ofCredit(diff); } } public Balance invert() { return new Balance(this.credit, this.debit); } // // // // // @ToString private static class BalanceBuilder { private Money debit; private Money credit; public void add(@NonNull Balance balance) { add(balance.getDebit(), balance.getCredit()); }
public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder) { add(balanceBuilder.debit, balanceBuilder.credit); return this; } public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd) { if (debitToAdd != null) { this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd; } if (creditToAdd != null) { this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd; } } public Optional<Balance> build() { return debit != null || credit != null ? Optional.of(new Balance(debit, credit)) : Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Other SQL Clause. @param OtherClause Other SQL Clause */ public void setOtherClause (String OtherClause) { set_Value (COLUMNNAME_OtherClause, OtherClause); } /** Get Other SQL Clause. @return Other SQL Clause */ public String getOtherClause () { return (String)get_Value(COLUMNNAME_OtherClause); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ContainerTTable.java
1
请在Spring Boot框架中完成以下Java代码
public void setUsername(String username) { this.username = username; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public LocalDate getTargetDate() { return targetDate; } public void setTargetDate(LocalDate targetDate) { this.targetDate = targetDate; }
public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } @Override public String toString() { return "Todo [id=" + id + ", username=" + username + ", description=" + description + ", targetDate=" + targetDate + ", done=" + done + "]"; } }
repos\master-spring-and-spring-boot-main\91-aws\03-rest-api-full-stack-h2\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\todo\Todo.java
2
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set UPC/EAN. @param UPC Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number) */ @Override public void setUPC (java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } /** Get UPC/EAN. @return Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number) */ @Override public java.lang.String getUPC () { return (java.lang.String)get_Value(COLUMNNAME_UPC); } /** Set Verwendet für Kunden.
@param UsedForCustomer Verwendet für Kunden */ @Override public void setUsedForCustomer (boolean UsedForCustomer) { set_Value (COLUMNNAME_UsedForCustomer, Boolean.valueOf(UsedForCustomer)); } /** Get Verwendet für Kunden. @return Verwendet für Kunden */ @Override public boolean isUsedForCustomer () { Object oo = get_Value(COLUMNNAME_UsedForCustomer); 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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_EDI_M_Product_Lookup_UPC_v.java
1
请在Spring Boot框架中完成以下Java代码
class BookingTicketsController { private final TicketBookingCommandHandler bookedTickets; BookingTicketsController(TicketBookingCommandHandler bookedTicketService) { this.bookedTickets = bookedTicketService; } /* curl -X POST http://localhost:8080/api/ticket-booking ^ -H "Content-Type: application/json" ^ -d "{\"id\": 1, \"seat\": \"A1\"}" */ @PostMapping BookingResponse bookTicket(@RequestBody BookTicket request) { long id = bookedTickets.bookTicket(request); return new BookingResponse(id); } record BookingResponse(Long bookingId) { } /*
curl -X DELETE http://localhost:8080/api/ticket-booking/1 */ @DeleteMapping("/{movieId}") CancellationResponse cancelBooking(@PathVariable Long movieId) { long id = bookedTickets.cancelTicket(new CancelTicket(movieId)); return new CancellationResponse(id); } record CancellationResponse(Long cancellationId) { } @ExceptionHandler public ResponseEntity handleException(Exception e) { return ResponseEntity.badRequest() .body(new ErrorResponse(e.getMessage())); } public record ErrorResponse(String error) { } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\java\com\baeldung\spring\modulith\cqrs\ticket\BookingTicketsController.java
2
请完成以下Java代码
public int getPP_Order_IssueSchedule_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_IssueSchedule_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 setQtyIssued (final BigDecimal QtyIssued) { set_Value (COLUMNNAME_QtyIssued, QtyIssued); } @Override public BigDecimal getQtyIssued() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyIssued); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReject (final @Nullable BigDecimal QtyReject) { set_Value (COLUMNNAME_QtyReject, QtyReject); } @Override public BigDecimal getQtyReject() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToIssue (final BigDecimal QtyToIssue) {
set_ValueNoCheck (COLUMNNAME_QtyToIssue, QtyToIssue); } @Override public BigDecimal getQtyToIssue() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_ValueNoCheck (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_IssueSchedule.java
1
请在Spring Boot框架中完成以下Java代码
public SampleOidEntity read(Request request, Response response) { String id = request.getHeader(Constants.Url.SAMPLE_ID, "No resource ID supplied"); SampleOidEntity entity = service.read(Identifiers.MONGOID.parse(id)); return entity; } public List<SampleOidEntity> readAll(Request request, Response response) { QueryFilter filter = QueryFilters.parseFrom(request); QueryOrder order = QueryOrders.parseFrom(request); QueryRange range = QueryRanges.parseFrom(request, 20); List<SampleOidEntity> entities = service.readAll(filter, range, order); long count = service.count(filter); response.setCollectionResponse(range, entities.size(), count); return entities;
} public void update(Request request, Response response) { String id = request.getHeader(Constants.Url.SAMPLE_ID, "No resource ID supplied"); SampleOidEntity entity = request.getBodyAs(SampleOidEntity.class, "Resource details not provided"); entity.setId(Identifiers.MONGOID.parse(id)); service.update(entity); response.setResponseNoContent(); } public void delete(Request request, Response response) { String id = request.getHeader(Constants.Url.SAMPLE_ID, "No resource ID supplied"); service.delete(Identifiers.MONGOID.parse(id)); response.setResponseNoContent(); } }
repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\objectid\SampleOidEntityController.java
2
请完成以下Java代码
public class Email { private Integer id; private Integer employeeId; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Email{" + "id=" + id + ", address=" + address + '}'; } }
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\dbutils\Email.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonResponseComposite { @ApiModelProperty(required = true, value = "The `AD_Org.Value` of the `C_BPartner`'s AD_Org_ID") @JsonInclude(Include.NON_NULL) String orgCode; JsonResponseBPartner bpartner; @ApiModelProperty(value = "The location's GLN can be used to lookup the whole bpartner; if nultiple locations with GLN are provided, then only the first one is used") @JsonInclude(Include.NON_EMPTY) List<JsonResponseLocation> locations; @JsonInclude(Include.NON_EMPTY) List<JsonResponseContact> contacts; @Builder(toBuilder = true) @JsonCreator private JsonResponseComposite( @JsonProperty("orgCode") @NonNull final String orgCode, @JsonProperty("bpartner") @NonNull final JsonResponseBPartner bpartner, @JsonProperty("locations") @Singular final List<JsonResponseLocation> locations, @JsonProperty("contacts") @Singular final List<JsonResponseContact> contacts) { this.orgCode = orgCode; this.bpartner = bpartner; this.locations = coalesce(locations, ImmutableList.of()); this.contacts = coalesce(contacts, ImmutableList.of()); final boolean lokupValuesAreOk = !EmptyUtil.isEmpty(bpartner.getCode(), true) || bpartner.getExternalId() != null || !extractLocationGlns().isEmpty(); if (!lokupValuesAreOk) { throw new RuntimeException("At least one of bpartner.code, bpartner.externalId or one location.gln needs to be non-empty; this=" + this); } }
public ImmutableList<String> extractLocationGlns() { return this.locations .stream() .map(JsonResponseLocation::getGln) .filter(gln -> !EmptyUtil.isEmpty(gln, true)) .collect(ImmutableList.toImmutableList()); } public JsonResponseComposite withExternalId(@NonNull final JsonExternalId externalId) { if (Objects.equals(externalId, bpartner.getExternalId())) { return this; // nothing to do } return toBuilder() .bpartner(bpartner.toBuilder().externalId(externalId).build()) .build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\response\JsonResponseComposite.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "string", value = "Type of the variable.", notes = "When writing a variable and this value is omitted, the type will be deducted from the raw JSON-attribute request type and is limited to either string, double, integer and boolean. It’s advised to always include a type to make sure no wrong assumption about the type can be done. Some known types are: string, integer, long, short, double, instant, date, localDate, localDateTime, boolean, json") @JsonInclude(JsonInclude.Include.NON_NULL) public String getType() { return type; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "test", value = "Value of the variable.", notes = "When writing a variable and value is omitted, null will be used as value.") public Object getValue() { return value;
} public void setValue(Object value) { this.value = value; } @ApiModelProperty(example = "http://....", notes = "When reading a variable of type binary or serializable, this attribute will point to the URL where the raw binary data can be fetched from.") public void setValueUrl(String valueUrl) { this.valueUrl = valueUrl; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getValueUrl() { return valueUrl; } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\EngineRestVariable.java
1
请完成以下Java代码
public class JdkDto { protected String version; protected String vendor; public JdkDto(String vendor, String version) { this.version = version; this.vendor = vendor; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version;
} public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public static JdkDto fromEngineDto(Jdk other) { return new JdkDto( other.getVendor(), other.getVersion()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\JdkDto.java
1
请完成以下Java代码
private String computeJson() { return elements.stream() .map(ContextPathElement::toJson) .collect(Collectors.joining(".")); } public ContextPath newChild(@NonNull final String name) { return newChild(ContextPathElement.ofName(name)); } public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor) { return newChild(ContextPathElement.ofNameAndId( extractName(entityDescriptor), AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull()) )); } private ContextPath newChild(@NonNull final ContextPathElement element) { return new ContextPath(ImmutableList.<ContextPathElement>builder() .addAll(elements) .add(element) .build()); } public AdWindowId getAdWindowId() { return AdWindowId.ofRepoId(elements.get(0).getId()); } @Override public int compareTo(@NonNull final ContextPath other) { return toJson().compareTo(other.toJson()); } } @Value class ContextPathElement { @NonNull String name; int id; @JsonCreator public static ContextPathElement ofJson(@NonNull final String json) { try
{ final int idx = json.indexOf("/"); if (idx > 0) { String name = json.substring(0, idx); int id = Integer.parseInt(json.substring(idx + 1)); return new ContextPathElement(name, id); } else { return new ContextPathElement(json, -1); } } catch (final Exception ex) { throw new AdempiereException("Failed parsing: " + json, ex); } } public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);} public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);} @Override public String toString() {return toJson();} @JsonValue public String toJson() {return id > 0 ? name + "/" + id : name;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java
1
请完成以下Java代码
boolean matches(String content) { return content.replaceAll("\\s", "").contains("\"bomFormat\":\"CycloneDX\""); } }, SPDX(MimeType.valueOf("application/spdx+json")) { @Override boolean matches(String content) { return content.contains("\"spdxVersion\""); } }, SYFT(MimeType.valueOf("application/vnd.syft+json")) { @Override boolean matches(String content) { return content.contains("\"FoundBy\"") || content.contains("\"foundBy\""); } }, UNKNOWN(null) { @Override boolean matches(String content) { return false;
} }; private final @Nullable MimeType mediaType; SbomType(@Nullable MimeType mediaType) { this.mediaType = mediaType; } @Nullable MimeType getMediaType() { return this.mediaType; } abstract boolean matches(String content); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomEndpointWebExtension.java
1
请完成以下Java代码
public TbMsgBuilder ruleNodeId(RuleNodeId ruleNodeId) { this.ruleNodeId = ruleNodeId; return this; } public TbMsgBuilder resetRuleNodeId() { return ruleNodeId(null); } public TbMsgBuilder correlationId(UUID correlationId) { this.correlationId = correlationId; return this; } public TbMsgBuilder partition(Integer partition) { this.partition = partition; return this; } public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds); return this; } public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) { this.ctx = ctx; return this; }
public TbMsgBuilder callback(TbMsgCallback callback) { this.callback = callback; return this; } public TbMsg build() { return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback); } public String toString() { return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts + ", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator + ", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType + ", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId + ", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds + ", ctx=" + this.ctx + ", callback=" + this.callback + ")"; } } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java
1
请完成以下Java代码
public GridFieldVOsLoader setAdWindowId(@Nullable final AdWindowId adWindowId) { _adWindowId = adWindowId; return this; } private AdWindowId getAD_Window_ID() { return _adWindowId; } public GridFieldVOsLoader setAD_Tab_ID(final int AD_Tab_ID) { _adTabId = AD_Tab_ID; return this; } public GridFieldVOsLoader setTemplateTabId(int templateTabId) { this._templateTabId = templateTabId; return this; } private int getAD_Tab_ID() { return _adTabId; } private int getTemplateTabIdEffective() { return _templateTabId > 0 ? _templateTabId : getAD_Tab_ID(); } public GridFieldVOsLoader setTabIncludeFiltersStrategy(@NonNull final TabIncludeFiltersStrategy tabIncludeFiltersStrategy) { this.tabIncludeFiltersStrategy = tabIncludeFiltersStrategy; return this; } public GridFieldVOsLoader setTabReadOnly(final boolean tabReadOnly) { _tabReadOnly = tabReadOnly; return this; }
private boolean isTabReadOnly() { return _tabReadOnly; } public GridFieldVOsLoader setLoadAllLanguages(final boolean loadAllLanguages) { _loadAllLanguages = loadAllLanguages; return this; } private boolean isLoadAllLanguages() { return _loadAllLanguages; } public GridFieldVOsLoader setApplyRolePermissions(final boolean applyRolePermissions) { this._applyRolePermissions = applyRolePermissions; return this; } private boolean isApplyRolePermissions() { return _applyRolePermissions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVOsLoader.java
1
请完成以下Java代码
protected UserDetailsChecker getPreAuthenticationChecks() { return this.preAuthenticationChecks; } /** * Sets the policy will be used to verify the status of the loaded * <tt>UserDetails</tt> <em>before</em> validation of the credentials takes place. * @param preAuthenticationChecks strategy to be invoked prior to authentication. */ public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) { this.preAuthenticationChecks = preAuthenticationChecks; } protected UserDetailsChecker getPostAuthenticationChecks() { return this.postAuthenticationChecks; } public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) { this.postAuthenticationChecks = postAuthenticationChecks; } public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { this.authoritiesMapper = authoritiesMapper; } private class DefaultPreAuthenticationChecks implements UserDetailsChecker { @Override public void check(UserDetails user) { if (!user.isAccountNonLocked()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account is locked"); throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } if (!user.isEnabled()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account is disabled"); throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account has expired"); throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired")); } } } private class DefaultPostAuthenticationChecks implements UserDetailsChecker { @Override public void check(UserDetails user) { if (!user.isCredentialsNonExpired()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account credentials have expired"); throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\dao\AbstractUserDetailsAuthenticationProvider.java
1
请完成以下Java代码
default <R> R process(final Function<IHUContext, R> procesor) { final Mutable<R> resultHolder = new Mutable<>(); createHUContextProcessorExecutor().run(huContext -> { final R result = procesor.apply(huContext); resultHolder.setValue(result); }); return resultHolder.getValue(); } /** * Iterate the {@link IHUTransactionCandidate}s that were added so far and aggregate those that only differ in their quantity. * In other words, group the them by their properties (besides qty) and store a new list with summed-up qtys. The new candidates have unique properties. */ List<IHUTransactionCandidate> aggregateTransactions(List<IHUTransactionCandidate> transactions); static I_C_UOM extractUOMOrNull(@NonNull final I_M_HU_Trx_Line trxLine) {
final UomId uomId = UomId.ofRepoIdOrNull(trxLine.getC_UOM_ID()); return uomId != null ? Services.get(IUOMDAO.class).getById(uomId) : null; } static I_M_Product extractProductOrNull(@NonNull final I_M_HU_Trx_Line trxLine) { final ProductId productId = extractProductId(trxLine); return productId != null ? Services.get(IProductDAO.class).getById(productId) : null; } @Nullable static ProductId extractProductId(@NotNull final I_M_HU_Trx_Line trxLine) { return ProductId.ofRepoIdOrNull(trxLine.getM_Product_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\IHUTrxBL.java
1
请完成以下Java代码
public boolean open(InputStream stream, int nbest, int vlevel, double costFactor) { featureIndex_ = new DecoderFeatureIndex(); nbest_ = nbest; vlevel_ = vlevel; if (costFactor > 0) { featureIndex_.setCostFactor_(costFactor); } return featureIndex_.open(stream); } public boolean open(String model, int nbest, int vlevel, double costFactor) { try { InputStream stream = IOUtil.newInputStream(model); return open(stream, nbest, vlevel, costFactor); } catch (Exception e) { return false; } } public String getTemplate() { if (featureIndex_ != null) { return featureIndex_.getTemplate(); } else { return null; } } public int getNbest_() { return nbest_; } public void setNbest_(int nbest_)
{ this.nbest_ = nbest_; } public int getVlevel_() { return vlevel_; } public void setVlevel_(int vlevel_) { this.vlevel_ = vlevel_; } public DecoderFeatureIndex getFeatureIndex_() { return featureIndex_; } public void setFeatureIndex_(DecoderFeatureIndex featureIndex_) { this.featureIndex_ = featureIndex_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\ModelImpl.java
1
请完成以下Java代码
private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions() { return allowedViewCloseActions != null ? ImmutableSet.copyOf(allowedViewCloseActions) : DEFAULT_allowedViewCloseActions; } public Builder setHasTreeSupport(final boolean hasTreeSupport) { this.hasTreeSupport = hasTreeSupport; return this; } public Builder setTreeCollapsible(final boolean treeCollapsible) { this.treeCollapsible = treeCollapsible; return this; }
public Builder setTreeExpandedDepth(final int treeExpandedDepth) { this.treeExpandedDepth = treeExpandedDepth; return this; } public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails) { this.allowOpeningRowDetails = allowOpeningRowDetails; return this; } public Builder setFocusOnFieldName(final String focusOnFieldName) { this.focusOnFieldName = focusOnFieldName; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java
1
请完成以下Java代码
public Amount convertToRelativeValue(@NonNull final Amount realValue) { final int toRelativeValueMultiplier = getToRelativeValueMultiplier(); return toRelativeValueMultiplier > 0 ? realValue : realValue.negate(); } public boolean isNegateToConvertToRealValue() { return getToRealValueMultiplier() < 0; } private int getToRealValueMultiplier() { int toRealValueMultiplier = this.toRealValueMultiplier; if (toRealValueMultiplier == 0) { toRealValueMultiplier = this.toRealValueMultiplier = computeToRealValueMultiplier(); } return toRealValueMultiplier; } private int computeToRealValueMultiplier() { int multiplier = 1; // Adjust by SOTrx if needed if (!isAPAdjusted) { final int multiplierAP = soTrx.isPurchase() ? -1 : +1; multiplier *= multiplierAP; } // Adjust by Credit Memo if needed if (!isCreditMemoAdjusted) { final int multiplierCM = isCreditMemo ? -1 : +1; multiplier *= multiplierCM; } return multiplier; } private int getToRelativeValueMultiplier() { // NOTE: the relative->real and real->relative value multipliers are the same return getToRealValueMultiplier(); } public Money fromNotAdjustedAmount(@NonNull final Money money) { final int multiplier = computeFromNotAdjustedAmountMultiplier(); return multiplier > 0 ? money : money.negate(); } private int computeFromNotAdjustedAmountMultiplier() { int multiplier = 1;
// Do we have to SO adjust? if (isAPAdjusted) { final int multiplierAP = soTrx.isPurchase() ? -1 : +1; multiplier *= multiplierAP; } // Do we have to adjust by Credit Memo? if (isCreditMemoAdjusted) { final int multiplierCM = isCreditMemo ? -1 : +1; multiplier *= multiplierCM; } return multiplier; } /** * @return {@code true} for purchase-invoice and sales-creditmemo. {@code false} otherwise. */ public boolean isOutgoingMoney() { return isCreditMemo ^ soTrx.isPurchase(); } public InvoiceAmtMultiplier withAPAdjusted(final boolean isAPAdjustedNew) { return isAPAdjusted == isAPAdjustedNew ? this : toBuilder().isAPAdjusted(isAPAdjustedNew).build().intern(); } public InvoiceAmtMultiplier withCMAdjusted(final boolean isCreditMemoAdjustedNew) { return isCreditMemoAdjusted == isCreditMemoAdjustedNew ? this : toBuilder().isCreditMemoAdjusted(isCreditMemoAdjustedNew).build().intern(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceAmtMultiplier.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getUserId() { return userId;
} public void setUserId(String userId) { this.userId = userId; } @Override public String toString() { return "LocationEntity{" + "id='" + id + '\'' + ", location='" + location + '\'' + ", name='" + name + '\'' + ", phone='" + phone + '\'' + ", postCode='" + postCode + '\'' + ", userId='" + userId + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\LocationEntity.java
2
请完成以下Java代码
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; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getNewsContent() { return newsContent; } public void setNewsContent(String newsContent) {
this.newsContent = newsContent; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", newsId=").append(newsId); sb.append(", newsTitle=").append(newsTitle); sb.append(", newsCategoryId=").append(newsCategoryId); sb.append(", newsCoverImage=").append(newsCoverImage); sb.append(", newsStatus=").append(newsStatus); sb.append(", newsViews=").append(newsViews); sb.append(", isDeleted=").append(isDeleted); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\News.java
1
请完成以下Java代码
public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } @Override public void addEventListener(ActivitiEventListener listenerToAdd) { eventSupport.addEventListener(listenerToAdd); } @Override public void addEventListener(ActivitiEventListener listenerToAdd, ActivitiEventType... types) { eventSupport.addEventListener(listenerToAdd, types); } @Override public void removeEventListener(ActivitiEventListener listenerToRemove) { eventSupport.removeEventListener(listenerToRemove); } @Override public void dispatchEvent(ActivitiEvent event) { if (enabled) { eventSupport.dispatchEvent(event); } if (event.getType() == ActivitiEventType.ENTITY_DELETED && event instanceof ActivitiEntityEvent) { ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event; if (entityEvent.getEntity() instanceof ProcessDefinition) { // process definition deleted event doesn't need to be dispatched to event listeners return; } } // Try getting hold of the Process definition, based on the process definition key, if a context is active CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { BpmnModel bpmnModel = extractBpmnModelFromEvent(event);
if (bpmnModel != null) { ((ActivitiEventSupport) bpmnModel.getEventSupport()).dispatchEvent(event); } } } /** * In case no process-context is active, this method attempts to extract a process-definition based on the event. In case it's an event related to an entity, this can be deducted by inspecting the * entity, without additional queries to the database. * * If not an entity-related event, the process-definition will be retrieved based on the processDefinitionId (if filled in). This requires an additional query to the database in case not already * cached. However, queries will only occur when the definition is not yet in the cache, which is very unlikely to happen, unless evicted. * * @param event * @return */ protected BpmnModel extractBpmnModelFromEvent(ActivitiEvent event) { BpmnModel result = null; if (result == null && event.getProcessDefinitionId() != null) { ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition( event.getProcessDefinitionId(), true ); if (processDefinition != null) { result = Context.getProcessEngineConfiguration() .getDeploymentManager() .resolveProcessDefinition(processDefinition) .getBpmnModel(); } } return result; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventDispatcherImpl.java
1
请完成以下Java代码
public Class<?> getStubClass() { return this.stubClazz; } public GrpcClient getClient() { return this.client; } public Class<?> getTargetClazz() { return this.targetClazz; } public BeanDefinition getTargetBeanDefinition() { return this.targetBeanDefinition; } public int getConstructorArgumentIndex() { return this.constructorArgumentIndex; } }
public List<Registry> getRegistries() { return this.injections; } public GrpcClientConstructorInjection add(final Registry injection) { this.injections.add(injection); return this; } public boolean isEmpty() { return this.injections.isEmpty(); } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\inject\GrpcClientConstructorInjection.java
1
请完成以下Java代码
public final boolean isHighVolume() { // NOTE: method will never be called because isCached() == true return false; } @Override public LookupSource getLookupSourceType() { return LookupSource.list; } @Override public boolean hasParameters() { return !getDependsOnFieldNames().isEmpty(); } @Override public abstract boolean isNumericKey(); @Override public abstract Set<String> getDependsOnFieldNames(); // // // // ----------------------- // // @Override public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return LookupDataSourceContext.builderWithoutTableName(); } @Override @Nullable public abstract LookupValue retrieveLookupValueById(@NonNull LookupDataSourceContext evalCtx); @Override public LookupDataSourceContext.Builder newContextForFetchingList() { return LookupDataSourceContext.builderWithoutTableName(); } @Override public abstract LookupValuesPage retrieveEntities(LookupDataSourceContext evalCtx);
@Override @Nullable public final String getCachePrefix() { // NOTE: method will never be called because isCached() == true return null; } @Override public final boolean isCached() { return true; } @Override public void cacheInvalidate() { } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\SimpleLookupDescriptorTemplate.java
1
请完成以下Java代码
public void setGlueSource(String glueSource) { this.glueSource = glueSource; } public String getGlueRemark() { return glueRemark; } public void setGlueRemark(String glueRemark) { this.glueRemark = glueRemark; } public Date getGlueUpdatetime() { return glueUpdatetime; } public void setGlueUpdatetime(Date glueUpdatetime) { this.glueUpdatetime = glueUpdatetime; } public String getChildJobId() { return childJobId; } public void setChildJobId(String childJobId) { this.childJobId = childJobId;
} public int getTriggerStatus() { return triggerStatus; } public void setTriggerStatus(int triggerStatus) { this.triggerStatus = triggerStatus; } public long getTriggerLastTime() { return triggerLastTime; } public void setTriggerLastTime(long triggerLastTime) { this.triggerLastTime = triggerLastTime; } public long getTriggerNextTime() { return triggerNextTime; } public void setTriggerNextTime(long triggerNextTime) { this.triggerNextTime = triggerNextTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java
1
请完成以下Java代码
public String getMake() { return make; } public int getYear() { return year; } /** * Standard implementation of equals() for value equality. */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Car car = (Car) obj; // Use Objects.equals for safe String comparison return year == car.year && Objects.equals(make, car.make); } /** * Standard implementation of hashCode() based on make and year. */ @Override public int hashCode() { return Objects.hash(make, year); }
/** * Standard implementation of toString() for debugging and logging. */ @Override public String toString() { return "Car{" + "make='" + make + '\'' + ", year=" + year + '}'; } /** * Overrides the protected clone() method from Object to perform a shallow copy. * This is the standard pattern when implementing the Cloneable marker interface. */ @Override public Object clone() throws CloneNotSupportedException { // Calls Object's native clone() method return super.clone(); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\objectclassguide\Car.java
1
请在Spring Boot框架中完成以下Java代码
AnnotatedControllerConfigurer annotatedControllerConfigurer( @Qualifier(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) ObjectProvider<Executor> executorProvider, ObjectProvider<HandlerMethodArgumentResolver> argumentResolvers) { AnnotatedControllerConfigurer controllerConfigurer = new AnnotatedControllerConfigurer(); controllerConfigurer .configureBinder((options) -> options.conversionService(ApplicationConversionService.getSharedInstance())); executorProvider.ifAvailable(controllerConfigurer::setExecutor); argumentResolvers.orderedStream().forEach(controllerConfigurer::addCustomArgumentResolver); return controllerConfigurer; } @Bean DataFetcherExceptionResolver annotatedControllerConfigurerDataFetcherExceptionResolver( AnnotatedControllerConfigurer annotatedControllerConfigurer) { return annotatedControllerConfigurer.getExceptionResolver(); } @ConditionalOnClass(ScrollPosition.class) @Configuration(proxyBeanMethods = false) static class GraphQlDataAutoConfiguration { @Bean @ConditionalOnMissingBean EncodingCursorStrategy<ScrollPosition> cursorStrategy() { return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64()); } @Bean @SuppressWarnings("unchecked") GraphQlSourceBuilderCustomizer cursorStrategyCustomizer(CursorStrategy<?> cursorStrategy) { if (cursorStrategy.supports(ScrollPosition.class)) {
CursorStrategy<ScrollPosition> scrollCursorStrategy = (CursorStrategy<ScrollPosition>) cursorStrategy; ConnectionFieldTypeVisitor connectionFieldTypeVisitor = ConnectionFieldTypeVisitor .create(List.of(new WindowConnectionAdapter(scrollCursorStrategy), new SliceConnectionAdapter(scrollCursorStrategy))); return (builder) -> builder.typeVisitors(List.of(connectionFieldTypeVisitor)); } return (builder) -> { }; } } static class GraphQlResourcesRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("graphql/**/*.graphqls").registerPattern("graphql/**/*.gqls"); } } }
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\GraphQlAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public DataSource getPrimaryDataSource() { return hikariConfig.getHikariDataSource(primaryUrl); } @Bean(name = "userDataSource") public DataSource getUserDataSource() { return hikariConfig.getHikariDataSource(userUrl); } //当两个数据库连接账号密码不一样时使用 // @Bean(name = "userDataSource") // public DataSource getUserDataSource() { // return hikariConfig.getHikariDataSource(userUrl, userName, password); // } @Bean("dynamicDataSource") public DynamicDataSource dynamicDataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource, @Qualifier("userDataSource") DataSource userDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DatabaseTypeEnum.PRIMARY, primaryDataSource); targetDataSources.put(DatabaseTypeEnum.USER, userDataSource); DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法 dataSource.setDefaultTargetDataSource(primaryDataSource);// 默认的datasource设置为myTestDbDataSource return dataSource; } /** * 根据数据源创建SqlSessionFactory */ @Bean public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dynamicDataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(resources)); return bean.getObject(); } }
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\config\DynamicDataSourceConfig.java
2
请完成以下Java代码
public class SendToUserRequest implements Message { public static final String TYPE = "SEND_TO_USER_REQUEST"; /** * 消息编号 */ private String msgId; /** * 内容 */ private String content; public String getMsgId() { return msgId; }
public SendToUserRequest setMsgId(String msgId) { this.msgId = msgId; return this; } public String getContent() { return content; } public SendToUserRequest setContent(String content) { this.content = content; return this; } }
repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\message\SendToUserRequest.java
1
请完成以下Java代码
public boolean benchmarkStringEqualsIgnoreCase() { return longString.equalsIgnoreCase(baeldung); } @Benchmark public boolean benchmarkStringMatches() { return longString.matches(baeldung); } @Benchmark public boolean benchmarkPrecompiledMatches() { return longPattern.matcher(baeldung).matches(); } @Benchmark public int benchmarkStringCompareTo() { return longString.compareTo(baeldung); } @Benchmark public boolean benchmarkStringIsEmpty() { return longString.isEmpty(); }
@Benchmark public boolean benchmarkStringLengthZero() { return longString.length() == 0; } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(StringPerformance.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-strings\src\main\java\com\baeldung\stringperformance\StringPerformance.java
1
请完成以下Java代码
public void setDocStatus (final @Nullable java.lang.String DocStatus) { set_Value (COLUMNNAME_DocStatus, DocStatus); } @Override public java.lang.String getDocStatus() { return get_ValueAsString(COLUMNNAME_DocStatus); } @Override public void setDocumentNo (final @Nullable java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setIsProcessing (final boolean IsProcessing) { set_Value (COLUMNNAME_IsProcessing, IsProcessing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_IsProcessing); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override
public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQM_Analysis_Report_ID (final int QM_Analysis_Report_ID) { if (QM_Analysis_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, QM_Analysis_Report_ID); } @Override public int getQM_Analysis_Report_ID() { return get_ValueAsInt(COLUMNNAME_QM_Analysis_Report_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_QM_Analysis_Report.java
1
请完成以下Java代码
public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import) { set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import); } @Override public void setESR_Import_ID (final int ESR_Import_ID) { if (ESR_Import_ID < 1) set_Value (COLUMNNAME_ESR_Import_ID, null); else set_Value (COLUMNNAME_ESR_Import_ID, ESR_Import_ID); } @Override public int getESR_Import_ID() { return get_ValueAsInt(COLUMNNAME_ESR_Import_ID); } @Override public void setFileName (final @Nullable java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); } @Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); }
@Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportFile.java
1
请完成以下Java代码
public Boolean getPackaging() { return this.packaging; } public void setPackaging(Boolean packaging) { this.packaging = packaging; } public Boolean getType() { return this.type; } public void setType(Boolean type) { this.type = type; } public InvalidDependencyInformation getDependencies() { return this.dependencies; } public void triggerInvalidDependencies(List<String> dependencies) { this.dependencies = new InvalidDependencyInformation(dependencies); } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid) .add("javaVersion=" + this.javaVersion) .add("language=" + this.language) .add("configurationFileFormat=" + this.configurationFileFormat) .add("packaging=" + this.packaging) .add("type=" + this.type) .add("dependencies=" + this.dependencies) .add("message='" + this.message + "'") .toString();
} } /** * Invalid dependencies information. */ public static class InvalidDependencyInformation { private boolean invalid = true; private final List<String> values; public InvalidDependencyInformation(List<String> values) { this.values = values; } public boolean isInvalid() { return this.invalid; } public List<String> getValues() { return this.values; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString(); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
1
请完成以下Java代码
public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPP_Weighting_Spec_ID (final int PP_Weighting_Spec_ID) { if (PP_Weighting_Spec_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Weighting_Spec_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Weighting_Spec_ID, PP_Weighting_Spec_ID); } @Override public int getPP_Weighting_Spec_ID() {
return get_ValueAsInt(COLUMNNAME_PP_Weighting_Spec_ID); } @Override public void setTolerance_Perc (final BigDecimal Tolerance_Perc) { set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc); } @Override public BigDecimal getTolerance_Perc() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeightChecksRequired (final int WeightChecksRequired) { set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired); } @Override public int getWeightChecksRequired() { return get_ValueAsInt(COLUMNNAME_WeightChecksRequired); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Weighting_Spec.java
1
请完成以下Java代码
private int sendAlertToResponsible( WFResponsible responsible, final ArrayList<UserId> alreadyNotifiedUserIds, WFActivityPendingInfo activity, String subject, String message, File pdf) { int counter = 0; if (responsible.isInvoker()) { // nothing } // Human else if (responsible.isHuman() && !alreadyNotifiedUserIds.contains(responsible.getUserId())) { if (m_client.sendEMail(responsible.getUserId(), subject, message, pdf)) { counter++; } alreadyNotifiedUserIds.add(responsible.getUserId()); } // Org of the Document else if (responsible.getType() == WFResponsibleType.Organization) { final TableRecordReference documentRef = activity.getProcessDocumentRef(); PO document = documentRef != null ? TableModelLoader.instance.getPO(documentRef) : null; if (document != null) { final OrgId orgId = OrgId.ofRepoId(document.getAD_Org_ID()); final OrgInfo org = Services.get(IOrgDAO.class).getOrgInfoById(orgId); final UserId supervisorId = org.getSupervisorId(); if (supervisorId != null && !alreadyNotifiedUserIds.contains(supervisorId)) { if (m_client.sendEMail(supervisorId, subject, message, pdf)) { counter++; } alreadyNotifiedUserIds.add(supervisorId); } } } // Role else if (responsible.isRole()) {
final RoleId roleId = responsible.getRoleId(); final Set<UserId> allRoleUserIds = Services.get(IRoleDAO.class).retrieveUserIdsForRoleId(roleId); for (final UserId adUserId : allRoleUserIds) { if (!alreadyNotifiedUserIds.contains(adUserId)) { if (m_client.sendEMail(adUserId, subject, message, pdf)) { counter++; } alreadyNotifiedUserIds.add(adUserId); } } } return counter; } @Override public String getServerInfo() { return "#" + getRunCount() + " - Last=" + m_summary.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\WorkflowProcessor.java
1
请完成以下Java代码
protected void setPropertyFieldValue(String name, ServiceTask task, ObjectNode propertiesNode) { for (FieldExtension extension : task.getFieldExtensions()) { if (name.substring(8).equalsIgnoreCase(extension.getFieldName())) { if (StringUtils.isNotEmpty(extension.getStringValue())) { setPropertyValue(name, extension.getStringValue(), propertiesNode); } else if (StringUtils.isNotEmpty(extension.getExpression())) { setPropertyValue(name, extension.getExpression(), propertiesNode); } } } } protected void setPropertyFieldValue( String propertyName, String fieldName, ServiceTask task, ObjectNode propertiesNode ) {
for (FieldExtension extension : task.getFieldExtensions()) { if (fieldName.equalsIgnoreCase(extension.getFieldName())) { if (StringUtils.isNotEmpty(extension.getStringValue())) { setPropertyValue(propertyName, extension.getStringValue(), propertiesNode); } else if (StringUtils.isNotEmpty(extension.getExpression())) { setPropertyValue(propertyName, extension.getExpression(), propertiesNode); } } } } @Override public void setDecisionTableKeyMap(Map<String, ModelInfo> decisionTableKeyMap) { this.decisionTableKeyMap = decisionTableKeyMap; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\ServiceTaskJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean ifRemember){ // param if (username==null || username.trim().length()==0 || password==null || password.trim().length()==0){ return new ReturnT<String>(500, I18nUtil.getString("login_param_empty")); } // valid passowrd XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(username); if (xxlJobUser == null) { return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid")); } String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes()); if (!passwordMd5.equals(xxlJobUser.getPassword())) { return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid")); } String loginToken = makeToken(xxlJobUser); // do login CookieUtil.set(response, LOGIN_IDENTITY_KEY, loginToken, ifRemember); return ReturnT.SUCCESS; } /** * logout * * @param request * @param response */ public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY); return ReturnT.SUCCESS; } /** * logout
* * @param request * @return */ public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response){ String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY); if (cookieToken != null) { XxlJobUser cookieUser = null; try { cookieUser = parseToken(cookieToken); } catch (Exception e) { logout(request, response); } if (cookieUser != null) { XxlJobUser dbUser = xxlJobUserDao.loadByUserName(cookieUser.getUsername()); if (dbUser != null) { if (cookieUser.getPassword().equals(dbUser.getPassword())) { return dbUser; } } } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\service\LoginService.java
2
请完成以下Java代码
public Optional<FAOpenItemTrxInfo> computeTrxInfo(final FactLine factLine) { return computeTrxInfo(FAOpenItemTrxInfoComputeRequest.builder() .accountConceptualName(factLine.getAccountConceptualName()) .elementValueId(factLine.getAccountId()) .tableName(factLine.getDocRecordRef().getTableName()) .recordId(factLine.getDocRecordRef().getRecord_ID()) .lineId(factLine.getLine_ID()) .subLineId(factLine.getSubLine_ID()) .build()); } public Optional<FAOpenItemTrxInfo> computeTrxInfo(@NonNull final FAOpenItemTrxInfoComputeRequest request) { final FAOpenItemsHandler handler = getHandler(request.getAccountConceptualName(), request.getTableName()); return handler.computeTrxInfo(request); } @NonNull private FAOpenItemsHandler getHandler(@Nullable final AccountConceptualName accountConceptualName, @NonNull String docTableName) { if (accountConceptualName != null) { final FAOpenItemsHandler handler = handlersByKey.get(FAOpenItemsHandlerMatchingKey.of(accountConceptualName, docTableName)); if (handler != null) { return handler; } } return genericOIHandler; } public int processScheduled() { final int batchSize = getProcessingBatchSize(); final Stopwatch stopwatch = Stopwatch.createStarted(); final int count = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, "SELECT de_metas_acct.fact_acct_openItems_to_update_process(p_BatchSize:=?)", batchSize); stopwatch.stop(); logger.debug("Processed {} records in {} (batchSize={})", count, stopwatch, batchSize); return count; } private int getProcessingBatchSize() { final int batchSize = sysConfigBL.getIntValue(SYSCONFIG_ProcessingBatchSize, -1); return batchSize > 0 ? batchSize : DEFAULT_ProcessingBatchSize;
} public void fireGLJournalCompleted(final SAPGLJournal glJournal) { for (SAPGLJournalLine line : glJournal.getLines()) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { continue; } handlersByKey.values() .stream() .distinct() .forEach(handler -> handler.onGLJournalLineCompleted(line)); } } public void fireGLJournalReactivated(final SAPGLJournal glJournal) { for (SAPGLJournalLine line : glJournal.getLines()) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { continue; } handlersByKey.values().forEach(handler -> handler.onGLJournalLineReactivated(line)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\FAOpenItemsService.java
1
请完成以下Java代码
public List<BestellungPosition> getPositionen() { if (positionen == null) { positionen = new ArrayList<BestellungPosition>(); } return this.positionen; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the auftragsart property. * * @return * possible object is * {@link Auftragsart } * */ public Auftragsart getAuftragsart() { return auftragsart; } /** * Sets the value of the auftragsart property. * * @param value * allowed object is * {@link Auftragsart } * */ public void setAuftragsart(Auftragsart value) { this.auftragsart = value; } /** * Gets the value of the auftragskennung property. * * @return * possible object is * {@link String } * */ public String getAuftragskennung() {
return auftragskennung; } /** * Sets the value of the auftragskennung property. * * @param value * allowed object is * {@link String } * */ public void setAuftragskennung(String value) { this.auftragskennung = value; } /** * Gets the value of the gebindeId property. * * @return * possible object is * {@link String } * */ public String getGebindeId() { return gebindeId; } /** * Sets the value of the gebindeId property. * * @param value * allowed object is * {@link String } * */ public void setGebindeId(String value) { this.gebindeId = value; } /** * Gets the value of the auftragsSupportID property. * */ public int getAuftragsSupportID() { return auftragsSupportID; } /** * Sets the value of the auftragsSupportID property. * */ public void setAuftragsSupportID(int value) { this.auftragsSupportID = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAuftrag.java
1
请完成以下Java代码
public final class PatternedDateTimeFormatter { @NonNull private final String pattern; @NonNull private final DateTimeFormatter formatter; private PatternedDateTimeFormatter(@NonNull final String pattern) { this.pattern = pattern; this.formatter = DateTimeFormatter.ofPattern(pattern); } @NonNull public static PatternedDateTimeFormatter ofPattern(@NonNull final String pattern) { return new PatternedDateTimeFormatter(pattern); } @Nullable public static PatternedDateTimeFormatter ofNullablePattern(@Nullable final String pattern) { final String patternNorm = StringUtils.trimBlankToNull(pattern); if (patternNorm == null) { return null; } return new PatternedDateTimeFormatter(patternNorm);
} @Override @Deprecated public String toString() {return toPattern();} public String toPattern() {return pattern;} @Nullable public static String toPattern(@Nullable final PatternedDateTimeFormatter obj) {return obj != null ? obj.toPattern() : null;} @NonNull public LocalDate parseLocalDate(@NonNull final String valueStr) { return LocalDate.parse(valueStr, formatter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\PatternedDateTimeFormatter.java
1
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; }
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(", id=").append(id); sb.append(", title=").append(title); sb.append(", startDate=").append(startDate); sb.append(", endDate=").append(endDate); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotion.java
1
请在Spring Boot框架中完成以下Java代码
public class ColumnSqlSourceDescriptor { @NonNull String targetTableName; @NonNull String sourceTableName; public enum FetchTargetRecordsMethod {LINK_COLUMN, SQL} @NonNull FetchTargetRecordsMethod fetchTargetRecordsMethod; @Nullable String sqlToGetTargetRecordIdBySourceRecordId; @Nullable String sourceLinkColumnName; @Builder private ColumnSqlSourceDescriptor( @NonNull final String targetTableName, @NonNull final String sourceTableName, @NonNull final FetchTargetRecordsMethod fetchTargetRecordsMethod, @Nullable final String sqlToGetTargetRecordIdBySourceRecordId, @Nullable final String sourceLinkColumnName) { this.targetTableName = targetTableName; this.sourceTableName = sourceTableName; this.fetchTargetRecordsMethod = fetchTargetRecordsMethod;
if (fetchTargetRecordsMethod == FetchTargetRecordsMethod.LINK_COLUMN) { this.sourceLinkColumnName = Check.assumeNotEmpty(sourceLinkColumnName, "sourceLinkColumnName is not empty"); this.sqlToGetTargetRecordIdBySourceRecordId = null; } else if (fetchTargetRecordsMethod == FetchTargetRecordsMethod.SQL) { this.sourceLinkColumnName = null; this.sqlToGetTargetRecordIdBySourceRecordId = Check.assumeNotEmpty(sqlToGetTargetRecordIdBySourceRecordId, "sqlToGetTargetRecordIdBySourceRecordId is not empty"); } else { throw new AdempiereException("Unknown fetch method: " + fetchTargetRecordsMethod); } } @NonNull public String getSourceLinkColumnNameNotNull() {return Check.assumeNotNull(sourceLinkColumnName, "sourceLinkColumnName is not empty");} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\ColumnSqlSourceDescriptor.java
2
请完成以下Java代码
public Object execute(final String script) { final ScriptEngine engine = getEngine(); try { final Object result = engine.eval(script); if (throwExceptionIfResultNotEmpty) { final String errmsg = result == null ? null : result.toString(); if (!Check.isEmpty(errmsg)) { throw new AdempiereException(errmsg); } } return result; } catch (final ScriptException e) { throw new AdempiereException("Script execution failed: " + e.getLocalizedMessage() + "\n Engine: " + engine + "\n Script: " + script, e); } } private ScriptEngine getEngine() { return _engine; } public ScriptExecutor putContext(final Properties ctx, final int windowNo) { Check.assumeNotNull(ctx, "Parameter ctx is not null"); final ScriptEngine engine = getEngine(); for (final Enumeration<?> en = ctx.propertyNames(); en.hasMoreElements();) { final String key = en.nextElement().toString(); // filter if (key == null || key.length() == 0 || key.startsWith("P") // Preferences || key.indexOf('|') != -1 && !key.startsWith(String.valueOf(windowNo)) // other Window Settings || key.indexOf('|') != -1 && key.indexOf('|') != key.lastIndexOf('|') // other tab ) { continue; } final String value = ctx.getProperty(key); if (value != null) { final String engineKey = convertToEngineKey(key, windowNo); engine.put(engineKey, value); } } // // Also put the context and windowNo as argument putArgument("Ctx", ctx);
putArgument("WindowNo", windowNo); return this; } public ScriptExecutor putArgument(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); getEngine().put(ARGUMENTS_PREFIX + name, value); return this; } public ScriptExecutor putProcessParameter(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); getEngine().put(PARAMETERS_PREFIX + name, value); return this; } public static String convertToEngineKey(final String key, final int windowNo) { final String keyPrefix = windowNo + "|"; if (key.startsWith(keyPrefix)) { String retValue = WINDOW_CONTEXT_PREFIX + key.substring(keyPrefix.length()); retValue = StringUtils.replace(retValue, "|", "_"); return retValue; } else { String retValue = null; if (key.startsWith("#")) { retValue = GLOBAL_CONTEXT_PREFIX + key.substring(1); } else { retValue = key; } retValue = StringUtils.replace(retValue, "#", "_"); return retValue; } } public ScriptExecutor putAll(final Map<String, ? extends Object> context) { final ScriptEngine engine = getEngine(); context.entrySet() .stream() .forEach(entry -> engine.put(entry.getKey(), entry.getValue())); return this; } public ScriptExecutor setThrowExceptionIfResultNotEmpty() { throwExceptionIfResultNotEmpty = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\ScriptExecutor.java
1
请完成以下Java代码
public I_C_Country getByCountryCode(final String countryCode) { final I_C_Country country = getByCountryCodeOrNull(countryCode); if (country == null) { throw new AdempiereException("No active country found for countryCode=" + countryCode); } return country; } /** * @return the country with the given code, unless the `C_Country` record is inactive. */ @NonNull public CountryId getIdByCountryCode(@NonNull final String countryCode) { final I_C_Country country = getByCountryCode(countryCode); return CountryId.ofRepoId(country.getC_Country_ID()); }
@NonNull public CountryId getIdByCountryCode(@NonNull final CountryCode countryCode) { return getIdByCountryCode(countryCode.getAlpha2()); } @Nullable public CountryId getIdByCountryCodeOrNull(@Nullable final String countryCode) { final I_C_Country country = getByCountryCodeOrNull(countryCode); return country != null ? CountryId.ofRepoId(country.getC_Country_ID()) : null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\CountryDAO.java
1
请完成以下Java代码
public BpmnModelInstance getBpmnModelInstance() { if (processDefinitionId != null) { return Context.getProcessEngineConfiguration().getDeploymentCache().findBpmnModelInstanceForProcessDefinition(processDefinitionId); } else { return null; } } @Override public ProcessEngineServices getProcessEngineServices() { return Context.getProcessEngineConfiguration().getProcessEngine(); } @Override
public ProcessEngine getProcessEngine() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public String getProcessDefinitionTenantId() { return getProcessDefinition().getTenantId(); } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } @Override public String getProcessDefinitionKey() { return processDefinitionKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExecutionEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class FirstEntityManagerFactory { @Bean @Primary public LocalContainerEntityManagerFactoryBean ds1EntityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("dataSourceBooksDb") DataSource dataSource) { return builder .dataSource(dataSource) .packages(packagesToScan()) .persistenceUnit("ds1-pu") .properties(hibernateProperties()) .build(); } @Bean @Primary public PlatformTransactionManager ds1TransactionManager( @Qualifier("ds1EntityManagerFactory") EntityManagerFactory ds1EntityManagerFactory) { return new JpaTransactionManager(ds1EntityManagerFactory); }
protected String[] packagesToScan() { return new String[]{ "com.bookstore.ds1" }; } protected Map<String, String> hibernateProperties() { return new HashMap<String, String>() { { put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); } }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayMySQLTwoDatabases\src\main\java\com\bookstore\config\FirstEntityManagerFactory.java
2
请在Spring Boot框架中完成以下Java代码
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { // auth.inMemoryAuthentication() // .withUser("user").password("password").roles("USER") // .and() // .withUser("app_client").password("nopass").roles("USER") // .and() // .withUser("admin").password("password").roles("ADMIN"); //配置用户来源于数据库 auth.userDetailsService(userDetailsService()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and() .httpBasic().and().csrf().disable(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }
@Override @Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { // 通过用户名获取用户信息 Account account = accountRepository.findByName(name); if (account != null) { // 创建spring security安全用户 User user = new User(account.getName(), account.getPassword(), AuthorityUtils.createAuthorityList(account.getRoles())); return user; } else { throw new UsernameNotFoundException("用户[" + name + "]不存在"); } } }; } }
repos\spring-boot-quick-master\quick-oauth2\quick-oauth2-server\src\main\java\com\quick\auth\server\security\OAuth2SecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { return userRepository .findOneWithAuthoritiesByEmailIgnoreCase(login) .map(user -> createSpringSecurityUser(login, user)) .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); return userRepository .findOneWithAuthoritiesByLogin(lowercaseLogin) .map(user -> createSpringSecurityUser(lowercaseLogin, user)) .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
} private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.isActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<SimpleGrantedAuthority> grantedAuthorities = user .getAuthorities() .stream() .map(Authority::getName) .map(SimpleGrantedAuthority::new) .toList(); return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\security\DomainUserDetailsService.java
2
请完成以下Java代码
public void paint(Graphics g) { boolean dotLTR = true; // left-to-right Position.Bias dotBias = Position.Bias.Forward; // if (isVisible()) { try { TextUI mapper = getComponent().getUI(); Rectangle r = mapper.modelToView(getComponent(), getDot(), dotBias); Rectangle e = mapper.modelToView(getComponent(), getDot()+1, dotBias); // g.setColor(getComponent().getCaretColor()); g.setColor(Color.blue); // int cWidth = e.x-r.x; int cHeight = 4; int cThick = 2; // g.fillRect(r.x-1, r.y, cWidth, cThick); // top g.fillRect(r.x-1, r.y, cThick, cHeight); // | g.fillRect(r.x-1+cWidth, r.y, cThick, cHeight); // | // int yStart = r.y+r.height; g.fillRect(r.x-1, yStart-cThick, cWidth, cThick); // button g.fillRect(r.x-1, yStart-cHeight, cThick, cHeight); // | g.fillRect(r.x-1+cWidth, yStart-cHeight, cThick, cHeight); // | } catch (BadLocationException e) { // can't render // System.err.println("Can't render cursor"); } } // isVisible
} // paint /** * Damages the area surrounding the caret to cause * it to be repainted in a new location. * This method should update the caret bounds (x, y, width, and height). * * @param r the current location of the caret * @see #paint */ protected synchronized void damage(Rectangle r) { if (r != null) { x = r.x - 4; // start 4 pixles before (one required) y = r.y; width = 18; // sufficent for standard font (18-4=14) height = r.height; repaint(); } } // damage } // VOvrCaret
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VOvrCaret.java
1
请完成以下Java代码
public void setM_Product_AlbertaPackagingUnit_ID (final int M_Product_AlbertaPackagingUnit_ID) { if (M_Product_AlbertaPackagingUnit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, M_Product_AlbertaPackagingUnit_ID); } @Override public int getM_Product_AlbertaPackagingUnit_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaPackagingUnit_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 setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaPackagingUnit.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_TaxCategory_ID (final int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID); } @Override public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public void setCommodityCode (final @Nullable java.lang.String CommodityCode) { set_Value (COLUMNNAME_CommodityCode, CommodityCode); } @Override public java.lang.String getCommodityCode() { return get_ValueAsString(COLUMNNAME_CommodityCode); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setInternalName (final @Nullable java.lang.String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public java.lang.String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @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); } /** * ProductType AD_Reference_ID=270 * Reference name: M_Product_ProductType */ public static final int PRODUCTTYPE_AD_Reference_ID=270; /** Item = I */ public static final String PRODUCTTYPE_Item = "I"; /** Service = S */ public static final String PRODUCTTYPE_Service = "S"; /** Resource = R */
public static final String PRODUCTTYPE_Resource = "R"; /** ExpenseType = E */ public static final String PRODUCTTYPE_ExpenseType = "E"; /** Online = O */ public static final String PRODUCTTYPE_Online = "O"; /** FreightCost = F */ public static final String PRODUCTTYPE_FreightCost = "F"; @Override public void setProductType (final @Nullable java.lang.String ProductType) { set_Value (COLUMNNAME_ProductType, ProductType); } @Override public java.lang.String getProductType() { return get_ValueAsString(COLUMNNAME_ProductType); } /** * VATType AD_Reference_ID=540842 * Reference name: VATType */ public static final int VATTYPE_AD_Reference_ID=540842; /** RegularVAT = N */ public static final String VATTYPE_RegularVAT = "N"; /** ReducedVAT = R */ public static final String VATTYPE_ReducedVAT = "R"; /** TaxExempt = E */ public static final String VATTYPE_TaxExempt = "E"; @Override public void setVATType (final @Nullable java.lang.String VATType) { set_Value (COLUMNNAME_VATType, VATType); } @Override public java.lang.String getVATType() { return get_ValueAsString(COLUMNNAME_VATType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxCategory.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("value", value); persistentState.put("password", passwordBytes); return persistentState; } public int getRevisionNext() { return revision+1; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public byte[] getPasswordBytes() { return passwordBytes; } public void setPasswordBytes(byte[] passwordBytes) { this.passwordBytes = passwordBytes; } public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; } public String getName() { return key; } public String getUsername() { return value; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", type=" + type + ", userId=" + userId + ", key=" + key + ", value=" + value + ", password=" + password + ", parentId=" + parentId + ", details=" + details + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityInfoEntity.java
1
请完成以下Java代码
public I_M_HU_Item createHUItem(final I_M_HU hu, final I_M_HU_PI_Item piItem) { final I_M_HU_Item item = createHUItemNoSave(hu, piItem); return finalizeAndStoreItem(hu, item); } @Override public I_M_HU_Item createChildHUItem(@NonNull final I_M_HU hu) { return createHuItemWithoutPI(hu, X_M_HU_Item.ITEMTYPE_Material); } @Override public I_M_HU_Item createAggregateHUItem(@NonNull final I_M_HU hu) { return createHuItemWithoutPI(hu, X_M_HU_Item.ITEMTYPE_HUAggregate); } private I_M_HU_Item createHuItemWithoutPI(@NonNull final I_M_HU hu, @NonNull final String itemType) { final I_M_HU_Item item = InterfaceWrapperHelper.newInstance(I_M_HU_Item.class, hu); item.setAD_Org_ID(hu.getAD_Org_ID()); item.setM_HU(hu);
item.setItemType(itemType); return finalizeAndStoreItem(hu, item); } private I_M_HU_Item finalizeAndStoreItem(final I_M_HU hu, final I_M_HU_Item item) { InterfaceWrapperHelper.save(item); // Update HU Items cache HUItemsLocalCache .getCreate(hu) .addItem(item); return item; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAndItemsDAO.java
1
请完成以下Java代码
public class FindMajorityElement { public static Integer findMajorityElementUsingForLoop(int[] nums) { int majorityThreshold = nums.length / 2; Integer majorityElement = null; for (int i = 0; i < nums.length; i++) { int count = 0; for (int j = 0; j < nums.length; j++) { if (nums[i] == nums[j]) { count++; } } if (count > majorityThreshold) { return majorityElement = nums[i]; } } return majorityElement; } public static Integer findMajorityElementUsingSorting(int[] nums) { Arrays.sort(nums); int majorityThreshold = nums.length / 2; int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == nums[majorityThreshold]) { count++; } if (count > majorityThreshold) { return nums[majorityThreshold]; } } return null; } public static Integer findMajorityElementUsingHashMap(int[] nums) { Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } int majorityThreshold = nums.length / 2; for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { if (entry.getValue() > majorityThreshold) { return entry.getKey(); } } return null; } public static Integer findMajorityElementUsingMooreVoting(int[] nums) { int majorityThreshold = nums.length / 2;
int candidate = nums[0]; int count = 1; for (int i = 1; i < nums.length; i++) { if (count == 0) { candidate = nums[i]; count = 1; } else if (candidate == nums[i]) { count++; } else { count--; } System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]"); } count = 0; for (int num : nums) { if (num == candidate) { count++; } } return count > majorityThreshold ? candidate : null; } public static void main(String[] args) { int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; Integer majorityElement = findMajorityElementUsingMooreVoting(nums); if (majorityElement != null) { System.out.println("Majority element with maximum occurrences: " + majorityElement); } else { System.out.println("No majority element found"); } } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\majorityelement\FindMajorityElement.java
1
请完成以下Java代码
private final boolean removeSelectedRowsIfHUDestoyed() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return false; } else if (selectedRowIds.isAll()) { return false; } final HUEditorView view = getView(); final ImmutableSet<HuId> selectedHUIds = view.streamByIds(selectedRowIds) .map(HUEditorRow::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); return removeHUsIfDestroyed(selectedHUIds); } /** * @return true if at least one HU was removed */ private boolean removeHUsIfDestroyed(final Collection<HuId> huIds) {
final ImmutableSet<HuId> destroyedHUIds = huIds.stream() .distinct() .map(huId -> load(huId, I_M_HU.class)) .filter(Services.get(IHandlingUnitsBL.class)::isDestroyed) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (destroyedHUIds.isEmpty()) { return false; } final HUEditorView view = getView(); final boolean changes = view.removeHUIds(destroyedHUIds); return changes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_Add_Batch_SerialNo_To_CUs.java
1
请完成以下Java代码
public class StudentV1 { private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } // Default constructor for Gson public StudentV1() { } public StudentV1(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\multiplefields\StudentV1.java
1
请完成以下Java代码
public PdfCollator addPages(final byte[] pdfData, final int pageFrom, final int pageTo) { final PdfReader reader; try { reader = new PdfReader(pdfData); } catch (final IOException e) { throw new AdempiereException(e); } return addPages(reader, pageFrom, pageTo); } private PdfCollator addPages(final PdfReader reader, final int pageFrom, final int pageTo) { Check.assume(!closed, "collator not closed"); // // Add pages final PdfCopy copy = getPdfCopy(); for (int page = pageFrom; page <= pageTo; page++) { try { copy.addPage(copy.getImportedPage(reader, page)); } catch (final BadPdfFormatException e) { throw new AdempiereException("Error adding page " + page, e); } catch (final IOException e) { throw new AdempiereException(e); } } // // Free reader try { copy.freeReader(reader); } catch (final IOException e) { throw new AdempiereException(e); } reader.close(); return this; } public PdfCollator close() {
if (closed) { return this; } closed = true; if (pdfCopy == null) { return this; } pdfDocument.close(); pdfCopy = null; pdfDocument = null; return this; } public byte[] toByteArray() { if (out instanceof ByteArrayOutputStream) { close(); final ByteArrayOutputStream baos = (ByteArrayOutputStream)out; return baos.toByteArray(); } else { throw new RuntimeException("Output stream not supported: " + out); // NOPMD by tsa on 2/28/13 2:15 AM } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\util\PdfCollator.java
1
请完成以下Java代码
public JsonStructure delete(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); jsonPointer.getValue(jsonStructure); jsonStructure = jsonPointer.remove(jsonStructure); return jsonStructure; } public String fetchValueFromKey(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure); return jsonString.getString(); } public String fetchListValues(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString(); } public String fetchFullJSON() { JsonPointer jsonPointer = Json.createPointer(""); JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); return jsonObject.toString(); } public boolean check(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); boolean found = jsonPointer.containsValue(jsonStructure); return found; } }
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonpointer\JsonPointerCrud.java
1
请完成以下Java代码
public void deleteArticleComment(Article article, long commentId) { article.removeCommentByUser(this, commentId); } public Set<Comment> viewArticleComments(Article article) { return article.getComments().stream() .map(this::viewComment) .collect(toSet()); } Comment viewComment(Comment comment) { viewProfile(comment.getAuthor()); return comment; } Profile viewProfile(User user) { return user.profile.withFollowing(followingUsers.contains(user)); } public Profile getProfile() { return profile; } boolean matchesPassword(String rawPassword, PasswordEncoder passwordEncoder) { return password.matchesPassword(rawPassword, passwordEncoder); } void changeEmail(Email email) { this.email = email; } void changePassword(Password password) { this.password = password; } void changeName(UserName userName) { profile.changeUserName(userName); } void changeBio(String bio) { profile.changeBio(bio); } void changeImage(Image image) { profile.changeImage(image); } public Long getId() {
return id; } public Email getEmail() { return email; } public UserName getName() { return profile.getUserName(); } String getBio() { return profile.getBio(); } Image getImage() { return profile.getImage(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final var user = (User) o; return email.equals(user.email); } @Override public int hashCode() { return Objects.hash(email); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java
1
请完成以下Java代码
public void handleContextRefreshed(ContextRefreshedEvent event) { printAllActiveProperties((ConfigurableEnvironment) event.getApplicationContext().getEnvironment()); printAllApplicationProperties((ConfigurableEnvironment) event.getApplicationContext().getEnvironment()); } private void printAllActiveProperties(ConfigurableEnvironment env) { LOGGER.info("************************* ALL PROPERTIES(EVENT) ******************************"); env.getPropertySources() .stream() .filter(ps -> ps instanceof MapPropertySource) .map(ps -> ((MapPropertySource) ps).getSource().keySet()) .flatMap(Collection::stream) .distinct() .sorted() .forEach(key -> LOGGER.info("{}={}", key, env.getProperty(key))); LOGGER.info("******************************************************************************"); }
private void printAllApplicationProperties(ConfigurableEnvironment env) { LOGGER.info("************************* APP PROPERTIES(EVENT) ******************************"); env.getPropertySources() .stream() .filter(ps -> ps instanceof MapPropertySource && ps.getName().contains("application.properties")) .map(ps -> ((MapPropertySource) ps).getSource().keySet()) .flatMap(Collection::stream) .distinct() .sorted() .forEach(key -> LOGGER.info("{}={}", key, env.getProperty(key))); LOGGER.info("******************************************************************************"); } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\java\com\baeldung\properties\log\AppContextRefreshedEventPropertiesPrinter.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<ApiResponse> addJob(@Valid JobForm form) { try { jobService.addJob(form); } catch (Exception e) { return new ResponseEntity<>(ApiResponse.msg(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(ApiResponse.msg("操作成功"), HttpStatus.CREATED); } /** * 删除定时任务 */ @DeleteMapping public ResponseEntity<ApiResponse> deleteJob(JobForm form) throws SchedulerException { if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) { return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST); } jobService.deleteJob(form); return new ResponseEntity<>(ApiResponse.msg("删除成功"), HttpStatus.OK); } /** * 暂停定时任务 */ @PutMapping(params = "pause") public ResponseEntity<ApiResponse> pauseJob(JobForm form) throws SchedulerException { if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) { return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST); } jobService.pauseJob(form); return new ResponseEntity<>(ApiResponse.msg("暂停成功"), HttpStatus.OK); } /** * 恢复定时任务 */ @PutMapping(params = "resume") public ResponseEntity<ApiResponse> resumeJob(JobForm form) throws SchedulerException { if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) { return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST); }
jobService.resumeJob(form); return new ResponseEntity<>(ApiResponse.msg("恢复成功"), HttpStatus.OK); } /** * 修改定时任务,定时时间 */ @PutMapping(params = "cron") public ResponseEntity<ApiResponse> cronJob(@Valid JobForm form) { try { jobService.cronJob(form); } catch (Exception e) { return new ResponseEntity<>(ApiResponse.msg(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(ApiResponse.msg("修改成功"), HttpStatus.OK); } @GetMapping public ResponseEntity<ApiResponse> jobList(Integer currentPage, Integer pageSize) { if (ObjectUtil.isNull(currentPage)) { currentPage = 1; } if (ObjectUtil.isNull(pageSize)) { pageSize = 10; } PageInfo<JobAndTrigger> all = jobService.list(currentPage, pageSize); return ResponseEntity.ok(ApiResponse.ok(Dict.create().set("total", all.getTotal()).set("data", all.getList()))); } }
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\controller\JobController.java
2
请在Spring Boot框架中完成以下Java代码
public Batch updateBatch(Batch batch) { return getBatchEntityManager().update((BatchEntity) batch); } @Override public void deleteBatch(String batchId) { getBatchEntityManager().delete(batchId); } @Override public BatchPartEntity getBatchPart(String id) { return getBatchPartEntityManager().findById(id); } @Override public List<BatchPart> findBatchPartsByBatchId(String batchId) { return getBatchPartEntityManager().findBatchPartsByBatchId(batchId); } @Override public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) { return getBatchPartEntityManager().findBatchPartsByBatchIdAndStatus(batchId, status); } @Override public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) { return getBatchPartEntityManager().findBatchPartsByScopeIdAndType(scopeId, scopeType); } @Override public BatchPart createBatchPart(Batch batch, String status, String scopeId, String subScopeId, String scopeType) { return getBatchPartEntityManager().createBatchPart((BatchEntity) batch, status, scopeId, subScopeId, scopeType); } @Override public BatchPart completeBatchPart(String batchPartId, String status, String resultJson) { return getBatchPartEntityManager().completeBatchPart(batchPartId, status, resultJson); }
@Override public Batch completeBatch(String batchId, String status) { return getBatchEntityManager().completeBatch(batchId, status); } public Batch createBatch(BatchBuilder batchBuilder) { return getBatchEntityManager().createBatch(batchBuilder); } public BatchEntityManager getBatchEntityManager() { return configuration.getBatchEntityManager(); } public BatchPartEntityManager getBatchPartEntityManager() { return configuration.getBatchPartEntityManager(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchServiceImpl.java
2