instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class TbGetTenantDetailsNode extends TbAbstractGetEntityDetailsNode<TbGetTenantDetailsNodeConfiguration, TenantId> { private static final String TENANT_PREFIX = "tenant_"; @Override protected TbGetTenantDetailsNodeConfiguration loadNodeConfiguration(TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbGetTenantDetailsNodeConfiguration.class); checkIfDetailsListIsNotEmptyOrElseThrow(config.getDetailsList()); return config; } @Override protected String getPrefix() { return TENANT_PREFIX; } @Override
protected ListenableFuture<Tenant> getContactBasedFuture(TbContext ctx, TbMsg msg) { return ctx.getTenantService().findTenantByIdAsync(ctx.getTenantId(), ctx.getTenantId()); } @Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { return fromVersion == 0 ? upgradeRuleNodesWithOldPropertyToUseFetchTo( oldConfiguration, "addToMetadata", TbMsgSource.METADATA.name(), TbMsgSource.DATA.name()) : new TbPair<>(false, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbGetTenantDetailsNode.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) {
this.taskId = taskId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public boolean isJoinParallelActivitiesOnComplete() { return joinParallelActivitiesOnComplete; } public void setJoinParallelActivitiesOnComplete(boolean joinParallelActivitiesOnComplete) { this.joinParallelActivitiesOnComplete = joinParallelActivitiesOnComplete; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\InjectActivityRequest.java
2
请完成以下Java代码
public static class Palette { private String shade50 = "#EEFCFA"; private String shade100 = "#D9F7F4"; private String shade200 = "#B7F0EA"; private String shade300 = "#91E8E0"; private String shade400 = "#6BE0D5"; private String shade500 = "#47D9CB"; private String shade600 = "#27BEAF"; private String shade700 = "#1E9084"; private String shade800 = "#14615A"; private String shade900 = "#0A2F2B"; public void set50(String shade50) { this.shade50 = shade50; } public void set100(String shade100) { this.shade100 = shade100; } public void set200(String shade200) { this.shade200 = shade200;
} public void set300(String shade300) { this.shade300 = shade300; } public void set400(String shade400) { this.shade400 = shade400; } public void set500(String shade500) { this.shade500 = shade500; } public void set600(String shade600) { this.shade600 = shade600; } public void set700(String shade700) { this.shade700 = shade700; } public void set800(String shade800) { this.shade800 = shade800; } public void set900(String shade900) { this.shade900 = shade900; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiProperties.java
1
请完成以下Java代码
public String getEanParty() { return eanParty; } /** * Sets the value of the eanParty property. * * @param value * allowed object is * {@link String } * */ public void setEanParty(String value) { this.eanParty = value; } /** * Gets the value of the regNumber property. * * @return
* possible object is * {@link String } * */ public String getRegNumber() { return regNumber; } /** * Sets the value of the regNumber property. * * @param value * allowed object is * {@link String } * */ public void setRegNumber(String value) { this.regNumber = 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\EmployerAddressType.java
1
请完成以下Java代码
public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(HistoricProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); } 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 rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PhonecallSchema { @NonNull PhonecallSchemaId id; @NonNull String name; @Getter(AccessLevel.PRIVATE) ImmutableList<PhonecallSchemaVersion> versions; @Builder private PhonecallSchema( @NonNull final PhonecallSchemaId id, @NonNull final String name, @NonNull final List<PhonecallSchemaVersion> versions) { this.id = id; this.name = name; this.versions = versions.stream() .sorted(Comparator.comparing(PhonecallSchemaVersion::getValidFrom)) .collect(ImmutableList.toImmutableList()); } public List<PhonecallSchemaVersion> getChronologicallyOrderedPhonecallSchemaVersions(@NonNull final LocalDate endDate) {
ImmutableList<PhonecallSchemaVersion> phonecallVersionsForDateRange = versions.stream() .filter(version -> version.getValidFrom().compareTo(endDate) <= 0) .collect(ImmutableList.toImmutableList()); if (phonecallVersionsForDateRange.isEmpty()) { throw new AdempiereException("No version found before " + endDate); } return phonecallVersionsForDateRange; } public Optional<PhonecallSchemaVersion> getVersionByValidFrom(@NonNull final LocalDate validFrom) { return getVersions() .stream() .filter(version -> version.getValidFrom().equals(validFrom)) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\PhonecallSchema.java
2
请在Spring Boot框架中完成以下Java代码
public class MyServiceImpl implements MyService { private static final Logger logger = LoggerFactory.getLogger(MyServiceImpl.class); @Override public void retryService() { // This is correct for logging the retry count (0 on first attempt, 1 on first retry, etc.) logger.info("Retry Number: " + RetrySynchronizationManager.getContext() .getRetryCount()); logger.info("throw RuntimeException in method retryService()"); // Always throws the exception to force the retry aspect to kick in throw new RuntimeException(); } @Override public void retryServiceWithRecovery(String sql) throws SQLException { if (StringUtils.isEmpty(sql)) { logger.info("throw SQLException in method retryServiceWithRecovery()"); throw new SQLException(); } } @Override public void retryServiceWithCustomization(String sql) throws SQLException { if (StringUtils.isEmpty(sql)) { logger.info("throw SQLException in method retryServiceWithCustomization()"); // Correctly throws SQLException to trigger the 2 retry attempts throw new SQLException(); } } @Override public void retryServiceWithExternalConfiguration(String sql) throws SQLException { if (StringUtils.isEmpty(sql)) { logger.info("throw SQLException in method retryServiceWithExternalConfiguration()");
throw new SQLException(); } } @Override public void recover(SQLException e, String sql) { logger.info("In recover method"); } @Override public void templateRetryService() { logger.info("throw RuntimeException in method templateRetryService()"); throw new RuntimeException(); } // **NEW Implementation for Concurrency Limit** @Override @ConcurrencyLimit(5) public void concurrentLimitService() { // The ConcurrencyLimit aspect will wrap this method. logger.info("Concurrency Limit Active. Current Thread: " + Thread.currentThread().getName()); // Simulate a time-consuming task to observe throttling try { Thread.sleep(1000); // Correctly blocks to hold the lock } catch (InterruptedException e) { Thread.currentThread().interrupt(); } logger.info("Concurrency Limit Released. Current Thread: " + Thread.currentThread().getName()); } }
repos\tutorials-master\spring-scheduling\src\main\java\com\baeldung\springretry\MyServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerBankAccount existingBankAccountInInitialPartner) { final OrgMappingId orgMappingId = existingBankAccountInInitialPartner.getOrgMappingId(); if (orgMappingId != null) { return orgMappingId; } final I_AD_Org_Mapping orgMapping = newInstance(I_AD_Org_Mapping.class); orgMapping.setAD_Org_ID(0); orgMapping.setAD_Table_ID(getTableId(I_C_BP_BankAccount.class)); orgMapping.setValue(existingBankAccountInInitialPartner.getIban()); save(orgMapping); return OrgMappingId.ofRepoId(orgMapping.getAD_Org_Mapping_ID()); } public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerContact contact) { final OrgMappingId orgMappingId = contact.getOrgMappingId(); if (orgMappingId != null) { return orgMappingId; } final I_AD_Org_Mapping orgMapping = newInstance(I_AD_Org_Mapping.class); orgMapping.setAD_Org_ID(0); orgMapping.setAD_Table_ID(getTableId(I_C_BP_BankAccount.class)); orgMapping.setValue(contact.getValue());
save(orgMapping); return OrgMappingId.ofRepoId(orgMapping.getAD_Org_Mapping_ID()); } public OrgMappingId getCreateOrgMappingId(@NonNull final BPartnerId bpartnerId) { final I_C_BPartner bPartnerRecord = bPartnerDAO.getById(bpartnerId); OrgMappingId orgMappingId = OrgMappingId.ofRepoIdOrNull(bPartnerRecord.getAD_Org_Mapping_ID()); if (orgMappingId == null) { orgMappingId = createOrgMappingForBPartner(bPartnerRecord); bPartnerRecord.setAD_Org_Mapping_ID(orgMappingId.getRepoId()); save(bPartnerRecord); } return orgMappingId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\repository\OrgMappingRepository.java
2
请完成以下Java代码
public InventoryLineHU withZeroQtyCount() { return withQtyCount(getQtyCount().toZero()); } public InventoryLineHU withQtyCount(@NonNull final Quantity newQtyCount) { assertPhysicalInventory(); return toBuilder().qtyCount(newQtyCount).build(); } public static ImmutableSet<HuId> extractHuIds(@NonNull final Collection<InventoryLineHU> lineHUs) { return extractHuIds(lineHUs.stream()); } static ImmutableSet<HuId> extractHuIds(@NonNull final Stream<InventoryLineHU> lineHUs) { return lineHUs .map(InventoryLineHU::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter) { return toBuilder() .qtyCount(qtyConverter.apply(getQtyCount())) .qtyBook(qtyConverter.apply(getQtyBook())) .build(); } public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request) { return toBuilder().updatingFrom(request).build(); } public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request) { return builder().updatingFrom(request).build();
} // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder { InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请完成以下Java代码
public class OrderKafkaResponse { private Long id; private String email; private String additionsPhone; private String address; private String name; private String comment; private UserResponse user; private OrderStatus orderStatus; private List<GoodOrderDetailsResponse> goodList; private Float deliveryPrice; private BigDecimal totalSum = new BigDecimal(0); public OrderKafkaResponse(Orders orders) { this.id = orders.getId(); this.email = orders.getEmail(); this.additionsPhone = orders.getAdditionalPhone(); this.address = orders.getAddress();
this.name = orders.getName(); this.comment = orders.getComment(); this.user = new UserResponse(orders.getUser()); this.orderStatus = orders.getStatus(); this.deliveryPrice = orders.getDeliveryPrice(); if(orders.getOrderDetailsList() != null) { List<GoodOrderDetailsResponse> orderDetailsResponses = new ArrayList<>(); for(OrderDetails goodOrderDetailsResponse: orders.getOrderDetailsList()){ orderDetailsResponses.add(new GoodOrderDetailsResponse(goodOrderDetailsResponse.getGood(), goodOrderDetailsResponse.getQuantity(), goodOrderDetailsResponse.getGood().getImageUrl(), goodOrderDetailsResponse.getGood().getRetailer())); } this.goodList = orderDetailsResponses; } for(OrderDetails orderDetails: orders.getOrderDetailsList()) { this.totalSum = this.totalSum.add(orderDetails.getGood().getCurrentPrice() !=null ? orderDetails.getGood().getCurrentPrice().multiply(new BigDecimal(orderDetails.getQuantity())): new BigDecimal(0)); } } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\payload\order\OrderKafkaResponse.java
1
请完成以下Java代码
public Object run() { RequestContext context = RequestContext.getCurrentContext(); Throwable throwable = context.getThrowable(); if (throwable instanceof ZuulException) { final ZuulException zuulException = (ZuulException) throwable; log.error("Zuul exception: " + zuulException.getMessage()); if (throwable.getCause().getCause().getCause() instanceof ConnectException) { // reset throwable to prevent further error handling in follow up filters context.remove("throwable"); // set custom response attributes context.setResponseBody(RESPONSE_BODY); context.getResponse() .setContentType("application/json"); context.setResponseStatusCode(503); }
} return null; } @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return -1; } @Override public String filterType() { return "error"; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul\spring-zuul-ui\src\main\java\com\baeldung\spring\cloud\zuul\filter\CustomZuulErrorFilter.java
1
请完成以下Java代码
public class NumberAndSumOfTransactions1 { @XmlElement(name = "NbOfNtries") protected String nbOfNtries; @XmlElement(name = "Sum") protected BigDecimal sum; /** * Gets the value of the nbOfNtries property. * * @return * possible object is * {@link String } * */ public String getNbOfNtries() { return nbOfNtries; } /** * Sets the value of the nbOfNtries property. * * @param value * allowed object is * {@link String } * */ public void setNbOfNtries(String value) { this.nbOfNtries = value; } /** * Gets the value of the sum property. * * @return * possible object is * {@link BigDecimal }
* */ public BigDecimal getSum() { return sum; } /** * Sets the value of the sum property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSum(BigDecimal value) { this.sum = 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\NumberAndSumOfTransactions1.java
1
请在Spring Boot框架中完成以下Java代码
DynamicClientRegistrationRepository.RegistrationRestTemplate registrationRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.build(DynamicClientRegistrationRepository.RegistrationRestTemplate.class); } // As of Spring Boot 3.2, we could use a record instead of a class. @ConfigurationProperties(prefix = "baeldung.security.client.registration") @Getter @Setter public static final class RegistrationProperties { URI registrationEndpoint; String registrationUsername; String registrationPassword; List<String> registrationScopes; List<String> grantTypes; List<String> redirectUris; URI tokenEndpoint; } @Bean public OAuth2AuthorizationRequestResolver pkceResolver(ClientRegistrationRepository repo) { var resolver = new DefaultOAuth2AuthorizationRequestResolver(repo, "/oauth2/authorization"); resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
return resolver; } @Bean SecurityFilterChain oauth2SecurityFilterChain(HttpSecurity http, OAuth2AuthorizationRequestResolver resolver) throws Exception { http.authorizeHttpRequests((requests) -> { requests.anyRequest().authenticated(); }); http.oauth2Login(a -> a.authorizationEndpoint(c -> c.authorizationRequestResolver(resolver))) ; http.oauth2Client(Customizer.withDefaults()); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\java\com\baeldung\spring\security\dynreg\client\config\OAuth2DynamicClientConfiguration.java
2
请完成以下Java代码
public void createTopicWithOptions(String topicName) throws Exception { Properties props = new Properties(); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); try (Admin admin = Admin.create(props)) { int partitions = 1; short replicationFactor = 1; NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor); CreateTopicsOptions topicOptions = new CreateTopicsOptions().validateOnly(true) .retryOnQuotaViolation(true); CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic), topicOptions); KafkaFuture<Void> future = result.values() .get(topicName); future.get(); } } public void createCompactedTopicWithCompression(String topicName) throws Exception { Properties props = new Properties(); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); try (Admin admin = Admin.create(props)) {
int partitions = 1; short replicationFactor = 1; // Create a compacted topic with 'lz4' compression codec Map<String, String> newTopicConfig = new HashMap<>(); newTopicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); newTopicConfig.put(TopicConfig.COMPRESSION_TYPE_CONFIG, "lz4"); NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor).configs(newTopicConfig); CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic)); KafkaFuture<Void> future = result.values() .get(topicName); future.get(); } } }
repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\kafka\admin\KafkaTopicApplication.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "3") public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @ApiModelProperty(example = "http://localhost:8182/repository/process-definition/3") public String getProcessDefinitionUrl() { return processDefinitionUrl; } public void setProcessDefinitionUrl(String processDefinitionUrl) { this.processDefinitionUrl = processDefinitionUrl; } @ApiModelProperty(example = "6") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "http://localhost:8182/runtime/task/6") public String getTaskUrl() { return taskUrl; }
public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public List<RestFormProperty> getFormProperties() { return formProperties; } public void setFormProperties(List<RestFormProperty> formProperties) { this.formProperties = formProperties; } public void addFormProperty(RestFormProperty formProperty) { formProperties.add(formProperty); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\form\FormDataResponse.java
2
请在Spring Boot框架中完成以下Java代码
public int getOrder() { return 0; } @Override public void customize(ConfigurableServletWebServerFactory factory) { PropertyMapper map = PropertyMapper.get(); map.from(this.serverProperties::getPort).to(factory::setPort); map.from(this.serverProperties::getAddress).to(factory::setAddress); map.from(this.serverProperties.getServlet()::getContextPath).to(factory::setContextPath); map.from(this.serverProperties.getServlet()::getApplicationDisplayName).to(factory::setDisplayName); map.from(this.serverProperties.getServlet()::isRegisterDefaultServlet).to(factory::setRegisterDefaultServlet); map.from(this.serverProperties.getServlet()::getSession).to(factory::setSession); map.from(this.serverProperties::getSsl).to(factory::setSsl); map.from(this.serverProperties.getServlet()::getJsp).to(factory::setJsp);
map.from(this.serverProperties::getCompression).to(factory::setCompression); map.from(this.serverProperties::getHttp2).to(factory::setHttp2); map.from(this.serverProperties::getServerHeader).to(factory::setServerHeader); map.from(this.serverProperties.getServlet()::getContextParameters).to(factory::setInitParameters); map.from(this.serverProperties.getShutdown()).to(factory::setShutdown); map.from(() -> this.sslBundles).to(factory::setSslBundles); map.from(() -> this.cookieSameSiteSuppliers) .whenNot(CollectionUtils::isEmpty) .to(factory::setCookieSameSiteSuppliers); map.from(this.serverProperties::getMimeMappings).to(factory::addMimeMappings); map.from(this.serverProperties.getServlet().getEncoding()::getMapping).to(factory::setLocaleCharsetMappings); this.webListenerRegistrars.forEach((registrar) -> registrar.register(factory)); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\servlet\ServletWebServerFactoryCustomizer.java
2
请在Spring Boot框架中完成以下Java代码
public void generateSitemap() { log.info("start generate sitemap"); String tempPath = "D://tmp/"; File file = new File(tempPath); if (!file.exists()) { file.mkdirs(); } String domain = "http://www.liuhaihua.cn"; try { WebSitemapGenerator g1 = WebSitemapGenerator.builder(domain, file).maxUrls(10000) .fileNamePrefix("article").build(); Date date = new Date(); for (int i = 1; i < 160000; i++) { WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/article/" + i).lastMod(date).build(); g1.addUrl(url); } WebSitemapGenerator g2 = WebSitemapGenerator.builder(domain, file) .fileNamePrefix("tag").build(); Date date2 = new Date(); for (int i = 1; i < 21; i++) { WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/tag/" + i).lastMod(date2).build(); g2.addUrl(url); } WebSitemapGenerator g3 = WebSitemapGenerator.builder(domain, file) .fileNamePrefix("type").build(); Date date3 = new Date(); for (int i = 1; i < 21; i++) { WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/type/" + i).lastMod(date3).build(); g3.addUrl(url); } List<String> fileNames = new ArrayList<>(); // 生成 sitemap 文件 List<File> articleFiles = g1.write(); articleFiles.forEach(e -> fileNames.add(e.getName()));
List<File> tagFiles = g2.write(); tagFiles.forEach(e -> fileNames.add(e.getName())); List<File> typeFiles = g3.write(); typeFiles.forEach(e -> fileNames.add(e.getName())); // 构造 sitemap_index 生成器 W3CDateFormat dateFormat = new W3CDateFormat(W3CDateFormat.Pattern.DAY); SitemapIndexGenerator sitemapIndexGenerator = new SitemapIndexGenerator .Options(domain, new File(tempPath + "sitemap_index.xml")) .dateFormat(dateFormat) .autoValidate(true) .build(); fileNames.forEach(e -> { try { // 组装 sitemap 文件 URL 地址 sitemapIndexGenerator.addUrl(domain + "/" + e); } catch (MalformedURLException e1) { e1.printStackTrace(); } }); // 生成 sitemap_index 文件 sitemapIndexGenerator.write(); log.info("end generate sitemap"); } catch (MalformedURLException e) { e.printStackTrace(); } } }
repos\springboot-demo-master\sitemap\src\main\java\com\et\sitemap\job\SiteMapJob.java
2
请完成以下Java代码
protected void configureQuery(HistoricBatchQueryImpl query) { getAuthorizationManager().configureHistoricBatchQuery(query); getTenantManager().configureQuery(query); } @SuppressWarnings("unchecked") public List<CleanableHistoricBatchReportResult> findCleanableHistoricBatchesReportByCriteria(CleanableHistoricBatchReportImpl query, Page page, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); query.getOrderingProperties().add(new QueryOrderingProperty(new QueryPropertyImpl("TYPE_"), Direction.ASCENDING)); if (batchOperationsForHistoryCleanup.isEmpty()) { return getDbEntityManager().selectList("selectOnlyFinishedBatchesReportEntities", query, page); } else { return getDbEntityManager().selectList("selectFinishedBatchesReportEntities", query, page); } } public long findCleanableHistoricBatchesReportCountByCriteria(CleanableHistoricBatchReportImpl query, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); if (batchOperationsForHistoryCleanup.isEmpty()) { return (Long) getDbEntityManager().selectOne("selectOnlyFinishedBatchesReportEntitiesCount", query); } else { return (Long) getDbEntityManager().selectOne("selectFinishedBatchesReportEntitiesCount", query); } } public DbOperation deleteHistoricBatchesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricBatchEntity.class, "deleteHistoricBatchesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); }
public void addRemovalTimeById(String id, Date removalTime) { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricIncidentManager() .addRemovalTimeToHistoricIncidentsByBatchId(id, removalTime); commandContext.getHistoricJobLogManager() .addRemovalTimeToJobLogByBatchId(id, removalTime); Map<String, Object> parameters = new HashMap<>(); parameters.put("id", id); parameters.put("removalTime", removalTime); getDbEntityManager() .updatePreserveOrder(HistoricBatchEntity.class, "updateHistoricBatchRemovalTimeById", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricBatchManager.java
1
请完成以下Java代码
public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ExternalTaskQueryDto getExternalTaskQuery() { return externalTaskQuery; } public void setExternalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { this.externalTaskQuery = externalTaskQuery; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQueryDto) { this.processInstanceQuery = processInstanceQueryDto; }
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto) { this.historicProcessInstanceQuery = historicProcessInstanceQueryDto; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\SetRetriesForExternalTasksDto.java
1
请完成以下Java代码
public CallableElement getCallableElement() { return callableElement; } public void setCallableElement(CallableElement callableElement) { this.callableElement = callableElement; } protected String getBusinessKey(ActivityExecution execution) { return getCallableElement().getBusinessKey(execution); } protected VariableMap getInputVariables(ActivityExecution callingExecution) { return getCallableElement().getInputVariables(callingExecution); } protected VariableMap getOutputVariables(VariableScope calledElementScope) { return getCallableElement().getOutputVariables(calledElementScope); } protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) { return getCallableElement().getOutputVariablesLocal(calledElementScope); } protected Integer getVersion(ActivityExecution execution) { return getCallableElement().getVersion(execution); } protected String getDeploymentId(ActivityExecution execution) { return getCallableElement().getDeploymentId(); }
protected CallableElementBinding getBinding() { return getCallableElement().getBinding(); } protected boolean isLatestBinding() { return getCallableElement().isLatestBinding(); } protected boolean isDeploymentBinding() { return getCallableElement().isDeploymentBinding(); } protected boolean isVersionBinding() { return getCallableElement().isVersionBinding(); } protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java
1
请完成以下Java代码
public class TenantProfileCacheKey implements Serializable { @Serial private static final long serialVersionUID = 8220455917177676472L; private final TenantProfileId tenantProfileId; private final boolean defaultProfile; private TenantProfileCacheKey(TenantProfileId tenantProfileId, boolean defaultProfile) { this.tenantProfileId = tenantProfileId; this.defaultProfile = defaultProfile; } public static TenantProfileCacheKey fromId(TenantProfileId id) { return new TenantProfileCacheKey(id, false); }
public static TenantProfileCacheKey defaultProfile() { return new TenantProfileCacheKey(null, true); } @Override public String toString() { if (defaultProfile) { return "default"; } else { return tenantProfileId.toString(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\TenantProfileCacheKey.java
1
请完成以下Java代码
protected static abstract class SelectableRowProcessor { public abstract void process(SelectableRowAdapter row); public boolean isContinue() { return true; } } protected static final class SelectableRowAdapter { private final AnnotatedTableModel<?> tableModel; private final int rowModelIndex; private final int selectedColumnIndex; public SelectableRowAdapter(final AnnotatedTableModel<?> tableModel, final int rowModelIndex, final int selectedColumnIndex) {
super(); this.tableModel = tableModel; this.rowModelIndex = rowModelIndex; this.selectedColumnIndex = selectedColumnIndex; } public void setSelected(final boolean selected) { tableModel.setValueAt(selected, rowModelIndex, selectedColumnIndex); } public boolean isSelected() { final Object valueObj = tableModel.getValueAt(rowModelIndex, selectedColumnIndex); return DisplayType.toBoolean(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AbstractManageSelectableRowsAction.java
1
请在Spring Boot框架中完成以下Java代码
public boolean supportsLimit() { return true; } protected String getLimitString(String query, boolean hasOffset) { return new StringBuffer(query.length() + 20). append(query). append(hasOffset ? " limit ? offset ?" : " limit ?"). toString(); } public boolean supportsTemporaryTables() { return true; } public String getCreateTemporaryTableString() { return "create temporary table if not exists"; } public boolean dropTemporaryTableAfterUse() { return false; } public boolean supportsCurrentTimestampSelection() { return true; } public boolean isCurrentTimestampSelectStringCallable() { return false; } public String getCurrentTimestampSelectString() { return "select current_timestamp"; } public boolean supportsUnionAll() { return true; } public boolean hasAlterTable() { return false; // As specify in NHibernate dialect } public boolean dropConstraints() { return false; } public String getAddColumnString() { return "add column"; } public String getForUpdateString() { return ""; } public boolean supportsOuterJoinForUpdate() { return false; }
public String getDropForeignKeyString() { throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect"); } public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) { throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect"); } public String getAddPrimaryKeyConstraintString(String constraintName) { throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect"); } public boolean supportsIfExistsBeforeTableName() { return true; } public boolean supportsCascadeDelete() { return false; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\config\SQLiteDialect.java
2
请完成以下Java代码
public static void dumpHistogram(final Map<String, Set<ITableRecordReference>> result) { final Set<ITableRecordReference> allRecords = result.values() .stream() .flatMap(records -> records.stream()) .collect(Collectors.toSet()); System.out.println("overall size=" + allRecords.size()); final PlainContextAware ctxProvider = PlainContextAware.newOutOfTrx(Env.getCtx()); allRecords.stream() .collect(Collectors.groupingBy(ITableRecordReference::getTableName)) .forEach((t, r) -> { System.out.println(t + ":\tsize=" + r.size() + ";\trepresentant=" + r.get(0).getModel(ctxProvider, IDLMAware.class)); }); } public static Iterator<WorkQueue> loadQueue(final int dlm_Partition_ID, final IContextAware contextAware) { final IQueryBL queryBL = Services.get(IQueryBL.class); final Iterator<I_DLM_Partition_Workqueue> iterator = queryBL.createQueryBuilder(I_DLM_Partition_Workqueue.class, contextAware) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DLM_Partition_Workqueue.COLUMN_DLM_Partition_ID, dlm_Partition_ID) .orderBy().addColumn(I_DLM_Partition_Workqueue.COLUMNNAME_DLM_Partition_Workqueue_ID).endOrderBy() .create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 5000) .iterate(I_DLM_Partition_Workqueue.class); return new Iterator<WorkQueue>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public WorkQueue next() { return WorkQueue.of(iterator.next()); } @Override public String toString() { return "PartitionerTools.loadQueue() [dlm_Partition_ID=" + dlm_Partition_ID + "; iterator=" + iterator + "]"; } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\PartitionerTools.java
1
请在Spring Boot框架中完成以下Java代码
public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; } public Mono<City> save(City city) { return cityRepository.save(city); } public Mono<City> findCityById(Long id) { return cityRepository.findById(id); }
public Flux<City> findAllCity() { return cityRepository.findAll(); } public Mono<City> modifyCity(City city) { return cityRepository.save(city); } public Mono<Long> deleteCity(Long id) { return cityRepository.deleteById(id).flatMap(mono -> Mono.create(cityMonoSink -> cityMonoSink.success(id))); } }
repos\springboot-learning-example-master\springboot-webflux-3-mongodb\src\main\java\org\spring\springboot\handler\CityHandler.java
2
请完成以下Java代码
public void setFeature_index_(FeatureIndex feature_index_) { this.feature_index_ = feature_index_; } public List<List<String>> getX_() { return x_; } public void setX_(List<List<String>> x_) { this.x_ = x_; } public List<List<Node>> getNode_() { return node_; } public void setNode_(List<List<Node>> node_) { this.node_ = node_; } public List<Integer> getAnswer_() { return answer_; } public void setAnswer_(List<Integer> answer_) { this.answer_ = answer_; } public List<Integer> getResult_() { return result_; } public void setResult_(List<Integer> result_) { this.result_ = result_; } public static void main(String[] args) throws Exception { if (args.length < 1) { return; }
TaggerImpl tagger = new TaggerImpl(Mode.TEST); InputStream stream = null; try { stream = IOUtil.newInputStream(args[0]); } catch (IOException e) { System.err.printf("model not exits for %s", args[0]); return; } if (stream != null && !tagger.open(stream, 2, 0, 1.0)) { System.err.println("open error"); return; } System.out.println("Done reading model"); if (args.length >= 2) { InputStream fis = IOUtil.newInputStream(args[1]); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); while (true) { ReadStatus status = tagger.read(br); if (ReadStatus.ERROR == status) { System.err.println("read error"); return; } else if (ReadStatus.EOF == status) { break; } if (tagger.getX_().isEmpty()) { break; } if (!tagger.parse()) { System.err.println("parse error"); return; } System.out.print(tagger.toString()); } br.close(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class LombokDefaultBook implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; 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 String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLombokEqualsAndHashCode\src\main\java\com\app\LombokDefaultBook.java
2
请完成以下Java代码
public class SysUserOnlineVO { /** * 会话id */ private String id; /** * 会话编号 */ private String token; /** * 用户名 */ private String username; /** * 用户名 */ private String realname; /** * 头像
*/ private String avatar; /** * 生日 */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; /** * 性别(1:男 2:女) */ @Dict(dicCode = "sex") private Integer sex; /** * 手机号 */ private String phone; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\SysUserOnlineVO.java
1
请完成以下Java代码
public Integer getIntegration() { return integration; } public void setIntegration(Integer integration) { this.integration = integration; } public Integer getGrowth() { return growth; } public void setGrowth(Integer growth) { this.growth = growth; } public Integer getLuckeyCount() { return luckeyCount; } public void setLuckeyCount(Integer luckeyCount) { this.luckeyCount = luckeyCount; } public Integer getHistoryIntegration() { return historyIntegration; } public void setHistoryIntegration(Integer historyIntegration) { this.historyIntegration = historyIntegration; } @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(", memberLevelId=").append(memberLevelId); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", nickname=").append(nickname); sb.append(", phone=").append(phone); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", icon=").append(icon); sb.append(", gender=").append(gender); sb.append(", birthday=").append(birthday); sb.append(", city=").append(city); sb.append(", job=").append(job); sb.append(", personalizedSignature=").append(personalizedSignature); sb.append(", sourceType=").append(sourceType); sb.append(", integration=").append(integration); sb.append(", growth=").append(growth); sb.append(", luckeyCount=").append(luckeyCount); sb.append(", historyIntegration=").append(historyIntegration); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMember.java
1
请完成以下Java代码
public XMLGregorianCalendar getYr() { return yr; } /** * Sets the value of the yr property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setYr(XMLGregorianCalendar value) { this.yr = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link TaxRecordPeriod1Code } * */ public TaxRecordPeriod1Code getTp() { return tp; } /** * Sets the value of the tp property. * * @param value
* allowed object is * {@link TaxRecordPeriod1Code } * */ public void setTp(TaxRecordPeriod1Code value) { this.tp = value; } /** * Gets the value of the frToDt property. * * @return * possible object is * {@link DatePeriodDetails } * */ public DatePeriodDetails getFrToDt() { return frToDt; } /** * Sets the value of the frToDt property. * * @param value * allowed object is * {@link DatePeriodDetails } * */ public void setFrToDt(DatePeriodDetails value) { this.frToDt = 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\TaxPeriod1.java
1
请完成以下Java代码
public void setOnKeyPress(String script) { addAttribute ( "onkeypress", script ); } /** The onkeydown event occurs when a key is pressed down over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyDown(String script) { addAttribute ( "onkeydown", script );
} /** The onkeyup event occurs when a key is released over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyUp(String script) { addAttribute ( "onkeyup", script ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\center.java
1
请完成以下Java代码
public String getHeroName() { return heroName; } public void setHeroName(String heroName) { this.heroName = heroName; } public String getUniquePower() { return uniquePower; } public void setUniquePower(String uniquePower) { this.uniquePower = uniquePower; }
public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } }
repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\SuperHero.java
1
请完成以下Java代码
public class DiagramInterchangeInfoValidator extends ValidatorImpl { @Override public void validate(BpmnModel bpmnModel, List<ValidationError> errors) { if (!bpmnModel.getLocationMap().isEmpty()) { // Location map for (String bpmnReference : bpmnModel.getLocationMap().keySet()) { if (bpmnModel.getFlowElement(bpmnReference) == null) { // ACT-1625: don't warn when artifacts are referenced from // DI if (bpmnModel.getArtifact(bpmnReference) == null) { // check if it's a Pool or Lane, then DI is ok if (bpmnModel.getPool(bpmnReference) == null && bpmnModel.getLane(bpmnReference) == null) { addWarning(errors, Problems.DI_INVALID_REFERENCE, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: could not find " + bpmnReference); } } } else if (!(bpmnModel.getFlowElement(bpmnReference) instanceof FlowNode)) { addWarning(errors, Problems.DI_DOES_NOT_REFERENCE_FLOWNODE, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: " + bpmnReference + " does not reference a flow node"); } } } if (!bpmnModel.getFlowLocationMap().isEmpty()) {
// flowlocation map for (String bpmnReference : bpmnModel.getFlowLocationMap().keySet()) { if (bpmnModel.getFlowElement(bpmnReference) == null) { // ACT-1625: don't warn when artifacts are referenced from // DI if (bpmnModel.getArtifact(bpmnReference) == null) { addWarning(errors, Problems.DI_INVALID_REFERENCE, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: could not find " + bpmnReference); } } else if (!(bpmnModel.getFlowElement(bpmnReference) instanceof SequenceFlow)) { addWarning(errors, Problems.DI_DOES_NOT_REFERENCE_SEQ_FLOW, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: " + bpmnReference + " does not reference a sequence flow"); } } } } }
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\DiagramInterchangeInfoValidator.java
1
请完成以下Java代码
public ReplicationTrxLinesProcessorResult getResult() { return result; } @Override public boolean isSameChunk(final I_EXP_ReplicationTrxLine item) { return false; } @Override public void newChunk(final I_EXP_ReplicationTrxLine item) { currentTrxLines = new ArrayList<I_EXP_ReplicationTrxLine>(); } @Override public void process(final I_EXP_ReplicationTrxLine item) throws Exception { final IReplicationIssueAware issueAware = Services.get(IReplicationIssueSolverDAO.class).retrieveReplicationIssueAware(item); issueSolver.solveIssues(issueAware, params); currentTrxLines.add(item); result.addReplicationIssueAware(issueAware); } @Override
public void completeChunk() { for (final I_EXP_ReplicationTrxLine line : currentTrxLines) { line.setReplicationTrxStatus(X_EXP_ReplicationTrxLine.REPLICATIONTRXSTATUS_Vollstaendig); InterfaceWrapperHelper.save(line); } } @Override public void cancelChunk() { currentTrxLines = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\trx\api\impl\ReplicationTrxLinesProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class DummyTaskProcessor extends TaskProcessor<DummyTask, DummyTaskResult> { @Override public DummyTaskResult process(DummyTask task) throws Exception { if (task.getProcessingTimeMs() > 0) { Thread.sleep(task.getProcessingTimeMs()); } if (task.isFailAlways()) { throw new RuntimeException(task.getErrors().get(0)); } if (task.getErrors() != null && task.getAttempt() <= task.getErrors().size()) { String error = task.getErrors().get(task.getAttempt() - 1); throw new RuntimeException(error); } return DummyTaskResult.success(task); }
@Override public long getProcessingTimeout(DummyTask task) { return task.getProcessingTimeoutMs() > 0 ? task.getProcessingTimeoutMs() : 2000; } public Map<Object, Pair<Task<DummyTaskResult>, Future<DummyTaskResult>>> getCurrentTasks() { return currentTasks; } @Override public JobType getJobType() { return JobType.DUMMY; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\job\task\DummyTaskProcessor.java
2
请完成以下Java代码
public void setPropagationType (final java.lang.String PropagationType) { set_Value (COLUMNNAME_PropagationType, PropagationType); } @Override public java.lang.String getPropagationType() { return get_ValueAsString(COLUMNNAME_PropagationType); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSplitterStrategy_JavaClass_ID (final int SplitterStrategy_JavaClass_ID)
{ if (SplitterStrategy_JavaClass_ID < 1) set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, null); else set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, SplitterStrategy_JavaClass_ID); } @Override public int getSplitterStrategy_JavaClass_ID() { return get_ValueAsInt(COLUMNNAME_SplitterStrategy_JavaClass_ID); } @Override public void setUseInASI (final boolean UseInASI) { set_Value (COLUMNNAME_UseInASI, UseInASI); } @Override public boolean isUseInASI() { return get_ValueAsBoolean(COLUMNNAME_UseInASI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Attribute.java
1
请完成以下Java代码
default void onPartitionsRevokedAfterCommit(Consumer<?, ?> consumer, Collection<TopicPartition> partitions) { } /** * The same as {@link #onPartitionsLost(Collection)} with an additional consumer parameter. * @param consumer the consumer. * @param partitions the partitions. * @since 2.4 */ default void onPartitionsLost(Consumer<?, ?> consumer, Collection<TopicPartition> partitions) { onPartitionsLost(partitions); } /** * The same as {@link #onPartitionsAssigned(Collection)} with the additional consumer * parameter. * @param consumer the consumer. * @param partitions the partitions. */
default void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions) { onPartitionsAssigned(partitions); } @Override default void onPartitionsRevoked(Collection<TopicPartition> partitions) { } @Override default void onPartitionsAssigned(Collection<TopicPartition> partitions) { } @Override default void onPartitionsLost(Collection<TopicPartition> partitions) { } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ConsumerAwareRebalanceListener.java
1
请完成以下Java代码
public class MigrationPlanImpl implements MigrationPlan { protected String sourceProcessDefinitionId; protected String targetProcessDefinitionId; protected List<MigrationInstruction> instructions; protected VariableMap variables; public MigrationPlanImpl(String sourceProcessDefinitionId, String targetProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; this.targetProcessDefinitionId = targetProcessDefinitionId; this.instructions = new ArrayList<MigrationInstruction>(); } public String getSourceProcessDefinitionId() { return sourceProcessDefinitionId; } public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetProcessDefinitionId() { return targetProcessDefinitionId; } @Override public VariableMap getVariables() { return variables; } public void setVariables(VariableMap variables) { this.variables = variables; } public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId;
} public List<MigrationInstruction> getInstructions() { return instructions; } public void setInstructions(List<MigrationInstruction> instructions) { this.instructions = instructions; } public String toString() { return "MigrationPlan[" + "sourceProcessDefinitionId='" + sourceProcessDefinitionId + '\'' + ", targetProcessDefinitionId='" + targetProcessDefinitionId + '\'' + ", instructions=" + instructions + ']'; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationPlanImpl.java
1
请完成以下Java代码
public static List<Event> readEventsByDateRange(LocalDateTime from, LocalDateTime to) { BasicDBObject object = new BasicDBObject(); object.put("dateTime", BasicDBObjectBuilder .start("$gte", from) .add("$lte", to) .get()); try { List<Event> list = new ArrayList<Event>(collection.find(object).into(new ArrayList<Event>())); return list; } catch (MongoException me) { System.err.println("Failed to read with error: " + me); throw me; } } public static LocalDateTime readEventsByDateWithTZ(LocalDateTime localDateTime) { try { Event event = collection .find(eq("dateTime", localDateTime)) .first(); OffsetDateTime offsetDateTime = OffsetDateTime.of(event.dateTime, ZoneOffset.of(pianoLessonsTZ.timeZoneOffset)); ZonedDateTime zoned = offsetDateTime.atZoneSameInstant(ZoneId.of("America/Toronto")); return zoned.toLocalDateTime(); } catch (MongoException me) { System.err.println("Failed to read with error: " + me); throw me; } } public static long updateDateField() { Document document = new Document().append("title", "Piano lessons"); Bson update = Updates.currentDate("updatedAt"); UpdateOptions options = new UpdateOptions().upsert(false); try { UpdateResult result = collection.updateOne(document, update, options); return result.getModifiedCount(); } catch (MongoException me) { System.err.println("Failed to update with error: " + me); throw me; } } public static long updateManyEventsWithDateCriteria(LocalDate updateManyFrom, LocalDate updateManyTo) { Bson query = and(gte("dateTime", updateManyFrom), lt("dateTime", updateManyTo)); Bson updates = Updates.currentDate("dateTime"); try { UpdateResult result = collection.updateMany(query, updates);
return result.getModifiedCount(); } catch(MongoException me) { System.err.println("Failed to replace/update with error: " + me); throw me; } } public static long deleteEventsByDate(LocalDate from, LocalDate to) { Bson query = and(gte("dateTime", from), lt("dateTime", to)); try { DeleteResult result = collection.deleteMany(query); return result.getDeletedCount(); } catch (MongoException me) { System.err.println("Failed to delete with error: " + me); throw me; } } public static void dropDb() { db.drop(); } public static void main(String[] args) { } }
repos\tutorials-master\persistence-modules\java-mongodb-queries\src\main\java\com\baeldung\mongo\crud\CrudClient.java
1
请完成以下Java代码
public String getErrorCode() { return errorCode; } /** * Sets the value of the errorCode property. * * @param value * allowed object is * {@link String } * */ public void setErrorCode(String value) { this.errorCode = value; } /** * Gets the value of the errorMessage property. * * @return * possible object is * {@link String } * */ public String getErrorMessage() {
return errorMessage; } /** * Sets the value of the errorMessage property. * * @param value * allowed object is * {@link String } * */ public void setErrorMessage(String value) { this.errorMessage = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\authentication\v2_0\types\AuthenticationFault.java
1
请完成以下Java代码
public int getC_Queue_Processor_Assign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_Assign_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_Processor getC_Queue_Processor() { return get_ValueAsPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class); } @Override public void setC_Queue_Processor(de.metas.async.model.I_C_Queue_Processor C_Queue_Processor) { set_ValueFromPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class, C_Queue_Processor); } /** Set Queue Processor Definition. @param C_Queue_Processor_ID Queue Processor Definition */ @Override public void setC_Queue_Processor_ID (int C_Queue_Processor_ID) {
if (C_Queue_Processor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, Integer.valueOf(C_Queue_Processor_ID)); } /** Get Queue Processor Definition. @return Queue Processor Definition */ @Override public int getC_Queue_Processor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor_Assign.java
1
请在Spring Boot框架中完成以下Java代码
public static class Card { @NonNull String type; @NonNull String last4Digits; @Override @Deprecated public String toString() {return getAsString();} public String getAsString() {return type + "-" + last4Digits;} } // // // // // // @RequiredArgsConstructor @Getter public enum LastSyncStatus implements ReferenceListAwareEnum { OK(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_OK), Error(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_Error), ; private static final ValuesIndex<LastSyncStatus> index = ReferenceListAwareEnums.index(values()); @NonNull private final String code; public static LastSyncStatus ofCode(@NonNull String code) {return index.ofCode(code);} public static LastSyncStatus ofNullableCode(@Nullable String code) {return index.ofNullableCode(code);} } // // // // // //
@Value @Builder @Jacksonized @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public static class LastSync { @NonNull LastSyncStatus status; @Nullable Instant timestamp; @Nullable AdIssueId errorId; public static LastSync ok() { return builder() .status(LastSyncStatus.OK) .timestamp(SystemTime.asInstant()) .build(); } public static LastSync error(@NonNull final AdIssueId errorId) { return builder() .status(LastSyncStatus.Error) .timestamp(SystemTime.asInstant()) .errorId(errorId) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransaction.java
2
请完成以下Java代码
public final class BearerTokenAuthenticationConverter implements AuthenticationConverter { private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource(); private BearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver(); @Override public Authentication convert(HttpServletRequest request) { String token = this.bearerTokenResolver.resolve(request); if (StringUtils.hasText(token)) { BearerTokenAuthenticationToken authenticationToken = new BearerTokenAuthenticationToken(token); authenticationToken.setDetails(this.authenticationDetailsSource.buildDetails(request)); return authenticationToken; } return null; } public void setBearerTokenResolver(BearerTokenResolver bearerTokenResolver) {
Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null"); this.bearerTokenResolver = bearerTokenResolver; } /** * Set the {@link AuthenticationDetailsSource} to use. Defaults to * {@link WebAuthenticationDetailsSource}. * @param authenticationDetailsSource the {@code AuthenticationDetailsSource} to use */ public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "authenticationDetailsSource cannot be null"); this.authenticationDetailsSource = authenticationDetailsSource; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\authentication\BearerTokenAuthenticationConverter.java
1
请完成以下Java代码
public Set<String> getHeaders() { return headers; } public void setHeaders(Set<String> headers) { Objects.requireNonNull(headers, "headers may not be null"); this.headers = headers.stream().map(String::toLowerCase).collect(Collectors.toSet()); } @Override public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public HttpHeaders filter(HttpHeaders originalHeaders, ServerWebExchange exchange) { HttpHeaders filtered = new HttpHeaders(); List<String> connectionOptions = originalHeaders.getConnection().stream().map(String::toLowerCase).toList(); Set<String> headersToRemove = new HashSet<>(headers); headersToRemove.addAll(connectionOptions);
for (Map.Entry<String, List<String>> entry : originalHeaders.headerSet()) { if (!headersToRemove.contains(entry.getKey().toLowerCase(Locale.ROOT))) { filtered.addAll(entry.getKey(), entry.getValue()); } } return filtered; } @Override public boolean supports(Type type) { return type.equals(Type.REQUEST) || type.equals(Type.RESPONSE); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\RemoveHopByHopHeadersFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class PushArticlesProcessor implements Processor { @Override public void process(final Exchange exchange) throws Exception { final AlbertaProductApi albertaProductApi = getPropertyOrThrowError(exchange, ROUTE_PROPERTY_ALBERTA_PRODUCT_API, AlbertaProductApi.class); final UpsertArticleRequest upsertArticleRequest = exchange.getIn().getBody(UpsertArticleRequest.class); if (upsertArticleRequest == null) { exchange.getIn().setBody(null); return; //nothing more to do } final ArticleMapping articleMapping = upsertArticleRequest.isFirstExport() ? albertaProductApi.addProductFallbackUpdate(upsertArticleRequest.getArticle()) : albertaProductApi.updateProductFallbackAdd(upsertArticleRequest.getArticle()); final JsonRequestExternalReferenceUpsert externalReferenceUpsert = buildUpsertExternalRefRequest(articleMapping, upsertArticleRequest.getProductId()); exchange.getIn().setBody(externalReferenceUpsert); }
@NonNull private JsonRequestExternalReferenceUpsert buildUpsertExternalRefRequest( @NonNull final ArticleMapping articleMapping, @NonNull final JsonMetasfreshId productId) { return JsonRequestExternalReferenceUpsert.builder() .systemName(JsonExternalSystemName.of(ALBERTA_EXTERNAL_REFERENCE_SYSTEM)) .externalReferenceItem(JsonExternalReferenceItem.builder() .metasfreshId(productId) .lookupItem(JsonExternalReferenceLookupItem.builder() .type(PRODUCT_EXTERNAL_REFERENCE_TYPE) .id(articleMapping.getId().toString()) .build()) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\product\processor\PushArticlesProcessor.java
2
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRestartedProcessInstanceId() { return restartedProcessInstanceId; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId) { this.restartedProcessInstanceId = restartedProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[businessKey=" + businessKey + ", startUserId=" + startUserId + ", superProcessInstanceId=" + superProcessInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", superCaseInstanceId=" + superCaseInstanceId + ", deleteReason=" + deleteReason + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", removalTime=" + removalTime + ", endActivityId=" + endActivityId + ", startActivityId=" + startActivityId + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", tenantId=" + tenantId + ", restartedProcessInstanceId=" + restartedProcessInstanceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java
1
请完成以下Java代码
public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID) { if (M_HU_Item_Storage_ID < 1) set_Value (COLUMNNAME_M_HU_Item_Storage_ID, null); else set_Value (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID); } @Override public int getM_HU_Item_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID); } @Override public void setM_HU_Item_Storage_Snapshot_ID (final int M_HU_Item_Storage_Snapshot_ID) { if (M_HU_Item_Storage_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, M_HU_Item_Storage_Snapshot_ID); } @Override public int getM_HU_Item_Storage_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_Snapshot_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() {
return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final 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 setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java
1
请完成以下Java代码
public boolean isActive() { return getActiveStatus() == JsonProductPackageState.ACTIVE; } public boolean isFraud() { return getActiveStatus() == JsonProductPackageState.FRAUD; } public void productDecommissioned(@NonNull final String decommissionedServerTransactionId) { if (decommissioned) { throw new AdempiereException("Product already decommissioned: " + this); }
this.decommissioned = true; this.decommissionedServerTransactionId = decommissionedServerTransactionId; } public void productDecommissionUndo(@NonNull final String undoDecommissionedServerTransactionId) { if (!decommissioned) { throw new AdempiereException("Product is not decommissioned: " + this); } this.decommissioned = false; this.decommissionedServerTransactionId = undoDecommissionedServerTransactionId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\product\ProductDetails.java
1
请完成以下Java代码
public static String getSenderId() { return SENDER_ID; } /** * @return true of calls to {@link IEventBus#processEvent(Event)} shall be performed asynchronously */ public static boolean isEventBusPostAsync(@NonNull final Topic topic) { if (alwaysConsiderAsyncTopics.contains(topic)) { return true; } // NOTE: in case of unit tests which are checking what notifications were arrived, // allowing the events to be posted async could be a problem because the event might arrive after the check. if (Adempiere.isUnitTestMode()) { return false; } final String nameForAllTopics = "de.metas.event.asyncEventBus"; final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final Map<String, String> valuesForPrefix = sysConfigBL.getValuesForPrefix(nameForAllTopics, ClientAndOrgId.SYSTEM); final String keyForTopic = nameForAllTopics + ".topic_" + topic.getName(); final String valueForTopic = valuesForPrefix.get(keyForTopic); if (Check.isNotBlank(valueForTopic)) { getLogger(EventBusConfig.class).debug("SysConfig returned value={} for keyForTopic={}", valueForTopic, keyForTopic); return StringUtils.toBoolean(valueForTopic); } final String standardValue = valuesForPrefix.get(nameForAllTopics); getLogger(EventBusConfig.class).debug("SysConfig returned value={} for keyForTopic={}", standardValue, keyForTopic); return StringUtils.toBoolean(standardValue); } public static void alwaysConsiderAsync(@NonNull final Topic topic) { alwaysConsiderAsyncTopics.add(topic); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\EventBusConfig.java
1
请在Spring Boot框架中完成以下Java代码
public String getKey(String key) { try { String _response = evCache.<String>get(key); return _response; } catch (Exception e) { e.printStackTrace(); return null; } } public void setVerboseMode( boolean verboseMode ) { this.verboseMode = verboseMode; } public boolean setVerboseMode() { return this.verboseMode; } // public static void main(String[] args) { // // // set verboseMode based on the environment variable // verboseMode = ("true".equals(System.getenv("EVCACHE_SAMPLE_VERBOSE"))); // // if (verboseMode) { // System.out.println("To run this sample app without using Gradle:"); // System.out.println("java -cp " + System.getProperty("java.class.path") + " com.netflix.evcache.sample.EVCacheClientSample"); // } //
// try { // EVCacheClientSample evCacheClientSample = new EVCacheClientSample(); // // // Set ten keys to different values // for (int i = 0; i < 10; i++) { // String key = "key_" + i; // String value = "data_" + i; // // Set the TTL to 24 hours // int ttl = 10; // evCacheClientSample.setKey(key, value, ttl); // } // // // Do a "get" for each of those same keys // for (int i = 0; i < 10; i++) { // String key = "key_" + i; // String value = evCacheClientSample.getKey(key); // System.out.println("Get of " + key + " returned " + value); // } // } catch (Exception e) { // e.printStackTrace(); // } // // // System.exit(0); // } }
repos\Spring-Boot-In-Action-master\springbt_evcache\src\main\java\cn\codesheep\springbt_evcache\config\EVCacheClientSample.java
2
请完成以下Java代码
public Optional<HuId> getHUIdByValueOrExternalBarcode(@NonNull final ScannedCode scannedCode) { return Optionals.firstPresentOfSuppliers( () -> getHUIdByValue(scannedCode.getAsString()), () -> getByExternalBarcode(scannedCode) ); } private Optional<HuId> getHUIdByValue(final String value) { final HuId huId = HuId.ofHUValueOrNull(value); return huId != null && existsById(huId) ? Optional.of(huId) : Optional.empty(); } private Optional<HuId> getByExternalBarcode(@NonNull final ScannedCode scannedCode) { return handlingUnitsRepo.createHUQueryBuilder()
.setOnlyActiveHUs(true) .setOnlyTopLevelHUs() .addOnlyWithAttribute(AttributeConstants.ATTR_ExternalBarcode, scannedCode.getAsString()) .firstIdOnly(); } @Override public Set<HuPackingMaterialId> getHUPackingMaterialIds(@NonNull final HuId huId) { return handlingUnitsRepo.retrieveAllItemsNoCache(Collections.singleton(huId)) .stream() .map(item -> HuPackingMaterialId.ofRepoIdOrNull(item.getM_HU_PackingMaterial_ID())) .filter(Objects::nonNull) .collect(Collectors.toSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsBL.java
1
请完成以下Java代码
public int getMinorVersion() { return minorVersion; } public SentinelVersion setMinorVersion(int minorVersion) { this.minorVersion = minorVersion; return this; } public int getFixVersion() { return fixVersion; } public SentinelVersion setFixVersion(int fixVersion) { this.fixVersion = fixVersion; return this; } public String getPostfix() { return postfix; } public SentinelVersion setPostfix(String postfix) { this.postfix = postfix; return this; } public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } public boolean greaterOrEqual(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() >= version.getFullVersion(); } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SentinelVersion that = (SentinelVersion)o; if (getFullVersion() != that.getFullVersion()) { return false; } return postfix != null ? postfix.equals(that.postfix) : that.postfix == null; } @Override public int hashCode() { int result = majorVersion; result = 31 * result + minorVersion; result = 31 * result + fixVersion; result = 31 * result + (postfix != null ? postfix.hashCode() : 0); return result; } @Override public String toString() { return "SentinelVersion{" + "majorVersion=" + majorVersion + ", minorVersion=" + minorVersion + ", fixVersion=" + fixVersion + ", postfix='" + postfix + '\'' + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\SentinelVersion.java
1
请完成以下Java代码
private static boolean isAggregable(@NonNull final I_M_Attribute attribute) { return !Weightables.isWeightableAttribute(AttributeCode.ofString(attribute.getValue())); } // // // @RequiredArgsConstructor private static class AttributeAggregator { private final AttributeCode attributeCode; private final AttributeValueType attributeValueType; private final HashSet<Object> values = new HashSet<>(); void collect(@NonNull final IAttributeSet from) { final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>() { @Nullable @Override public Object string() { return from.getValueAsString(attributeCode); } @Override public Object number() { return from.getValueAsBigDecimal(attributeCode); } @Nullable @Override public Object date() { return from.getValueAsDate(attributeCode); }
@Nullable @Override public Object list() { return from.getValueAsString(attributeCode); } }); values.add(value); } void updateAggregatedValueTo(@NonNull final IAttributeSet to) { if (values.size() == 1 && to.hasAttribute(attributeCode)) { to.setValue(attributeCode, values.iterator().next()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java
1
请完成以下Java代码
static ServerResponse.BodyBuilder permanentRedirect(URI location) { ServerResponse.BodyBuilder builder = status(HttpStatus.PERMANENT_REDIRECT); return builder.location(location); } /** * Create a builder with a {@linkplain HttpStatus#BAD_REQUEST 400 Bad Request} status. * @return the created builder */ static ServerResponse.BodyBuilder badRequest() { return status(HttpStatus.BAD_REQUEST); } /** * Create a builder with a {@linkplain HttpStatus#NOT_FOUND 404 Not Found} status. * @return the created builder */ static ServerResponse.HeadersBuilder<?> notFound() { return status(HttpStatus.NOT_FOUND); } /** * Create a builder with a {@linkplain HttpStatus#UNPROCESSABLE_ENTITY 422 * Unprocessable Entity} status. * @return the created builder */ static ServerResponse.BodyBuilder unprocessableEntity() { return status(HttpStatus.UNPROCESSABLE_ENTITY); } /** * Create a (built) response with the given asynchronous response. Parameter * {@code asyncResponse} can be a {@link CompletableFuture * CompletableFuture&lt;ServerResponse&gt;} or {@link Publisher * Publisher&lt;ServerResponse&gt;} (or any asynchronous producer of a single * {@code ServerResponse} that can be adapted via the * {@link ReactiveAdapterRegistry}). * * <p> * This method can be used to set the response status code, headers, and body based on * an asynchronous result. If only the body is asynchronous, * {@link ServerResponse.BodyBuilder#body(Object)} can be used instead. * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or * {@code Publisher<ServerResponse>} * @return the asynchronous response * @since 5.3 */ static ServerResponse async(Object asyncResponse) { return GatewayAsyncServerResponse.create(asyncResponse, null);
} /** * Create a (built) response with the given asynchronous response. Parameter * {@code asyncResponse} can be a {@link CompletableFuture * CompletableFuture&lt;ServerResponse&gt;} or {@link Publisher * Publisher&lt;ServerResponse&gt;} (or any asynchronous producer of a single * {@code ServerResponse} that can be adapted via the * {@link ReactiveAdapterRegistry}). * * <p> * This method can be used to set the response status code, headers, and body based on * an asynchronous result. If only the body is asynchronous, * {@link ServerResponse.BodyBuilder#body(Object)} can be used instead. * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or * {@code Publisher<ServerResponse>} * @param timeout maximum time period to wait for before timing out * @return the asynchronous response * @since 5.3.2 */ static ServerResponse async(Object asyncResponse, Duration timeout) { return GatewayAsyncServerResponse.create(asyncResponse, timeout); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponse.java
1
请完成以下Java代码
public void createShipmentDeclarationIfNeeded(final I_M_InOut inout) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inout)) { if (!inout.isSOTrx()) { // Only applies to shipments return; } final InOutId shipmentId = InOutId.ofRepoId(inout.getM_InOut_ID()); shipmentDeclarationCreator.createShipmentDeclarationsIfNeeded(shipmentId); } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void createRequestIfConfigured(final I_M_InOut inout) { if (docTypeBL.hasRequestType(DocTypeId.ofRepoId(inout.getC_DocType_ID()))) { inOutBL.createRequestFromInOut(inout); } } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE }) public void forbidReactivateOnCompletedShipmentDeclaration(final I_M_InOut inout) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inout)) { if (!inout.isSOTrx()) { // Only applies to shipments
return; } final InOutId shipmentId = InOutId.ofRepoId(inout.getM_InOut_ID()); if (shipmentDeclarationRepo.existCompletedShipmentDeclarationsForShipmentId(shipmentId)) { throw new AdempiereException(ERR_ShipmentDeclaration).markAsUserValidationError(); } } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE, }, ifColumnsChanged = { I_M_InOut.COLUMNNAME_DropShip_Location_ID, I_M_InOut.COLUMNNAME_C_BPartner_Location_ID }) public void onBPartnerLocation(final I_M_InOut inout) { if (InterfaceWrapperHelper.isUIAction(inout)) { inOutBL.setShipperId(inout); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\model\interceptor\M_InOut.java
1
请在Spring Boot框架中完成以下Java代码
public String secure(Map<String, Object> model, Principal principal) { model.put("title", "SECURE AREA"); model.put("message", "Only Authorised Users Can See This Page"); model.put("username", getUserName(principal)); model.put("userroles", getUserRoles(principal)); return "home"; } private String getUserName(Principal principal) { if (principal == null) { return "anonymous"; } else { final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities(); for (GrantedAuthority grantedAuthority : authorities) { System.out.println(grantedAuthority.getAuthority()); } return principal.getName(); } }
private Collection<String> getUserRoles(Principal principal) { if (principal == null) { return Arrays.asList("none"); } else { Set<String> roles = new HashSet<String>(); final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal(); Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities(); for (GrantedAuthority grantedAuthority : authorities) { roles.add(grantedAuthority.getAuthority()); } return roles; } } }
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\controller\MyController.java
2
请完成以下Java代码
public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null; }
@Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "AppDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java
1
请完成以下Java代码
final protected void execute() throws IOException { vectorsReader.readVectorFile(); final int words = vectorsReader.getNumWords(); final int size = vectorsReader.getSize(); try { scanner = new Scanner(System.in); Result result = null; while ((result = getTargetVector()) != null) { double[] bestd = new double[N]; String[] bestw = new String[N]; next_word: for (int i = 0; i < words; i++) { for (int bi : result.bi) { if (i == bi) continue next_word; } double dist = 0; for (int j = 0; j < size; j++) { dist += result.vec[j] * vectorsReader.getMatrixElement(i, j); } for (int j = 0; j < N; j++) { if (dist > bestd[j]) { for (int k = N - 1; k > j; k--) { bestd[k] = bestd[k - 1]; bestw[k] = bestw[k - 1]; } bestd[j] = dist; bestw[j] = vectorsReader.getWord(i); break; } }
} System.out.printf("\n Word Cosine cosine\n------------------------------------------------------------------------\n"); for (int j = 0; j < N; j++) System.out.printf("%50s\t\t%f\n", bestw[j], bestd[j]); } } finally { scanner.close(); } } protected static class Result { float[] vec; int[] bi; public Result(float[] vec, int[] bi) { this.vec = vec; this.bi = bi; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractClosestVectors.java
1
请完成以下Java代码
public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getStoreType() { return storeType; } public void setStoreType(String storeType) { this.storeType = storeType; } public Double getFileSize() {
return fileSize; } public void setFileSize(Double fileSize) { this.fileSize = fileSize; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysFilesModel.java
1
请完成以下Java代码
protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(externalSystemParentConfig.getChildConfig()); if (EmptyUtil.isEmpty(grsConfig.getCamelHttpResourceAuthKey())) { throw new AdempiereException("camelHttpResourceAuthKey for childConfig should not be empty at this point") .appendParametersToMessage() .setParameter("childConfigId", grsConfig.getId()); } final Map<String, String> parameters = new HashMap<>(); parameters.put(ExternalSystemConstants.PARAM_CAMEL_HTTP_RESOURCE_AUTH_KEY, grsConfig.getCamelHttpResourceAuthKey()); parameters.put(ExternalSystemConstants.PARAM_BASE_PATH, grsConfig.getBaseUrl()); return parameters; } @Override protected String getTabName() { return ExternalSystemType.GRSSignum.getValue(); } @Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.GRSSignum; } @Override
protected long getSelectedRecordCount(final IProcessPreconditionsContext context) { return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_ExternalSystem_Config_GRSSignum.Table_Name.equals(recordRef.getTableName())) .count(); } @Override protected String getOrgCode(@NonNull final ExternalSystemParentConfig config) { return orgDAO.getById(config.getOrgId()).getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeGRSSignumAction.java
1
请完成以下Java代码
protected void validateParams(String userId, String groupId, String processInstanceId, String type) { if (processInstanceId == null) { throw new FlowableIllegalArgumentException("processInstanceId is null"); } if (type == null) { throw new FlowableIllegalArgumentException("type is required when deleting a process identity link"); } if (userId == null && groupId == null) { throw new FlowableIllegalArgumentException("userId and groupId cannot both be null"); } } @Override public Void execute(CommandContext commandContext) { ExecutionEntity processInstance = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstanceId); if (processInstance == null) { throw new FlowableObjectNotFoundException("Cannot find process instance with id " + processInstanceId, ExecutionEntity.class);
} if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, processInstance.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.deleteIdentityLinkForProcessInstance(processInstanceId, userId, groupId, type); return null; } IdentityLinkUtil.deleteProcessInstanceIdentityLinks(processInstance, userId, groupId, type); CommandContextUtil.getHistoryManager(commandContext).createProcessInstanceIdentityLinkComment(processInstance, userId, groupId, type, false); return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\DeleteIdentityLinkForProcessInstanceCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductsToPick_MarkWillNotPickSelected extends ProductsToPickViewBasedProcess { @Autowired private PickingCandidateService pickingCandidatesService; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final List<ProductsToPickRow> selectedRows = getSelectedRows(); if (selectedRows.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } if (!selectedRows.stream().allMatch(ProductsToPickRow::isEligibleForRejectPicking)) { return ProcessPreconditionsResolution.rejectWithInternalReason("select only rows that can be picked"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { getSelectedRows() .stream() .filter(ProductsToPickRow::isEligibleForRejectPicking) .forEach(this::markAsWillNotPick);
invalidateView(); return MSG_OK; } private void markAsWillNotPick(final ProductsToPickRow row) { final RejectPickingResult result = pickingCandidatesService.rejectPicking(RejectPickingRequest.builder() .shipmentScheduleId(row.getShipmentScheduleId()) .qtyToReject(row.getQtyEffective()) .rejectPickingFromHuId(row.getPickFromHUId()) .existingPickingCandidateId(row.getPickingCandidateId()) .build()); updateViewRowFromPickingCandidate(row.getId(), result.getPickingCandidate()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_MarkWillNotPickSelected.java
2
请完成以下Java代码
public Inventory updateById(final InventoryId inventoryId, UnaryOperator<Inventory> updater) { final Inventory inventory = loadById(inventoryId); final Inventory inventoryChanged = updater.apply(inventory); if (Objects.equals(inventory, inventoryChanged)) { return inventory; } saveInventory(inventoryChanged); return inventoryChanged; } public void updateInventoryLineByRecord(final I_M_InventoryLine inventoryLineRecord, UnaryOperator<InventoryLine> updater) { final InventoryId inventoryId = extractInventoryId(inventoryLineRecord); final InventoryLine inventoryLine = toInventoryLine(inventoryLineRecord); final InventoryLine inventoryLineChanged = updater.apply(inventoryLine); if (Objects.equals(inventoryLine, inventoryLineChanged)) { return; } saveInventoryLineHURecords(inventoryLine, inventoryId); } public Stream<InventoryReference> streamReferences(InventoryQuery query) { final ImmutableList<I_M_Inventory> inventories = inventoryDAO.stream(query).collect(ImmutableList.toImmutableList()); return inventories.stream().map(this::toInventoryJobReference);
} private InventoryReference toInventoryJobReference(final I_M_Inventory inventory) { return InventoryReference.builder() .inventoryId(extractInventoryId(inventory)) .documentNo(inventory.getDocumentNo()) .movementDate(extractMovementDate(inventory)) .warehouseId(WarehouseId.ofRepoId(inventory.getM_Warehouse_ID())) .responsibleId(extractResponsibleId(inventory)) .build(); } public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater) { final ImmutableList<I_M_Inventory> inventoriesRecords = inventoryDAO.stream(query).collect(ImmutableList.toImmutableList()); if (inventoriesRecords.isEmpty()) {return;} warmUp(inventoriesRecords); for (final I_M_Inventory inventoryRecord : inventoriesRecords) { final Inventory inventory = toInventory(inventoryRecord); final Inventory inventoryChanged = updater.apply(inventory); if (!Objects.equals(inventory, inventoryChanged)) { saveInventory(inventoryChanged); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLoaderAndSaver.java
1
请在Spring Boot框架中完成以下Java代码
public class JobDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements JobDefinitionRestService { public JobDefinitionRestServiceImpl(String engineName, ObjectMapper objectMapper) { super(engineName, objectMapper); } @Override public JobDefinitionResource getJobDefinition(String jobDefinitionId) { return new JobDefinitionResourceImpl(getProcessEngine(), jobDefinitionId); } @Override public List<JobDefinitionDto> getJobDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { JobDefinitionQueryDto queryDto = new JobDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryJobDefinitions(queryDto, firstResult, maxResults); } @Override public CountResultDto getJobDefinitionsCount(UriInfo uriInfo) { JobDefinitionQueryDto queryDto = new JobDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryJobDefinitionsCount(queryDto); } @Override public List<JobDefinitionDto> queryJobDefinitions(JobDefinitionQueryDto queryDto, Integer firstResult, Integer maxResults) { queryDto.setObjectMapper(getObjectMapper()); JobDefinitionQuery query = queryDto.toQuery(getProcessEngine()); List<JobDefinition> matchingJobDefinitions = QueryUtil.list(query, firstResult, maxResults); List<JobDefinitionDto> jobDefinitionResults = new ArrayList<JobDefinitionDto>(); for (JobDefinition jobDefinition : matchingJobDefinitions) { JobDefinitionDto result = JobDefinitionDto.fromJobDefinition(jobDefinition); jobDefinitionResults.add(result); } return jobDefinitionResults; } @Override
public CountResultDto queryJobDefinitionsCount(JobDefinitionQueryDto queryDto) { queryDto.setObjectMapper(getObjectMapper()); JobDefinitionQuery query = queryDto.toQuery(getProcessEngine()); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } @Override public void updateSuspensionState(JobDefinitionSuspensionStateDto dto) { if (dto.getJobDefinitionId() != null) { String message = "Either processDefinitionId or processDefinitionKey can be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } try { dto.updateSuspensionState(getProcessEngine()); } catch (IllegalArgumentException e) { String message = String.format("Could not update the suspension state of Job Definitions due to: %s", e.getMessage()) ; throw new InvalidRequestException(Status.BAD_REQUEST, e, message); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\JobDefinitionRestServiceImpl.java
2
请完成以下Java代码
public MessagesMap getMap() { return messagesCache.getOrLoad(0, MessagesMapRepository::retrieveMap); } private static MessagesMap retrieveMap() { if (Adempiere.isUnitTestMode()) { return MessagesMap.EMPTY; } final Stopwatch stopwatch = Stopwatch.createStarted(); final String sql = "SELECT" + " m.AD_Message_ID, m.Value, m.MsgText, m.MsgTip, m.ErrorCode," + " trl.AD_Language, trl.MsgText as trl_MsgText, trl.MsgTip as trl_MsgTip" + " FROM AD_Message m" + " LEFT OUTER JOIN AD_Message_Trl trl on trl.AD_Message_ID=m.AD_Message_ID" + " WHERE m.IsActive='Y'" + " ORDER BY m.AD_Message_ID"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); final ArrayList<Message> list = new ArrayList<>(2200); AdMessageId currentAdMessageId = null; AdMessageKey currentAdMessage = null; ImmutableTranslatableString.ImmutableTranslatableStringBuilder msgTextBuilder = null; ImmutableTranslatableString.ImmutableTranslatableStringBuilder msgTipBuilder = null; String errorCode = null; while (rs.next()) { final AdMessageId adMessageId = AdMessageId.ofRepoId(rs.getInt("AD_Message_ID")); if (!AdMessageId.equals(adMessageId, currentAdMessageId)) { if (currentAdMessageId != null) { list.add(Message.ofTextTipAndErrorCode(currentAdMessageId, currentAdMessage, msgTextBuilder.build(), msgTipBuilder.build(), errorCode)); currentAdMessageId = null; currentAdMessage = null; msgTextBuilder = null; msgTipBuilder = null; errorCode = null; }
} if (currentAdMessageId == null) { currentAdMessageId = adMessageId; currentAdMessage = AdMessageKey.of(rs.getString("Value")); msgTextBuilder = ImmutableTranslatableString.builder().defaultValue(normalizeToJavaMessageFormat(rs.getString("MsgText"))); msgTipBuilder = ImmutableTranslatableString.builder().defaultValue(normalizeToJavaMessageFormat(rs.getString("MsgTip"))); errorCode = rs.getString("ErrorCode"); } final String adLanguage = rs.getString("AD_Language"); if (Check.isBlank(adLanguage)) { continue; } msgTextBuilder.trl(adLanguage, normalizeToJavaMessageFormat(rs.getString("trl_MsgText"))); msgTipBuilder.trl(adLanguage, normalizeToJavaMessageFormat(rs.getString("trl_MsgTip"))); } if (currentAdMessageId != null) { list.add(Message.ofTextTipAndErrorCode(currentAdMessageId, currentAdMessage, msgTextBuilder.build(), msgTipBuilder.build(), errorCode)); } final MessagesMap result = new MessagesMap(list); logger.info("Loaded {} in {}", result, stopwatch); return result; } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); } } public void cacheReset() { messagesCache.reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessagesMapRepository.java
1
请完成以下Java代码
public abstract class MultiWorker { protected abstract class WorkerThread extends Thread { abstract public Object doWork(); @Override public void run() { isWorking = true; value = doWork(); isWorking = false; } @Override public void interrupt() { super.interrupt(); isWorking = false; } } protected boolean isWorking; protected WorkerThread workerThread; protected int timeout; protected Object value; public MultiWorker() { setTimeout(-1); } public abstract void start(); public int getTimeout() { return timeout; } public void setTimeout(int timeout) {
this.timeout = timeout; } public boolean isWorking() { return isWorking; } public void waitForComplete(int timeout) { setTimeout(timeout); waitForComplete(); } public void stop() { workerThread.interrupt(); } public void waitForComplete() { boolean to = getTimeout() > -1; int c = 0; int i = 1000; while(isWorking()) { try { Thread.sleep(i); c+= to ? c+=i : -1; } catch(Exception e) {} if(to && c >= getTimeout()) { workerThread.interrupt(); workerThread = null; break; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\tools\worker\MultiWorker.java
1
请完成以下Java代码
public static HttpResponse<String> sendPostWithFormData(String serviceUrl) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); Map<String, String> formData = new HashMap<>(); formData.put("username", "baeldung"); formData.put("message", "hello"); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(serviceUrl)) .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData))) .build(); HttpResponse<String> response = client .send(request, HttpResponse.BodyHandlers.ofString()); return response; } public static HttpResponse<String> sendPostWithFileData(String serviceUrl, Path file) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(serviceUrl)) .POST(HttpRequest.BodyPublishers.ofFile(file)) .build();
HttpResponse<String> response = client .send(request, HttpResponse.BodyHandlers.ofString()); return response; } private static String getFormDataAsString(Map<String, String> formData) { StringBuilder formBodyBuilder = new StringBuilder(); for (Map.Entry<String, String> singleEntry : formData.entrySet()) { if (formBodyBuilder.length() > 0) { formBodyBuilder.append("&"); } formBodyBuilder.append(URLEncoder.encode(singleEntry.getKey(), StandardCharsets.UTF_8)); formBodyBuilder.append("="); formBodyBuilder.append(URLEncoder.encode(singleEntry.getValue(), StandardCharsets.UTF_8)); } return formBodyBuilder.toString(); } }
repos\tutorials-master\core-java-modules\core-java-httpclient\src\main\java\com\baeldung\httpclient\HttpClientPost.java
1
请在Spring Boot框架中完成以下Java代码
public boolean send() { // 创建 Message Demo01Message message = new Demo01Message() .setId(new Random().nextInt()); // 创建 Spring Message 对象 Message<Demo01Message> springMessage = MessageBuilder.withPayload(message) .build(); // 发送消息 return mySource.demo01Output().send(springMessage); } @GetMapping("/send_delay") public boolean sendDelay() { // 创建 Message Demo01Message message = new Demo01Message() .setId(new Random().nextInt()); // 创建 Spring Message 对象 Message<Demo01Message> springMessage = MessageBuilder.withPayload(message) .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "3") // 设置延迟级别为 3,10 秒后消费。 .build(); // 发送消息 boolean sendResult = mySource.demo01Output().send(springMessage); logger.info("[sendDelay][发送消息完成, 结果 = {}]", sendResult); return sendResult; } @GetMapping("/send_tag") public boolean sendTag() {
for (String tag : new String[]{"yunai", "yutou", "tudou"}) { // 创建 Message Demo01Message message = new Demo01Message() .setId(new Random().nextInt()); // 创建 Spring Message 对象 Message<Demo01Message> springMessage = MessageBuilder.withPayload(message) .setHeader(MessageConst.PROPERTY_TAGS, tag) // 设置 Tag .build(); // 发送消息 mySource.demo01Output().send(springMessage); } return true; } }
repos\SpringBoot-Labs-master\labx-06-spring-cloud-stream-rocketmq\labx-06-sca-stream-rocketmq-producer-actuator\src\main\java\cn\iocoder\springcloudalibaba\labx6\rocketmqdemo\producerdemo\controller\Demo01Controller.java
2
请完成以下Java代码
public CSVWriter setFieldDelimiter(String delimiter) { this.fieldDelimiter = delimiter; return this; } public void setFieldQuote(String quote) { this.fieldQuote = quote; } public void setLineEnding(String lineEnding) { this.lineEnding = lineEnding; } @SuppressWarnings("UnusedReturnValue") public CSVWriter setAllowMultilineFields(final boolean allowMultilineFields) { this.allowMultilineFields = allowMultilineFields; return this; } public void setHeader(final List<String> header) { Check.assumeNotNull(header, "header not null"); Check.assume(!header.isEmpty(), "header not empty"); Check.assume(!headerAppended, "header was not already appended"); this.header = header; } private void appendHeader() throws IOException { if (headerAppended) { return; } Check.assumeNotNull(header, "header not null"); final StringBuilder headerLine = new StringBuilder(); for (final String headerCol : header) { if (headerLine.length() > 0) { headerLine.append(fieldDelimiter); } final String headerColQuoted = quoteCsvValue(headerCol); headerLine.append(headerColQuoted); } writer.append(headerLine.toString()); writer.append(lineEnding); headerAppended = true; } @Override public void appendLine(List<Object> values) throws IOException { appendHeader(); final StringBuilder line = new StringBuilder(); final int cols = header.size(); final int valuesCount = values.size(); for (int i = 0; i < cols; i++) { final Object csvValue; if (i < valuesCount) { csvValue = values.get(i); } else { csvValue = null; } final String csvValueQuoted = toCsvValue(csvValue); if (line.length() > 0) { line.append(fieldDelimiter); }
line.append(csvValueQuoted); } writer.append(line.toString()); writer.append(lineEnding); } private String toCsvValue(Object value) { final String valueStr; if (value == null) { valueStr = ""; } else if (value instanceof java.util.Date) { valueStr = dateFormat.format(value); } else { valueStr = value.toString(); } return quoteCsvValue(valueStr); } private String quoteCsvValue(String valueStr) { return fieldQuote + valueStr.replace(fieldQuote, fieldQuote + fieldQuote) + fieldQuote; } @Override public void close() throws IOException { if (writer == null) { return; } try { writer.flush(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // shall not happen e.printStackTrace(); // NOPMD by tsa on 3/13/13 1:46 PM } writer = null; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\CSVWriter.java
1
请完成以下Java代码
public void setType(String value) { this.type = value; } /** * Gets the value of the participantNumber property. * * @return * possible object is * {@link String } * */ public String getParticipantNumber() { return participantNumber; } /** * Sets the value of the participantNumber property. * * @param value * allowed object is * {@link String } * */ public void setParticipantNumber(String value) { this.participantNumber = value; } /** * Gets the value of the referenceNumber property. * * @return * possible object is * {@link String } * */ public String getReferenceNumber() { return referenceNumber; } /** * Sets the value of the referenceNumber property. * * @param value * allowed object is * {@link String } *
*/ public void setReferenceNumber(String value) { this.referenceNumber = value; } /** * Gets the value of the codingLine property. * * @return * possible object is * {@link String } * */ public String getCodingLine() { return codingLine; } /** * Sets the value of the codingLine property. * * @param value * allowed object is * {@link String } * */ public void setCodingLine(String value) { this.codingLine = 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\Esr5Type.java
1
请完成以下Java代码
private byte[] computeDataWithCopyFlagSetToTrue(@NonNull final AttachmentEntry attachmentEntry) { byte[] attachmentData = attachmentEntryService.retrieveData(attachmentEntry.getId()); // get the converter to use final String xsdName = XmlIntrospectionUtil.extractXsdValueOrNull(new ByteArrayInputStream(attachmentData)); final CrossVersionRequestConverter converter = crossVersionServiceRegistry.getRequestConverterForXsdName(xsdName); Check.assumeNotNull(converter, "Missing CrossVersionRequestConverter for XSD={}; attachmentEntry={}", xsdName, attachmentEntry); // convert to crossVersion data final XmlRequest crossVersionRequest = converter.toCrossVersionRequest(new ByteArrayInputStream(attachmentData)); // patch final XmlRequest updatedCrossVersionRequest = updateCrossVersionRequest(crossVersionRequest); // convert back to byte[] final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); converter.fromCrossVersionRequest(updatedCrossVersionRequest, outputStream);
return outputStream.toByteArray(); } private XmlRequest updateCrossVersionRequest(@NonNull final XmlRequest crossVersionRequest) { final RequestMod mod = RequestMod .builder() .payloadMod(PayloadMod .builder() .copy(true) .build()) .build(); return crossVersionRequest.withMod(mod); } }
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\store\StoreForumDatenaustauschAttachmentService.java
1
请完成以下Java代码
protected CmmnActivityBehavior createDefaultHttpActivityBehaviour(PlanItem planItem, ServiceTask serviceTask) { if (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(serviceTask.getImplementationType())) { return createCmmnClassDelegate(planItem, serviceTask); } else if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType())) { return createPlanItemDelegateExpressionActivityBehavior(planItem, serviceTask); } else { return classDelegateFactory.create(DefaultCmmnHttpActivityDelegate.class.getName(), serviceTask.getFieldExtensions()); } } @Override public CmmnActivityBehavior createEmailActivityBehavior(PlanItem planItem, ServiceTask task) { return classDelegateFactory.create(CmmnMailActivityDelegate.class.getName(), task.getFieldExtensions()); } @Override public SendEventActivityBehavior createSendEventActivityBehavior(PlanItem planItem, SendEventServiceTask sendEventServiceTask) { return new SendEventActivityBehavior(sendEventServiceTask); } @Override public ExternalWorkerTaskActivityBehavior createExternalWorkerActivityBehaviour(PlanItem planItem, ExternalWorkerServiceTask externalWorkerServiceTask) { return new ExternalWorkerTaskActivityBehavior(externalWorkerServiceTask); } @Override public ScriptTaskActivityBehavior createScriptTaskActivityBehavior(PlanItem planItem, ScriptServiceTask task) { return new ScriptTaskActivityBehavior(task); } @Override public CasePageTaskActivityBehaviour createCasePageTaskActivityBehaviour(PlanItem planItem, CasePageTask task) { return new CasePageTaskActivityBehaviour(task); } public void setClassDelegateFactory(CmmnClassDelegateFactory classDelegateFactory) { this.classDelegateFactory = classDelegateFactory; }
public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } protected Expression createExpression(String refExpressionString) { Expression expression = null; if (StringUtils.isNotEmpty(refExpressionString)) { expression = expressionManager.createExpression(refExpressionString); } return expression; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\DefaultCmmnActivityBehaviorFactory.java
1
请完成以下Java代码
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int col) { updateEditor(table, row); return super.getTableCellEditorComponent(table, value, isSelected, row, col); } @Override protected CComboBox<Operator> getEditor() { if (_editor == null) { _editor = new CComboBox<>(); _editor.enableAutoCompletion(); } return _editor; } private void updateEditor(final JTable table, final int viewRowIndex) { final CComboBox<Operator> editor = getEditor(); final IUserQueryRestriction row = getRow(table, viewRowIndex); final FindPanelSearchField searchField = FindPanelSearchField.castToFindPanelSearchField(row.getSearchField()); if (searchField != null) { // check if the column is columnSQL with reference (08757) // final String columnName = searchField.getColumnName(); final int displayType = searchField.getDisplayType(); final boolean isColumnSQL = searchField.isVirtualColumn(); final boolean isReference = searchField.getAD_Reference_Value_ID() != null; if (isColumnSQL && isReference) { // make sure also the columnSQLs with reference are only getting the ID operators (08757) editor.setModel(modelForLookupColumns); }
else if (DisplayType.isAnyLookup(displayType)) { editor.setModel(modelForLookupColumns); } else if (DisplayType.YesNo == displayType) { editor.setModel(modelForYesNoColumns); } else { editor.setModel(modelDefault); } } else { editor.setModel(modelEmpty); } } private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex) { final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel(); final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex); return model.getRow(modelRowIndex); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindOperatorCellEditor.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (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(); } @Override public org.compiere.model.I_M_Requisition getM_Requisition() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Requisition_ID, org.compiere.model.I_M_Requisition.class); } @Override public void setM_Requisition(org.compiere.model.I_M_Requisition M_Requisition) { set_ValueFromPO(COLUMNNAME_M_Requisition_ID, org.compiere.model.I_M_Requisition.class, M_Requisition); } /** Set Bedarf. @param M_Requisition_ID Material Requisition */ @Override public void setM_Requisition_ID (int M_Requisition_ID) { if (M_Requisition_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Requisition_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Requisition_ID, Integer.valueOf(M_Requisition_ID)); } /** Get Bedarf. @return Material Requisition */ @Override public int getM_Requisition_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Requisition_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bedarfs-Position. @param M_RequisitionLine_ID Material Requisition Line */ @Override public void setM_RequisitionLine_ID (int M_RequisitionLine_ID) { if (M_RequisitionLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_RequisitionLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_RequisitionLine_ID, Integer.valueOf(M_RequisitionLine_ID)); } /** Get Bedarfs-Position. @return Material Requisition Line */ @Override public int getM_RequisitionLine_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Einzelpreis. @param PriceActual Actual Price */ @Override public void setPriceActual (java.math.BigDecimal PriceActual) { set_Value (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Actual Price */ @Override public java.math.BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RequisitionLine.java
1
请完成以下Java代码
public static void clear_UUID_TO_PAGE() { UUID_TO_PAGE.clear(); } @Override public <ET extends T> QueryResultPage<ET> paginate(Class<ET> clazz, int pageSize) throws DBException { final List<ET> bigList = list(clazz); final String firstUUID = UIDStringUtil.createRandomUUID(); final Instant resultTimestamp = SystemTime.asInstant(); PageDescriptor currentPageDescriptor = PageDescriptor.createNew(firstUUID, pageSize, bigList.size(), resultTimestamp); final List<List<ET>> pages = Lists.partition(bigList, pageSize); if (bigList.isEmpty()) { return new QueryResultPage<>(currentPageDescriptor, null, 0, resultTimestamp, ImmutableList.of()); } PageDescriptor nextPageDescriptor = pages.size() > 1 ? currentPageDescriptor.createNext() : null; final QueryResultPage<ET> firstQueryResultPage = new QueryResultPage<>(currentPageDescriptor, nextPageDescriptor, bigList.size(), resultTimestamp, ImmutableList.copyOf(pages.get(0))); UUID_TO_PAGE.put(firstQueryResultPage.getCurrentPageDescriptor().getPageIdentifier().getCombinedUid(), firstQueryResultPage); currentPageDescriptor = nextPageDescriptor; for (int i = 1; i < pages.size(); i++) { final boolean lastPage = pages.size() <= i + 1; nextPageDescriptor = lastPage ? null : currentPageDescriptor.createNext(); final QueryResultPage<ET> queryResultPage = new QueryResultPage<>(currentPageDescriptor, nextPageDescriptor, bigList.size(), resultTimestamp, ImmutableList.copyOf(pages.get(i))); UUID_TO_PAGE.put(queryResultPage.getCurrentPageDescriptor().getPageIdentifier().getCombinedUid(), queryResultPage); currentPageDescriptor = nextPageDescriptor;
} return firstQueryResultPage; } @SuppressWarnings("unchecked") public static <T> QueryResultPage<T> getPage(Class<T> clazz, String next) { return (QueryResultPage<T>)UUID_TO_PAGE.get(next); } @Override public List<Money> sumMoney(@NonNull String amountColumnName, @NonNull String currencyIdColumnName) { throw new UnsupportedOperationException("sumMoney"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\POJOQuery.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } @Override public FlowElement getCurrentFlowElement() { return currentFlowElement; } @Override public boolean isActive() { return active; } @Override public boolean isEnded() { return ended; } @Override public boolean isConcurrent() { return concurrent; } @Override public boolean isProcessInstanceType() { return processInstanceType; } @Override public boolean isScope() { return scope; }
@Override public boolean isMultiInstanceRoot() { return multiInstanceRoot; } @Override public Object getVariable(String variableName) { return variables.get(variableName); } @Override public boolean hasVariable(String variableName) { return variables.containsKey(variableName); } @Override public Set<String> getVariableNames() { return variables.keySet(); } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("id='" + id + "'") .add("currentActivityId='" + currentActivityId + "'") .add("processInstanceId='" + processInstanceId + "'") .add("processDefinitionId='" + processDefinitionId + "'") .add("tenantId='" + tenantId + "'") .toString(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java
1
请完成以下Java代码
public boolean isMatching(final @NonNull EAN13ProductCode expectedProductCode) { final EAN13 ean13 = toEAN13().orElse(null); return ean13 != null && ean13.isMatching(expectedProductCode); } public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode) { final EAN13 ean13 = toEAN13().orElse(null); return ean13 != null && ean13.productCodeEndsWith(expectedProductCode); } /** * @return true if fixed code (e.g. not a variable weight EAN13 etc) */
public boolean isFixed() { final EAN13 ean13 = toEAN13().orElse(null); return ean13 == null || ean13.isFixed(); } /** * @return true if fixed code (e.g. not a variable weight EAN13 etc) */ public boolean isVariable() { final EAN13 ean13 = toEAN13().orElse(null); return ean13 == null || ean13.isVariableWeight(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GTIN.java
1
请完成以下Java代码
protected Void execute(CommandContext commandContext, TaskEntity task) { if (variables != null) { if (localScope) { task.setVariablesLocal(variables); } else if (task.getExecutionId() != null) { task.setExecutionVariables(variables); } else { task.setVariables(variables); } } if (transientVariables != null) { if (localScope) { task.setTransientVariablesLocal(transientVariables); } else { task.setTransientVariables(transientVariables); } } Map<String, Object> taskLocalVariables = new HashMap<>(task.getVariablesLocal()); taskLocalVariables.put(ASSIGNEE_VARIABLE_NAME, task.getAssignee()); setTaskVariables(taskLocalVariables); executeTaskComplete(commandContext, task, variables, localScope); return null; } @Override protected String getSuspendedTaskException() {
return "Cannot complete a suspended task"; } public Map<String, Object> getTaskVariables() { return taskVariables; } private void setTaskVariables(Map<String, Object> taskVariables) { this.taskVariables = taskVariables; } public String getTaskId() { return taskId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\CompleteTaskCmd.java
1
请完成以下Java代码
public class Server { private static final List<User> AUTHENTICATED_USERS = List.of( new User("1", "admin", "123456", true), new User("2", "user", "123456", false) ); public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance(); private final Controller controller = new Controller(); public void serve(HttpServletRequest request, HttpServletResponse response) { Optional<User> user = authenticateUser(request); if (user.isPresent()) { ScopedValue.where(LOGGED_IN_USER, user.get()) .run(() -> controller.processRequest(request, response)); } else {
response.setStatus(401); } } private Optional<User> authenticateUser(HttpServletRequest request) { return AUTHENTICATED_USERS.stream() .filter(user -> checkUserPassword(user, request)) .findFirst(); } private boolean checkUserPassword(User user, HttpServletRequest request) { return user.name().equals(request.getParameter("user_name")) && user.password().equals(request.getParameter("user_pw")); } }
repos\tutorials-master\core-java-modules\core-java-20\src\main\java\com\baeldung\scopedvalues\scoped\Server.java
1
请完成以下Java代码
public int getAD_Tree_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Node_ID. @param Node_ID Node_ID */ public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_ValueNoCheck (COLUMNNAME_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent. @param Parent_ID Parent of Entity */ public void setParent_ID (int Parent_ID) { if (Parent_ID < 1) set_Value (COLUMNNAME_Parent_ID, null);
else set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID)); } /** Get Parent. @return Parent of Entity */ public int getParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeNode.java
1
请完成以下Java代码
public abstract class DataObjectPropertyName { private DataObjectPropertyName() { } /** * Return the specified Java Bean property name in dashed form. * @param name the source name * @return the dashed from */ public static String toDashedForm(String name) { StringBuilder result = new StringBuilder(name.length()); boolean inIndex = false; for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (inIndex) { result.append(ch); if (ch == ']') { inIndex = false; }
} else { if (ch == '[') { inIndex = true; result.append(ch); } else { ch = (ch != '_') ? ch : '-'; if (Character.isUpperCase(ch) && !result.isEmpty() && result.charAt(result.length() - 1) != '-') { result.append('-'); } result.append(Character.toLowerCase(ch)); } } } return result.toString(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\DataObjectPropertyName.java
1
请完成以下Java代码
public OrgId getOrgId() {return OrgId.ofRepoId(po.getAD_Org_ID());} @Override public UserId getUpdatedBy() {return UserId.ofRepoIdOrSystem(po.getUpdatedBy());} @Override @Nullable public DocStatus getDocStatus() { final int index = po.get_ColumnIndex("DocStatus"); return index >= 0 ? DocStatus.ofNullableCodeOrUnknown((String)po.get_Value(index)) : null; } @Override public boolean isProcessing() {return po.get_ValueAsBoolean("Processing");} @Override public boolean isProcessed() {return po.get_ValueAsBoolean("Processed");} @Override public boolean isActive() {return po.isActive();} @Override public PostingStatus getPostingStatus() {return PostingStatus.ofNullableCode(po.get_ValueAsString("Posted"));} @Override public boolean hasColumnName(final String columnName) {return po.getPOInfo().hasColumnName(columnName);} @Override public int getValueAsIntOrZero(final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Integer ii = (Integer)po.get_Value(index); if (ii != null) { return ii; } } return 0; } @Override @Nullable public <T extends RepoIdAware> T getValueAsIdOrNull(final String columnName, final IntFunction<T> idOrNullMapper) { final int index = po.get_ColumnIndex(columnName); if (index < 0) { return null; } final Object valueObj = po.get_Value(index); final Integer valueInt = NumberUtils.asInteger(valueObj, null); if (valueInt == null) { return null; } return idOrNullMapper.apply(valueInt); }
@Override @Nullable public LocalDateAndOrgId getValueAsLocalDateOrNull(@NonNull final String columnName, @NonNull final Function<OrgId, ZoneId> timeZoneMapper) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Timestamp ts = po.get_ValueAsTimestamp(index); if (ts != null) { final OrgId orgId = OrgId.ofRepoId(po.getAD_Org_ID()); return LocalDateAndOrgId.ofTimestamp(ts, orgId, timeZoneMapper); } } return null; } @Override @Nullable public Boolean getValueAsBooleanOrNull(@NonNull final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Object valueObj = po.get_Value(index); return DisplayType.toBoolean(valueObj, null); } return null; } @Override @Nullable public String getValueAsString(@NonNull final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Object valueObj = po.get_Value(index); return valueObj != null ? valueObj.toString() : null; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\POAcctDocModel.java
1
请完成以下Java代码
public boolean accept(File file) { // Need to accept directories if (file.isDirectory()) return true; String ext = file.getName(); int pos = ext.lastIndexOf('.'); // No extension if (pos == -1) return false; ext = ext.substring(pos+1); if (m_extension.equalsIgnoreCase(ext)) return true; return false; } // accept /** * Verify file name with filer * @param file file * @param filter filter * @return file name */ public static String getFileName(File file, FileFilter filter) { return getFile(file, filter).getAbsolutePath(); } // getFileName /** * Verify file with filter * @param file file
* @param filter filter * @return file */ public static File getFile(File file, FileFilter filter) { String fName = file.getAbsolutePath(); if (fName == null || fName.equals("")) fName = "Adempiere"; // ExtensionFileFilter eff = null; if (filter instanceof ExtensionFileFilter) eff = (ExtensionFileFilter)filter; else return file; // int pos = fName.lastIndexOf('.'); // No extension if (pos == -1) { fName += '.' + eff.getExtension(); return new File(fName); } String ext = fName.substring(pos+1); // correct extension if (ext.equalsIgnoreCase(eff.getExtension())) return file; fName += '.' + eff.getExtension(); return new File(fName); } // getFile } // ExtensionFileFilter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ExtensionFileFilter.java
1
请完成以下Java代码
private static String buildMsg(final int warehouseId, final boolean maxVolumeExceeded, final boolean maxWeightExceeded) { final StringBuffer sb = new StringBuffer(); sb.append(Msg.translate(Env.getCtx(), MSG_NO_SUFFICIENT_CONTAINERS)); if (warehouseId > 0) { sb.append("\n@M_Warehouse_ID@ "); sb.append(Services.get(IWarehouseDAO.class).getWarehouseName(WarehouseId.ofRepoId(warehouseId))); } if (maxVolumeExceeded || maxWeightExceeded) { sb.append(Msg.translate(Env.getCtx(), MSG_INSUFFICIENT_FEATURES)); } if (maxVolumeExceeded) {
appendExceed(sb, I_M_PackagingContainer.COLUMNNAME_MaxVolume); } if (maxWeightExceeded) { appendExceed(sb, I_M_PackagingContainer.COLUMNNAME_MaxWeight); } return sb.toString(); } private static void appendExceed(final StringBuffer sb, final String colName) { sb.append("\n"); sb.append("@"); sb.append(colName); sb.append("@"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\exception\NoContainerException.java
1
请完成以下Java代码
public Optional<BPartnerLocation> extractLocation(@NonNull final BPartnerLocationId bPartnerLocationId) { final Predicate<BPartnerLocation> predicate = l -> bPartnerLocationId.equals(l.getId()); return createFilteredLocationStream(predicate).findAny(); } public Optional<BPartnerLocation> extractBillToLocation() { final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsBillToOr(false); return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsBillToDefaultOr(false))); } public Optional<BPartnerLocation> extractShipToLocation() { final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsShipToOr(false); return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsShipToDefaultOr(false))); } public Optional<BPartnerLocation> extractLocationByHandle(@NonNull final String handle) { return extractLocation(bpLocation -> bpLocation.containsHandle(handle)); } public Optional<BPartnerLocation> extractLocation(@NonNull final Predicate<BPartnerLocation> filter) { return createFilteredLocationStream(filter).findAny(); } private Stream<BPartnerLocation> createFilteredLocationStream(@NonNull final Predicate<BPartnerLocation> filter) { return getLocations() .stream() .filter(filter); } public void addBankAccount(@NonNull final BPartnerBankAccount bankAccount)
{ bankAccounts.add(bankAccount); } public Optional<BPartnerBankAccount> getBankAccountByIBAN(@NonNull final String iban) { Check.assumeNotEmpty(iban, "iban is not empty"); return bankAccounts.stream() .filter(bankAccount -> iban.equals(bankAccount.getIban())) .findFirst(); } public void addCreditLimit(@NonNull final BPartnerCreditLimit creditLimit) { creditLimits.add(creditLimit); } @NonNull public Stream<BPartnerContactId> streamContactIds() { return this.getContacts().stream().map(BPartnerContact::getId); } @NonNull public Stream<BPartnerLocationId> streamBPartnerLocationIds() { return this.getLocations().stream().map(BPartnerLocation::getId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerComposite.java
1
请完成以下Java代码
private static DistributionFacetId ofRepoId(@NonNull DistributionFacetGroupType groupType, @NonNull RepoIdAware id) { final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofId(groupType.toWorkflowLaunchersFacetGroupId(), id); return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId); } @SuppressWarnings("SameParameterValue") private static DistributionFacetId ofLocalDate(@NonNull DistributionFacetGroupType groupType, @NonNull LocalDate localDate) { final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofLocalDate(groupType.toWorkflowLaunchersFacetGroupId(), localDate); return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId); } public static DistributionFacetId ofQuantity(@NonNull Quantity qty) { return ofWorkflowLaunchersFacetId( WorkflowLaunchersFacetId.ofQuantity( DistributionFacetGroupType.QUANTITY.toWorkflowLaunchersFacetGroupId(), qty.toBigDecimal(), qty.getUomId()
) ); } public static DistributionFacetId ofPlantId(@NonNull final ResourceId plantId) { return ofRepoId(DistributionFacetGroupType.PLANT_RESOURCE_ID, plantId); } private static Quantity getAsQuantity(final @NonNull WorkflowLaunchersFacetId workflowLaunchersFacetId) { final ImmutablePair<BigDecimal, Integer> parts = workflowLaunchersFacetId.getAsQuantity(); return Quantitys.of(parts.getLeft(), UomId.ofRepoId(parts.getRight())); } public WorkflowLaunchersFacetId toWorkflowLaunchersFacetId() {return workflowLaunchersFacetId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetId.java
1
请完成以下Java代码
public ResourceId getTargetPlantId() {return getDdOrderCandidate().getTargetPlantId();} @NonNull @JsonIgnore public WarehouseId getTargetWarehouseId() {return getDdOrderCandidate().getTargetWarehouseId();} @NonNull @JsonIgnore public WarehouseId getSourceWarehouseId() {return getDdOrderCandidate().getSourceWarehouseId();} @NonNull @JsonIgnore public ShipperId getShipperId() {return getDdOrderCandidate().getShipperId();} @NonNull @JsonIgnore public SupplyRequiredDescriptor getSupplyRequiredDescriptorNotNull() {return Check.assumeNotNull(getSupplyRequiredDescriptor(), "supplyRequiredDescriptor shall be set for " + this);} @Nullable @JsonIgnore public ProductPlanningId getProductPlanningId() {return getDdOrderCandidate().getProductPlanningId();} @Nullable @JsonIgnore public DistributionNetworkAndLineId getDistributionNetworkAndLineId() {return getDdOrderCandidate().getDistributionNetworkAndLineId();} @Nullable @JsonIgnore
public MaterialDispoGroupId getMaterialDispoGroupId() {return getDdOrderCandidate().getMaterialDispoGroupId();} @Nullable @JsonIgnore public PPOrderRef getForwardPPOrderRef() {return getDdOrderCandidate().getForwardPPOrderRef();} @JsonIgnore public int getExistingDDOrderCandidateId() {return getDdOrderCandidate().getExitingDDOrderCandidateId();} @Nullable public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_DD_Order_Candidate.Table_Name,ddOrderCandidate.getExitingDDOrderCandidateId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\AbstractDDOrderCandidateEvent.java
1
请完成以下Java代码
public class ProductsToPick_Request4EyesReview extends ProductsToPickViewBasedProcess { @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (isReviewProfile()) { return ProcessPreconditionsResolution.rejectWithInternalReason("already reviewing"); } final ProductsToPickView view = getView(); if (!view.isEligibleForReview()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not all rows are eligible"); }
return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final ProductsToPickView view = getView(); final ViewId viewId = view.getViewId(); final GlobalActionEvent openViewEvent = GlobalActionEvents.openView(viewId, PickingConstantsV2.PROFILE_ID_ProductsToPickView_Review); getResult().setDisplayQRCode(openViewEvent.toDisplayQRCodeProcessResult()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_Request4EyesReview.java
1
请在Spring Boot框架中完成以下Java代码
public class ExampleController { @RequestMapping("/string") public String string(ModelMap map) { map.addAttribute("userName", "ityouknow"); return "string"; } @RequestMapping("/if") public String ifunless(ModelMap map) { map.addAttribute("flag", "yes"); return "if"; } @RequestMapping("/list") public String list(ModelMap map) { map.addAttribute("users", getUserList()); return "list"; } @RequestMapping("/url") public String url(ModelMap map) { map.addAttribute("type", "link"); map.addAttribute("pageId", "springcloud/2017/09/11/"); map.addAttribute("img", "http://www.ityouknow.com/assets/images/neo.jpg"); return "url"; } @RequestMapping("/eq") public String eq(ModelMap map) { map.addAttribute("name", "neo"); map.addAttribute("age", 30);
map.addAttribute("flag", "yes"); return "eq"; } @RequestMapping("/switch") public String switchcase(ModelMap map) { map.addAttribute("sex", "woman"); return "switch"; } private List<User> getUserList(){ List<User> list=new ArrayList<User>(); User user1=new User("大牛",12,"123456"); User user2=new User("小牛",6,"123563"); User user3=new User("纯洁的微笑",66,"666666"); list.add(user1); list.add(user2); list.add(user3); return list; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-3 课 模板引擎 Thymeleaf 基础使用\spring-boot-thymeleaf\src\main\java\com\neo\web\ExampleController.java
2
请完成以下Java代码
public Integer getVersion(VariableScope variableScope) { Object result = versionValueProvider.getValue(variableScope); if (result != null) { if (result instanceof String) { return Integer.valueOf((String) result); } else if (result instanceof Integer) { return (Integer) result; } else { throw new ProcessEngineException("It is not possible to transform '"+result+"' into an integer."); } } return null; } public ParameterValueProvider getVersionValueProvider() { return versionValueProvider; } public void setVersionValueProvider(ParameterValueProvider version) { this.versionValueProvider = version; } public String getVersionTag(VariableScope variableScope) { Object result = versionTagValueProvider.getValue(variableScope); if (result != null) { if (result instanceof String) { return (String) result; } else { throw new ProcessEngineException("It is not possible to transform '"+result+"' into a string."); } } return null; } public ParameterValueProvider getVersionTagValueProvider() { return versionTagValueProvider; } public void setVersionTagValueProvider(ParameterValueProvider version) { this.versionTagValueProvider = version; } public void setTenantIdProvider(ParameterValueProvider tenantIdProvider) { this.tenantIdProvider = tenantIdProvider; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId; } public String getDefinitionTenantId(VariableScope variableScope, String defaultTenantId) { if (tenantIdProvider != null) { return (String) tenantIdProvider.getValue(variableScope); } else { return defaultTenantId; } } public ParameterValueProvider getTenantIdProvider() { return tenantIdProvider; } /** * @return true if any of the references that specify the callable element are non-literal and need to be resolved with * potential side effects to determine the process or case definition that is to be called. */ public boolean hasDynamicReferences() { return (tenantIdProvider != null && tenantIdProvider.isDynamic()) || definitionKeyValueProvider.isDynamic() || versionValueProvider.isDynamic() || versionTagValueProvider.isDynamic(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\BaseCallableElement.java
1
请完成以下Java代码
public void onGroupEvent(SocketIOClient client, AckRequest request, GroupMessageRequest data) { Collection<SocketIOClient> clients = server.getRoomOperations(data.getGroupId()).getClients(); boolean inGroup = false; for (SocketIOClient socketIOClient : clients) { if (ObjectUtil.equal(socketIOClient.getSessionId(), client.getSessionId())) { inGroup = true; break; } } if (inGroup) { log.info("群号 {} 收到来自 {} 的群聊消息:{}", data.getGroupId(), data.getFromUid(), data.getMessage()); sendToGroup(data); } else { request.sendAckData("请先加群!"); } } /** * 单聊 */ public void sendToSingle(UUID sessionId, SingleMessageRequest message) { server.getClient(sessionId).sendEvent(Event.CHAT, message); }
/** * 广播 */ public void sendToBroadcast(BroadcastMessageRequest message) { log.info("系统紧急广播一条通知:{}", message.getMessage()); for (UUID clientId : dbTemplate.findAll()) { if (server.getClient(clientId) == null) { continue; } server.getClient(clientId).sendEvent(Event.BROADCAST, message); } } /** * 群聊 */ public void sendToGroup(GroupMessageRequest message) { server.getRoomOperations(message.getGroupId()).sendEvent(Event.GROUP, message); } }
repos\spring-boot-demo-master\demo-websocket-socketio\src\main\java\com\xkcoding\websocket\socketio\handler\MessageEventHandler.java
1
请完成以下Java代码
protected String getXMLElementName() { return ELEMENT_EVENT_CATCH; } @Override @SuppressWarnings("unchecked") protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { IntermediateCatchEvent catchEvent = new IntermediateCatchEvent(); BpmnXMLUtil.addXMLLocation(catchEvent, xtr); String elementId = xtr.getAttributeValue(null, ATTRIBUTE_ID); catchEvent.setId(elementId); BpmnXMLUtil.addCustomAttributes(xtr, catchEvent, defaultElementAttributes, defaultActivityAttributes); parseChildElements(getXMLElementName(), catchEvent, childParserMap, model, xtr); return catchEvent; } @Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
} @Override protected boolean writeExtensionChildElements(BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception { IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) element; didWriteExtensionStartElement = writeVariableListenerDefinition(catchEvent, didWriteExtensionStartElement, xtw); return didWriteExtensionStartElement; } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) element; writeEventDefinitions(catchEvent, catchEvent.getEventDefinitions(), model, xtw); } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\CatchEventXMLConverter.java
1
请完成以下Java代码
protected void addRemovalTime(String instanceId, Date removalTime, CommandContext commandContext) { commandContext.getHistoricBatchManager() .addRemovalTimeById(instanceId, removalTime); } protected boolean hasBaseTime(HistoricBatchEntity instance, CommandContext commandContext) { return isStrategyStart(commandContext) || (isStrategyEnd(commandContext) && isEnded(instance)); } protected boolean isEnded(HistoricBatchEntity instance) { return instance.getEndTime() != null; } protected boolean isStrategyStart(CommandContext commandContext) { return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy(commandContext)); } protected boolean isStrategyEnd(CommandContext commandContext) { return HISTORY_REMOVAL_TIME_STRATEGY_END.equals(getHistoryRemovalTimeStrategy(commandContext)); } protected String getHistoryRemovalTimeStrategy(CommandContext commandContext) { return commandContext.getProcessEngineConfiguration() .getHistoryRemovalTimeStrategy(); } protected boolean isDmnEnabled(CommandContext commandContext) { return commandContext.getProcessEngineConfiguration().isDmnEnabled(); } protected Date calculateRemovalTime(HistoricBatchEntity batch, CommandContext commandContext) { return commandContext.getProcessEngineConfiguration() .getHistoryRemovalTimeProvider() .calculateRemovalTime(batch); } protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) { return commandContext.getDbEntityManager() .selectById(ByteArrayEntity.class, byteArrayId); } protected HistoricBatchEntity findBatchById(String instanceId, CommandContext commandContext) { return commandContext.getHistoricBatchManager() .findHistoricBatchById(instanceId); }
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration, List<String> batchIds) { return new SetRemovalTimeBatchConfiguration(batchIds) .setRemovalTime(configuration.getRemovalTime()) .setHasRemovalTime(configuration.hasRemovalTime()); } protected SetRemovalTimeJsonConverter getJsonConverterInstance() { return SetRemovalTimeJsonConverter.INSTANCE; } public String getType() { return Batch.TYPE_BATCH_SET_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\BatchSetRemovalTimeJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteIdentityLink(IdentityLinkEntity identityLink) { delete(identityLink); } @Override public void deleteIdentityLinksByTaskId(String taskId) { dataManager.deleteIdentityLinksByTaskId(taskId); } @Override public void deleteIdentityLinksByProcDef(String processDefId) { dataManager.deleteIdentityLinksByProcDef(processDefId); } @Override public void deleteIdentityLinksByProcessInstanceId(String processInstanceId) { dataManager.deleteIdentityLinksByProcessInstanceId(processInstanceId); } @Override public void deleteIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
dataManager.deleteIdentityLinksByScopeIdAndScopeType(scopeId, scopeType); } @Override public void deleteIdentityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) { dataManager.deleteIdentityLinksByScopeDefinitionIdAndScopeType(scopeDefinitionId, scopeType); } @Override public void bulkDeleteIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) { dataManager.bulkDeleteIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType); } protected IdentityLinkEventHandler getIdentityLinkEventHandler() { return serviceConfiguration.getIdentityLinkEventHandler(); } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\IdentityLinkEntityManagerImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setFlushMode(FlushMode flushMode) { this.flushMode = flushMode; } public SaveMode getSaveMode() { return this.saveMode; } public void setSaveMode(SaveMode saveMode) { this.saveMode = saveMode; } public @Nullable String getCleanupCron() { return this.cleanupCron; } public void setCleanupCron(@Nullable String cleanupCron) { this.cleanupCron = cleanupCron; } public ConfigureAction getConfigureAction() { return this.configureAction; } public void setConfigureAction(ConfigureAction configureAction) { this.configureAction = configureAction; } public RepositoryType getRepositoryType() { return this.repositoryType; } public void setRepositoryType(RepositoryType repositoryType) { this.repositoryType = repositoryType; } /** * Strategies for configuring and validating Redis. */ public enum ConfigureAction { /** * Ensure that Redis Keyspace events for Generic commands and Expired events are * enabled. */ NOTIFY_KEYSPACE_EVENTS,
/** * No not attempt to apply any custom Redis configuration. */ NONE } /** * Type of Redis session repository to auto-configure. */ public enum RepositoryType { /** * Auto-configure a RedisSessionRepository or ReactiveRedisSessionRepository. */ DEFAULT, /** * Auto-configure a RedisIndexedSessionRepository or * ReactiveRedisIndexedSessionRepository. */ INDEXED } }
repos\spring-boot-4.0.1\module\spring-boot-session-data-redis\src\main\java\org\springframework\boot\session\data\redis\autoconfigure\SessionDataRedisProperties.java
2
请在Spring Boot框架中完成以下Java代码
private static void updateRecord(final I_M_Picking_Job_Step_HUAlternative existingRecord, final PickingJobStepPickFrom pickFrom) { existingRecord.setPickFrom_HU_ID(pickFrom.getPickFromHUId().getRepoId()); updateRecord(existingRecord, pickFrom.getPickedTo()); } private static void updateRecord(final I_M_Picking_Job_Step_HUAlternative existingRecord, final PickingJobStepPickedTo pickedTo) { final UomId uomId; final BigDecimal qtyRejectedBD; final String rejectReason; if (pickedTo != null && pickedTo.getQtyRejected() != null) { final QtyRejectedWithReason qtyRejected = pickedTo.getQtyRejected(); uomId = qtyRejected.toQuantity().getUomId();
qtyRejectedBD = qtyRejected.toBigDecimal(); rejectReason = qtyRejected.getReasonCode().getCode(); } else { uomId = null; qtyRejectedBD = BigDecimal.ZERO; rejectReason = null; } existingRecord.setC_UOM_ID(UomId.toRepoId(uomId)); existingRecord.setQtyRejectedToPick(qtyRejectedBD); existingRecord.setRejectReason(rejectReason); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\PickingJobSaver.java
2
请完成以下Spring Boot application配置
# make sure the same data is configured in KerberosMiniKdc # otherwise configuration/communication error will occur app.service-principal=HTTP/localhost app.user-principal=client/localhost app.keytab-location=@proj
ect.basedir@\\krb-test-workdir\\example.keytab app.access-url=http://localhost:8080/endpoint
repos\tutorials-master\spring-security-modules\spring-security-oauth2-sso\spring-security-sso-kerberos\src\main\resources\application.properties
2
请完成以下Java代码
public boolean matches(Message<?> message) { return true; } @Override public String toString() { return "ANY_MESSAGE"; } }; /** * Returns true if the {@link Message} matches, else false * @param message the {@link Message} to match on * @return true if the {@link Message} matches, else false */ boolean matches(Message<? extends T> message); /** * Returns a {@link MatchResult} for this {@code MessageMatcher}. The default * implementation returns {@link Collections#emptyMap()} when * {@link MatchResult#getVariables()} is invoked. * @return the {@code MatchResult} from comparing this {@code MessageMatcher} against * the {@code Message} * @since 6.5 */ default MatchResult matcher(Message<? extends T> message) { boolean match = matches(message); return new MatchResult(match, Collections.emptyMap()); } /** * The result of matching against a {@code Message} contains the status, true or * false, of the match and if present, any variables extracted from the match * * @since 6.5 */ class MatchResult { private final boolean match; private final Map<String, String> variables; MatchResult(boolean match, Map<String, String> variables) { this.match = match; this.variables = variables; } /** * Return whether the comparison against the {@code Message} produced a successful * match */ public boolean isMatch() { return this.match; } /**
* Returns the extracted variable values where the key is the variable name and * the value is the variable value * @return a map containing key-value pairs representing extracted variable names * and variable values */ public Map<String, String> getVariables() { return this.variables; } /** * Creates an instance of {@link MatchResult} that is a match with no variables */ public static MatchResult match() { return new MatchResult(true, Collections.emptyMap()); } /** * Creates an instance of {@link MatchResult} that is a match with the specified * variables */ public static MatchResult match(Map<String, String> variables) { return new MatchResult(true, variables); } /** * Creates an instance of {@link MatchResult} that is not a match. * @return a {@code MatchResult} with match set to false */ public static MatchResult notMatch() { return new MatchResult(false, Collections.emptyMap()); } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\util\matcher\MessageMatcher.java
1
请在Spring Boot框架中完成以下Java代码
public ISyncAfterCommitCollector add(@NonNull final Rfq rfq) { createAndStoreSyncConfirmRecord(rfq); rfqs.add(rfq); return this; } @Override public ISyncAfterCommitCollector add(@NonNull final User user) { users.add(user); return this; } /** * Creates a new local DB record for the given <code>abstractEntity</code>. */ private void createAndStoreSyncConfirmRecord(final AbstractSyncConfirmAwareEntity abstractEntity) { final SyncConfirm syncConfirmRecord = new SyncConfirm(); syncConfirmRecord.setEntryType(abstractEntity.getClass().getSimpleName()); syncConfirmRecord.setEntryUuid(abstractEntity.getUuid()); syncConfirmRecord.setEntryId(abstractEntity.getId()); syncConfirmRepo.save(syncConfirmRecord); abstractEntity.setSyncConfirmId(syncConfirmRecord.getId()); } @Override public void afterCommit() { publishToMetasfreshAsync(); } public void publishToMetasfreshAsync() { logger.debug("Synchronizing: {}", this); // // Sync daily product supplies { final List<ProductSupply> productSupplies = ImmutableList.copyOf(this.productSupplies);
this.productSupplies.clear(); pushDailyReportsAsync(productSupplies); } // // Sync weekly product supplies { final List<WeekSupply> weeklySupplies = ImmutableList.copyOf(this.weeklySupplies); this.weeklySupplies.clear(); pushWeeklyReportsAsync(weeklySupplies); } // // Sync RfQ changes { final List<Rfq> rfqs = ImmutableList.copyOf(this.rfqs); this.rfqs.clear(); pushRfqsAsync(rfqs); } // // Sync User changes { final List<User> users = ImmutableList.copyOf(this.users); this.users.clear(); pushUsersAsync(users); } } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SenderToMetasfreshService.java
2
请完成以下Java代码
public List<HistoricProcessInstance> findHistoricProcessInstancesAndVariablesByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { setSafeInValueLists(historicProcessInstanceQuery); return getDbSqlSession().selectList("selectHistoricProcessInstancesWithVariablesByQueryCriteria", historicProcessInstanceQuery, getManagedEntityClass()); } @Override @SuppressWarnings("unchecked") public List<HistoricProcessInstance> findHistoricProcessInstanceIdsByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { setSafeInValueLists(historicProcessInstanceQuery); return getDbSqlSession().selectList("selectHistoricProcessInstanceIdsByQueryCriteria", historicProcessInstanceQuery, getManagedEntityClass()); } @Override @SuppressWarnings("unchecked") public List<HistoricProcessInstance> findHistoricProcessInstancesByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectHistoricProcessInstanceByNativeQuery", parameterMap); } @Override public long findHistoricProcessInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectHistoricProcessInstanceCountByNativeQuery", parameterMap); } @Override
public void deleteHistoricProcessInstances(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { getDbSqlSession().delete("bulkDeleteHistoricProcessInstances", historicProcessInstanceQuery, HistoricProcessInstanceEntityImpl.class); } @Override public void bulkDeleteHistoricProcessInstances(Collection<String> processInstanceIds) { getDbSqlSession().delete("bulkDeleteHistoricProcessInstancesByIds", createSafeInValuesList(processInstanceIds), HistoricProcessInstanceEntityImpl.class); } protected void setSafeInValueLists(HistoricProcessInstanceQueryImpl processInstanceQuery) { if (processInstanceQuery.getProcessInstanceIds() != null) { processInstanceQuery.setSafeProcessInstanceIds(createSafeInValuesList(processInstanceQuery.getProcessInstanceIds())); } if (processInstanceQuery.getInvolvedGroups() != null) { processInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(processInstanceQuery.getInvolvedGroups())); } if (processInstanceQuery.getOrQueryObjects() != null && !processInstanceQuery.getOrQueryObjects().isEmpty()) { for (HistoricProcessInstanceQueryImpl orProcessInstanceQuery : processInstanceQuery.getOrQueryObjects()) { setSafeInValueLists(orProcessInstanceQuery); } } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisHistoricProcessInstanceDataManager.java
1