instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static Optional<FreightCostId> extractDefaultFreightCost(final Collection<FreightCost> freightCosts) { if (freightCosts.isEmpty()) { return Optional.empty(); } final ImmutableList<FreightCost> defaults = freightCosts.stream() .filter(FreightCost::isDefaultFreightCost) .sorted(Comparator.comparing(FreightCost::getId)) // just to have a predictible order .collect(ImmutableList.toImmutableList()); if (defaults.isEmpty()) { return Optional.empty(); } else if (defaults.size() == 1) { return Optional.of(defaults.get(0).getId()); } else { logger.warn("More than one default freight costs found. Considering the first one: {}", defaults); return Optional.of(defaults.get(0).getId()); } } private static ImmutableSet<ProductId> extractFreightCostProductIds(final Collection<FreightCost> freightCosts) { return freightCosts.stream() .map(FreightCost::getFreightCostProductId) .collect(ImmutableSet.toImmutableSet());
} public boolean isFreightCostProduct(@NonNull final ProductId productId) { return freightCostProductIds.contains(productId); } public FreightCost getById(@NonNull final FreightCostId id) { final FreightCost freightCost = freightCosts.get(id); if (freightCost == null) { throw new AdempiereException("@NotFound@ @M_FreightCost_ID@: " + id); } return freightCost; } public Optional<FreightCost> getDefaultFreightCost() { return getDefaultFreightCostId().map(this::getById); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCostRepository.java
1
请完成以下Java代码
private void insertSubscriptionProgressEvent(@NonNull final I_C_Flatrate_Term term, @NonNull final String eventType, @Nullable final Object eventValue) { final Timestamp today = SystemTime.asDayTimestamp(); final List<I_C_SubscriptionProgress> subscriptionProgressList = subscriptionDAO.retrieveSubscriptionProgresses(SubscriptionProgressQuery.builder() .term(term).build()); final int seqNoToUse = getSeqNoToUse(today, subscriptionProgressList);//default start seq number. Should not happen. final I_C_SubscriptionProgress changeEvent = newInstance(I_C_SubscriptionProgress.class); changeEvent.setEventType(eventType); changeEvent.setC_Flatrate_Term(term); changeEvent.setStatus(X_C_SubscriptionProgress.STATUS_Planned); changeEvent.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running); changeEvent.setEventDate(today); changeEvent.setSeqNo(seqNoToUse); changeEvent.setDropShip_BPartner_ID(term.getDropShip_BPartner_ID()); changeEvent.setDropShip_Location_ID(term.getDropShip_Location_ID()); addEventValue(changeEvent, eventType, eventValue); save(changeEvent); subscriptionProgressList.stream() .filter(sp -> today.before(sp.getEventDate())) .forEach(this::incrementSeqNoAndSave); } private int getSeqNoToUse(final Timestamp today, final List<I_C_SubscriptionProgress> subscriptionProgressList) { return subscriptionProgressList.stream() .filter(sp -> today.before(sp.getEventDate())) .mapToInt(I_C_SubscriptionProgress::getSeqNo) .min()//smallest seqNo after today's date .orElse(subscriptionProgressList.stream() .mapToInt(I_C_SubscriptionProgress::getSeqNo) .map(Math::incrementExact) .max()//greatest seqNo + 1 before today .orElse(SEQNO_FIRST_VALUE)); } private void addEventValue(final I_C_SubscriptionProgress changeEvent, final String eventType, @Nullable final Object eventValue) {
if (Objects.equals(eventType, X_C_SubscriptionProgress.EVENTTYPE_Quantity) && eventValue != null) { changeEvent.setQty((BigDecimal)eventValue); } } private void incrementSeqNoAndSave(final I_C_SubscriptionProgress subscriptionProgress) { subscriptionProgress.setSeqNo(subscriptionProgress.getSeqNo() + 1); save(subscriptionProgress); } public boolean isSubscription(@NonNull final I_C_OrderLine ol) { final ConditionsId conditionsId = ConditionsId.ofRepoIdOrNull(ol.getC_Flatrate_Conditions_ID()); if (conditionsId == null) { return false; } final I_C_Flatrate_Conditions typeConditions = flatrateDAO.getConditionsById(conditionsId); return X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription.equals(typeConditions.getType_Conditions()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionBL.java
1
请完成以下Java代码
public String getSectionMajor() { return sectionMajor; } /** * Sets the value of the sectionMajor property. * * @param value * allowed object is * {@link String } * */ public void setSectionMajor(String value) { this.sectionMajor = value; } /** * Gets the value of the hasExpenseLoading property. * * @return * possible object is * {@link Boolean } * */ public boolean isHasExpenseLoading() { if (hasExpenseLoading == null) { return true; } else { return hasExpenseLoading; } } /** * Sets the value of the hasExpenseLoading property. * * @param value * allowed object is
* {@link Boolean } * */ public void setHasExpenseLoading(Boolean value) { this.hasExpenseLoading = value; } /** * Gets the value of the doCostAssessment property. * * @return * possible object is * {@link Boolean } * */ public boolean isDoCostAssessment() { if (doCostAssessment == null) { return false; } else { return doCostAssessment; } } /** * Sets the value of the doCostAssessment property. * * @param value * allowed object is * {@link Boolean } * */ public void setDoCostAssessment(Boolean value) { this.doCostAssessment = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraStationaryType.java
1
请完成以下Java代码
public List<HistoricDetailEntity> findHistoricDetailsByTaskId(String taskId) { return getDbSqlSession().selectList("selectHistoricDetailByTaskId", taskId); } @Override public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) { return (Long) getDbSqlSession().selectOne( "selectHistoricDetailCountByQueryCriteria", historicVariableUpdateQuery ); } @Override @SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByQueryCriteria( HistoricDetailQueryImpl historicVariableUpdateQuery, Page page ) { return getDbSqlSession().selectList("selectHistoricDetailsByQueryCriteria", historicVariableUpdateQuery, page); } @Override @SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByNativeQuery( Map<String, Object> parameterMap,
int firstResult, int maxResults ) { return getDbSqlSession().selectListWithRawParameter( "selectHistoricDetailByNativeQuery", parameterMap, firstResult, maxResults ); } @Override public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByNativeQuery", parameterMap); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricDetailDataManager.java
1
请完成以下Java代码
public void onOrderLineDeleted(final I_C_OrderLine orderLine) { if (!isEligible(orderLine)) { return; } final boolean groupCompensationLine = orderLine.isGroupCompensationLine(); if (groupCompensationLine) { onCompensationLineDeleted(orderLine); } } private void onCompensationLineDeleted(final I_C_OrderLine compensationLine) { final GroupId groupId = OrderGroupRepository.extractGroupId(compensationLine); final Group group = groupsRepo.retrieveGroupIfExists(groupId); // If no group found => nothing to do // Usually this case happens when we delete the order, so all the lines together. if (group == null) { return; } if (!group.hasCompensationLines()) { groupsRepo.destroyGroup(group); } else { group.updateAllCompensationLines(); groupsRepo.saveGroup(group); } } public void updateCompensationLineNoSave(final I_C_OrderLine orderLine) { final Group group = groupsRepo.createPartialGroupFromCompensationLine(orderLine);
group.updateAllCompensationLines(); final OrderLinesStorage orderLinesStorage = groupsRepo.createNotSaveableSingleOrderLineStorage(orderLine); groupsRepo.saveGroup(group, orderLinesStorage); } @Nullable public GroupTemplateId getGroupTemplateId(@NonNull final GroupId groupId) { return groupsRepo.getGroupTemplateId(groupId); } public boolean isProductExcludedFromFlatrateConditions(@Nullable final GroupTemplateId groupTemplateId, @NonNull final ProductId productId) { if (groupTemplateId == null) { return false; } return flatrateConditionsExcludedProductsRepo.isProductExcludedFromFlatrateConditions(groupTemplateId, productId); } public IQueryBuilder<I_C_OrderLine> retrieveGroupOrderLinesQuery(final GroupId groupId) { return groupsRepo.retrieveGroupOrderLinesQuery(groupId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupCompensationChangesHandler.java
1
请在Spring Boot框架中完成以下Java代码
public String pay(String orderId, String userId) { // 构造受理上下文 OrderProcessContext<String> context = buildContext(orderId, userId,null, ProcessReqEnum.Pay); // 受理下单请求 processEngine.process(context); // 获取结果 return context.getOrderProcessRsp(); } @Override public void cancelOrder(String orderId, String userId) { // 构造受理上下文 OrderProcessContext<String> context = buildContext(orderId, userId,null, ProcessReqEnum.CancelOrder); // 受理下单请求 processEngine.process(context); } @Override public void confirmDelivery(String orderId, String expressNo, String userId) { // 构造受理上下文 OrderProcessContext<String> context = buildContext(orderId, userId, expressNo, ProcessReqEnum.ConfirmDelivery); // 受理下单请求 processEngine.process(context); } @Override public void confirmReceive(String orderId, String userId) { // 构造受理上下文 OrderProcessContext<String> context = buildContext(orderId, userId,null, ProcessReqEnum.ConfirmReceive); // 受理下单请求 processEngine.process(context);
} /** * 请求参数校验 * @param req 请求参数 * @param expCodeEnum 异常枚举 * @param <T> 请求参数类型 */ private <T> void checkParam(T req, ExpCodeEnum expCodeEnum) { if (req == null) { throw new CommonBizException(expCodeEnum); } } private <T> OrderProcessContext<String> buildContext(String orderId, String userId, T reqData, ProcessReqEnum processReqEnum) { OrderProcessContext context = new OrderProcessContext(); // 受理请求 OrderProcessReq req = new OrderProcessReq(); req.setProcessReqEnum(processReqEnum); req.setUserId(userId); if (StringUtils.isNotEmpty(orderId)) { req.setOrderId(orderId); } if (reqData != null) { req.setReqData(reqData); } context.setOrderProcessReq(req); return context; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\service\OrderServiceImpl.java
2
请完成以下Java代码
private I_GO_DeliveryOrder retrieveGODeliveryOrderPOById(@NonNull final OrderId orderId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_GO_DeliveryOrder.class) .addEqualsFilter(I_GO_DeliveryOrder.COLUMN_GO_AX4Number, orderId.getOrderIdAsString()) .create() .firstOnly(I_GO_DeliveryOrder.class); } private void saveAssignedPackageIds(final int deliveryOrderRepoId, final Set<PackageId> packageIds) { final IQueryBL queryBL = Services.get(IQueryBL.class); final Set<PackageId> prevPackageIds = retrieveGODeliveryOrderPackageIds(deliveryOrderRepoId); final Set<PackageId> packageIdsToDelete = Sets.difference(prevPackageIds, packageIds); if (!packageIdsToDelete.isEmpty()) { queryBL.createQueryBuilder(I_GO_DeliveryOrder_Package.class) .addEqualsFilter(I_GO_DeliveryOrder_Package.COLUMN_GO_DeliveryOrder_ID, deliveryOrderRepoId) .addInArrayFilter(I_GO_DeliveryOrder_Package.COLUMN_M_Package_ID, packageIdsToDelete) .create() .delete(); } final Set<PackageId> packageIdsToAdd = Sets.difference(packageIds, prevPackageIds); packageIdsToAdd.forEach(packageId -> createGODeliveryOrderPackage(deliveryOrderRepoId, packageId.getRepoId())); } private Set<PackageId> retrieveGODeliveryOrderPackageIds(final int deliveryOrderRepoId) { if (deliveryOrderRepoId <= 0) { return ImmutableSet.of(); }
final List<Integer> mpackageIds = Services.get(IQueryBL.class) .createQueryBuilder(I_GO_DeliveryOrder_Package.class) .addEqualsFilter(I_GO_DeliveryOrder_Package.COLUMN_GO_DeliveryOrder_ID, deliveryOrderRepoId) .create() .listDistinct(I_GO_DeliveryOrder_Package.COLUMNNAME_M_Package_ID, Integer.class); final ImmutableSet<PackageId> packageIds = mpackageIds.stream() .map(PackageId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); return packageIds; } private void createGODeliveryOrderPackage(final int deliveryOrderRepoId, final int packageId) { final I_GO_DeliveryOrder_Package orderPackagePO = InterfaceWrapperHelper.newInstance(I_GO_DeliveryOrder_Package.class); orderPackagePO.setGO_DeliveryOrder_ID(deliveryOrderRepoId); orderPackagePO.setM_Package_ID(packageId); InterfaceWrapperHelper.save(orderPackagePO); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GODeliveryOrderRepository.java
1
请完成以下Java代码
public String getTimeCycle() { return timeCycle; } public void setTimeCycle(String timeCycle) { this.timeCycle = timeCycle; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getEndDate() { return endDate; } public String getCalendarName() { return calendarName; } public void setCalendarName(String calendarName) { this.calendarName = calendarName;
} public TimerEventDefinition clone() { TimerEventDefinition clone = new TimerEventDefinition(); clone.setValues(this); return clone; } public void setValues(TimerEventDefinition otherDefinition) { super.setValues(otherDefinition); setTimeDate(otherDefinition.getTimeDate()); setTimeDuration(otherDefinition.getTimeDuration()); setTimeCycle(otherDefinition.getTimeCycle()); setEndDate(otherDefinition.getEndDate()); setCalendarName(otherDefinition.getCalendarName()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\TimerEventDefinition.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable UiService getUiService() { return this.uiService; } public void setUiService(@Nullable UiService uiService) { this.uiService = uiService; } public @Nullable Boolean getAnalyticsEnabled() { return this.analyticsEnabled; } public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) { this.analyticsEnabled = analyticsEnabled; } public @Nullable String getLicenseKey() { return this.licenseKey; } public void setLicenseKey(@Nullable String licenseKey) { this.licenseKey = licenseKey; } /** * Enumeration of types of summary to show. Values are the same as those on * {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum * is not used directly. */ public enum ShowSummary { /** * Do not show a summary. */ OFF, /** * Show a summary. */ SUMMARY, /** * Show a verbose summary. */ VERBOSE } /** * Enumeration of destinations to which the summary should be output. Values are the * same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards * compatibility, the Liquibase enum is not used directly. */ public enum ShowSummaryOutput { /** * Log the summary.
*/ LOG, /** * Output the summary to the console. */ CONSOLE, /** * Log the summary and output it to the console. */ ALL } /** * Enumeration of types of UIService. Values are the same as those on * {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is * not used directly. */ public enum UiService { /** * Console-based UIService. */ CONSOLE, /** * Logging-based UIService. */ LOGGER } }
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java
2
请完成以下Java代码
private static EAN13 parseInternalUseOrVariableMeasure(@NonNull final String barcode, @NonNull final EAN13Prefix prefix, final int checksum) { // 4 digits for article code (IIII), // The digit at index 6 does not belong to the product code. It can be used for other purposes. For the time being it's ignored. // see https://www.gs1.org/docs/barcodes/SummaryOfGS1MOPrefixes20-29.pdf, page 81 (2.71 GS1 Switzerland) final EAN13ProductCode productNo = EAN13ProductCode.ofString(barcode.substring(2, 6)); final String weightStr = barcode.substring(7, 12); // 5 digits for weight (GGGGG) // Interpret the weight/measure (assume it's in grams or kilograms) final BigDecimal weightInKg = new BigDecimal(weightStr).divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP); return EAN13.builder() .barcode(barcode) .prefix(prefix) .productNo(productNo) .weightInKg(weightInKg) .checksum(checksum)
.build(); } private static EAN13 parseStandardProduct(@NonNull final String barcode, @NonNull final EAN13Prefix prefix, final int checksum) { final String manufacturerAndProductCode = barcode.substring(3, 12); final EAN13ProductCode productNo = EAN13ProductCode.ofString(manufacturerAndProductCode); return EAN13.builder() .barcode(barcode) .prefix(prefix) .productNo(productNo) .checksum(checksum) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\ean13\EAN13Parser.java
1
请完成以下Java代码
public void invalidate() { super.invalidate(); SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true; setCurrentSession(null); clearRequestedSessionCache(); SessionRepositoryFilter.this.sessionRepository.deleteById(getId()); } } /** * Ensures session is committed before issuing an include. * * @since 1.3.4 */ private final class SessionCommittingRequestDispatcher implements RequestDispatcher { private final RequestDispatcher delegate; SessionCommittingRequestDispatcher(RequestDispatcher delegate) { this.delegate = delegate; } @Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.delegate.forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (!SessionRepositoryRequestWrapper.this.hasCommittedInInclude) { SessionRepositoryRequestWrapper.this.commitSession(); SessionRepositoryRequestWrapper.this.hasCommittedInInclude = true; } this.delegate.include(request, response); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\SessionRepositoryFilter.java
1
请完成以下Spring Boot application配置
spring: cloud: config: server: native: search-locations: classpath:/shared profiles: active: native security: use
r: password: ${CONFIG_SERVICE_PASSWORD} server: port: 8888
repos\piggymetrics-master\config\src\main\resources\application.yml
2
请完成以下Java代码
public boolean process(Sentence sentence) { sequenceList.add(convertToSequence(sentence)); return false; } }); TagSet tagSet = getTagSet(); List<int[][]> sampleList = new ArrayList<int[][]>(sequenceList.size()); for (List<String[]> sequence : sequenceList) { int[][] sample = new int[2][sequence.size()]; int i = 0; for (String[] os : sequence) {
sample[0][i] = vocabulary.idOf(os[0]); assert sample[0][i] != -1; sample[1][i] = tagSet.add(os[1]); assert sample[1][i] != -1; ++i; } sampleList.add(sample); } model.train(sampleList); vocabulary.mutable = false; } protected abstract List<String[]> convertToSequence(Sentence sentence); protected abstract TagSet getTagSet(); }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMTrainer.java
1
请完成以下Java代码
public static ExternalSystemMap ofList(final List<ExternalSystem> list) { return list.isEmpty() ? EMPTY : new ExternalSystemMap(list); } public static Collector<ExternalSystem, ?, ExternalSystemMap> collect() { return GuavaCollectors.collectUsingListAccumulator(ExternalSystemMap::ofList); } @Nullable public ExternalSystem getByTypeOrNull(@NonNull final ExternalSystemType type) { return byType.get(type); } public Optional<ExternalSystem> getOptionalByType(@NonNull final ExternalSystemType type) { return Optional.ofNullable(getByTypeOrNull(type)); }
@NonNull public ExternalSystem getByType(@NonNull final ExternalSystemType type) { return getOptionalByType(type) .orElseThrow(() -> new AdempiereException("Unknown external system type: " + type)); } public @NonNull ExternalSystem getById(final @NonNull ExternalSystemId id) { final ExternalSystem externalSystem = byId.get(id); if (externalSystem == null) { throw new AdempiereException("No active external system found for id: " + id); } return externalSystem; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemMap.java
1
请在Spring Boot框架中完成以下Java代码
public static class RateLimitConfig { Function<RateLimitConfig, BucketConfiguration> configurationBuilder = DEFAULT_CONFIGURATION_BUILDER; long capacity; @org.jspecify.annotations.Nullable Duration period; @org.jspecify.annotations.Nullable Function<ServerRequest, String> keyResolver; HttpStatusCode statusCode = HttpStatus.TOO_MANY_REQUESTS; @org.jspecify.annotations.Nullable Duration timeout; int tokens = 1; String headerName = DEFAULT_HEADER_NAME; public Function<RateLimitConfig, BucketConfiguration> getConfigurationBuilder() { return configurationBuilder; } public void setConfigurationBuilder(Function<RateLimitConfig, BucketConfiguration> configurationBuilder) { Objects.requireNonNull(configurationBuilder, "configurationBuilder may not be null"); this.configurationBuilder = configurationBuilder; } public long getCapacity() { return capacity; } public RateLimitConfig setCapacity(long capacity) { this.capacity = capacity; return this; } public @Nullable Duration getPeriod() { return period; } public RateLimitConfig setPeriod(Duration period) { this.period = period; return this; } public @Nullable Function<ServerRequest, String> getKeyResolver() { return keyResolver; } public RateLimitConfig setKeyResolver(Function<ServerRequest, String> keyResolver) { Objects.requireNonNull(keyResolver, "keyResolver may not be null");
this.keyResolver = keyResolver; return this; } public HttpStatusCode getStatusCode() { return statusCode; } public RateLimitConfig setStatusCode(HttpStatusCode statusCode) { this.statusCode = statusCode; return this; } public @Nullable Duration getTimeout() { return timeout; } public RateLimitConfig setTimeout(Duration timeout) { this.timeout = timeout; return this; } public int getTokens() { return tokens; } public RateLimitConfig setTokens(int tokens) { Assert.isTrue(tokens > 0, "tokens must be greater than zero"); this.tokens = tokens; return this; } public String getHeaderName() { return headerName; } public RateLimitConfig setHeaderName(String headerName) { Objects.requireNonNull(headerName, "headerName may not be null"); this.headerName = headerName; return this; } } public static class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(Bucket4jFilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\Bucket4jFilterFunctions.java
2
请在Spring Boot框架中完成以下Java代码
public class JsonSetClearanceStatusRequest { @NonNull @JsonProperty("huIdentifier") JsonHUIdentifier huIdentifier; @NonNull @JsonProperty("clearanceStatus") JsonClearanceStatus clearanceStatus; @Nullable @JsonProperty("clearanceNote") String clearanceNote; @Builder public JsonSetClearanceStatusRequest( @JsonProperty("huIdentifier") @NonNull final JsonSetClearanceStatusRequest.JsonHUIdentifier huIdentifier, @JsonProperty("clearanceStatus") @NonNull final JsonClearanceStatus clearanceStatus, @JsonProperty("clearanceNote") @Nullable final String clearanceNote) { this.huIdentifier = huIdentifier; this.clearanceStatus = clearanceStatus; this.clearanceNote = clearanceNote; } @Value public static class JsonHUIdentifier { @Nullable @JsonProperty("metasfreshId") JsonMetasfreshId metasfreshId; @Nullable @JsonProperty("qrCode") String qrCode;
@Builder public JsonHUIdentifier( @JsonProperty("metasfreshId") @Nullable final JsonMetasfreshId metasfreshId, @JsonProperty("qrCode") @Nullable final String qrCode) { Check.assume(qrCode == null || metasfreshId == null, "metasfreshId and qrCode cannot be set at the same time!"); Check.assume(qrCode != null || metasfreshId != null, "metasfreshId or qrCode must be set!"); this.metasfreshId = metasfreshId; this.qrCode = qrCode; } @NonNull public static JsonHUIdentifier ofJsonMetasfreshId(@NonNull final JsonMetasfreshId metasfreshId) { return JsonHUIdentifier.builder() .metasfreshId(metasfreshId) .build(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonSetClearanceStatusRequest.java
2
请完成以下Java代码
public boolean isAcknowledged() { return get_ValueAsBoolean(COLUMNNAME_IsAcknowledged); } @Override public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRoot_AD_Table_ID (final int Root_AD_Table_ID) { if (Root_AD_Table_ID < 1) set_Value (COLUMNNAME_Root_AD_Table_ID, null); else set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID); } @Override public int getRoot_AD_Table_ID() { return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID); } @Override public void setRoot_Record_ID (final int Root_Record_ID) { if (Root_Record_ID < 1) set_Value (COLUMNNAME_Root_Record_ID, null); else set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID); }
@Override public int getRoot_Record_ID() { return get_ValueAsInt(COLUMNNAME_Root_Record_ID); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity) { set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
1
请在Spring Boot框架中完成以下Java代码
public class RuntimeParametersProcessor implements Processor { @Override public void process(final Exchange exchange) throws Exception { final ImportCustomersRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_CUSTOMERS_CONTEXT, ImportCustomersRouteContext.class); if (context.isSkipNextImportTimestamp()) { //nothing to do exchange.getIn().setBody(null); return; } final Instant updatedAt = Optional .ofNullable(context.getOldestFailingCustomer())
.orElse(Instant.now()); final JsonRuntimeParameterUpsertItem runtimeParameterUpsertItem = JsonRuntimeParameterUpsertItem.builder() .externalSystemParentConfigId(context.getExternalSystemRequest().getExternalSystemConfigId()) .name(PARAM_UPDATED_AFTER) .request(context.getExternalSystemRequest().getCommand()) .value(updatedAt.toString()) .build(); final JsonESRuntimeParameterUpsertRequest request = JsonESRuntimeParameterUpsertRequest.builder() .runtimeParameterUpsertItems(ImmutableList.of(runtimeParameterUpsertItem)) .build(); exchange.getIn().setBody(request); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\customer\processor\RuntimeParametersProcessor.java
2
请完成以下Java代码
public boolean isEmbedded() { return this.embedded; } public FindPanelBuilder setHideStatusBar(boolean hideStatusBar) { this.hideStatusBar = hideStatusBar; return this; } public boolean isHideStatusBar() { return hideStatusBar; } public FindPanelBuilder setSearchPanelCollapsed(final boolean searchPanelCollapsed) { this.searchPanelCollapsed = searchPanelCollapsed; return this; } public boolean isSearchPanelCollapsed() { return searchPanelCollapsed; } public FindPanelBuilder setMaxQueryRecordsPerTab(final int maxQueryRecordsPerTab) { this.maxQueryRecordsPerTab = maxQueryRecordsPerTab; return this; }
public int getMaxQueryRecordsPerTab() { if (maxQueryRecordsPerTab != null) { return maxQueryRecordsPerTab; } else if (gridTab != null) { return gridTab.getMaxQueryRecords(); } return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindPanelBuilder.java
1
请完成以下Java代码
class SpringBootMetadataReader { private static final Comparator<DefaultMetadataElement> VERSION_METADATA_ELEMENT_COMPARATOR = new VersionMetadataElementComparator(); private final JsonNode content; /** * Parse the content of the metadata at the specified url. * @param objectMapper the object mapper * @param restTemplate the rest template * @param url the metadata URL * @throws IOException on load error */ SpringBootMetadataReader(ObjectMapper objectMapper, RestTemplate restTemplate, String url) throws IOException { this.content = objectMapper.readTree(restTemplate.getForObject(url, String.class)); } /** * Return the boot versions parsed by this instance. * @return the versions */ List<DefaultMetadataElement> getBootVersions() { ArrayNode releases = (ArrayNode) this.content.get("_embedded").get("releases"); List<DefaultMetadataElement> list = new ArrayList<>(); for (JsonNode node : releases) { DefaultMetadataElement versionMetadata = parseVersionMetadata(node); if (versionMetadata != null) { list.add(versionMetadata); } } list.sort(VERSION_METADATA_ELEMENT_COMPARATOR.reversed()); return list; } private DefaultMetadataElement parseVersionMetadata(JsonNode node) { String versionId = node.get("version").textValue(); Version version = VersionParser.DEFAULT.safeParse(versionId); if (version == null) { return null; } DefaultMetadataElement versionMetadata = new DefaultMetadataElement(); versionMetadata.setId(versionId); versionMetadata.setName(determineDisplayName(version)); versionMetadata.setDefault(node.get("current").booleanValue()); return versionMetadata; } private String determineDisplayName(Version version) { StringBuilder sb = new StringBuilder(); sb.append(version.getMajor()).append(".").append(version.getMinor()).append(".").append(version.getPatch()); if (version.getQualifier() != null) { sb.append(determineSuffix(version.getQualifier())); } return sb.toString(); } private String determineSuffix(Qualifier qualifier) { String id = qualifier.getId();
if (id.equals("RELEASE")) { return ""; } StringBuilder sb = new StringBuilder(" ("); if (id.contains("SNAPSHOT")) { sb.append("SNAPSHOT"); } else { sb.append(id); if (qualifier.getVersion() != null) { sb.append(qualifier.getVersion()); } } sb.append(")"); return sb.toString(); } private static final class VersionMetadataElementComparator implements Comparator<DefaultMetadataElement> { private static final VersionParser versionParser = VersionParser.DEFAULT; @Override public int compare(DefaultMetadataElement o1, DefaultMetadataElement o2) { Version o1Version = versionParser.parse(o1.getId()); Version o2Version = versionParser.parse(o2.getId()); return o1Version.compareTo(o2Version); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\SpringBootMetadataReader.java
1
请完成以下Java代码
public static Topic local(final String name) { return builder().name(name).type(Type.LOCAL).build(); } public static Topic localAndAsync(final String name) { final Topic topic = local(name); EventBusConfig.alwaysConsiderAsync(topic); return topic; } public static Topic of(final String name, final Type type) { return builder().name(name).type(type).build(); } @Builder(toBuilder = true) private Topic( @NonNull final String name, @NonNull final Type type) { if (!EventBusConfig.isEnabled()) { logger.warn("trying to create a distributed Topic (topicName={}) but EventBusConfig.isEnabled() == false, fallback to Local topic...", name); this.type = Type.LOCAL; }
else { this.type = type; } this.name = Check.assumeNotEmpty(name, "name not empty"); this.fullName = type + "." + name; } public Topic toLocal() { if (type == Type.LOCAL) { return this; } return toBuilder().type(Type.LOCAL).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\Topic.java
1
请完成以下Java代码
public class GetFormKeyCmd implements Command<String> { protected String taskDefinitionKey; protected String processDefinitionId; /** * Retrieves a start form key. */ public GetFormKeyCmd(String processDefinitionId) { setProcessDefinitionId(processDefinitionId); } /** * Retrieves a task form key. */ public GetFormKeyCmd(String processDefinitionId, String taskDefinitionKey) { setProcessDefinitionId(processDefinitionId); if (taskDefinitionKey == null || taskDefinitionKey.length() < 1) { throw new ProcessEngineException("The task definition key is mandatory, but '" + taskDefinitionKey + "' has been provided."); } this.taskDefinitionKey = taskDefinitionKey; } protected void setProcessDefinitionId(String processDefinitionId) { if (processDefinitionId == null || processDefinitionId.length() < 1) { throw new ProcessEngineException("The process definition id is mandatory, but '" + processDefinitionId + "' has been provided."); } this.processDefinitionId = processDefinitionId; } public String execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache(); ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadProcessDefinition(processDefinition); } Expression formKeyExpression = null; if (taskDefinitionKey == null) { FormDefinition formDefinition = processDefinition.getStartFormDefinition(); formKeyExpression = formDefinition.getFormKey(); } else { TaskDefinition taskDefinition = processDefinition.getTaskDefinitions().get(taskDefinitionKey); formKeyExpression = taskDefinition.getFormKey(); } String formKey = null; if (formKeyExpression != null) { formKey = formKeyExpression.getExpressionText(); } return formKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetFormKeyCmd.java
1
请完成以下Java代码
public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override
public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item_Product.java
1
请完成以下Java代码
public static Map<String, Map<String, String>> parseIniFile(File fileToParse) throws IOException, ConfigurationException { Map<String, Map<String, String>> iniFileContents = new HashMap<>(); INIConfiguration iniConfiguration = new INIConfiguration(); try (FileReader fileReader = new FileReader(fileToParse)) { iniConfiguration.read(fileReader); } for (String section : iniConfiguration.getSections()) { Map<String, String> subSectionMap = new HashMap<>(); SubnodeConfiguration confSection = iniConfiguration.getSection(section); Iterator<String> keyIterator = confSection.getKeys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); String value = confSection.getProperty(key) .toString();
subSectionMap.put(key, value); } iniFileContents.put(section, subSectionMap); } return iniFileContents; } public static String readIniFileValue(File fileToParse, String section, String value) throws IOException, ConfigurationException { INIConfiguration iniConfiguration = new INIConfiguration(); try (FileReader fileReader = new FileReader(fileToParse)) { iniConfiguration.read(fileReader); } return iniConfiguration.getSection(section).getProperty(value).toString(); } }
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\ini\CommonsParser.java
1
请完成以下Java代码
public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName ()
{ return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue.java
1
请完成以下Java代码
public class SmsFlashPromotion implements Serializable { private Long id; @ApiModelProperty(value = "秒杀时间段名称") private String title; @ApiModelProperty(value = "开始日期") private Date startDate; @ApiModelProperty(value = "结束日期") private Date endDate; @ApiModelProperty(value = "上下线状态") private Integer status; @ApiModelProperty(value = "创建时间") private Date createTime; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } 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
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("adLanguageParamName", adLanguageParamName) .add("stringBaseLang", stringBaseLang) .add("stringTrl", stringTrl) .toString(); } @Override public String getAD_LanguageParamName() { return adLanguageParamName; } @Override public String getStringBaseLanguage() { return stringBaseLang; } @Override public String getStringTrlPattern() { return stringTrl; } @Override public String translate(final String adLanguage) { if (Language.isBaseLanguage(adLanguage)) { return stringBaseLang; } else { return stringTrl; } } } private static final class NoTranslatableParameterizedString extends TranslatableParameterizedString { private final String adLanguageParamName; private final String string; private NoTranslatableParameterizedString(final String adLanguageParamName, final String string) { super(); this.adLanguageParamName = adLanguageParamName; this.string = string; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues()
.add("adLanguageParamName", adLanguageParamName) .add("string", string) .toString(); } @Override public String getAD_LanguageParamName() { return adLanguageParamName; } @Override public String getStringBaseLanguage() { return string; } @Override public String getStringTrlPattern() { return string; } @Override public String translate() { return string; } @Override public String translate(final String adLanguage) { return string; } @Override public NoTranslatableParameterizedString transform(final Function<String, String> mappingFunction) { final String stringTransformed = mappingFunction.apply(string); if (Objects.equals(string, stringTransformed)) { return this; } return new NoTranslatableParameterizedString(adLanguageParamName, stringTransformed); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableParameterizedString.java
1
请完成以下Java代码
private Collection<TbTransportService> getTransportServices() { return applicationContext.getBeansOfType(TbTransportService.class).values(); } @Override public ServiceInfo getServiceInfo() { return serviceInfo; } @Override public boolean isMonolith() { return serviceType.equalsIgnoreCase("monolith"); } @Override public boolean isService(ServiceType serviceType) { return serviceTypes.contains(serviceType); } @Override public ServiceInfo generateNewServiceInfoWithCurrentSystemInfo() { ServiceInfo.Builder builder = ServiceInfo.newBuilder() .setServiceId(serviceId) .addAllServiceTypes(serviceTypes.stream().map(ServiceType::name).collect(Collectors.toList())) .setSystemInfo(getCurrentSystemInfoProto()); if (CollectionsUtil.isNotEmpty(assignedTenantProfiles)) { builder.addAllAssignedTenantProfiles(assignedTenantProfiles.stream().map(UUID::toString).collect(Collectors.toList())); } if (edqsConfig != null) { builder.setLabel(edqsConfig.getLabel()); } builder.setReady(ready); builder.addAllTaskTypes(taskTypes.stream().map(JobType::name).toList()); return serviceInfo = builder.build(); } @Override
public boolean setReady(boolean ready) { boolean changed = this.ready != ready; this.ready = ready; return changed; } private TransportProtos.SystemInfoProto getCurrentSystemInfoProto() { TransportProtos.SystemInfoProto.Builder builder = TransportProtos.SystemInfoProto.newBuilder(); getCpuUsage().ifPresent(builder::setCpuUsage); getMemoryUsage().ifPresent(builder::setMemoryUsage); getDiscSpaceUsage().ifPresent(builder::setDiskUsage); getCpuCount().ifPresent(builder::setCpuCount); getTotalMemory().ifPresent(builder::setTotalMemory); getTotalDiscSpace().ifPresent(builder::setTotalDiscSpace); return builder.build(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\discovery\DefaultTbServiceInfoProvider.java
1
请完成以下Java代码
public boolean isAutoActivate() { return isAutoActivate; } public void setProcessEngines(List<ProcessEngineImpl> processEngines) { this.processEngines = processEngines; } public void setAutoActivate(boolean isAutoActivate) { this.isAutoActivate = isAutoActivate; } public int getMaxJobsPerAcquisition() { return maxJobsPerAcquisition; } public void setMaxJobsPerAcquisition(int maxJobsPerAcquisition) { this.maxJobsPerAcquisition = maxJobsPerAcquisition; } public float getWaitIncreaseFactor() { return waitIncreaseFactor; } public void setWaitIncreaseFactor(float waitIncreaseFactor) { this.waitIncreaseFactor = waitIncreaseFactor; } public long getMaxWait() { return maxWait; } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } public long getMaxBackoff() { return maxBackoff; } public void setMaxBackoff(long maxBackoff) { this.maxBackoff = maxBackoff; } public int getBackoffDecreaseThreshold() { return backoffDecreaseThreshold; } public void setBackoffDecreaseThreshold(int backoffDecreaseThreshold) { this.backoffDecreaseThreshold = backoffDecreaseThreshold; } public String getName() { return name; } public Command<AcquiredJobs> getAcquireJobsCmd(int numJobs) { return acquireJobsCmdFactory.getCommand(numJobs); } public AcquireJobsCommandFactory getAcquireJobsCmdFactory() { return acquireJobsCmdFactory; } public void setAcquireJobsCmdFactory(AcquireJobsCommandFactory acquireJobsCmdFactory) { this.acquireJobsCmdFactory = acquireJobsCmdFactory; } public boolean isActive() { return isActive; }
public RejectedJobsHandler getRejectedJobsHandler() { return rejectedJobsHandler; } public void setRejectedJobsHandler(RejectedJobsHandler rejectedJobsHandler) { this.rejectedJobsHandler = rejectedJobsHandler; } protected void startJobAcquisitionThread() { if (jobAcquisitionThread == null) { jobAcquisitionThread = new Thread(acquireJobsRunnable, getName()); jobAcquisitionThread.start(); } } protected void stopJobAcquisitionThread() { try { jobAcquisitionThread.join(); } catch (InterruptedException e) { LOG.interruptedWhileShuttingDownjobExecutor(e); } jobAcquisitionThread = null; } public AcquireJobsRunnable getAcquireJobsRunnable() { return acquireJobsRunnable; } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutor.java
1
请完成以下Java代码
protected void addListenerEntry(final int workpackageId, final ListenerEntry entry) { listenersLock.lock(); try { _listeners.add(workpackageId, entry); } finally { listenersLock.unlock(); } } protected boolean removeListenerEntry(final int workpackageId) { List<ListenerEntry> entries; listenersLock.lock(); try { entries = _listeners.remove(workpackageId); } finally { listenersLock.unlock(); } return entries != null && !entries.isEmpty(); } protected boolean removeListenerEntry(final int workpackageId, final IQueueProcessorListener callback) { listenersLock.lock(); try { final List<ListenerEntry> entries = _listeners.get(workpackageId); if (entries == null) { return false; } boolean removed = false; for (final Iterator<ListenerEntry> it = entries.iterator(); it.hasNext();) { final ListenerEntry entry = it.next(); if (Util.same(entry.getListener(), callback)) { it.remove(); removed = true; } } if (entries.isEmpty()) { _listeners.remove(workpackageId); } return removed; } finally { listenersLock.unlock(); } } @Override public void fireWorkpackageProcessed(final I_C_Queue_WorkPackage workpackage, final IWorkpackageProcessor workpackageProcessor) { final int workpackageId = workpackage.getC_Queue_WorkPackage_ID(); final List<ListenerEntry> entries = getAndRemoveListenerEntries(workpackageId); if (entries == null) { return; } for (final ListenerEntry entry : entries) { final IQueueProcessorListener listener = entry.getListener();
try { listener.onWorkpackageProcessed(workpackage, workpackageProcessor); } catch (final Exception e) { logger.error("Error while executing " + listener + " for " + workpackage + " [SKIP]", e); // NOTE: we are not throwing the error because there is not much to handle it, everything was consumed before } } } @Override public void registerListener(@NonNull final IQueueProcessorListener listener, final int workpackageId) { Check.assume(workpackageId > 0, "workpackageId > 0"); // If it's null then don't register it if (listener == NullQueueProcessorListener.instance) { return; } final ListenerEntry entry = new ListenerEntry(listener, workpackageId); addListenerEntry(workpackageId, entry); } @Override public boolean unregisterListener(final IQueueProcessorListener callback, final int workpackageId) { // If it's null then don't unregister it because it was never registered if (callback == NullQueueProcessorListener.instance) { return false; } return removeListenerEntry(workpackageId, callback); } @Override public boolean unregisterListeners(final int workpackageId) { return removeListenerEntry(workpackageId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\DefaultQueueProcessorEventDispatcher.java
1
请完成以下Java代码
public AccessorBuilder<?> withBody(CodeBlock code) { this.code = code; return this; } /** * Builds the accessor. * @return the parent getter / setter */ public T buildAccessor() { this.accessorFunction.accept(new Accessor(this)); return this.parent; } } static final class Accessor implements Annotatable { private final AnnotationContainer annotations; private final CodeBlock code; Accessor(AccessorBuilder<?> builder) {
this.annotations = builder.annotations.deepCopy(); this.code = builder.code; } CodeBlock getCode() { return this.code; } @Override public AnnotationContainer annotations() { return this.annotations; } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java
1
请完成以下Java代码
public class ReportingSource1Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link String }
* */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = 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_02\ReportingSource1Choice.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthenticationImpl implements Authentication { private final String name; private final Collection<GrantedAuthorityImpl> grantedAuthorities; private boolean isAuthenticated; public AuthenticationImpl(String name, List<String> roles) { this.name = name; List<GrantedAuthorityImpl> authorities = new ArrayList<>(); roles.forEach(r->{ authorities.add(new GrantedAuthorityImpl(r)); }); this.grantedAuthorities = Collections.unmodifiableCollection(authorities); this.isAuthenticated = true; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return grantedAuthorities; } @Override public Object getCredentials() { return null; } @Override public Object getDetails() { return null; }
@Override public Object getPrincipal() { return name; } @Override public boolean isAuthenticated() { return isAuthenticated; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { this.isAuthenticated = isAuthenticated; } @Override public String getName() { return name; } }
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\AuthenticationImpl.java
2
请完成以下Java代码
public static void setCurrentProcessApplication(ProcessApplicationReference reference) { Deque<ProcessApplicationReference> stack = getStack(processApplicationContext); stack.push(reference); } public static void removeCurrentProcessApplication() { Deque<ProcessApplicationReference> stack = getStack(processApplicationContext); stack.pop(); } /** * Use {@link #executeWithinProcessApplication(Callable, ProcessApplicationReference, InvocationContext)} * instead if an {@link InvocationContext} is available. */ public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) { return executeWithinProcessApplication(callback, processApplicationReference, null); } public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference, InvocationContext invocationContext) { String paName = processApplicationReference.getName(); try { ProcessApplicationInterface processApplication = processApplicationReference.getProcessApplication(); setCurrentProcessApplication(processApplicationReference); try { // wrap callback ProcessApplicationClassloaderInterceptor<T> wrappedCallback = new ProcessApplicationClassloaderInterceptor<T>(callback); // execute wrapped callback return processApplication.execute(wrappedCallback, invocationContext); } catch (Exception e) {
// unwrap exception if(e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); }else { throw new ProcessEngineException("Unexpected exeption while executing within process application ", e); } } finally { removeCurrentProcessApplication(); } } catch (ProcessApplicationUnavailableException e) { throw new ProcessEngineException("Cannot switch to process application '"+paName+"' for execution: "+e.getMessage(), e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\context\Context.java
1
请在Spring Boot框架中完成以下Java代码
public class ImpFormatRepository { private final ImportTableDescriptorRepository importTableDescriptorRepo; public ImpFormatRepository(@NonNull final ImportTableDescriptorRepository importTableDescriptorRepo) { this.importTableDescriptorRepo = importTableDescriptorRepo; } public ImpFormat getById(@NonNull final ImpFormatId impFormatId) { final I_AD_ImpFormat impFormatRecord = InterfaceWrapperHelper.loadOutOfTrx(impFormatId, I_AD_ImpFormat.class); return toImpFormat(impFormatRecord); } public ImpFormat toImpFormat(@NonNull final I_AD_ImpFormat impFormatRecord) { final ImpFormatId impFormatId = ImpFormatId.ofRepoId(impFormatRecord.getAD_ImpFormat_ID()); final ImmutableList<ImpFormatColumn> columns = retrieveColumns(impFormatId); final AdTableId adTableId = AdTableId.ofRepoId(impFormatRecord.getAD_Table_ID()); final ImportTableDescriptor importTableDescriptor = importTableDescriptorRepo.getByTableId(adTableId); return ImpFormat.builder() .id(impFormatId) .name(impFormatRecord.getName()) .formatType(ImpFormatType.ofCode(impFormatRecord.getFormatType())) .multiLine(impFormatRecord.isMultiLine()) .manualImport(impFormatRecord.isManualImport()) .importTableDescriptor(importTableDescriptor) .columns(columns) .charset(Charset.forName(impFormatRecord.getFileCharset())) .skipFirstNRows(impFormatRecord.getSkipFirstNRows()) .build(); } private ImmutableList<ImpFormatColumn> retrieveColumns(@NonNull final ImpFormatId impFormatId) { return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_ImpFormat_Row.class) .addEqualsFilter(I_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_ID, impFormatId)
.addOnlyActiveRecordsFilter() .orderBy(I_AD_ImpFormat_Row.COLUMNNAME_SeqNo) .create() .stream(I_AD_ImpFormat_Row.class) .map(this::toImpFormatRowOrNull) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } private ImpFormatColumn toImpFormatRowOrNull(final I_AD_ImpFormat_Row rowRecord) { final I_AD_Column adColumn = rowRecord.getAD_Column(); if (!adColumn.isActive()) { return null; } return ImpFormatColumn.builder() .name(rowRecord.getName()) .columnName(adColumn.getColumnName()) .startNo(rowRecord.getStartNo()) .endNo(rowRecord.getEndNo()) .dataType(ImpFormatColumnDataType.ofCode(rowRecord.getDataType())) .maxLength(adColumn.getFieldLength()) .dataFormat(rowRecord.getDataFormat()) .decimalSeparator(DecimalSeparator.ofNullableStringOrDot(rowRecord.getDecimalPoint())) .divideBy100(rowRecord.isDivideBy100()) .constantValue(rowRecord.getConstantValue()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatRepository.java
2
请完成以下Java代码
public String getDunningExportProviderId() { return ForumDatenaustauschChConstants.DUNNING_EXPORT_PROVIDER_ID; } @Override public Optional<DunningExportClient> newClientForDunning(@NonNull final DunningToExport dunning) { final String requiredAttachmentTagName = InvoiceExportClientFactory.ATTACHMENT_TAGNAME_EXPORT_PROVIDER; final String requiredAttachmentTagValue = ForumDatenaustauschChConstants.INVOICE_EXPORT_PROVIDER_ID; boolean atLeastOneattachmentWasCreatedByForumDatenaustausch = false; for (final DunningAttachment dunningAttachment : dunning.getDunningAttachments()) { final String invoiceExportProvider = dunningAttachment.getTags().get(requiredAttachmentTagName); if (requiredAttachmentTagValue.equals(invoiceExportProvider)) { atLeastOneattachmentWasCreatedByForumDatenaustausch = true; break; } } if (!atLeastOneattachmentWasCreatedByForumDatenaustausch) { Loggables.addLog("forum_datenaustausch_ch - The dunning with id={} has no attachment with an {}={}-tag", dunning.getId(), requiredAttachmentTagName, requiredAttachmentTagValue); return Optional.empty(); } final BPartnerId recipientId = dunning.getRecipientId(); final BPartnerQuery query = BPartnerQuery .builder() .bPartnerId(de.metas.bpartner.BPartnerId.ofRepoId(recipientId.getRepoId()))
.build(); final ExportConfig config = configRepository.getForQueryOrNull(query); if (config == null) { Loggables.addLog("forum_datenaustausch_ch - There is no export config for the recipiend-id={} of the invoice with id={}", recipientId, dunning.getId()); return Optional.empty(); } final DunningExportClientImpl client = new DunningExportClientImpl(crossVersionServiceRegistry, config); if (!client.canExport(dunning)) { Loggables.addLog("forum_datenaustausch_ch - the export-client {} claims that it can't export the dunning with id={}", client.getClass().getSimpleName(), dunning.getId()); return Optional.empty(); } return Optional.of(client); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientFactoryImpl.java
1
请完成以下Java代码
public WarehouseId getWarehouseId() { return Services.get(IShipmentScheduleEffectiveBL.class).getWarehouseId(shipmentSchedule); } public I_C_UOM getOrderPriceUOM() { final int priceUomId = getSalesOrderLine().getPrice_UOM_ID(); return Services.get(IUOMDAO.class).getById(priceUomId); } public BigDecimal getOrderQtyReserved() { return getSalesOrderLine().getQtyReserved(); } public BigDecimal getOrderPriceActual() { return getSalesOrderLine().getPriceActual(); } public DocStatus getOrderDocStatus() { return DocStatus.ofCode(getSalesOrderLine().getC_Order().getDocStatus()); } public I_M_ShipmentSchedule getSched() { return shipmentSchedule; } public ShipmentScheduleId getShipmentScheduleId() { return ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID()); } /** * @return shipment schedule's QtyToDeliver_Override or <code>null</code> */ public BigDecimal getQtyOverride() { return InterfaceWrapperHelper.getValueOrNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
} public BigDecimal getInitialSchedQtyDelivered() { return initialSchedQtyDelivered; } public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt) { shipmentSchedule.setLineNetAmt(lineNetAmt); } @Nullable public String getSalesOrderPORef() { return salesOrder.map(I_C_Order::getPOReference).orElse(null); } @Nullable public InputDataSourceId getSalesOrderADInputDatasourceID() { if(!salesOrder.isPresent()) { return null; } final I_C_Order orderRecord = salesOrder.get(); return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Product Nutrition. @param M_Product_Nutrition_ID Product Nutrition */ @Override public void setM_Product_Nutrition_ID (int M_Product_Nutrition_ID) { if (M_Product_Nutrition_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Nutrition_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Nutrition_ID, Integer.valueOf(M_Product_Nutrition_ID)); } /** Get Product Nutrition. @return Product Nutrition */
@Override public int getM_Product_Nutrition_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Nutrition_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Nutrition Quanitity. @param NutritionQty Nutrition Quanitity */ @Override public void setNutritionQty (java.lang.String NutritionQty) { set_Value (COLUMNNAME_NutritionQty, NutritionQty); } /** Get Nutrition Quanitity. @return Nutrition Quanitity */ @Override public java.lang.String getNutritionQty () { return (java.lang.String)get_Value(COLUMNNAME_NutritionQty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Nutrition.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisConn { private String host; private int port; private int timeout; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; }
public void setPort(int port) { this.port = port; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } @Override public String toString() { return "Redis [localhost=" + host + ", port=" + port + ", timeout=" + timeout + "]"; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\redis\RedisConn.java
2
请完成以下Java代码
public class Book { private long id; private String name; public Book() { } public Book(long id, String name) { this.id = id; this.name = name; } @XmlAttribute public void setId(Long id) { this.id = id;
} @XmlElement(name = "title") public void setName(String name) { this.name = name; } public String getName() { return name; } public Long getId() { return id; } }
repos\tutorials-master\core-java-modules\core-java-9\src\main\java\com\baeldung\java9\prejpms\Book.java
1
请完成以下Java代码
private String getValueFrom(String field, String duedateDescription) { int fieldIndex = duedateDescription.indexOf(field + ":"); if (fieldIndex > -1) { int nextWhiteSpace = duedateDescription.indexOf(" ", fieldIndex); fieldIndex += field.length() + 1; if (nextWhiteSpace > -1) { return duedateDescription.substring(fieldIndex, nextWhiteSpace); } else { return duedateDescription.substring(fieldIndex); } } return null; }
private String removeValueFrom(String field, String duedateDescription) { int fieldIndex = duedateDescription.indexOf(field + ":"); if (fieldIndex > -1) { int nextWhiteSpace = duedateDescription.indexOf(" ", fieldIndex); if (nextWhiteSpace > -1) { return duedateDescription.replace(duedateDescription.substring(fieldIndex, nextWhiteSpace), ""); } else { return duedateDescription.substring(0, fieldIndex); } } return duedateDescription; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\AdvancedCycleBusinessCalendar.java
1
请完成以下Java代码
public AttributeListValue getCreateAttributeValue(final IContextAware context, final ICountryAware countryAware) { final Properties ctx = context.getCtx(); final String trxName = context.getTrxName(); final I_C_Country country = countryAware.getC_Country(); final SOTrx soTrx = SOTrx.ofBoolean(countryAware.isSOTrx()); final AttributeListValue attributeValue = Services.get(ICountryAttributeDAO.class).retrieveAttributeValue(ctx, country, false/* includeInactive */); final AttributeAction attributeAction = Services.get(IAttributesBL.class).getAttributeAction(ctx); if (attributeValue == null) { if (attributeAction == AttributeAction.Error) { throw new AdempiereException(MSG_NoCountryAttribute, country.getName()); } else if (attributeAction == AttributeAction.GenerateNew) { final Attribute countryAttribute = Services.get(ICountryAttributeDAO.class).retrieveCountryAttribute(ctx); final IAttributeValueGenerator generator = Services.get(IAttributesBL.class).getAttributeValueGenerator(countryAttribute); return generator.generateAttributeValue(ctx, I_C_Country.Table_ID, country.getC_Country_ID(), false, trxName); // SO trx doesn't matter here } else if (attributeAction == AttributeAction.Ignore) { // Ignore: do not throw error, no not generate new attribute } else { throw new AdempiereException("@NotSupported@ AttributeAction " + attributeAction);
} return attributeValue; } else { if (!attributeValue.isMatchingSOTrx(soTrx)) { if (attributeAction == AttributeAction.Error) { throw new AttributeRestrictedException(ctx, soTrx, attributeValue, country.getCountryCode()); } // We have an attribute value, but it is marked for a different transaction. Change type to "null", to make it available for both. final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); return attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValue.getId()) .availableForTrx(AttributeListValueTrxRestriction.ANY_TRANSACTION) .build()); } else { return attributeValue; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\Country2CountryAwareAttributeService.java
1
请完成以下Java代码
public class Article implements Serializable { //主键 private Integer id; //文章标题 private String articleTitle; //文章内容 private String articleContent; //添加人 private String addName; //添加时间 @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date createTime; //最新更新时间 @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date updateTime; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public void setArticleTitle(String articleTitle) { this.articleTitle = articleTitle; } public String getArticleTitle() { return articleTitle; } public void setArticleContent(String articleContent) { this.articleContent = articleContent; }
public String getArticleContent() { return articleContent; } public void setAddName(String addName) { this.addName = addName; } public String getAddName() { return addName; } 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; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\entity\Article.java
1
请完成以下Java代码
public ViewRowIdsOrderedSelections withOrderBysSelectionIfAbsent( @NonNull final DocumentQueryOrderByList orderBys, @NonNull final ViewRowIdsOrderedSelectionFactory factory) { final ViewRowIdsOrderedSelection selection = getSelectionOrNull(orderBys); if (selection != null) { return this; } final ImmutableMap<DocumentQueryOrderByList, ViewRowIdsOrderedSelection> selectionsByOrderBysNew = ImmutableMap.<DocumentQueryOrderByList, ViewRowIdsOrderedSelection> builder() .putAll(selectionsByOrderBys) .put(orderBys, factory.create(defaultSelection, orderBys)) .build(); return new ViewRowIdsOrderedSelections(defaultSelectionBeforeFacetsFiltering, defaultSelection, selectionsByOrderBysNew); } public ViewRowIdsOrderedSelection getSelection(final DocumentQueryOrderByList orderBys) { final ViewRowIdsOrderedSelection selection = getSelectionOrNull(orderBys); if (selection == null) { throw new AdempiereException("No selection found for " + orderBys + " in " + this); } return selection; } private ViewRowIdsOrderedSelection getSelectionOrNull(final DocumentQueryOrderByList orderBys) { if (orderBys == null || orderBys.isEmpty()) { return defaultSelection; }
if (DocumentQueryOrderByList.equals(defaultSelection.getOrderBys(), orderBys)) { return defaultSelection; } return selectionsByOrderBys.get(orderBys); } public ImmutableSet<String> getSelectionIds() { final ImmutableSet.Builder<String> selectionIds = ImmutableSet.builder(); selectionIds.add(defaultSelection.getSelectionId()); for (final ViewRowIdsOrderedSelection selection : selectionsByOrderBys.values()) { selectionIds.add(selection.getSelectionId()); } return selectionIds.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelections.java
1
请完成以下Java代码
final class Regex implements CharSequence { static final Pattern DOMAIN; static { Regex component = Regex.oneOf("[a-zA-Z0-9]", "[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]"); Regex dotComponent = Regex.group("[.]", component); Regex colonPort = Regex.of("[:][0-9]+"); Regex dottedDomain = Regex.group(component, dotComponent.oneOrMoreTimes()); Regex dottedDomainAndPort = Regex.group(component, dotComponent.oneOrMoreTimes(), colonPort); Regex nameAndPort = Regex.group(component, colonPort); DOMAIN = Regex.oneOf(dottedDomain, nameAndPort, dottedDomainAndPort, "localhost").compile(); } private static final Regex PATH_COMPONENT; static { Regex segment = Regex.of("[a-z0-9]+"); Regex separator = Regex.group("[._-]{1,2}"); Regex separatedSegment = Regex.group(separator, segment).oneOrMoreTimes(); PATH_COMPONENT = Regex.of(segment, Regex.group(separatedSegment).zeroOrOnce()); } static final Pattern PATH; static { Regex component = PATH_COMPONENT; Regex slashComponent = Regex.group("[/]", component); Regex slashComponents = Regex.group(slashComponent.oneOrMoreTimes()); PATH = Regex.of(component, slashComponents.zeroOrOnce()).compile(); } static final Pattern TAG = Regex.of("^[\\w][\\w.-]{0,127}").compile(); static final Pattern DIGEST = Regex.of("^[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[A-Fa-f0-9]]{32,}") .compile(); private final String value; private Regex(CharSequence value) { this.value = value.toString(); } private Regex oneOrMoreTimes() { return new Regex(this.value + "+"); } private Regex zeroOrOnce() { return new Regex(this.value + "?"); } Pattern compile() { return Pattern.compile("^" + this.value + "$"); } @Override public int length() { return this.value.length(); } @Override public char charAt(int index) {
return this.value.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.value.subSequence(start, end); } @Override public String toString() { return this.value; } private static Regex of(CharSequence... expressions) { return new Regex(String.join("", expressions)); } private static Regex oneOf(CharSequence... expressions) { return new Regex("(?:" + String.join("|", expressions) + ")"); } private static Regex group(CharSequence... expressions) { return new Regex("(?:" + String.join("", expressions) + ")"); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\Regex.java
1
请完成以下Java代码
public String getEngineName() { return NAME; } public String getEngineVersion() { return VERSION; } public List<String> getExtensions() { return extensions; } public List<String> getMimeTypes() { return mimeTypes; } public List<String> getNames() { return names; } public String getLanguageName() { return NAME; } public String getLanguageVersion() { return VERSION; } public Object getParameter(String key) { if (key.equals(ScriptEngine.NAME)) { return getLanguageName(); } else if (key.equals(ScriptEngine.ENGINE)) { return getEngineName(); } else if (key.equals(ScriptEngine.ENGINE_VERSION)) { return getEngineVersion(); } else if (key.equals(ScriptEngine.LANGUAGE)) { return getLanguageName(); } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { return getLanguageVersion(); } else if (key.equals("THREADING")) { return "MULTITHREADED"; } else { return null; } } public String getMethodCallSyntax(String object, String method, String... args) { return "${" + object + "." + method + "(" + joinStrings(", ", args) + ")}"; }
public String getOutputStatement(String toDisplay) { return toDisplay; } public String getProgram(String... statements) { return joinStrings("\n", statements); } protected String joinStrings(String delimiter, String[] values) { if (values == null) { return null; } else { return String.join(delimiter, values); } } public ScriptEngine getScriptEngine() { return new FreeMarkerScriptEngine(this); } }
repos\camunda-bpm-platform-master\freemarker-template-engine\src\main\java\org\camunda\templateengines\FreeMarkerScriptEngineFactory.java
1
请完成以下Spring Boot application配置
## tomcat\u914D\u7F6E server.port=9666 #server.tomcat.maxHttpHeaderSize=8192 server.tomcat.uri-encoding=UTF-8 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true spring.messages.encoding=UTF-8 # tomcat\u6700\u5927\u7EBF\u7A0B\u6570\uFF0C\u9ED8\u8BA4\u4E3A200 server.tomcat.max-threads=800 # session\u6700\u5927\u8D85\u65F6\u65F6\u95F4(\u5206\u949F)\uFF0C\u9ED8\u8BA4\u4E3A30 server.session-timeout=60 ## spring \u914D\u7F6E spring.application.name=redis-queue application.main=cn.abel.queue.Application ## LOG logging.file=./logs/redis-queue.log ## spring cache #\u7F13\u5B58\u7684\u540D\u79F0\u96C6\u5408\uFF0C\u591A\u4E2A\u91C7\u7528\u9017\u53F7\u5206\u5272 #spring.cache.cache-names=admin,role #\u7F13\u5B58\u7684\u7C7B\u578B\uFF0C\u5B98\u65B9\u63D0\u4F9B\u4E86\u5F88\u591A\uFF0C\u8FD9\u91CC\u6211\u4EEC\u586B\u5199redis spring.cache.type=redis #\u662F\u5426\u7F13\u5B58null\u6570\u636E\uFF0C\u9ED8\u8BA4\u662Ffalse #spring.cache.redis.cache-null-values=false #redis\u4E2D\u7F13\u5B58\u8D85\u65F6\u7684\u65F6\u95F4\uFF0C\u9ED8\u8BA460000ms #spring.cache.redis.time-to-live=60000 #\u7F13\u5B58\u6570\u636Ekey\u662F\u5426\u4F7F\u7528\u524D\u7F00\uFF0C\u9ED8\u8BA4\u662Ftrue #spring.cache.redis.use-key-prefix=true #\u7F13\u5B58\u6570\u636Ekey\u7684\u524D\u7F00\uFF0C\u5728\u4E0A\u9762\u7684\u914D\u7F6E\u4E3Atrue\u65F6\u6709\u6548\uFF0C # Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u5E93\uFF09 spring.redis.database=2 # Redis\u670D\u52A1\u5668\u5730\u5740 spring.redis.host=127.0.0.1 # Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3 spring.redis.port=6379 # Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\u
FF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09 spring.redis.password= # \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 spring.redis.lettuce.pool.max-active=100 # \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 spring.redis.lettuce.pool.max-wait=1000 # \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5 spring.redis.lettuce.pool.max-idle=50 # \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5 spring.redis.lettuce.pool.min-idle=0 # \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09 spring.redis.lettuce.shutdown-timeout=0
repos\springBoot-master\springboot-redis-queue\src\main\resources\local\application.properties
2
请完成以下Java代码
public boolean match(Class<C> callbackType, C callbackInstance, A argument, Object[] additionalArguments) { ResolvableType type = ResolvableType.forClass(callbackType, callbackInstance.getClass()); if (type.getGenerics().length == 1 && type.resolveGeneric() != null) { return type.resolveGeneric().isInstance(argument); } return true; } } /** * The result of a callback which may be a value, {@code null} or absent entirely if * the callback wasn't suitable. Similar in design to {@link Optional} but allows for * {@code null} as a valid value. * * @param <R> the result type */ public static final class InvocationResult<R> { private static final InvocationResult<?> NONE = new InvocationResult<>(null); private final R value; private InvocationResult(R value) { this.value = value; } /** * Return true if a result in present. * @return if a result is present */ public boolean hasResult() { return this != NONE; } /** * Return the result of the invocation or {@code null} if the callback wasn't * suitable. * @return the result of the invocation or {@code null} */ public R get() { return this.value;
} /** * Return the result of the invocation or the given fallback if the callback * wasn't suitable. * @param fallback the fallback to use when there is no result * @return the result of the invocation or the fallback */ public R get(R fallback) { return (this != NONE) ? this.value : fallback; } /** * Create a new {@link InvocationResult} instance with the specified value. * @param value the value (may be {@code null}) * @param <R> the result type * @return an {@link InvocationResult} */ public static <R> InvocationResult<R> of(R value) { return new InvocationResult<>(value); } /** * Return an {@link InvocationResult} instance representing no result. * @param <R> the result type * @return an {@link InvocationResult} */ @SuppressWarnings("unchecked") public static <R> InvocationResult<R> noResult() { return (InvocationResult<R>) NONE; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\util\LambdaSafe.java
1
请完成以下Java代码
public class TimerDemoExample { private void scheduleOnce() { TimerTask task = new TimerTask() { public void run() { System.out.println("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread() .getName()); } }; Timer timer = new Timer("Timer"); long delay = 1000L; timer.schedule(task, delay); } private void scheduleRecurrently() { TimerTask task = new TimerTask() {
public void run() { System.out.println("Recurrent Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread() .getName()); } }; Timer timer = new Timer("Timer"); long delay = 1000L; final long period = 1000L; timer.scheduleAtFixedRate(task, delay, period); } public static void main(String[] args) { TimerDemoExample timerDemoExample = new TimerDemoExample(); timerDemoExample.scheduleOnce(); timerDemoExample.scheduleRecurrently(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-simple\src\main\java\com\baeldung\concurrent\startathread\TimerDemoExample.java
1
请在Spring Boot框架中完成以下Java代码
static class MongoCommandMetricsConfiguration { @Bean @ConditionalOnMissingBean MongoMetricsCommandListener mongoMetricsCommandListener(MeterRegistry meterRegistry, MongoCommandTagsProvider mongoCommandTagsProvider) { return new MongoMetricsCommandListener(meterRegistry, mongoCommandTagsProvider); } @Bean @ConditionalOnMissingBean MongoCommandTagsProvider mongoCommandTagsProvider() { return new DefaultMongoCommandTagsProvider(); } @Bean MongoClientSettingsBuilderCustomizer mongoMetricsCommandListenerClientSettingsBuilderCustomizer( MongoMetricsCommandListener mongoMetricsCommandListener) { return (clientSettingsBuilder) -> clientSettingsBuilder.addCommandListener(mongoMetricsCommandListener); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(MongoMetricsConnectionPoolListener.class) @ConditionalOnBooleanProperty(name = "management.metrics.mongodb.connectionpool.enabled", matchIfMissing = true) static class MongoConnectionPoolMetricsConfiguration {
@Bean @ConditionalOnMissingBean MongoMetricsConnectionPoolListener mongoMetricsConnectionPoolListener(MeterRegistry meterRegistry, MongoConnectionPoolTagsProvider mongoConnectionPoolTagsProvider) { return new MongoMetricsConnectionPoolListener(meterRegistry, mongoConnectionPoolTagsProvider); } @Bean @ConditionalOnMissingBean MongoConnectionPoolTagsProvider mongoConnectionPoolTagsProvider() { return new DefaultMongoConnectionPoolTagsProvider(); } @Bean MongoClientSettingsBuilderCustomizer mongoMetricsConnectionPoolListenerClientSettingsBuilderCustomizer( MongoMetricsConnectionPoolListener mongoMetricsConnectionPoolListener) { return (clientSettingsBuilder) -> clientSettingsBuilder .applyToConnectionPoolSettings((connectionPoolSettingsBuilder) -> connectionPoolSettingsBuilder .addConnectionPoolListener(mongoMetricsConnectionPoolListener)); } } }
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\metrics\MongoMetricsAutoConfiguration.java
2
请完成以下Java代码
public long getPZN() { return pzn; } /** * Sets the value of the pzn property. * */ public void setPZN(long value) { this.pzn = value; } /** * Gets the value of the retourenMenge property. * */ public int getRetourenMenge() { return retourenMenge; } /** * Sets the value of the retourenMenge property. * */ public void setRetourenMenge(int value) { this.retourenMenge = value; } /** * Gets the value of the retouregrund property. * * @return * possible object is * {@link RetoureGrund } * */ public RetoureGrund getRetouregrund() { return retouregrund; } /** * Sets the value of the retouregrund property. * * @param value * allowed object is * {@link RetoureGrund } * */ public void setRetouregrund(RetoureGrund value) { this.retouregrund = value; } /** * Gets the value of the charge property. * * @return * possible object is * {@link String } * */ public String getCharge() { return charge; } /** * Sets the value of the charge property. * * @param value
* allowed object is * {@link String } * */ public void setCharge(String value) { this.charge = value; } /** * Gets the value of the verfalldatum property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getVerfalldatum() { return verfalldatum; } /** * Sets the value of the verfalldatum property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setVerfalldatum(XMLGregorianCalendar value) { this.verfalldatum = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourePositionType.java
1
请完成以下Java代码
public boolean isConstant() { return true; } @Override public boolean constantValue() { return value; } @Override public ILogicExpression toConstantExpression(final boolean constantValue) { if (constantValue != value) { throw new ExpressionCompileException("Cannot convert a constant expression to a constant expression of opposite value" + "\n Expression: " + this + "\n Target value: " + constantValue); } return this; } @Override public String getExpressionString() { return expressionString; } @Override public Set<CtxName> getParameters() { return ImmutableSet.of(); } @Override public String toString() { return toStringValue; } @Override public String getFormatedExpressionString() { return expressionString; } @Override public Boolean evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{ return value; } @Override public Boolean evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) { return value; } @Override public LogicExpressionResult evaluateToResult(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { return value ? LogicExpressionResult.TRUE : LogicExpressionResult.FALSE; } @Override public ILogicExpression evaluatePartial(final Evaluatee ctx) { return this; } @Override public ILogicExpression negate() {return of(!value);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ConstantLogicExpression.java
1
请完成以下Java代码
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { logger.info("handleTextMessage start"); // 将消息进行转化,因为是消息是json数据,可能里面包含了发送给某个人的信息,所以需要用json相关的工具类处理之后再封装成TextMessage, // 我这儿并没有做处理,消息的封装格式一般有{from:xxxx,to:xxxxx,msg:xxxxx},来自哪里,发送给谁,什么消息等等 String msg = message.getPayload(); logger.info("msg = " + msg); WsParam<String> wsParam = JacksonUtil.json2Bean(msg, new TypeReference<WsParam<String>>(){}); if ("list".equals(wsParam.getMethod())) { logger.info("call list method..."); WsResponse<String> response = new WsResponse<>(); response.setResult("hello list"); sendMessageToUser(session, new TextMessage(JacksonUtil.bean2Json(response))); } logger.info("handleTextMessage end"); // 给所有用户群发消息 //sendMessagesToUsers(msg); // 给指定用户群发消息 //sendMessageToUser(userId, msg); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.info("Connected ... " + session.getId()); sessions.add(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { if (session.isOpen()) { session.close(); } sessions.remove(session); logger.info(String.format("Session %s closed because of %s", session.getId(), status.getReason())); } @Override public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception { logger.error("error occured at sender " + session, throwable); } /** * 给所有的用户发送消息 */ public void sendMessagesToUsers(TextMessage message) { for (WebSocketSession user : sessions) { try {
// isOpen()在线就发送 if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } /** * 发送消息给指定的用户 */ private void sendMessageToUser(WebSocketSession user, TextMessage message) { try { // 在线就发送 if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { logger.error("发送消息给指定的用户出错", e); } } }
repos\SpringBootBucket-master\springboot-websocket\src\main\java\com\xncoding\jwt\handler\SocketHandler.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(STATUS_KEY); } @Override public GatewayFilter apply(Config config) { String status = Objects.requireNonNull(config.status, "status must not be null"); HttpStatusHolder statusHolder = HttpStatusHolder.parse(status); return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // option 1 (runs in filter order) /* * exchange.getResponse().beforeCommit(() -> { * exchange.getResponse().setStatusCode(finalStatus); return Mono.empty(); * }); return chain.filter(exchange); */ // option 2 (runs in reverse filter order) return chain.filter(exchange).then(Mono.fromRunnable(() -> { // check not really needed, since it is guarded in setStatusCode, // but it's a good example HttpStatusCode statusCode = exchange.getResponse().getStatusCode(); boolean isStatusCodeUpdated = setResponseStatus(exchange, statusHolder); if (isStatusCodeUpdated && originalStatusHeaderName != null && statusCode != null) { exchange.getResponse() .getHeaders() .set(originalStatusHeaderName, singletonList(statusCode.value()).toString()); } })); } @Override public String toString() { return filterToStringCreator(SetStatusGatewayFilterFactory.this).append("status", config.getStatus()) .toString(); } }; }
public @Nullable String getOriginalStatusHeaderName() { return originalStatusHeaderName; } public void setOriginalStatusHeaderName(String originalStatusHeaderName) { this.originalStatusHeaderName = originalStatusHeaderName; } public static class Config { // TODO: relaxed HttpStatus converter private @Nullable String status; public @Nullable String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetStatusGatewayFilterFactory.java
1
请完成以下Java代码
public static KvEntry toKvEntry(Row row, String key) { KvEntry kvEntry = null; String strV = row.get(ModelConstants.STRING_VALUE_COLUMN, String.class); if (strV != null) { kvEntry = new StringDataEntry(key, strV); } else { Long longV = row.get(ModelConstants.LONG_VALUE_COLUMN, Long.class); if (longV != null) { kvEntry = new LongDataEntry(key, longV); } else { Double doubleV = row.get(ModelConstants.DOUBLE_VALUE_COLUMN, Double.class); if (doubleV != null) { kvEntry = new DoubleDataEntry(key, doubleV); } else { Boolean boolV = row.get(ModelConstants.BOOLEAN_VALUE_COLUMN, Boolean.class); if (boolV != null) { kvEntry = new BooleanDataEntry(key, boolV); } else { String jsonV = row.get(ModelConstants.JSON_VALUE_COLUMN, String.class); if (StringUtils.isNoneEmpty(jsonV)) { kvEntry = new JsonDataEntry(key, jsonV); } else { log.warn("All values in key-value row are nullable "); } } } } } return kvEntry; } protected List<TsKvEntry> convertResultToTsKvEntryList(List<Row> rows) { List<TsKvEntry> entries = new ArrayList<>(rows.size()); if (!rows.isEmpty()) { rows.forEach(row -> entries.add(convertResultToTsKvEntry(row))); } return entries; } private TsKvEntry convertResultToTsKvEntry(Row row) { String key = row.getString(ModelConstants.KEY_COLUMN); long ts = row.getLong(ModelConstants.TS_COLUMN); return new BasicTsKvEntry(ts, toKvEntry(row, key)); } protected TsKvEntry convertResultToTsKvEntry(String key, Row row) { if (row != null) { return getBasicTsKvEntry(key, row); } else { return new BasicTsKvEntry(System.currentTimeMillis(), new StringDataEntry(key, null)); } }
protected Optional<TsKvEntry> convertResultToTsKvEntryOpt(String key, Row row) { if (row != null) { return Optional.of(getBasicTsKvEntry(key, row)); } else { return Optional.empty(); } } private BasicTsKvEntry getBasicTsKvEntry(String key, Row row) { Optional<String> foundKeyOpt = getKey(row); long ts = row.getLong(ModelConstants.TS_COLUMN); return new BasicTsKvEntry(ts, toKvEntry(row, foundKeyOpt.orElse(key))); } private Optional<String> getKey(Row row){ try{ return Optional.ofNullable(row.getString(ModelConstants.KEY_COLUMN)); } catch (IllegalArgumentException e){ return Optional.empty(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\AbstractCassandraBaseTimeseriesDao.java
1
请完成以下Java代码
public Boolean checkPassword(String userId, String password, PasswordEncoder passwordEncoder, PasswordSalt salt) { User user = null; if (userId != null) { user = findById(userId); } return (user != null) && (password != null) && passwordEncoder.isMatches(password, user.getPassword(), salt); } @Override public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findUsersByNativeQuery(parameterMap); } @Override public long findUserCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findUserCountByNativeQuery(parameterMap); } @Override public boolean isNewUser(User user) { return ((UserEntity) user).getRevision() == 0; } @Override public Picture getUserPicture(User user) { UserEntity userEntity = (UserEntity) user; return userEntity.getPicture(); } @Override
public void setUserPicture(User user, Picture picture) { UserEntity userEntity = (UserEntity) user; userEntity.setPicture(picture); dataManager.update(userEntity); } @Override public List<User> findUsersByPrivilegeId(String name) { return dataManager.findUsersByPrivilegeId(name); } public UserDataManager getUserDataManager() { return dataManager; } public void setUserDataManager(UserDataManager userDataManager) { this.dataManager = userDataManager; } protected IdentityInfoEntityManager getIdentityInfoEntityManager() { return engineConfiguration.getIdentityInfoEntityManager(); } protected MembershipEntityManager getMembershipEntityManager() { return engineConfiguration.getMembershipEntityManager(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } // resource -> timestamp -> metric Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps());
oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } // Order by last minute b_qps DESC. return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\repository\metric\InMemoryMetricsRepository.java
2
请完成以下Java代码
public Amount add(@NonNull final Amount amtToAdd) { assertSameCurrency(this, amtToAdd); if (amtToAdd.isZero()) { return this; } else if (isZero()) { return amtToAdd; } else { return new Amount(value.add(amtToAdd.value), currencyCode); } } public Amount subtract(@NonNull final Amount amtToSubtract) { assertSameCurrency(this, amtToSubtract); if (amtToSubtract.isZero()) { return this; } else { return new Amount(value.subtract(amtToSubtract.value), currencyCode); } } public Amount multiply(@NonNull final Percent percent, @NonNull final CurrencyPrecision precision) { final BigDecimal newValue = percent.computePercentageOf(value, precision.toInt(), precision.getRoundingMode()); return !newValue.equals(value) ? new Amount(newValue, currencyCode)
: this; } public Amount abs() { return value.signum() < 0 ? new Amount(value.abs(), currencyCode) : this; } public Money toMoney(@NonNull final Function<CurrencyCode, CurrencyId> currencyIdMapper) { return Money.of(value, currencyIdMapper.apply(currencyCode)); } public static boolean equals(@Nullable final Amount a1, @Nullable final Amount a2) {return Objects.equals(a1, a2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\Amount.java
1
请在Spring Boot框架中完成以下Java代码
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; if(allowOrigin){ httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, httpServletRequest.getHeader(HttpHeaders.ORIGIN)); // 允许客户端请求方法 httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS,PUT,DELETE"); // 允许客户端提交的Header String requestHeaders = httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); if (StringUtils.isNotEmpty(requestHeaders)) { httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders); } // 允许客户端携带凭证信息(是否允许发送Cookie) httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } // 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态 if (RequestMethod.OPTIONS.name().equalsIgnoreCase(httpServletRequest.getMethod())) { httpServletResponse.setStatus(HttpStatus.OK.value()); return false; } // 代码逻辑说明: 多租户用到 String tenantId = httpServletRequest.getHeader(CommonConstant.TENANT_ID); TenantContext.setTenant(tenantId); return super.preHandle(request, response); }
/** * JwtFilter中ThreadLocal需要及时清除 #3634 * * @param request * @param response * @param exception * @throws Exception */ @Override public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception { //log.info("------清空线程中多租户的ID={}------",TenantContext.getTenant()); TenantContext.clear(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\filters\JwtFilter.java
2
请完成以下Java代码
public class RemoveExecutionVariablesCmd extends NeedsActiveExecutionCmd<Void> { private static final long serialVersionUID = 1L; private Collection<String> variableNames; private boolean isLocal; public RemoveExecutionVariablesCmd(String executionId, Collection<String> variableNames, boolean isLocal) { super(executionId); this.variableNames = variableNames; this.isLocal = isLocal; } @Override protected Void execute(CommandContext commandContext, ExecutionEntity execution) {
if (isLocal) { execution.removeVariablesLocal(variableNames); } else { execution.removeVariables(variableNames); } return null; } @Override protected String getSuspendedExceptionMessage() { return "Cannot remove variables because execution '" + executionId + "' is suspended"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\RemoveExecutionVariablesCmd.java
1
请完成以下Java代码
public String getBusinessKey() { return businessKey; } public boolean isOpen() { return unfinished; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public List<String> getProcessDefinitionKeyIn() { return processDefinitionKeyIn; } public String getProcessDefinitionIdLike() { return processDefinitionKey + ":%:%"; } public String getProcessDefinitionName() { return processDefinitionName; } public String getProcessDefinitionCategory() { return processDefinitionCategory; } public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public String getProcessInstanceId() { return processInstanceId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public String getStartedBy() { return startedBy; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public boolean isExcludeSubprocesses() { return excludeSubprocesses; } public List<String> getProcessKeyNotIn() { return processKeyNotIn; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; }
public Date getFinishedBefore() { return finishedBefore; } public String getInvolvedUser() { return involvedUser; } public String getName() { return name; } public String getNameLike() { return nameLike; } public static long getSerialversionuid() { return serialVersionUID; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public boolean isDeleted() { return deleted; } public boolean isNotDeleted() { return notDeleted; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isWithJobException() { return withJobException; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请完成以下Spring Boot application配置
server.port=9097 #management.security.enabled=false management.endpoint.restart.enabled=true management.endpoint.refresh.enabled=true management.endpoints.web.exposure.include=env,restart,refresh # =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle=true spring.datasource.validationQuery=SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Show or not log for each sql query spring.jpa.show-sql=true # Hibernate ddl auto (create, create-drop, update): with "create-drop" the database # schema will be automatically created afresh for every start of application spring.jp
a.hibernate.ddl-auto=create-drop # Naming strategy spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
repos\SpringBootVulExploit-master\repository\springboot-mysql-jdbc-rce\src\main\resources\application.properties
2
请完成以下Java代码
public ChangePlanItemStateBuilder childInstanceTaskVariables(String planItemDefinitionId, Map<String, Object> variables) { if (!this.childInstanceTaskVariables.containsKey(planItemDefinitionId)) { this.childInstanceTaskVariables.put(planItemDefinitionId, new HashMap<>()); } this.childInstanceTaskVariables.get(planItemDefinitionId).putAll(variables); return this; } @Override public void changeState() { if (runtimeService == null) { throw new FlowableException("CmmnRuntimeService cannot be null, Obtain your builder instance from the CmmnRuntimeService to access this feature"); } runtimeService.changePlanItemState(this); } public String getCaseInstanceId() { return caseInstanceId; } public Set<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitions() { return activatePlanItemDefinitions; } public Set<MoveToAvailablePlanItemDefinitionMapping> getChangeToAvailableStatePlanItemDefinitions() { return changeToAvailableStatePlanItemDefinitions; } public Set<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitions() { return terminatePlanItemDefinitions; } public Set<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitions() { return waitingForRepetitionPlanItemDefinitions; } public Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitions() { return removeWaitingForRepetitionPlanItemDefinitions;
} public Set<ChangePlanItemIdMapping> getChangePlanItemIds() { return changePlanItemIds; } public Set<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdsWithDefinitionId() { return changePlanItemIdsWithDefinitionId; } public Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIds() { return changePlanItemDefinitionWithNewTargetIds; } public Map<String, Object> getCaseVariables() { return caseVariables; } public Map<String, Map<String, Object>> getChildInstanceTaskVariables() { return childInstanceTaskVariables; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\ChangePlanItemStateBuilderImpl.java
1
请完成以下Java代码
public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public void setDeploymentIds(List<String> deploymentIds) { this.deploymentIds = deploymentIds; } public String getActiveActivityId() { return activeActivityId; } public void setActiveActivityId(String activeActivityId) { this.activeActivityId = activeActivityId; } public Set<String> getActiveActivityIds() { return activeActivityIds; } public void setActiveActivityIds(Set<String> activeActivityIds) { this.activeActivityIds = activeActivityIds; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy;
} public String getLocale() { return locale; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public String getCallbackId() { return callbackId; } public Set<String> getCallBackIds() { return callbackIds; } public String getCallbackType() { return callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public List<ExecutionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return null; } public String getParentScopeId() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public class X_AD_User_Occupation_AdditionalSpecialization extends org.compiere.model.PO implements I_AD_User_Occupation_AdditionalSpecialization, org.compiere.model.I_Persistent { private static final long serialVersionUID = -499859448L; /** Standard Constructor */ public X_AD_User_Occupation_AdditionalSpecialization (final Properties ctx, final int AD_User_Occupation_AdditionalSpecialization_ID, @Nullable final String trxName) { super (ctx, AD_User_Occupation_AdditionalSpecialization_ID, trxName); } /** Load Constructor */ public X_AD_User_Occupation_AdditionalSpecialization (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_Occupation_AdditionalSpecialization_ID (final int AD_User_Occupation_AdditionalSpecialization_ID) { if (AD_User_Occupation_AdditionalSpecialization_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, AD_User_Occupation_AdditionalSpecialization_ID); } @Override public int getAD_User_Occupation_AdditionalSpecialization_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID); }
@Override public org.compiere.model.I_CRM_Occupation getCRM_Occupation() { return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); } @Override public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation); } @Override public void setCRM_Occupation_ID (final int CRM_Occupation_ID) { if (CRM_Occupation_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID); } @Override public int getCRM_Occupation_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_AdditionalSpecialization.java
1
请完成以下Java代码
public List<Flower> copyListByAddAllMethod(List<Flower> source) { List<Flower> flowers = new ArrayList<>(); flowers.addAll(source); return flowers; } public List<Flower> copyListByAddAllMethodAndEditOneFlowerInTheNewList(List<Flower> source) { List<Flower> flowers = new ArrayList<>(); flowers.addAll(source); if(flowers.size() > 0) { flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); } return flowers; } public List<Integer> copyListByCopyMethod(List<Integer> source, List<Integer> dest) { Collections.copy(dest, source); return dest; } public List<Flower> copyListByStream(List<Flower> source) { return source.stream().collect(Collectors.toList()); } public List<Flower> copyListByStreamAndSkipFirstElement(List<Flower> source) { return source.stream().skip(1).collect(Collectors.toList());
} public List<Flower> copyListByStreamWithFilter(List<Flower> source, Integer moreThanPetals) { return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList()); } public List<Flower> copyListByStreamWithOptional(List<Flower> source) { return Optional.ofNullable(source) .map(List::stream) .orElseGet(Stream::empty) .collect(Collectors.toList()); } public List<Flower> copyListByStreamWithOptionalAndSkip(List<Flower> source) { return Optional.ofNullable(source) .map(List::stream) .orElseGet(Stream::empty) .skip(1) .collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\java\list\CopyListService.java
1
请完成以下Java代码
private void setLastLineCommentPrefixCharacter(int lastLineCommentPrefixCharacter) { this.lastLineCommentPrefixCharacter = lastLineCommentPrefixCharacter; } private void skipComment() throws IOException { while (this.character != '\n' && this.character != -1) { this.character = this.reader.read(); } this.columnNumber = -1; } private void readEscaped() throws IOException { this.character = this.reader.read(); int escapeIndex = ESCAPES[0].indexOf(this.character); if (escapeIndex != -1) { this.character = ESCAPES[1].charAt(escapeIndex); } else if (this.character == '\n') { this.columnNumber = -1; read(); } else if (this.character == 'u') { readUnicode(); } } private void readUnicode() throws IOException { this.character = 0; for (int i = 0; i < 4; i++) { int digit = this.reader.read(); if (digit >= '0' && digit <= '9') { this.character = (this.character << 4) + digit - '0'; } else if (digit >= 'a' && digit <= 'f') { this.character = (this.character << 4) + digit - 'a' + 10; } else if (digit >= 'A' && digit <= 'F') { this.character = (this.character << 4) + digit - 'A' + 10; } else { throw new IllegalStateException("Malformed \\uxxxx encoding."); } } } boolean isWhiteSpace() { return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f'); } boolean isEndOfFile() { return this.character == -1; } boolean isEndOfLine() { return this.character == -1 || (!this.escaped && this.character == '\n'); }
boolean isListDelimiter() { return !this.escaped && this.character == ','; } boolean isPropertyDelimiter() { return !this.escaped && (this.character == '=' || this.character == ':'); } char getCharacter() { return (char) this.character; } Location getLocation() { return new Location(this.reader.getLineNumber(), this.columnNumber); } boolean isSameLastLineCommentPrefix() { return this.lastLineCommentPrefixCharacter == this.character; } boolean isCommentPrefixCharacter() { return this.character == '#' || this.character == '!'; } boolean isHyphenCharacter() { return this.character == '-'; } } /** * A single document within the properties file. */ static class Document { private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>(); void put(String key, OriginTrackedValue value) { if (!key.isEmpty()) { this.values.put(key, value); } } boolean isEmpty() { return this.values.isEmpty(); } Map<String, OriginTrackedValue> asMap() { return this.values; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
1
请在Spring Boot框架中完成以下Java代码
public long findDecisionRequirementsDefinitionCountByQueryCriteria(DecisionRequirementsDefinitionQueryImpl query) { configureDecisionRequirementsDefinitionQuery(query); return (Long) getDbEntityManager().selectOne("selectDecisionRequirementsDefinitionCountByQueryCriteria", query); } protected void createDefaultAuthorizations(DecisionRequirementsDefinition decisionRequirementsDefinition) { if (isAuthorizationEnabled()) { ResourceAuthorizationProvider provider = getResourceAuthorizationProvider(); AuthorizationEntity[] authorizations = provider.newDecisionRequirementsDefinition(decisionRequirementsDefinition); saveDefaultAuthorizations(authorizations); } } protected void configureDecisionRequirementsDefinitionQuery(DecisionRequirementsDefinitionQueryImpl query) { getAuthorizationManager().configureDecisionRequirementsDefinitionQuery(query); getTenantManager().configureQuery(query); } @Override public DecisionRequirementsDefinitionEntity findLatestDefinitionByKey(String key) { return null; } @Override public DecisionRequirementsDefinitionEntity findLatestDefinitionById(String id) { return getDbEntityManager().selectById(DecisionRequirementsDefinitionEntity.class, id); } @Override public DecisionRequirementsDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return null; } @Override public DecisionRequirementsDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return null; } @Override public DecisionRequirementsDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { return null; } @Override public DecisionRequirementsDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return null; } @Override public DecisionRequirementsDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(DecisionRequirementsDefinitionEntity.class, definitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionRequirementsDefinitionManager.java
2
请完成以下Java代码
public abstract class AbstractDLMCustomizer implements IConnectionCustomizer { private final transient Logger logger = LogManager.getLogger(getClass()); public abstract int getDlmLevel(); public abstract int getDlmCoalesceLevel(); /** * Used to secure ourselves against a {@link StackOverflowError}. */ private final ThreadLocal<Boolean> inMethod = ThreadLocal.withInitial(() -> Boolean.FALSE); @Override public void customizeConnection(final Connection c) throws DBException { if (Adempiere.isUnitTestMode()) { logger.debug("doing nothing because we are in unit test mode"); return; } final boolean wasAlreadyInMethod = inMethod.get(); if (wasAlreadyInMethod) { return;
} try { inMethod.set(true); DLMConnectionUtils.setSearchPathForDLM(c); DLMConnectionUtils.changeDLMLevel(c, getDlmLevel()); DLMConnectionUtils.changeDLMCoalesceLevel(c, getDlmCoalesceLevel()); } catch (final SQLException e) { throw DBException.wrapIfNeeded(e); } finally { inMethod.set(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\AbstractDLMCustomizer.java
1
请在Spring Boot框架中完成以下Java代码
private Stream<AssignmentToRefundCandidate> streamAssignmentsToExtend( @NonNull final RefundInvoiceCandidate refundInvoiceCandidate, @NonNull final RefundConfig refundConfig, @NonNull final RefundConfig additionalRefundConfig) { Check.assumeNotNull(refundInvoiceCandidate.getId(), "The given refundInvoiceCandidate needs to have a not-null Id; assignableInvoiceCandidate={}", refundInvoiceCandidate); final RefundInvoiceCandidate candidateWithAdditionalConfig = refundInvoiceCandidate .toBuilder() .refundConfig(additionalRefundConfig) .build(); final IQueryBL queryBL = Services.get(IQueryBL.class); // these are to be excluded in the actual query final IQuery<I_C_Invoice_Candidate> assignableCandidatesWithAdditionalConfig = queryBL .createQueryBuilder(I_C_Invoice_Candidate_Assignment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Term_ID, refundInvoiceCandidate.getId().getRepoId()) .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Flatrate_RefundConfig_ID, additionalRefundConfig.getId().getRepoId()) .andCollect(I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Assigned_ID,
I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .create(); return queryBL .createQueryBuilder(I_C_Invoice_Candidate_Assignment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Term_ID, refundInvoiceCandidate.getId().getRepoId()) .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Flatrate_RefundConfig_ID, refundConfig.getId().getRepoId()) .addNotInSubQueryFilter( I_C_Invoice_Candidate_Assignment.COLUMNNAME_C_Invoice_Candidate_Assigned_ID, I_C_Invoice_Candidate.COLUMNNAME_C_Invoice_Candidate_ID, assignableCandidatesWithAdditionalConfig) .create() .iterateAndStream() .map(assignmentToRefundCandidateRepository::ofRecordOrNull) .map(a -> a.withRefundInvoiceCandidate(candidateWithAdditionalConfig)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\allqties\refundconfigchange\RefundConfigChangeService.java
2
请完成以下Java代码
public boolean isTenantIdSet() { return isTenantIdSet; } public String getVariableName() { return variableName; } public String getVariableNameLike() { return variableNameLike; } public QueryVariableValue getQueryVariableValue() { return queryVariableValue; } public Boolean getVariableNamesIgnoreCase() { return variableNamesIgnoreCase; } public Boolean getVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } @Override public HistoricVariableInstanceQuery includeDeleted() { includeDeleted = true; return this;
} public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public List<String> getVariableNameIn() { return variableNameIn; } public Date getCreatedAfter() { return createdAfter; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricVariableInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class AmountRefundConfigChangeHandler extends RefundConfigChangeHandler { public static AmountRefundConfigChangeHandler newInstance( @NonNull final RefundConfig currentRefundConfig) { return new AmountRefundConfigChangeHandler(currentRefundConfig); } private AmountRefundConfigChangeHandler( @NonNull final RefundConfig currentRefundConfig) { super(Check.assumeNotNull(currentRefundConfig, "currentRefundConfig may not be null")); } @Override public AssignmentToRefundCandidate createNewAssignment(@NonNull final AssignmentToRefundCandidate existingAssignment) { // note: currentRefundConfig can't be null final Money amountToApply = getCurrentRefundConfig() .getAmount() .subtract(getFormerRefundConfig().getAmount()); final Quantity quantityAssigendToRefundCandidate = existingAssignment.getQuantityAssigendToRefundCandidate();
final Money moneyToAssign = amountToApply.multiply(quantityAssigendToRefundCandidate.toBigDecimal()); return AssignmentToRefundCandidate.builder() .refundConfigId(getCurrentRefundConfig().getId()) .assignableInvoiceCandidateId(existingAssignment.getAssignableInvoiceCandidateId()) .refundInvoiceCandidate(existingAssignment.getRefundInvoiceCandidate()) .moneyBase(existingAssignment.getMoneyBase()) .moneyAssignedToRefundCandidate(moneyToAssign) .quantityAssigendToRefundCandidate(quantityAssigendToRefundCandidate) .useAssignedQtyInSum(getCurrentRefundConfig().isIncludeAssignmentsWithThisConfigInSum()) .build(); } @Override protected RefundBase getExpectedRefundBase() { return RefundBase.AMOUNT_PER_UNIT; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\allqties\refundconfigchange\AmountRefundConfigChangeHandler.java
2
请完成以下Java代码
public <T extends ThreadPoolTaskExecutor> T build(Class<T> taskExecutorClass) { return configure(BeanUtils.instantiateClass(taskExecutorClass)); } /** * Configure the provided {@link ThreadPoolTaskExecutor} instance using this builder. * @param <T> the type of task executor * @param taskExecutor the {@link ThreadPoolTaskExecutor} to configure * @return the task executor instance * @see #build() * @see #build(Class) */ public <T extends ThreadPoolTaskExecutor> T configure(T taskExecutor) { PropertyMapper map = PropertyMapper.get(); map.from(this.queueCapacity).to(taskExecutor::setQueueCapacity); map.from(this.corePoolSize).to(taskExecutor::setCorePoolSize); map.from(this.maxPoolSize).to(taskExecutor::setMaxPoolSize); map.from(this.keepAlive).asInt(Duration::getSeconds).to(taskExecutor::setKeepAliveSeconds); map.from(this.allowCoreThreadTimeOut).to(taskExecutor::setAllowCoreThreadTimeOut); map.from(this.acceptTasksAfterContextClose).to(taskExecutor::setAcceptTasksAfterContextClose); map.from(this.awaitTermination).to(taskExecutor::setWaitForTasksToCompleteOnShutdown); map.from(this.awaitTerminationPeriod).as(Duration::toMillis).to(taskExecutor::setAwaitTerminationMillis);
map.from(this.threadNamePrefix).whenHasText().to(taskExecutor::setThreadNamePrefix); map.from(this.taskDecorator).to(taskExecutor::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskExecutor)); } return taskExecutor; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\ThreadPoolTaskExecutorBuilder.java
1
请完成以下Java代码
public BigDecimal getP_Number() { return m_P_Number; } public String getP_Msg() { return m_P_Msg; } public List<String> getWarningMessages() { return warningMessages; } public void markAsSavedInDB() { savedInDB = true; } @Nullable public ITableRecordReference getTableRecordReference() {
return m_Table_Record_Ref; } @Nullable public AdIssueId getAdIssueId() { return m_Ad_Issue_ID; } @Nullable public String getTrxName() { return trxName; } public boolean isSavedInDB() { return savedInDB; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoLog.java
1
请完成以下Java代码
private static DocumentId createDocumentId( @NonNull final ProductId productId, @NonNull final ShipmentScheduleId shipmentScheduleId, @Nullable final HuId pickFromHUId, @Nullable PPOrderId pickFromPickingOrderId, @Nullable final PPOrderBOMLineId issueToOrderBOMLineId) { final StringBuilder sb = new StringBuilder(); sb.append("P").append(productId.getRepoId()); sb.append("_").append("S").append(shipmentScheduleId.getRepoId()); if (pickFromHUId != null) { sb.append("_").append("HU").append(pickFromHUId.getRepoId()); } if (pickFromPickingOrderId != null) {
sb.append("_").append("MO").append(pickFromPickingOrderId.getRepoId()); } if (issueToOrderBOMLineId != null) { sb.append("_").append("BOML").append(issueToOrderBOMLineId.getRepoId()); } return DocumentId.ofString(sb.toString()); } public DocumentId toDocumentId() { return documentId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowId.java
1
请完成以下Java代码
private void updateDueTimeAndScheduleTask() { final boolean taskWasAlreadyScheduled = dueTime > 0; final int delayInMillisEffective = bufferMaxSize > 0 && buffer.size() >= bufferMaxSize ? 0 // ASAP : delayInMillis; // we don't use SystemTime because in our usual tests it's rigged to return a fixed value. Fee free to use it here, too - maybe with an enhanced Timesource - when it makes sense dueTime = System.currentTimeMillis() + delayInMillisEffective; //System.out.println(this + " - new dueTime=" + dueTime); if (!taskWasAlreadyScheduled) { executor.schedule(this::executeTask, delayInMillisEffective, TimeUnit.MILLISECONDS); } } private void executeTask() { ArrayList<T> itemsToConsume = null; final long remaining; final int bufferSize; synchronized (lock) { // we don't use SystemTime because in our usual tests it's rigged to return a fixed value. Fee free to use it here, too - maybe with an enhanced Timesource - when it makes sense remaining = dueTime - System.currentTimeMillis(); bufferSize = buffer.size(); // // Re-schedule task if (remaining > 0 && bufferSize > 0 && (bufferMaxSize <= 0 || bufferMaxSize > bufferSize)) { //System.out.println("" + this + " - executeTask:Rescheduling in " + remaining + " ms(bufferSize = " + bufferSize + ") "); executor.schedule(this::executeTask, remaining, TimeUnit.MILLISECONDS); } // // Mark as terminated and invoke the consumer else { dueTime = -1; if (bufferSize > 0) { itemsToConsume = new ArrayList<>(buffer); buffer.clear(); } } } if (itemsToConsume != null) { //System.out.println("" + this + " - executeTask: consuming " + bufferSize + " items(remaining was" + remaining + "ms) "); consumer.accept(itemsToConsume); } } public int getCurrentBufferSize() { synchronized (lock) { return buffer.size(); } } public void processAndClearBufferSync() { synchronized (lock) { if (!buffer.isEmpty()) { final ArrayList<T> itemsToConsume = new ArrayList<>(buffer); consumer.accept(itemsToConsume); buffer.clear(); } } } public void purgeBuffer()
{ synchronized (lock) { buffer.clear(); } } public void shutdown() { executor.shutdown(); } /* public static void main(String[] args) throws InterruptedException { final Debouncer<Integer> debouncer = Debouncer.<Integer>builder() .name("test-debouncer") .delayInMillis(500) .bufferMaxSize(500) .consumer(items -> System.out.println("Got " + items.size() + " items: " + items.get(0) + "..." + items.get(items.size() - 1))) .build(); System.out.println("Start sending events..."); for (int i = 1; i <= 100; i++) { debouncer.add(i); //Thread.yield(); Thread.sleep(0, 1); } System.out.println("Enqueuing done. Waiting a bit to finish..."); Thread.sleep(5000); } */ }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\async\Debouncer.java
1
请完成以下Java代码
public void setIsRequireScanningProductCode (final boolean IsRequireScanningProductCode) { set_Value (COLUMNNAME_IsRequireScanningProductCode, IsRequireScanningProductCode); } @Override public boolean isRequireScanningProductCode() { return get_ValueAsBoolean(COLUMNNAME_IsRequireScanningProductCode); } @Override public void setIsRequireTrolley (final boolean IsRequireTrolley) { set_Value (COLUMNNAME_IsRequireTrolley, IsRequireTrolley); } @Override public boolean isRequireTrolley() { return get_ValueAsBoolean(COLUMNNAME_IsRequireTrolley); } @Override public void setMaxLaunchers (final int MaxLaunchers) { set_Value (COLUMNNAME_MaxLaunchers, MaxLaunchers); } @Override public int getMaxLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxLaunchers); }
@Override public void setMaxStartedLaunchers (final int MaxStartedLaunchers) { set_Value (COLUMNNAME_MaxStartedLaunchers, MaxStartedLaunchers); } @Override public int getMaxStartedLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxStartedLaunchers); } @Override public void setMobileUI_UserProfile_DD_ID (final int MobileUI_UserProfile_DD_ID) { if (MobileUI_UserProfile_DD_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, MobileUI_UserProfile_DD_ID); } @Override public int getMobileUI_UserProfile_DD_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_DD.java
1
请完成以下Java代码
public String getName() { return name; } @Override public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } @Override public IdentityService getIdentityService() { return identityService; } @Override public ManagementService getManagementService() { return managementService; } @Override public TaskService getTaskService() { return taskService; } @Override public HistoryService getHistoryService() { return historicDataService; } @Override public RuntimeService getRuntimeService() { return runtimeService; } @Override public RepositoryService getRepositoryService() { return repositoryService; } @Override public FormService getFormService() { return formService; } @Override public AuthorizationService getAuthorizationService() { return authorizationService; }
@Override public CaseService getCaseService() { return caseService; } @Override public FilterService getFilterService() { return filterService; } @Override public ExternalTaskService getExternalTaskService() { return externalTaskService; } @Override public DecisionService getDecisionService() { return decisionService; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessEngineImpl.java
1
请完成以下Java代码
public VendorProductInfo getVendorProductInfo( @NonNull final BPartnerId vendorId, @NonNull final ProductId productId, @NonNull final OrgId orgId) { final ProductAndCategoryAndManufacturerId product = productsRepo.retrieveProductAndCategoryAndManufacturerByProductId(productId); final int discountSchemaId = bpartnerBL.getDiscountSchemaId(vendorId, BPartnerType.VENDOR.getSOTrx()); final PricingConditionsId pricingConditionsId = PricingConditionsId.ofRepoId(discountSchemaId); final I_C_BPartner_Product bpartnerProductRecord = partnerProductDAO.retrieveByVendorId(vendorId, productId, orgId); return createVendorProductInfo( vendorId, product, pricingConditionsId, bpartnerProductRecord); } private VendorProductInfo createVendorProductInfo( @NonNull final BPartnerId vendorId, @NonNull final ProductAndCategoryAndManufacturerId product, @NonNull final PricingConditionsId pricingConditionsId, @Nullable final I_C_BPartner_Product bpartnerProductRecord) { final I_C_BPartner vendorRecord = bpartnersRepo.getById(vendorId); final boolean aggregatePOs = vendorRecord.isAggregatePO(); final Percent vendorFlatDiscount = Percent.of(vendorRecord.getFlatDiscount()); final PricingConditions pricingConditions = pricingConditionsRepo.getPricingConditionsById(pricingConditionsId); final ProductId productId = product.getProductId(); final String vendorProductNo = CoalesceUtil.coalesceSuppliers( () -> bpartnerProductRecord != null ? bpartnerProductRecord.getVendorProductNo() : null, () -> bpartnerProductRecord != null ? bpartnerProductRecord.getProductNo() : null, () -> productBL.getProductValue(productId)); final String vendorProductName = CoalesceUtil.coalesceSuppliers( () -> bpartnerProductRecord != null ? bpartnerProductRecord.getProductName() : null,
() -> productBL.getProductName(productId)); final boolean defaultVendor = bpartnerProductRecord != null ? bpartnerProductRecord.isCurrentVendor() : false; return VendorProductInfo.builder() .vendorId(vendorId) .defaultVendor(defaultVendor) .product(product) .attributeSetInstanceId(AttributeSetInstanceId.NONE) // this might change when we incorporate attribute based pricing .vendorProductNo(vendorProductNo) .vendorProductName(vendorProductName) .aggregatePOs(aggregatePOs) .vendorFlatDiscount(vendorFlatDiscount) .pricingConditions(pricingConditions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\VendorProductInfoService.java
1
请完成以下Java代码
public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_Value (COLUMNNAME_M_AttributeSearch_ID, null); else set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID); } @Override public int getM_AttributeSearch_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override) { set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override); } @Override public java.lang.String getPrintValue_Override() { return get_ValueAsString(COLUMNNAME_PrintValue_Override); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override
public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueMax (final @Nullable BigDecimal ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public BigDecimal getValueMax() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueMin (final @Nullable BigDecimal ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public BigDecimal getValueMin() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
static class RemoteRestartClientConfiguration { private final DevToolsProperties properties; RemoteRestartClientConfiguration(DevToolsProperties properties) { this.properties = properties; } @Bean ClassPathFileSystemWatcher classPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory, ClassPathRestartStrategy classPathRestartStrategy) { DefaultRestartInitializer restartInitializer = new DefaultRestartInitializer(); URL[] urls = restartInitializer.getInitialUrls(Thread.currentThread()); if (urls == null) { urls = new URL[0]; } return new ClassPathFileSystemWatcher(fileSystemWatcherFactory, classPathRestartStrategy, urls); } @Bean FileSystemWatcherFactory getFileSystemWatcherFactory() { return this::newFileSystemWatcher; } private FileSystemWatcher newFileSystemWatcher() { Restart restartProperties = this.properties.getRestart(); FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(), restartProperties.getQuietPeriod()); String triggerFile = restartProperties.getTriggerFile();
if (StringUtils.hasLength(triggerFile)) { watcher.setTriggerFilter(new TriggerFileFilter(triggerFile)); } return watcher; } @Bean ClassPathRestartStrategy classPathRestartStrategy() { return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory, @Value("${remoteUrl}") String remoteUrl) { String url = remoteUrl + this.properties.getRemote().getContextPath() + "/restart"; return new ClassPathChangeUploader(url, requestFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\RemoteClientConfiguration.java
2
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() {
return department; } public void setDepartment(String department) { this.department = department; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } }
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\jsonresponse\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public String getAccountingArea() { return accountingArea; } /** * Sets the value of the accountingArea property. * * @param value * allowed object is * {@link String } * */ public void setAccountingArea(String value) { this.accountingArea = value; } /** * The ID of an internal sub organization to which the document shall be associated to at the document recipient's side. * * @return * possible object is * {@link String } * */ public String getSubOrganizationID() { return subOrganizationID; } /** * Sets the value of the subOrganizationID property. * * @param value * allowed object is * {@link String } * */ public void setSubOrganizationID(String value) {
this.subOrganizationID = value; } /** * Gets the value of the customerExtension property. * * @return * possible object is * {@link CustomerExtensionType } * */ public CustomerExtensionType getCustomerExtension() { return customerExtension; } /** * Sets the value of the customerExtension property. * * @param value * allowed object is * {@link CustomerExtensionType } * */ public void setCustomerExtension(CustomerExtensionType value) { this.customerExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\CustomerType.java
2
请完成以下Java代码
private static String buildProviderUrl(List<String> urls, String baseDn) { Assert.notNull(baseDn, "The Base DN for the LDAP server must not be null."); Assert.notEmpty(urls, "At least one LDAP server URL must be provided."); String encodedBaseDn = encodeUrl(baseDn.trim()); StringBuilder providerUrl = new StringBuilder(); for (String serverUrl : urls) { String trimmedUrl = serverUrl.trim(); if (trimmedUrl.isEmpty()) { continue; } providerUrl.append(trimmedUrl); if (!trimmedUrl.endsWith("/")) { providerUrl.append("/"); } providerUrl.append(encodedBaseDn);
providerUrl.append(" "); } return providerUrl.toString(); } private static String encodeUrl(String url) { return URLEncoder.encode(url, StandardCharsets.UTF_8); } private String decodeUrl(String url) { return URLDecoder.decode(url, StandardCharsets.UTF_8); } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\DefaultSpringSecurityContextSource.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }
public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第12课:MongoDB 实战\spring-boot-multi-mongodb\src\main\java\com\neo\entity\UserEntity.java
1
请完成以下Java代码
public class BatchStatisticsEntity extends BatchEntity implements BatchStatistics { protected int remainingJobs; protected int failedJobs; public int getRemainingJobs() { return remainingJobs + getJobsToCreate(); } public void setRemainingJobs(int remainingJobs) { this.remainingJobs = remainingJobs; } public int getCompletedJobs() { return totalJobs - getRemainingJobs(); } public int getFailedJobs() { return failedJobs; } public void setFailedJobs(int failedJobs) { this.failedJobs = failedJobs; } public int getJobsToCreate() { return totalJobs - jobsCreated; }
public String toString() { return "BatchStatisticsEntity{" + "batchHandler=" + batchJobHandler + ", id='" + id + '\'' + ", type='" + type + '\'' + ", size=" + totalJobs + ", jobCreated=" + jobsCreated + ", remainingJobs=" + remainingJobs + ", failedJobs=" + failedJobs + ", batchJobsPerSeed=" + batchJobsPerSeed + ", invocationsPerBatchJob=" + invocationsPerBatchJob + ", seedJobDefinitionId='" + seedJobDefinitionId + '\'' + ", monitorJobDefinitionId='" + seedJobDefinitionId + '\'' + ", batchJobDefinitionId='" + batchJobDefinitionId + '\'' + ", configurationId='" + configuration.getByteArrayId() + '\'' + '}'; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchStatisticsEntity.java
1
请完成以下Java代码
private void updateIfFeasible( @NonNull final ContactPerson contactPerson, @NonNull final User user, @Nullable final String oldUserEmail, @Nullable final Language oldUserLanguage) { final boolean updateContactMail = isFitForUpdate(contactPerson.getEmailAddressStringOrNull(), oldUserEmail); final boolean updateContactLanguage = isFitForUpdate(contactPerson.getLanguage(), oldUserLanguage); if (!updateContactMail && !updateContactLanguage) { return; // nothing to do } final ContactPersonBuilder updatedContactPerson = contactPerson.toBuilder(); if (updateContactMail) { final EmailAddress userNewMailaddress = EmailAddress.ofStringOrNull(user.getEmailAddress()); updatedContactPerson.address(userNewMailaddress); } if (updateContactLanguage) { updatedContactPerson.language(user.getUserLanguage()); } contactPersonRepo.save(updatedContactPerson.build()); } public void updateUserFromContactPersonIfFeasible( @NonNull final ContactPerson contactPerson, @Nullable final String oldContactPersonMail, @Nullable final Language oldContactPersonLanguage) { final UserId userId = contactPerson.getUserId(); if (userId == null) { return; // no user to update the email } final User user = userRepo.getByIdInTrx(userId); final boolean updateUserMail = isFitForUpdate(user.getEmailAddress(), oldContactPersonMail); final boolean updateUserLanguage = isFitForUpdate(user.getUserLanguage(), oldContactPersonLanguage); if (!updateUserMail && !updateUserLanguage) { return; // nothing to do } final User.UserBuilder updatedUser = user.toBuilder(); if (updateUserMail) { updatedUser.emailAddress(contactPerson.getEmailAddressStringOrNull()); } if (updateUserLanguage) { updatedUser.userLanguage(contactPerson.getLanguage()); if (contactPerson.getLanguage() != null) { updatedUser.language(contactPerson.getLanguage()); }
} userRepo.save(updatedUser.build()); } private boolean isFitForUpdate( @Nullable final Object currentContactValue, @Nullable final Object oldUserValue) { if (Check.isEmpty(currentContactValue)) { return true; // contact has no value, so let's give him/her one } // if user and contact were in sync, then keep them in sync, i.e. forward the new user value to the contact. //noinspection UnnecessaryLocalVariable final boolean userValueInSyncWithOldcontactValue = Objects.equals(currentContactValue, oldUserValue); return userValueInSyncWithOldcontactValue; } public List<ContactPerson> saveSyncResults(final List<? extends SyncResult> syncResults) { final ArrayList<ContactPerson> savedContactPersons = new ArrayList<>(syncResults.size()); for (final SyncResult syncResult : syncResults) { final ContactPerson savedContactPerson = contactPersonRepo.saveSyncResult(syncResult); savedContactPersons.add(savedContactPerson); } return savedContactPersons; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\ContactPersonService.java
1
请在Spring Boot框架中完成以下Java代码
public AppDto findById(Long id) { App app = appRepository.findById(id).orElseGet(App::new); ValidationUtil.isNull(app.getId(),"App","id",id); return appMapper.toDto(app); } @Override @Transactional(rollbackFor = Exception.class) public void create(App resources) { // 验证应用名称是否存在恶意攻击payload,https://github.com/elunez/eladmin/issues/873 String appName = resources.getName(); if (appName.contains(";") || appName.contains("|") || appName.contains("&")) { throw new IllegalArgumentException("非法的应用名称,请勿包含[; | &]等特殊字符"); } verification(resources); appRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(App resources) { // 验证应用名称是否存在恶意攻击payload,https://github.com/elunez/eladmin/issues/873 String appName = resources.getName(); if (appName.contains(";") || appName.contains("|") || appName.contains("&")) { throw new IllegalArgumentException("非法的应用名称,请勿包含[; | &]等特殊字符"); } verification(resources); App app = appRepository.findById(resources.getId()).orElseGet(App::new); ValidationUtil.isNull(app.getId(),"App","id",resources.getId()); app.copy(resources); appRepository.save(app); } private void verification(App resources){ String opt = "/opt"; String home = "/home"; if (!(resources.getUploadPath().startsWith(opt) || resources.getUploadPath().startsWith(home))) { throw new BadRequestException("文件只能上传在opt目录或者home目录 "); } if (!(resources.getDeployPath().startsWith(opt) || resources.getDeployPath().startsWith(home))) { throw new BadRequestException("文件只能部署在opt目录或者home目录 "); } if (!(resources.getBackupPath().startsWith(opt) || resources.getBackupPath().startsWith(home))) { throw new BadRequestException("文件只能备份在opt目录或者home目录 "); } } @Override
@Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { appRepository.deleteById(id); } } @Override public void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (AppDto appDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("应用名称", appDto.getName()); map.put("端口", appDto.getPort()); map.put("上传目录", appDto.getUploadPath()); map.put("部署目录", appDto.getDeployPath()); map.put("备份目录", appDto.getBackupPath()); map.put("启动脚本", appDto.getStartScript()); map.put("部署脚本", appDto.getDeployScript()); map.put("创建日期", appDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\AppServiceImpl.java
2
请完成以下Java代码
public void beforeSave(final I_PP_Product_BOMLine bomLine) { validate(bomLine); // // Update Line# if (bomLine.getLine() <= 0) { final IProductBOMDAO productBOMsRepo = Services.get(IProductBOMDAO.class); final int lastLineNo = productBOMsRepo.retrieveLastLineNo(bomLine.getPP_Product_BOM_ID()); bomLine.setLine(lastLineNo + 10); } } private void validate(final I_PP_Product_BOMLine bomLine) { final BOMComponentType componentType = BOMComponentType.ofCode(bomLine.getComponentType()); // // For Co/By Products, Qty should be always negative: if (componentType.isCoProduct() && Services.get(IProductBOMBL.class).getQtyExcludingScrap(bomLine).signum() >= 0) { throw new LiberoException("@Qty@ > 0"); } if (componentType.isVariant() && Check.isEmpty(bomLine.getVariantGroup())) { throw new LiberoException("@MandatoryVariant@"); } final boolean valid = Services.get(IProductBOMBL.class).isValidVariantGroup(bomLine); if (!valid) { throw new LiberoException("@NoSuchVariantGroup@"); } ProductBOMDAO.extractIssuingToleranceSpec(bomLine); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_PP_Order_BOMLine.COLUMNNAME_VariantGroup) public void setVariantGroupToVA(final I_PP_Product_BOMLine bomLine) { final BOMComponentType currentComponentType = BOMComponentType.ofCode(bomLine.getComponentType()); if (currentComponentType.isComponent()) { final IProductBOMDAO bomDAO = Services.get(IProductBOMDAO.class); final List<I_PP_Product_BOMLine> bomLines = bomDAO.retrieveLines(bomLine.getPP_Product_BOM()); for (I_PP_Product_BOMLine bl : bomLines) { final BOMComponentType componentType = BOMComponentType.ofCode(bl.getComponentType()); if (componentType.isVariant() && noAccordinglyVariantGroup(bl)) { bl.setVariantGroup(bomLine.getVariantGroup()); bomDAO.save(bl);
} } } } private boolean noAccordinglyVariantGroup(final I_PP_Product_BOMLine bomLine) { final IProductBOMDAO bomDAO = Services.get(IProductBOMDAO.class); final List<I_PP_Product_BOMLine> bomLines = bomDAO.retrieveLines(bomLine.getPP_Product_BOM()); for (I_PP_Product_BOMLine bl : bomLines) { final BOMComponentType componentType = BOMComponentType.ofCode(bl.getComponentType()); if (componentType.isComponent() && bomLine.getVariantGroup().equals(bl.getVariantGroup())) { return false; } } return true; } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, skipIfCopying = true) public void checkingBOMCycle(final I_PP_Product_BOMLine bomLine) { final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID()); Services.get(IProductBOMBL.class).checkCycles(productId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Product_BOMLine.java
1
请完成以下Java代码
private static I_C_DocType getEmptiesDocType(final String docBaseType, final int adClientId, final int adOrgId, final boolean isSOTrx) { // // Search for specific empties shipment/receipt document sub-type (task 07694) // 07694: using the empties-subtype for receipts. final String docSubType = isSOTrx ? X_C_DocType.DOCSUBTYPE_Leergutanlieferung : X_C_DocType.DOCSUBTYPE_Leergutausgabe; final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); final List<I_C_DocType> docTypes = docTypeDAO.retrieveDocTypesByBaseType(DocTypeQuery.builder() .docBaseType(docBaseType) .docSubType(DocTypeQuery.DOCSUBTYPE_Any) .adClientId(adClientId) .adOrgId(adOrgId) .build()); if (docTypes == null) { logger.warn("No document types found for docBaseType={}, adClientId={}, adOrgId={}", docBaseType, adClientId, adOrgId); return null; } for (final I_C_DocType docType : docTypes) { final String subType = docType.getDocSubType(); if (docSubType.equals(subType)) { return docType; } } // // If the empties doc type was not found (should not happen) fallback to the default one { final I_C_DocType defaultDocType = docTypes.get(0); logger.warn("No empties document type found for docBaseType={}, docSubType={}, adClientId={}, adOrgId={}. Using fallback docType={}", docBaseType, docSubType, adClientId, adOrgId, defaultDocType); return defaultDocType; } } @Override protected void createLines() { inoutLinesBuilder.addSources(sources); inoutLinesBuilder.create();
} @Override protected int getReturnsDocTypeId(final String docBaseType, final boolean isSOTrx, final int adClientId, final int adOrgId) { final I_C_DocType docType = getEmptiesDocType(docBaseType, adClientId, adOrgId, isSOTrx); DocTypeId docTypeId = docType == null ? null : DocTypeId.ofRepoId(docType.getC_DocType_ID()); // If the empties doc type was not found (should not happen) fallback to the default one if (docTypeId == null) { final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); docTypeId = docTypeDAO.getDocTypeId( DocTypeQuery.builder() .docBaseType(docBaseType) .adClientId(adClientId) .adOrgId(adOrgId) .build() //Env.getCtx(), docBaseType, adClientId, adOrgId, ITrx.TRXNAME_None ); } return DocTypeId.toRepoId(docTypeId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\impl\EmptiesInOutProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserDetailsService userDetailsService; @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/user/{id}") public String getUser(@PathVariable("id") String id) { return "user"; } @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')") @GetMapping("/users") public String getUsers() { return "users"; } @GetMapping("v2/user/{id}") public String getUserUsingSecurityContext() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { return "user"; } throw new UnauthorizedException(); } @GetMapping("v2/users") public String getUsersUsingDetailsService() { UserDetails details = userDetailsService.loadUserByUsername("mike");
if (details != null && details.getAuthorities().stream() .anyMatch(a -> a.getAuthority().equals("ADMIN"))) { return "users"; } throw new UnauthorizedException(); } @GetMapping("v3/users") public String getUsers(HttpServletRequest request) { if (request.isUserInRole("ROLE_ADMIN")) { return "users"; } throw new UnauthorizedException(); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\checkrolejava\UserController.java
2
请完成以下Java代码
public final class Pair<F, S> implements IPair<F, S> { private final F first; private final S second; public Pair(final F first, final S second) { super(); this.first = first; this.second = second; } public F getFirst() { return first; } public S getSecond() { return second; } @Override public int hashCode() { // Note: i wanted to move ArrayKey from adempiere base to util, but i'm already kinda out of the tasks's original scope. final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Pair)) {
return false; } final Pair<?, ?> other = (Pair<?, ?>)obj; if (!Check.equals(this.first, other.first)) { return false; } if (!Check.equals(this.second, other.second)) { return false; } return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Pair [first="); builder.append(first); builder.append(", second="); builder.append(second); builder.append("]"); return builder.toString(); } @Override public F getLeft() { return getFirst(); } @Override public S getRight() { return getSecond(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Pair.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void 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 setStackabilityFactor (final int StackabilityFactor) { set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor); } @Override public int getStackabilityFactor()
{ return get_ValueAsInt(COLUMNNAME_StackabilityFactor); } @Override public void setWidth (final @Nullable BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTaskState() { return taskState; } public void setTaskState(String taskState) { this.taskState = taskState; } public static TaskDto fromEntity(Task task) { TaskDto dto = new TaskDto(); dto.id = task.getId(); dto.name = task.getName(); dto.assignee = task.getAssignee(); dto.created = task.getCreateTime(); dto.lastUpdated = task.getLastUpdated(); dto.due = task.getDueDate(); dto.followUp = task.getFollowUpDate(); if (task.getDelegationState() != null) { dto.delegationState = task.getDelegationState().toString(); } dto.description = task.getDescription(); dto.executionId = task.getExecutionId(); dto.owner = task.getOwner(); dto.parentTaskId = task.getParentTaskId(); dto.priority = task.getPriority(); dto.processDefinitionId = task.getProcessDefinitionId(); dto.processInstanceId = task.getProcessInstanceId(); dto.taskDefinitionKey = task.getTaskDefinitionKey(); dto.caseDefinitionId = task.getCaseDefinitionId(); dto.caseExecutionId = task.getCaseExecutionId(); dto.caseInstanceId = task.getCaseInstanceId(); dto.suspended = task.isSuspended(); dto.tenantId = task.getTenantId(); dto.taskState = task.getTaskState();
try { dto.formKey = task.getFormKey(); dto.camundaFormRef = task.getCamundaFormRef(); } catch (BadUserRequestException e) { // ignore (initializeFormKeys was not called) } return dto; } public void updateTask(Task task) { task.setName(getName()); task.setDescription(getDescription()); task.setPriority(getPriority()); task.setAssignee(getAssignee()); task.setOwner(getOwner()); DelegationState state = null; if (getDelegationState() != null) { DelegationStateConverter converter = new DelegationStateConverter(); state = converter.convertQueryParameterToType(getDelegationState()); } task.setDelegationState(state); task.setDueDate(getDue()); task.setFollowUpDate(getFollowUp()); task.setParentTaskId(getParentTaskId()); task.setCaseInstanceId(getCaseInstanceId()); task.setTenantId(getTenantId()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskDto.java
1
请在Spring Boot框架中完成以下Java代码
public void discardChanges( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentIdStr, @PathVariable("tabId") @SuppressWarnings("unused") final String tabIdStr_NOT_USED, @PathVariable("rowId") @SuppressWarnings("unused") final String rowIdStr_NOT_USED) { userSession.assertLoggedIn(); final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), DocumentId.of(documentIdStr)); // For now it's OK if we invalidate the whole root document documentCollection.invalidateRootDocument(documentPath); } @GetMapping("/{windowId}/{documentId}/changeLog") public JSONDocumentChangeLog getDocumentChangeLog( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentIdStr) { final WindowId windowId = WindowId.fromJson(windowIdStr); final DocumentPath documentPath = DocumentPath.rootDocumentPath(windowId, documentIdStr); return documentChangeLogService.getJSONDocumentChangeLog(documentPath); } @GetMapping("/{windowId}/{documentId}/{tabId}/{rowId}/changeLog") public JSONDocumentChangeLog getDocumentChangeLog( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentIdStr, @PathVariable("tabId") final String tabIdStr, @PathVariable("rowId") final String rowIdStr) { final WindowId windowId = WindowId.fromJson(windowIdStr); final DocumentId documentId = DocumentId.of(documentIdStr);
final DetailId tabId = DetailId.fromJson(tabIdStr); final DocumentId rowId = DocumentId.of(rowIdStr); final DocumentPath documentPath = DocumentPath.singleWindowDocumentPath(windowId, documentId, tabId, rowId); return documentChangeLogService.getJSONDocumentChangeLog(documentPath); } @GetMapping("/health") public JsonWindowsHealthCheckResponse healthCheck( @RequestParam(name = "windowIds", required = false) final String windowIdsCommaSeparated ) { return healthCheck(JsonWindowHealthCheckRequest.builder() .onlyAdWindowIds(RepoIdAwares.ofCommaSeparatedSet(windowIdsCommaSeparated, AdWindowId.class)) .checkContextVariables(false) .build()); } @PostMapping("/health") public JsonWindowsHealthCheckResponse healthCheck(@RequestBody JsonWindowHealthCheckRequest request) { return WindowHealthCheckCommand.builder() .documentDescriptorFactory(documentCollection.getDocumentDescriptorFactory()) .request(request) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\WindowRestController.java
2
请完成以下Java代码
public ResourceEntity findResourceByDeploymentIdAndResourceName(String deploymentId, String resourceName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("resourceName", resourceName); return (ResourceEntity) getDbEntityManager().selectOne("selectResourceByDeploymentIdAndResourceName", params); } @SuppressWarnings("unchecked") public List<ResourceEntity> findResourceByDeploymentIdAndResourceNames(String deploymentId, String... resourceNames) { Map<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("resourceNames", resourceNames); return getDbEntityManager().selectList("selectResourceByDeploymentIdAndResourceNames", params); } public ResourceEntity findResourceByDeploymentIdAndResourceId(String deploymentId, String resourceId) { Map<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("resourceId", resourceId); return (ResourceEntity) getDbEntityManager().selectOne("selectResourceByDeploymentIdAndResourceId", params); } @SuppressWarnings("unchecked") public List<ResourceEntity> findResourceByDeploymentIdAndResourceIds(String deploymentId, String... resourceIds) { Map<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("resourceIds", resourceIds); return getDbEntityManager().selectList("selectResourceByDeploymentIdAndResourceIds", params); } @SuppressWarnings("unchecked") public List<ResourceEntity> findResourcesByDeploymentId(String deploymentId) { return getDbEntityManager().selectList("selectResourcesByDeploymentId", deploymentId); } @SuppressWarnings("unchecked") public Map<String, ResourceEntity> findLatestResourcesByDeploymentName(String deploymentName, Set<String> resourcesToFind, String source, String tenantId) { Map<String, Object> params = new HashMap<String, Object>(); params.put("deploymentName", deploymentName); params.put("resourcesToFind", resourcesToFind);
params.put("source", source); params.put("tenantId", tenantId); List<ResourceEntity> resources = getDbEntityManager().selectList("selectLatestResourcesByDeploymentName", params); Map<String, ResourceEntity> existingResourcesByName = new HashMap<String, ResourceEntity>(); for (ResourceEntity existingResource : resources) { existingResourcesByName.put(existingResource.getName(), existingResource); } return existingResourcesByName; } public ResourceEntity findLicenseKeyResource() { PropertyEntity licenseProperty = (PropertyEntity) getDbEntityManager().selectOne("selectProperty", LicenseCmd.LICENSE_KEY_BYTE_ARRAY_ID); return licenseProperty == null ? null : (ResourceEntity) getDbEntityManager().selectOne("selectResourceById", licenseProperty.value); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ResourceManager.java
1
请完成以下Java代码
boolean matches(boolean directory, int size, int compressionMethod, InputStreamSupplier streamSupplier) throws IOException { if (this.entry.isDirectory() != directory) { fail("directory"); } if (this.entry.getMethod() != compressionMethod) { fail("compression method"); } if (this.entry.isDirectory()) { this.in.closeEntry(); return true; } try (DataInputStream expected = new DataInputStream(getInputStream(size, streamSupplier))) { assertSameContent(expected); } return true; } private InputStream getInputStream(int size, InputStreamSupplier streamSupplier) throws IOException { InputStream inputStream = streamSupplier.get(); return (this.entry.getMethod() != ZipEntry.DEFLATED) ? inputStream : new ZipInflaterInputStream(inputStream, this.inflater, size); } private void assertSameContent(DataInputStream expected) throws IOException { int len; while ((len = this.in.read(this.inBuffer)) > 0) { try { expected.readFully(this.compareBuffer, 0, len); if (Arrays.equals(this.inBuffer, 0, len, this.compareBuffer, 0, len)) { continue; }
} catch (EOFException ex) { // Continue and throw exception due to mismatched content length. } fail("content"); } if (expected.read() != -1) { fail("content"); } } private void fail(String check) { throw new IllegalStateException("Content mismatch when reading security info for entry '%s' (%s check)" .formatted(this.entry.getName(), check)); } @Override public void close() throws IOException { this.inflater.end(); this.in.close(); } @FunctionalInterface interface InputStreamSupplier { InputStream get() throws IOException; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\JarEntriesStream.java
1
请完成以下Java代码
public boolean isLast() { return tokens.length == 1; } public String currentToken() { return tokens[0]; } public JsonPathProcessingTask next(JsonNode next) { return new JsonPathProcessingTask( Arrays.copyOfRange(tokens, 1, tokens.length), variables, next); } public JsonPathProcessingTask next(JsonNode next, String key, String value) { Map<String, String> variables = new HashMap<>(this.variables); variables.put(key, value); return new JsonPathProcessingTask( Arrays.copyOfRange(tokens, 1, tokens.length), variables,
next); } @Override public String toString() { return "JsonPathProcessingTask{" + "tokens=" + Arrays.toString(tokens) + ", variables=" + variables + ", node=" + node.toString().substring(0, 20) + '}'; } } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\JacksonUtil.java
1
请完成以下Java代码
public class HistoricFormPropertyEntity extends HistoricDetailEntity implements HistoricFormProperty { private static final long serialVersionUID = 1L; protected String propertyId; protected String propertyValue; public HistoricFormPropertyEntity() { this.detailType = "FormProperty"; } public HistoricFormPropertyEntity(ExecutionEntity execution, String propertyId, String propertyValue) { this(execution, propertyId, propertyValue, null); } public HistoricFormPropertyEntity(ExecutionEntity execution, String propertyId, String propertyValue, String taskId) { this.processInstanceId = execution.getProcessInstanceId(); this.executionId = execution.getId(); this.taskId = taskId; this.propertyId = propertyId; this.propertyValue = propertyValue; this.time = Context.getProcessEngineConfiguration().getClock().getCurrentTime(); this.detailType = "FormProperty"; HistoricActivityInstanceEntity historicActivityInstance = Context.getCommandContext().getHistoryManager().findActivityInstance(execution); if (historicActivityInstance != null) { this.activityInstanceId = historicActivityInstance.getId(); } }
@Override public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } @Override public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricFormPropertyEntity.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String group() { return get(v1(V1::getGroup), DynatraceConfig.super::group); } @Override public DynatraceApiVersion apiVersion() { return obtain((properties) -> (properties.getV1().getDeviceId() != null) ? DynatraceApiVersion.V1 : DynatraceApiVersion.V2, DynatraceConfig.super::apiVersion); } @Override public String metricKeyPrefix() { return obtain(v2(V2::getMetricKeyPrefix), DynatraceConfig.super::metricKeyPrefix); } @Override public Map<String, String> defaultDimensions() { return obtain(v2(V2::getDefaultDimensions), DynatraceConfig.super::defaultDimensions); } @Override public boolean enrichWithDynatraceMetadata() { return obtain(v2(V2::isEnrichWithDynatraceMetadata), DynatraceConfig.super::enrichWithDynatraceMetadata); } @Override
public boolean useDynatraceSummaryInstruments() { return obtain(v2(V2::isUseDynatraceSummaryInstruments), DynatraceConfig.super::useDynatraceSummaryInstruments); } @Override public boolean exportMeterMetadata() { return obtain(v2(V2::isExportMeterMetadata), DynatraceConfig.super::exportMeterMetadata); } private <V> Getter<DynatraceProperties, V> v1(Getter<V1, V> getter) { return (properties) -> getter.get(properties.getV1()); } private <V> Getter<DynatraceProperties, V> v2(Getter<V2, V> getter) { return (properties) -> getter.get(properties.getV2()); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatracePropertiesConfigAdapter.java
2