instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public TransformsType getTransforms() { return transforms; } /** * Sets the value of the transforms property. * * @param value * allowed object is * {@link TransformsType } * */ public void setTransforms(TransformsType value) { this.transforms = value; } /** * Gets the value of the uri property. * * @return * possible object is
* {@link String } * */ public String getURI() { return uri; } /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setURI(String value) { this.uri = 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\CipherReferenceType.java
1
请在Spring Boot框架中完成以下Java代码
public static class Config { private @Nullable Class inClass; private @Nullable Predicate predicate; private @Nullable Map<String, Object> hints; public @Nullable Class getInClass() { return inClass; } public Config setInClass(Class inClass) { this.inClass = inClass; return this; } public @Nullable Predicate getPredicate() { return predicate; } public Config setPredicate(Predicate predicate) { this.predicate = predicate;
return this; } public <T> Config setPredicate(Class<T> inClass, Predicate<T> predicate) { setInClass(inClass); this.predicate = predicate; return this; } public @Nullable Map<String, Object> getHints() { return hints; } public Config setHints(Map<String, Object> hints) { this.hints = hints; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\ReadBodyRoutePredicateFactory.java
2
请在Spring Boot框架中完成以下Java代码
public void printAutomaticallyLetters(@NonNull final I_C_Async_Batch asyncBatch) { final List<IPrintingQueueSource> sources = createPrintingQueueSource(asyncBatch); if (sources.isEmpty()) { throw new AdempiereException("Nothing selected"); } for (final IPrintingQueueSource source : sources) { source.setName("Print letter for C_Async_Batch_ID = " + asyncBatch.getC_Async_Batch_ID()); print(source, asyncBatch); } } /** * Create Printing queue source. * * Contains printing queues for the letters that belong to a specific <code>C_Async_Batch_ID</code> */ private List<IPrintingQueueSource> createPrintingQueueSource(@NonNull final I_C_Async_Batch asyncBatch) { final IQuery<I_C_Printing_Queue> query = queryBL.createQueryBuilder(I_C_Printing_Queue.class, Env.getCtx(), ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_C_Printing_Queue.COLUMN_C_Async_Batch_ID, asyncBatch.getC_Async_Batch_ID()) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_Processed, false) .create(); final PInstanceId pinstanceId = PInstanceId.ofRepoId(asyncBatch.getAD_PInstance_ID()); final int selectionLength = query.createSelection(pinstanceId); if (selectionLength <= 0) { logger.info("Nothing to print!"); return Collections.emptyList();
} final IPrintingQueueQuery printingQuery = printingQueueBL.createPrintingQueueQuery(); printingQuery.setFilterByProcessedQueueItems(false); printingQuery.setOnlyAD_PInstance_ID(pinstanceId); final Properties ctx = Env.getCtx(); // we need to make sure exists AD_Session_ID in context; if not, a new session will be created sessionBL.getCurrentOrCreateNewSession(ctx); return printingQueueBL.createPrintingQueueSources(ctx, printingQuery); } private void print(@NonNull final IPrintingQueueSource source, @NonNull final I_C_Async_Batch asyncBatch) { final ContextForAsyncProcessing printJobContext = ContextForAsyncProcessing.builder() .adPInstanceId(PInstanceId.ofRepoIdOrNull(asyncBatch.getAD_PInstance_ID())) .parentAsyncBatchId(asyncBatch.getC_Async_Batch_ID()) .build(); printOutputFacade.print(source, printJobContext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\serialletter\src\main\java\de\metas\letter\service\SerialLetterService.java
2
请完成以下Java代码
public int getR_RequestProcessor_Route_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessor_Route_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestProcessor_Route.java
1
请完成以下Java代码
public class PerformanceBenchmark { private static final Random RANDOM = new Random(); private static final int ARRAY_SIZE = 10000; private static final int[] randomNumbers = RANDOM.ints(ARRAY_SIZE).toArray(); private static final int[] sameNumbers = IntStream.generate(() -> 42).limit(ARRAY_SIZE).toArray(); public static final Supplier<int[]> randomNumbersSupplier = randomNumbers::clone; public static final Supplier<int[]> sameNumbersSupplier = sameNumbers::clone; @Benchmark @BenchmarkMode(Mode.Throughput) @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) public void quickSortSameNumber() { Quicksort.sort(sameNumbersSupplier.get()); } @Benchmark @BenchmarkMode(Mode.Throughput) @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void quickSortRandomNumber() { Quicksort.sort(randomNumbersSupplier.get()); } @Benchmark @BenchmarkMode(Mode.Throughput) @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) public void mergeSortSameNumber() { MergeSort.sort(sameNumbersSupplier.get()); } @Benchmark @BenchmarkMode(Mode.Throughput) @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) public void mergeSortRandomNumber() { MergeSort.sort(randomNumbersSupplier.get()); } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\collectionsvsarrays\PerformanceBenchmark.java
1
请完成以下Java代码
public PageData<Notification> findNotificationsByRecipientIdAndReadStatus(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, boolean unreadOnly, PageLink pageLink) { if (unreadOnly) { return notificationDao.findUnreadByDeliveryMethodAndRecipientIdAndPageLink(tenantId, deliveryMethod, recipientId, pageLink); } else { return notificationDao.findByDeliveryMethodAndRecipientIdAndPageLink(tenantId, deliveryMethod, recipientId, pageLink); } } @Override public PageData<Notification> findLatestUnreadNotificationsByRecipientIdAndNotificationTypes(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, Set<NotificationType> types, int limit) { SortOrder sortOrder = new SortOrder(EntityKeyMapping.CREATED_TIME, SortOrder.Direction.DESC); PageLink pageLink = new PageLink(limit, 0, null, sortOrder); return notificationDao.findUnreadByDeliveryMethodAndRecipientIdAndNotificationTypesAndPageLink(tenantId, deliveryMethod, recipientId, types, pageLink); } @Override public int countUnreadNotificationsByRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId) { return notificationDao.countUnreadByDeliveryMethodAndRecipientId(tenantId, deliveryMethod, recipientId); } @Override public boolean deleteNotification(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationDao.deleteByIdAndRecipientId(tenantId, recipientId, notificationId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findNotificationById(tenantId, new NotificationId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(notificationDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationService.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final PublisherRepository publisherRepository; public BookstoreService(AuthorRepository authorRepository, PublisherRepository publisherRepository) { this.authorRepository = authorRepository; this.publisherRepository = publisherRepository; } @Transactional public void addPublisher() { Publisher publisher = new Publisher(); publisher.setName("GreatBooks Ltd"); publisher.setUrc(92284434); publisherRepository.save(publisher); } @Transactional public void addAuthorsWithBooks() { Publisher publisher = publisherRepository.findByUrc(92284434); Author author1 = new Author(); author1.setId(new AuthorId(publisher, "Alicia Tom")); author1.setGenre("Anthology"); Author author2 = new Author(); author2.setId(new AuthorId(publisher, "Joana Nimar")); author2.setGenre("History"); Book book1 = new Book(); book1.setIsbn("001-AT"); book1.setTitle("The book of swords");
Book book2 = new Book(); book2.setIsbn("002-AT"); book2.setTitle("Anthology of a day"); Book book3 = new Book(); book3.setIsbn("003-AT"); book3.setTitle("Anthology today"); author1.addBook(book1); // use addBook() helper author1.addBook(book2); author2.addBook(book3); authorRepository.save(author1); authorRepository.save(author2); } @Transactional(readOnly = true) public void fetchAuthorByName() { Author author = authorRepository.fetchByName("Alicia Tom"); System.out.println(author); } @Transactional public void removeBookOfAuthor() { Publisher publisher = publisherRepository.findByUrc(92284434); Author author = authorRepository.fetchWithBooks(new AuthorId(publisher, "Alicia Tom")); author.removeBook(author.getBooks().get(0)); } @Transactional public void removeAuthor() { Publisher publisher = publisherRepository.findByUrc(92284434); authorRepository.deleteById(new AuthorId(publisher, "Alicia Tom")); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddableMapRel\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
private Optional<UpsertArticleRequest> jsonProductToUpsertArticle(@NonNull final JsonProduct product) { if (product.getAlbertaProductInfo() == null || CollectionUtils.isEmpty(product.getAlbertaProductInfo().getPackagingUnits())) { return Optional.empty(); } final Article article = new Article(); final String productNo = product.getProductNo(); final String pcn = productNo.startsWith(ARTICLE_PCN_PREFIX) ? productNo.substring(ARTICLE_PCN_PREFIX.length()) : null; article.customerNumber(productNo) .name(product.getName()) .description(product.getDescription()) .manufacturer(product.getManufacturerName()) .manufacturerNumber(product.getManufacturerNumber()) .unavailableFrom(fromJavaLocalDate(product.getDiscontinuedFrom())); final JsonAlbertaProductInfo albertaProductInfo = product.getAlbertaProductInfo(); article.additionalDescription(albertaProductInfo.getAdditionalDescription()) .size(albertaProductInfo.getSize()) .purchaseRating(PurchaseRatingEnum.getValueByCodeOrNull(albertaProductInfo.getPurchaseRating())) .inventoryType(albertaProductInfo.getInventoryType() != null ? new BigDecimal(albertaProductInfo.getInventoryType()) : null) .status(albertaProductInfo.getStatus() != null ? new BigDecimal(albertaProductInfo.getStatus()) : null) .medicalAidPositionNumber(albertaProductInfo.getMedicalAidPositionNumber()) .stars(albertaProductInfo.getStars()) .assortmentType(albertaProductInfo.getAssortmentType() != null ? new BigDecimal(albertaProductInfo.getAssortmentType()) : null) .pharmacyPrice(albertaProductInfo.getPharmacyPrice() != null ? String.valueOf(albertaProductInfo.getPharmacyPrice()) : null) .fixedPrice(albertaProductInfo.getFixedPrice() != null ? String.valueOf(albertaProductInfo.getFixedPrice()) : null) .therapyIds(AlbertaUtil.asBigDecimalIds(albertaProductInfo.getTherapyIds()))
.billableTherapies(AlbertaUtil.asBigDecimalIds(albertaProductInfo.getBillableTherapies())) .packagingUnits(toPackageUnitList(albertaProductInfo.getPackagingUnits(), pcn)) .productGroupId(albertaProductInfo.getProductGroupId()); return Optional.of(UpsertArticleRequest.builder() .article(article) .productId(product.getId()) .firstExport(product.getAlbertaProductInfo().getAlbertaProductId() == null) .build()); } @Nullable private List<PackagingUnit> toPackageUnitList( @NonNull final List<JsonAlbertaPackagingUnit> albertaPackagingUnits, @Nullable final String pcn) { if (CollectionUtils.isEmpty(albertaPackagingUnits)) { return null; } return albertaPackagingUnits .stream() .map(mfPackageUnit -> new PackagingUnit() .pcn(pcn) .quantity(mfPackageUnit.getQuantity()) .unit(mfPackageUnit.getUnit())) .collect(ImmutableList.toImmutableList()); } }
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\PrepareAlbertaArticlesProcessor.java
2
请完成以下Java代码
public PricingSystemId getPricingSystemId() { PricingSystemId pricingSystemId = _pricingSystemId; if (pricingSystemId == null) { pricingSystemId = _pricingSystemId = PricingSystemId.ofRepoId(getC_Flatrate_Term().getM_PricingSystem_ID()); } return pricingSystemId; } @Override public I_C_Flatrate_Term getC_Flatrate_Term() { if (_flatrateTerm == null) { _flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID()); // shouldn't be null because we prevent even material-tracking purchase orders without a flatrate term. Check.errorIf(_flatrateTerm == null, "M_Material_Tracking {} has no flatrate term", materialTracking); } return _flatrateTerm; } @Override public String getInvoiceRule() { if (!_invoiceRuleSet) { // // Try getting the InvoiceRule from Flatrate Term final I_C_Flatrate_Term flatrateTerm = getC_Flatrate_Term(); final String invoiceRule = flatrateTerm .getC_Flatrate_Conditions()
.getInvoiceRule(); Check.assumeNotEmpty(invoiceRule, "Unable to retrieve invoiceRule from materialTracking {}", materialTracking); _invoiceRule = invoiceRule; _invoiceRuleSet = true; } return _invoiceRule; } /* package */void setM_PriceList_Version(final I_M_PriceList_Version priceListVersion) { _priceListVersion = priceListVersion; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingAsVendorInvoicingInfo.java
1
请在Spring Boot框架中完成以下Java代码
public RepositoryService repositoryService(ProcessEngine processEngine) { return processEngine.getRepositoryService(); } @Bean public RuntimeService runtimeService(ProcessEngine processEngine) { return processEngine.getRuntimeService(); } @Bean public TaskService taskService(ProcessEngine processEngine) { return processEngine.getTaskService(); } @Bean public HistoryService historyService(ProcessEngine processEngine) { return processEngine.getHistoryService(); }
@Bean public ManagementService managementService(ProcessEngine processEngine) { return processEngine.getManagementService(); } @Bean public IdentityService identityService(ProcessEngine processEngine) { return processEngine.getIdentityService(); } @Bean public FormService formService(ProcessEngine processEngine) { return processEngine.getFormService(); } }
repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\config\FlowableConfig.java
2
请在Spring Boot框架中完成以下Java代码
public boolean set(final String key, Serializable value) { boolean result = false; try { ValueOperations<Serializable, Serializable> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ @Override public boolean set(final String key, Serializable value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Serializable> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }
@Override public <K,HK,HV> boolean setMap(K key, Map<HK, HV> map, Long expireTime) { HashOperations<K, HK, HV> operations = redisTemplate.opsForHash(); operations.putAll(key, map); if (expireTime != null) { redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); } return false; } @Override public <K,HK,HV> Map<HK,HV> getMap(final K key) { HashOperations<K, HK, HV> operations = redisTemplate.opsForHash(); return operations.entries(key); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\service\RedisServiceImpl.java
2
请完成以下Java代码
public class CatchEventXMLConverter extends BaseBpmnXMLConverter { @Override public Class<? extends BaseElement> getBpmnElementType() { return IntermediateCatchEvent.class; } @Override protected String getXMLElementName() { return ELEMENT_EVENT_CATCH; } @Override protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { IntermediateCatchEvent catchEvent = new IntermediateCatchEvent(); BpmnXMLUtil.addXMLLocation(catchEvent, xtr);
parseChildElements(getXMLElementName(), catchEvent, model, xtr); return catchEvent; } @Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {} @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) element; writeEventDefinitions(catchEvent, catchEvent.getEventDefinitions(), model, xtw); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\CatchEventXMLConverter.java
1
请完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBlog() { return blog; }
public void setBlog(String blog) { this.blog = blog; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; } }
repos\tutorials-master\libraries-http\src\main\java\com\baeldung\retrofitguide\User.java
1
请完成以下Java代码
public static String calculateExactTimeAgoWithJodaTime(Date pastTime) { Period period = new Period(new DateTime(pastTime.getTime()), new DateTime(getCurrentTime())); PeriodFormatter formatter = new PeriodFormatterBuilder().appendYears() .appendSuffix(" year ", " years ") .appendSeparator("and ") .appendMonths() .appendSuffix(" month ", " months ") .appendSeparator("and ") .appendWeeks() .appendSuffix(" week ", " weeks ") .appendSeparator("and ") .appendDays() .appendSuffix(" day ", " days ") .appendSeparator("and ") .appendHours() .appendSuffix(" hour ", " hours ") .appendSeparator("and ") .appendMinutes() .appendSuffix(" minute ", " minutes ") .appendSeparator("and ") .appendSeconds() .appendSuffix(" second", " seconds") .toFormatter(); return formatter.print(period); } public static String calculateHumanFriendlyTimeAgoWithJodaTime(Date pastTime) { Period period = new Period(new DateTime(pastTime.getTime()), new DateTime(getCurrentTime())); if (period.getYears() != 0) return "several years ago"; else if (period.getMonths() != 0) return "several months ago"; else if (period.getWeeks() != 0) return "several weeks ago"; else if (period.getDays() != 0) return "several days ago";
else if (period.getHours() != 0) return "several hours ago"; else if (period.getMinutes() != 0) return "several minutes ago"; else return "moments ago"; } public static String calculateZonedTimeAgoWithJodaTime(Date pastTime, TimeZone zone) { DateTimeZone dateTimeZone = DateTimeZone.forID(zone.getID()); Period period = new Period(new DateTime(pastTime.getTime(), dateTimeZone), new DateTime(getCurrentTimeByTimeZone(zone))); return PeriodFormat.getDefault() .print(period); } }
repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\timeago\version7\TimeAgoCalculator.java
1
请完成以下Java代码
public I_K_Entry getK_Entry() throws RuntimeException { return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name) .getPO(getK_Entry_ID(), get_TrxName()); } /** Set Entry. @param K_Entry_ID Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID) { if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Rating. @param Rating Classification or Importance */ public void setRating (int Rating) { set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating)); } /** Get Rating. @return Classification or Importance */ public int getRating () { Integer ii = (Integer)get_Value(COLUMNNAME_Rating); if (ii == null)
return 0; return ii.intValue(); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Comment.java
1
请完成以下Java代码
public void setC_ConversionRate_Rule_ID (final int C_ConversionRate_Rule_ID) { if (C_ConversionRate_Rule_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ConversionRate_Rule_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ConversionRate_Rule_ID, C_ConversionRate_Rule_ID); } @Override public int getC_ConversionRate_Rule_ID() { return get_ValueAsInt(COLUMNNAME_C_ConversionRate_Rule_ID); } @Override public void setC_Currency_ID (final int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID); } @Override public int getC_Currency_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_ID); } @Override public void setC_Currency_To_ID (final int C_Currency_To_ID) { if (C_Currency_To_ID < 1) set_Value (COLUMNNAME_C_Currency_To_ID, null); else set_Value (COLUMNNAME_C_Currency_To_ID, C_Currency_To_ID); } @Override public int getC_Currency_To_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_To_ID); } @Override public void setMultiplyRate_Max (final @Nullable BigDecimal MultiplyRate_Max)
{ set_Value (COLUMNNAME_MultiplyRate_Max, MultiplyRate_Max); } @Override public BigDecimal getMultiplyRate_Max() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Max); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMultiplyRate_Min (final @Nullable BigDecimal MultiplyRate_Min) { set_Value (COLUMNNAME_MultiplyRate_Min, MultiplyRate_Min); } @Override public BigDecimal getMultiplyRate_Min() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Min); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionRate_Rule.java
1
请完成以下Java代码
public class StatementPersonDao { private final Connection connection; public StatementPersonDao(Connection connection) { this.connection = connection; } public Optional<PersonEntity> getById(int id) throws SQLException { String query = "SELECT id, name, FROM persons WHERE id = '" + id + "'"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query); if (resultSet.first()) { PersonEntity result = new PersonEntity(resultSet.getInt("id"), resultSet.getString("name")); return Optional.of(result); } else { return Optional.empty(); } } public void insert(PersonEntity personEntity) throws SQLException { String query = "INSERT INTO persons(id, name) VALUES(" + personEntity.getId() + ", '" + personEntity.getName() + "')"; Statement statement = connection.createStatement(); statement.executeUpdate(query); } public void insert(List<PersonEntity> personEntities) throws SQLException { for (PersonEntity personEntity : personEntities) { insert(personEntity); } } public void update(PersonEntity personEntity) throws SQLException { String query = "UPDATE persons SET name = '" + personEntity.getName() + "' WHERE id = " + personEntity.getId(); Statement statement = connection.createStatement();
statement.executeUpdate(query); } public void deleteById(int id) throws SQLException { String query = "DELETE FROM persons WHERE id = " + id; Statement statement = connection.createStatement(); statement.executeUpdate(query); } public List<PersonEntity> getAll() throws SQLException { String query = "SELECT id, name, FROM persons"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query); List<PersonEntity> result = new ArrayList<>(); while (resultSet.next()) { result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name"))); } return result; } }
repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\statmentVsPreparedstatment\StatementPersonDao.java
1
请完成以下Java代码
public boolean isReversal(final I_C_AllocationHdr allocationHdr) { if (allocationHdr == null) { return false; } if (allocationHdr.getReversal_ID() <= 0) { return false; } // the reversal is always younger than the original document return allocationHdr.getC_AllocationHdr_ID() > allocationHdr.getReversal_ID(); } @Override public void invoiceDiscountAndWriteOff(@NonNull final InvoiceDiscountAndWriteOffRequest request) { final org.compiere.model.I_C_Invoice invoice = request.getInvoice(); Timestamp dateTrx; Timestamp dateAcct; if (request.isUseInvoiceDate()) { dateTrx = invoice.getDateInvoiced(); dateAcct = invoice.getDateAcct(); } else { dateTrx = TimeUtil.asTimestamp(request.getDateTrx() != null ? request.getDateTrx() : SystemTime.asInstant()); dateAcct = dateTrx; } final Money discountAmt = request.getDiscountAmt(); final Money writeOffAmt = request.getWriteOffAmt(); if (Money.countNonZero(discountAmt, writeOffAmt) == 0) { throw new AdempiereException("At least one of the amounts shall be non-zero: " + request); } final CurrencyId currencyId = Money.getCommonCurrencyIdOfAll(discountAmt, writeOffAmt); newBuilder() .orgId(invoice.getAD_Org_ID()) .currencyId(currencyId) .dateAcct(dateAcct) .dateTrx(dateTrx) .description(StringUtils.trimBlankToNull(request.getDescription()))
// .addLine() .orgId(invoice.getAD_Org_ID()) .bpartnerId(invoice.getC_BPartner_ID()) .invoiceId(invoice.getC_Invoice_ID()) .discountAmt(Money.toBigDecimalOrZero(discountAmt)) .writeOffAmt(Money.toBigDecimalOrZero(writeOffAmt)) .lineDone() // .create(true); // complete=true } @Override public Optional<InvoiceId> getInvoiceId(@NonNull final PaymentAllocationLineId lineId) { final I_C_AllocationLine line = allocationDAO.getLineById(lineId); return InvoiceId.optionalOfRepoId(line.getC_Invoice_ID()); } @Override public Optional<PaymentId> getPaymentId(@NonNull final PaymentAllocationLineId lineId) { final I_C_AllocationLine line = allocationDAO.getLineById(lineId); return PaymentId.optionalOfRepoId(line.getC_Payment_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\impl\AllocationBL.java
1
请完成以下Java代码
public String toJson() { return idStr; } @Override public int hashCode() { return Objects.hash(idStr); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof StringDocumentId)) { return false; } final StringDocumentId other = (StringDocumentId)obj; return Objects.equals(idStr, other.idStr); } @Override public boolean isInt() { return false; } @Override
public int toInt() { if (isComposedKey()) { throw new AdempiereException("Composed keys cannot be converted to int: " + this); } else { throw new AdempiereException("String document IDs cannot be converted to int: " + this); } } @Override public boolean isNew() { return false; } @Override public boolean isComposedKey() { return idStr.contains(COMPOSED_KEY_SEPARATOR); } @Override public List<Object> toComposedKeyParts() { final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder(); COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add); return composedKeyParts.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java
1
请完成以下Java代码
public String getAttributeValueType() { return HUVendorBPartnerAttributeValuesProvider.ATTRIBUTEVALUETYPE; } @Override public IAttributeValuesProvider createAttributeValuesProvider(final @NotNull Attribute attribute) { return new HUVendorBPartnerAttributeValuesProvider(); } @Override public Object generateSeedValue(final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute, final Object valueInitialDefault) { // we don't support a value different from null Check.assumeNull(valueInitialDefault, "valueInitialDefault should be null"); return HUVendorBPartnerAttributeValuesProvider.staticNullValue(); } @Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute) { final I_M_HU hu = ihuAttributesBL.getM_HU_OrNull(attributeSet); if (hu == null) { // If there is no HU (e.g. ASI), consider it editable return false; } final String huStatus = hu.getHUStatus(); if (!X_M_HU.HUSTATUS_Planning.equals(huStatus)) { // Allow editing only Planning HUs return true; } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUVendorBPartnerAttributeHandler.java
1
请完成以下Java代码
private void validateJsonKeys(JsonNode userSettings) { Iterator<String> fieldNames = userSettings.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); if (fieldName.contains(".") || fieldName.contains(",")) { throw new DataValidationException("Json field name should not contain \".\" or \",\" symbols"); } } } public JsonNode update(JsonNode mainNode, JsonNode updateNode) { Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldExpression = fieldNames.next(); String[] fieldPath = fieldExpression.trim().split("\\."); var node = (ObjectNode) mainNode; for (int i = 0; i < fieldPath.length; i++) { var fieldName = fieldPath[i];
var last = i == (fieldPath.length - 1); if (last) { node.set(fieldName, updateNode.get(fieldExpression)); } else { if (!node.has(fieldName)) { node.set(fieldName, JacksonUtil.newObjectNode()); } node = (ObjectNode) node.get(fieldName); } } } return mainNode; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\user\UserSettingsServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
private OAuth2Request getRequest(Map<String, Object> map) { Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request"); String clientId = (String) request.get("clientId"); Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ? (Collection<String>) request.get("scope") : Collections.<String>emptySet()); return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope), null, null, null, null); } @Override public OAuth2AccessToken readAccessToken(String accessToken) { throw new UnsupportedOperationException("Not supported: read access token"); } @SuppressWarnings({ "unchecked" }) private Map<String, Object> getMap(String path, String accessToken) { this.logger.debug("Getting user info from: " + path); try { OAuth2RestOperations restTemplate = this.restTemplate; if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails(); resource.setClientId(this.clientId); restTemplate = new OAuth2RestTemplate(resource); } OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext() .getAccessToken(); if (existingToken == null || !accessToken.equals(existingToken.getValue())) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken( accessToken); token.setTokenType(this.tokenType); restTemplate.getOAuth2ClientContext().setAccessToken(token); } return restTemplate.getForEntity(path, Map.class).getBody(); } catch (Exception ex) { this.logger.info("Could not fetch user details: " + ex.getClass() + ", " + ex.getMessage()); return Collections.<String, Object>singletonMap("error", "Could not fetch user details"); } } }
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\service\security\CustomUserInfoTokenServices.java
2
请完成以下Java代码
public TokenType getTokenType() { return this.tokenType; } /** * Returns the scope(s) associated to the token. * @return the scope(s) associated to the token */ public Set<String> getScopes() { return this.scopes; } /** * Access Token Types. * * @see <a target="_blank" href= * "https://tools.ietf.org/html/rfc6749#section-7.1">Section 7.1 Access Token * Types</a> */ public static final class TokenType implements Serializable { private static final long serialVersionUID = 620L; public static final TokenType BEARER = new TokenType("Bearer"); /** * @since 6.5 */ public static final TokenType DPOP = new TokenType("DPoP"); private final String value; /** * Constructs a {@code TokenType} using the provided value. * @param value the value of the token type * @since 6.5 */ public TokenType(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the token type.
* @return the value of the token type */ public String getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } TokenType that = (TokenType) obj; return this.getValue().equalsIgnoreCase(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2AccessToken.java
1
请完成以下Java代码
private void onSessionDisconnectEvent(final SessionDisconnectEvent event) { final WebsocketSessionId sessionId = WebsocketSessionId.ofString(event.getSessionId()); final Set<WebsocketTopicName> topicNames = activeSubscriptionsIndex.removeSessionAndGetTopicNames(sessionId); websocketProducersRegistry.onSessionDisconnect(sessionId, topicNames); logger.debug("Disconnected from topicName={} [ sessionId={} ]", topicNames, sessionId); } private static WebsocketTopicName extractTopicName(final AbstractSubProtocolEvent event) { return WebsocketTopicName.ofString(SimpMessageHeaderAccessor.getDestination(event.getMessage().getHeaders())); } private static WebsocketSubscriptionId extractUniqueSubscriptionId(final AbstractSubProtocolEvent event) { final MessageHeaders headers = event.getMessage().getHeaders();
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(SimpMessageHeaderAccessor.getSessionId(headers)); final String simpSubscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers); return WebsocketSubscriptionId.of(sessionId, Objects.requireNonNull(simpSubscriptionId, "simpSubscriptionId")); } @NonNull private static Map<String, List<String>> extractNativeHeaders(@NonNull final AbstractSubProtocolEvent event) { final Object nativeHeaders = event.getMessage().getHeaders().get("nativeHeaders"); return Optional.ofNullable(nativeHeaders) .filter(headers -> headers instanceof Map) .filter(headers -> !((Map<?, ?>)headers).isEmpty()) .map(headers -> (Map<String, List<String>>)headers) .map(ImmutableMap::copyOf) .orElseGet(ImmutableMap::of); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducerConfiguration.java
1
请完成以下Java代码
public Optional<HUEditorView> getByKeyIfExists(@NonNull final PackingHUsViewKey key) { return Optional.ofNullable(packingHUsViewsByKey.get(key)); } @FunctionalInterface static interface PackingHUsViewSupplier { HUEditorView createPackingHUsView(PackingHUsViewKey key); } public HUEditorView computeIfAbsent(@NonNull final PackingHUsViewKey key, @NonNull final PackingHUsViewSupplier packingHUsViewFactory) { return packingHUsViewsByKey.computeIfAbsent(key, packingHUsViewFactory::createPackingHUsView); } public void put(@NonNull final PackingHUsViewKey key, @NonNull final HUEditorView packingHUsView) { packingHUsViewsByKey.put(key, packingHUsView); } public Optional<HUEditorView> removeIfExists(@NonNull final PackingHUsViewKey key) { final HUEditorView packingHUsViewRemoved = packingHUsViewsByKey.remove(key); return Optional.ofNullable(packingHUsViewRemoved); }
public void handleEvent(@NonNull final HUExtractedFromPickingSlotEvent event) { packingHUsViewsByKey.entrySet() .stream() .filter(entry -> isEventMatchingKey(event, entry.getKey())) .map(entry -> entry.getValue()) .forEach(packingHUsView -> packingHUsView.addHUIdAndInvalidate(HuId.ofRepoId(event.getHuId()))); } private static final boolean isEventMatchingKey(final HUExtractedFromPickingSlotEvent event, final PackingHUsViewKey key) { return key.isBPartnerIdMatching(event.getBpartnerId()) && key.isBPartnerLocationIdMatching(event.getBpartnerLocationId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PackingHUsViewsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "myBusinessKey") public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } @ApiModelProperty(example = "newOrderMessage") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "tenant1") public String getTenantId() { return tenantId; } @ApiModelProperty(example = "overrideTenant1") public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) {
this.variables = variables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getTransientVariables() { return transientVariables; } public void setTransientVariables(List<RestVariable> transientVariables) { this.transientVariables = transientVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getStartFormVariables() { return startFormVariables; } public void setStartFormVariables(List<RestVariable> startFormVariables) { this.startFormVariables = startFormVariables; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } @JsonIgnore public boolean isTenantSet() { return tenantId != null && !StringUtils.isEmpty(tenantId); } // Added by Ryan Johnston public boolean getReturnVariables() { return returnVariables; } // Added by Ryan Johnston public void setReturnVariables(boolean returnVariables) { this.returnVariables = returnVariables; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceCreateRequest.java
2
请完成以下Java代码
public void notify(DelegateTask task) { // get the event handler final HistoryEventHandler historyEventHandler = Context.getProcessEngineConfiguration() .getHistoryEventHandler(); ExecutionEntity execution = ((TaskEntity) task).getExecution(); if (execution != null) { // delegate creation of the history event to the producer HistoryEvent historyEvent = createHistoryEvent(task, execution); if(historyEvent != null) { // pass the event to the handler
historyEventHandler.handleEvent(historyEvent); } } } protected void ensureHistoryLevelInitialized() { if (historyLevel == null) { historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); } } protected abstract HistoryEvent createHistoryEvent(DelegateTask task, ExecutionEntity execution); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\parser\HistoryTaskListener.java
1
请在Spring Boot框架中完成以下Java代码
public class PollingMessageListener implements MessageListener { private static final Log log = LogFactory.getLog(PollingMessageListener.class); @Autowired private PollingQueue pollingQueue; @Autowired private PollingParam pollingParam; @Override public void onMessage(Message message) { try { ActiveMQTextMessage msg = (ActiveMQTextMessage) message; final String msgText = msg.getText(); log.info("== receive bankOrderNo :" + msgText); RpOrderResultQueryVo rpOrderResultQueryVo = new RpOrderResultQueryVo(); rpOrderResultQueryVo.setBankOrderNo(msgText); rpOrderResultQueryVo.setStatus(NotifyStatusEnum.CREATED.name()); rpOrderResultQueryVo.setCreateTime(new Date()); rpOrderResultQueryVo.setEditTime(new Date());
rpOrderResultQueryVo.setLastNotifyTime(new Date()); rpOrderResultQueryVo.setNotifyTimes(0); // 初始化通知0次 rpOrderResultQueryVo.setLimitNotifyTimes(pollingParam.getMaxNotifyTimes()); // 最大通知次数 Map<Integer, Integer> notifyParams = pollingParam.getNotifyParams(); rpOrderResultQueryVo.setNotifyRule(JSONObject.toJSONString(notifyParams)); // 保存JSON try { pollingQueue.addToNotifyTaskDelayQueue(rpOrderResultQueryVo); // 添加到通知队列(第一次通知) } catch (BizException e) { log.error("BizException :", e); } catch (Exception e) { log.error(e); } } catch (Exception e) { log.error(e); } } }
repos\roncoo-pay-master\roncoo-pay-app-order-polling\src\main\java\com\roncoo\pay\app\polling\listener\PollingMessageListener.java
2
请完成以下Java代码
public class MonitoringEvent { private int eventId; private String eventName; private String creationDate; private String eventType; private String status; private String deviceId; public int getEventId() { return eventId; } public void setEventId(int eventId) { this.eventId = eventId; } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getEventType() { return eventType; } public void setEventType(String eventType) {
this.eventType = eventType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } }
repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\model\MonitoringEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class ArrayOfMappings extends ArrayList<CustomerMapping> { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArrayOfMappings {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\ArrayOfMappings.java
2
请完成以下Java代码
public void setRuleValue(String ruleValue) { this.ruleValue = ruleValue; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy;
} public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysPermissionDataRuleModel.java
1
请在Spring Boot框架中完成以下Java代码
private void createDirectories(@NonNull final Path path) throws PrintingException { try { Files.createDirectories(path); } catch (final IOException e) { throw new PrintingException("IOException trying to create output directory: " + path, e); } } private ImmutableMultimap<Path, JsonPrintingSegment> extractAndAssignPaths( @NonNull final JsonPrintingData printingData, @NonNull final String baseDirectory) { final ImmutableMultimap.Builder<Path, JsonPrintingSegment> path2Segments = new ImmutableMultimap.Builder<>(); for (final JsonPrintingSegment segment : printingData.getSegments()) { final JsonPrinterHW printer = segment.getPrinterHW(); if (!OUTPUTTYPE_Queue.equals(printer.getOutputType())) { continue; } Path path = null; final int trayId = segment.getTrayId(); if (trayId > 0) { final List<JsonPrinterTray> trays = printer.getTrays(); for (final JsonPrinterTray tray : trays) {
if(tray.getTrayId() == trayId) { path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName()), FileUtil.stripIllegalCharacters(tray.getName())) // don't use the number for the path, because we want to control it entirely with the tray name ; break; } } if(path == null) { throw new PrintingException("Shouldn't happen. Segment has TrayId, that doesn't exist in Trays of PrinterHW"); } } else { path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName())); } path2Segments.put(path, segment); } return path2Segments.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-printingclient\src\main\java\de\metas\camel\externalsystems\PrintingClientPDFFileStorer.java
2
请完成以下Java代码
public final class CacheImmutableClassesIndex { public static final transient CacheImmutableClassesIndex instance = new CacheImmutableClassesIndex(); private final Set<Class<?>> immutableClassesSeed = ImmutableSet.<Class<?>> builder() // Primitives .add(Integer.class) .add(Double.class) .add(Short.class) .add(Float.class) .add(Boolean.class) .add(Character.class) .add(Byte.class) .add(Void.class) // // Some common java types: .add(Enum.class) .add(String.class) .add(BigDecimal.class) // // Some java reflect types: .add(Class.class) .add(Method.class) .add(Annotation.class) // // Java Date/Time .add(LocalDate.class) .add(LocalDateTime.class) .add(LocalTime.class) .add(ZonedDateTime.class) .add(Duration.class) .add(Instant.class) // // Some metasfresh types: .add(NamePair.class) .add(ArrayKey.class) .add(AdMessageKey.class) // // guava immutable stuff .add(ImmutableList.class) .add(ImmutableSet.class) .add(ImmutableMap.class) .build(); private final CopyOnWriteArraySet<Class<?>> immutableClasses = new CopyOnWriteArraySet<>(); private CacheImmutableClassesIndex() { immutableClasses.addAll(immutableClassesSeed); } /** * @param clazz * @return true if given class is considered to be immutable */ public boolean isImmutable(@NonNull final Class<?> clazz) {
// Primitive types are always immutable if (clazz.isPrimitive()) { return true; } // Assume IDs are immutable if (RepoIdAware.class.isAssignableFrom(clazz)) { return true; } for (final Class<?> immutableClass : immutableClasses) { if (immutableClass.isAssignableFrom(clazz)) { return true; } } return false; } /** * Register a new immutable class. * * WARNING: to be used only if it's really needed because this is kind of dirty hack which could affect our caching system. * * @param immutableClass */ public void registerImmutableClass(@NonNull final Class<?> immutableClass) { immutableClasses.add(immutableClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheImmutableClassesIndex.java
1
请在Spring Boot框架中完成以下Java代码
public void saveData(PmsOperatorLog pmsOperatorLog) { pmsOperatorLogDao.insert(pmsOperatorLog); } /** * 修改pmsOperator */ public void updateData(PmsOperatorLog pmsOperatorLog) { pmsOperatorLogDao.update(pmsOperatorLog); } /** * 根据id获取数据pmsOperator * * @param id * @return */ public PmsOperatorLog getDataById(Long id) { return pmsOperatorLogDao.getById(id);
} /** * 分页查询pmsOperator * * @param pageParam * @param ActivityVo * PmsOperator * @return */ public PageBean listPage(PageParam pageParam, PmsOperatorLog pmsOperatorLog) { Map<String, Object> paramMap = new HashMap<String, Object>(); return pmsOperatorLogDao.listPage(pageParam, paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorLogServiceImpl.java
2
请完成以下Java代码
public abstract class AbstractActivitiSmartLifeCycle implements SmartLifecycle, DisposableBean { private static Logger logger = LoggerFactory.getLogger(AbstractActivitiSmartLifeCycle.class); private Object lifeCycleMonitor = new Object(); private boolean autoStartup = true; private int phase = DEFAULT_PHASE; private volatile boolean running = false; public AbstractActivitiSmartLifeCycle() {} public abstract void doStart(); public abstract void doStop(); /** * Set whether to auto-start the activation after this component * has been initialized and the context has been refreshed. * <p>Default is "true". Turn this flag off to defer the endpoint * activation until an explicit {@link #start()} call. */ public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } /** * Return the value for the 'autoStartup' property. If "true", this * component will start upon a ContextRefreshedEvent. */ @Override public boolean isAutoStartup() { return this.autoStartup; } /** * Specify the phase in which this component should be started * and stopped. The startup order proceeds from lowest to highest, and * the shutdown order is the reverse of that. By default this value is * Integer.MAX_VALUE meaning that this component starts as late * as possible and stops as soon as possible. */ public void setPhase(int phase) { this.phase = phase; } /** * Return the phase in which this component will be started and stopped. */ @Override public int getPhase() { return this.phase;
} @Override public void start() { synchronized (this.lifeCycleMonitor) { if (!this.running) { logger.info("Starting..."); doStart(); this.running = true; logger.info("Started."); } } } @Override public void stop() { synchronized (this.lifeCycleMonitor) { if (this.running) { logger.info("Stopping..."); doStop(); this.running = false; logger.info("Stopped."); } } } @Override public void stop(Runnable callback) { synchronized (this.lifeCycleMonitor) { stop(); callback.run(); } } @Override public boolean isRunning() { return this.running; } @Override public void destroy() { stop(); } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\AbstractActivitiSmartLifeCycle.java
1
请在Spring Boot框架中完成以下Java代码
public Charset getCharset() { return this.charset; } public void setCharset(Charset charset) { this.charset = charset; } public boolean isForce() { return Boolean.TRUE.equals(this.force); } public void setForce(boolean force) { this.force = force; } public boolean isForceRequest() { return Boolean.TRUE.equals(this.forceRequest); } public void setForceRequest(boolean forceRequest) { this.forceRequest = forceRequest; } public boolean isForceResponse() { return Boolean.TRUE.equals(this.forceResponse); } public void setForceResponse(boolean forceResponse) { this.forceResponse = forceResponse; } public boolean shouldForce(HttpMessageType type) { Boolean force = (type != HttpMessageType.REQUEST) ? this.forceResponse : this.forceRequest;
if (force == null) { force = this.force; } if (force == null) { force = (type == HttpMessageType.REQUEST); } return force; } /** * Type of HTTP message to consider for encoding configuration. */ public enum HttpMessageType { /** * HTTP request message. */ REQUEST, /** * HTTP response message. */ RESPONSE } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\ServletEncodingProperties.java
2
请完成以下Java代码
private AuthResolution getAuthResolution(@NonNull final HttpServletRequest httpRequest) { // don't check auth for OPTIONS method calls because this causes troubles on chrome preflight checks if ("OPTIONS".equals(httpRequest.getMethod())) { return AuthResolution.DO_NOT_AUTHENTICATE; } return configuration.getAuthResolution(httpRequest).orElse(AuthResolution.AUTHENTICATION_REQUIRED); } @Nullable private static String extractTokenStringIfAvailable(final HttpServletRequest httpRequest) { // // Check Authorization header first { final String authorizationString = StringUtils.trimBlankToNull(httpRequest.getHeader(HEADER_Authorization)); if (authorizationString != null) { if (authorizationString.startsWith("Token ")) { return authorizationString.substring(5).trim(); } else if (authorizationString.startsWith("Basic ")) { final String userAndTokenString = new String(DatatypeConverter.parseBase64Binary(authorizationString.substring(5).trim())); final int index = userAndTokenString.indexOf(':'); return userAndTokenString.substring(index + 1); } else { return authorizationString; } } }
// // Check apiKey query parameter { return StringUtils.trimBlankToNull(httpRequest.getParameter(QUERY_PARAM_API_KEY)); } } @VisibleForTesting Optional<String> extractAdLanguage(@NonNull final HttpServletRequest httpRequest) { final String acceptLanguageHeader = StringUtils.trimBlankToNull(httpRequest.getHeader(HEADER_AcceptLanguage)); final ADLanguageList availableLanguages = languageDAO.retrieveAvailableLanguages(); final String adLanguage = availableLanguages.getAD_LanguageFromHttpAcceptLanguage(acceptLanguageHeader, availableLanguages.getBaseADLanguage()); return Optional.ofNullable(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String title; @OneToMany @Cascade(CascadeType.ALL) private List<Comment> comments; public Post() { } 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 List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } @Override public String toString() { return "Post{" + "id=" + id + ", title='" + title + '\'' + ", comments=" + comments + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-queries-2\src\main\java\com\baeldung\hibernate\distinct\entities\Post.java
2
请完成以下Java代码
public void localize(Task task, String locale, boolean withLocalizationFallback) { task.setLocalizedName(null); task.setLocalizedDescription(null); if (locale != null) { String processDefinitionId = task.getProcessDefinitionId(); if (processDefinitionId != null) { ObjectNode languageNode = BpmnOverrideContext.getLocalizationElementProperties(locale, task.getTaskDefinitionKey(), processDefinitionId, withLocalizationFallback); if (languageNode != null) { JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME); if (languageNameNode != null && !languageNameNode.isNull()) { task.setLocalizedName(languageNameNode.asString()); } JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION); if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) { task.setLocalizedDescription(languageDescriptionNode.asString()); } } } } } @Override public void localize(HistoricTaskInstance task, String locale, boolean withLocalizationFallback) { HistoricTaskInstanceEntity taskEntity = (HistoricTaskInstanceEntity) task; taskEntity.setLocalizedName(null); taskEntity.setLocalizedDescription(null);
if (locale != null) { String processDefinitionId = task.getProcessDefinitionId(); if (processDefinitionId != null) { ObjectNode languageNode = BpmnOverrideContext.getLocalizationElementProperties(locale, task.getTaskDefinitionKey(), processDefinitionId, withLocalizationFallback); if (languageNode != null) { JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME); if (languageNameNode != null && !languageNameNode.isNull()) { taskEntity.setLocalizedName(languageNameNode.asString()); } JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION); if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) { taskEntity.setLocalizedDescription(languageDescriptionNode.asString()); } } } } } protected ExecutionEntityManager getExecutionEntityManager() { return processEngineConfiguration.getExecutionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\DefaultTaskLocalizationManager.java
1
请完成以下Java代码
public void setBody(BodyType value) { this.body = value; } /** * Gets the value of the encryptedData property. * * @return * possible object is * {@link EncryptedDataType } * */ public EncryptedDataType getEncryptedData() { return encryptedData; } /** * Sets the value of the encryptedData property. * * @param value * allowed object is * {@link EncryptedDataType } * */ public void setEncryptedData(EncryptedDataType value) { this.encryptedData = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { if (type == null) { return "invoice"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the storno property. * * @return * possible object is * {@link Boolean } * */ public boolean isStorno() { if (storno == null) { return false; } else { return storno; } } /** * Sets the value of the storno property. * * @param value * allowed object is * {@link Boolean } * */ public void setStorno(Boolean value) { this.storno = value; } /** * Gets the value of the copy property. * * @return * possible object is * {@link Boolean } *
*/ public boolean isCopy() { if (copy == null) { return false; } else { return copy; } } /** * Sets the value of the copy property. * * @param value * allowed object is * {@link Boolean } * */ public void setCopy(Boolean value) { this.copy = value; } /** * Gets the value of the creditAdvice property. * * @return * possible object is * {@link Boolean } * */ public boolean isCreditAdvice() { if (creditAdvice == null) { return false; } else { return creditAdvice; } } /** * Sets the value of the creditAdvice property. * * @param value * allowed object is * {@link Boolean } * */ public void setCreditAdvice(Boolean value) { this.creditAdvice = 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\PayloadType.java
1
请在Spring Boot框架中完成以下Java代码
public class SysLogController { private final SysLogService sysLogService; @Log("导出数据") @ApiOperation("导出数据") @GetMapping(value = "/download") @PreAuthorize("@el.check()") public void exportLog(HttpServletResponse response, SysLogQueryCriteria criteria) throws IOException { criteria.setLogType("INFO"); sysLogService.download(sysLogService.queryAll(criteria), response); } @Log("导出错误数据") @ApiOperation("导出错误数据") @GetMapping(value = "/error/download") @PreAuthorize("@el.check()") public void exportErrorLog(HttpServletResponse response, SysLogQueryCriteria criteria) throws IOException { criteria.setLogType("ERROR"); sysLogService.download(sysLogService.queryAll(criteria), response); } @GetMapping @ApiOperation("日志查询") @PreAuthorize("@el.check()") public ResponseEntity<Object> queryLog(SysLogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("INFO"); return new ResponseEntity<>(sysLogService.queryAll(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/user") @ApiOperation("用户日志查询") public ResponseEntity<PageResult<SysLogSmallDto>> queryUserLog(SysLogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("INFO"); criteria.setUsername(SecurityUtils.getCurrentUsername()); return new ResponseEntity<>(sysLogService.queryAllByUser(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/error") @ApiOperation("错误日志查询") @PreAuthorize("@el.check()") public ResponseEntity<Object> queryErrorLog(SysLogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("ERROR");
return new ResponseEntity<>(sysLogService.queryAll(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/error/{id}") @ApiOperation("日志异常详情查询") @PreAuthorize("@el.check()") public ResponseEntity<Object> queryErrorLogDetail(@PathVariable Long id){ return new ResponseEntity<>(sysLogService.findByErrDetail(id), HttpStatus.OK); } @DeleteMapping(value = "/del/error") @Log("删除所有ERROR日志") @ApiOperation("删除所有ERROR日志") @PreAuthorize("@el.check()") public ResponseEntity<Object> delAllErrorLog(){ sysLogService.delAllByError(); return new ResponseEntity<>(HttpStatus.OK); } @DeleteMapping(value = "/del/info") @Log("删除所有INFO日志") @ApiOperation("删除所有INFO日志") @PreAuthorize("@el.check()") public ResponseEntity<Object> delAllInfoLog(){ sysLogService.delAllByInfo(); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-logging\src\main\java\me\zhengjie\rest\SysLogController.java
2
请完成以下Java代码
public List<I_M_HU> retrieveIncludedHUs(final I_M_HU huId) { return handlingUnitsRepo.retrieveIncludedHUs(huId); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIds(@NonNull final Collection<HuId> huIds) { final List<I_M_HU> hus = handlingUnitsRepo.getByIds(huIds); final ImmutableSet<Integer> locatorIds = hus .stream() .map(I_M_HU::getM_Locator_ID) .filter(locatorId -> locatorId > 0) .collect(ImmutableSet.toImmutableSet()); return warehouseBL.getLocatorIdsByRepoId(locatorIds); } @Override 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 boolean breakValueMatches(final BigDecimal value) { return value.compareTo(breakValue) >= 0; } public boolean productMatchesAnyOf(@NonNull final Set<ProductAndCategoryAndManufacturerId> products) { Check.assumeNotEmpty(products, "products is not empty"); return products.stream().anyMatch(this::productMatches); } public boolean productMatches(@NonNull final ProductAndCategoryAndManufacturerId product) { return productMatches(product.getProductId()) && productCategoryMatches(product.getProductCategoryId()) && productManufacturerMatches(product.getProductManufacturerId()); } private boolean productMatches(final ProductId productId) { if (this.productId == null) { return true; } return Objects.equals(this.productId, productId); } private boolean productCategoryMatches(final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) { return true; }
return Objects.equals(this.productCategoryId, productCategoryId); } private boolean productManufacturerMatches(final BPartnerId productManufacturerId) { if (this.productManufacturerId == null) { return true; } if (productManufacturerId == null) { return false; } return Objects.equals(this.productManufacturerId, productManufacturerId); } public boolean attributeMatches(@NonNull final ImmutableAttributeSet attributes) { final AttributeValueId breakAttributeValueId = this.attributeValueId; if (breakAttributeValueId == null) { return true; } return attributes.hasAttributeValueId(breakAttributeValueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakMatchCriteria.java
1
请完成以下Java代码
public static class JSONSelectViewRowsAction extends JSONResultAction { private final WindowId windowId; private final String viewId; private final Set<String> rowIds; public JSONSelectViewRowsAction(final ViewId viewId, final DocumentIdsSelection rowIds) { super("selectViewRows"); this.windowId = viewId.getWindowId(); this.viewId = viewId.getViewId(); this.rowIds = rowIds.toJsonSet(); } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Getter public static class JSONDisplayQRCodeAction extends JSONResultAction { private final String code; protected JSONDisplayQRCodeAction(@NonNull final String code) { super("displayQRCode"); this.code = code; } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Getter public static class JSONNewRecordAction extends JSONResultAction { @NonNull private final WindowId windowId; @NonNull private final Map<String, String> fieldValues; @NonNull private final String targetTab; public JSONNewRecordAction( @NonNull final WindowId windowId, @Nullable final Map<String, String> fieldValues, @NonNull final ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab) { super("newRecord"); this.windowId = windowId; this.fieldValues = fieldValues != null && !fieldValues.isEmpty() ? new HashMap<>(fieldValues) : ImmutableMap.of(); this.targetTab = targetTab.name(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONProcessInstanceResult.java
1
请完成以下Java代码
public HUConsolidationJob getById(final HUConsolidationJobId id) { final HUConsolidationJob job = jobs.get(id); if (job == null) { throw new AdempiereException("No job found for id=" + id + ". Available in memory jobs are: " + jobs); } return job; } public HUConsolidationJob updateById(@NonNull final HUConsolidationJobId id, @NonNull final UnaryOperator<HUConsolidationJob> mapper) { return trxManager.callInThreadInheritedTrx(() -> { final HUConsolidationJob job = getById(id); final HUConsolidationJob jobChanged = mapper.apply(job); if (Objects.equals(job, jobChanged)) { return job; } save(jobChanged); return jobChanged; });
} public void save(final HUConsolidationJob job) { jobs.put(job.getId(), job); } public List<HUConsolidationJob> getByNotProcessedAndResponsibleId(final @NonNull UserId userId) { return jobs.values() .stream() .filter(job -> UserId.equals(job.getResponsibleId(), userId) && !job.getDocStatus().isProcessed()) .collect(ImmutableList.toImmutableList()); } public ImmutableSet<PickingSlotId> getInUsePickingSlotIds() { return jobs.values() .stream() .filter(job -> !job.getDocStatus().isProcessed()) .flatMap(job -> job.getPickingSlotIds().stream()) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobRepository.java
1
请完成以下Spring Boot application配置
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=none spring.jpa.generate-ddl=true logging.level.org.hibernate.SQL=DE
BUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
private static TrustManager[] getTrustManager() { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } }
}; return trustAllCerts; } //获取HostnameVerifier public static HostnameVerifier getHostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; return hostnameVerifier; } }
repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\config\SSLSocketClient.java
2
请完成以下Java代码
public class X_AD_Sequence_No extends org.compiere.model.PO implements I_AD_Sequence_No, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1919657103L; /** Standard Constructor */ public X_AD_Sequence_No (final Properties ctx, final int AD_Sequence_No_ID, @Nullable final String trxName) { super (ctx, AD_Sequence_No_ID, trxName); } /** Load Constructor */ public X_AD_Sequence_No (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Sequence getAD_Sequence() { return get_ValueAsPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setAD_Sequence(final org.compiere.model.I_AD_Sequence AD_Sequence) { set_ValueFromPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class, AD_Sequence); } @Override public void setAD_Sequence_ID (final int AD_Sequence_ID) { if (AD_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, AD_Sequence_ID); } @Override public int getAD_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_AD_Sequence_ID); } @Override public void setCalendarDay (final @Nullable java.lang.String CalendarDay) { set_Value (COLUMNNAME_CalendarDay, CalendarDay); } @Override public java.lang.String getCalendarDay() { return get_ValueAsString(COLUMNNAME_CalendarDay);
} @Override public void setCalendarMonth (final @Nullable java.lang.String CalendarMonth) { set_Value (COLUMNNAME_CalendarMonth, CalendarMonth); } @Override public java.lang.String getCalendarMonth() { return get_ValueAsString(COLUMNNAME_CalendarMonth); } @Override public void setCalendarYear (final java.lang.String CalendarYear) { set_ValueNoCheck (COLUMNNAME_CalendarYear, CalendarYear); } @Override public java.lang.String getCalendarYear() { return get_ValueAsString(COLUMNNAME_CalendarYear); } @Override public void setCurrentNext (final int CurrentNext) { set_Value (COLUMNNAME_CurrentNext, CurrentNext); } @Override public int getCurrentNext() { return get_ValueAsInt(COLUMNNAME_CurrentNext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_No.java
1
请完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<Privilege> getPrivileges() { return privileges; } public void setPrivileges(Set<Privilege> privileges) { this.privileges = privileges; } public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((id == null) ? 0 : id.hashCode()); result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); result = (prime * result) + ((password == null) ? 0 : password.hashCode()); result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); result = (prime * result) + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; if (id == null) { if (other.id != null) { return false; }
} else if (!id.equals(other.id)) { return false; } if (organization == null) { if (other.organization != null) { return false; } } else if (!organization.equals(other.organization)) { return false; } if (password == null) { if (other.password != null) { return false; } } else if (!password.equals(other.password)) { return false; } if (privileges == null) { if (other.privileges != null) { return false; } } else if (!privileges.equals(other.privileges)) { return false; } if (username == null) { if (other.username != null) { return false; } } else if (!username.equals(other.username)) { return false; } return true; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\User.java
1
请完成以下Java代码
public class ProcessVariablesMapSerializer extends StdSerializer<ProcessVariablesMap<String, Object>> { private static final long serialVersionUID = 1L; private final ConversionService conversionService; public ProcessVariablesMapSerializer(ConversionService conversionService) { super(ProcessVariablesMap.class, true); this.conversionService = conversionService; } @Override public void serialize( ProcessVariablesMap<String, Object> processVariablesMap, JsonGenerator gen, SerializerProvider serializers ) throws IOException { HashMap<String, ProcessVariableValue> map = new HashMap<>(); for (Map.Entry<String, Object> entry : processVariablesMap.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); map.put(name, buildProcessVariableValue(value)); } gen.writeObject(map); } private ProcessVariableValue buildProcessVariableValue(Object value) { ProcessVariableValue variableValue = null; if (value != null) { Class<?> entryValueClass = value.getClass(); String entryType = resolveEntryType(entryValueClass, value); if (OBJECT_TYPE_KEY.equals(entryType)) { value = new ObjectValue(value); }
String entryValue = conversionService.convert(value, String.class); variableValue = new ProcessVariableValue(entryType, entryValue); } return variableValue; } private String resolveEntryType(Class<?> clazz, Object value) { Class<?> entryType; if (isScalarType(clazz)) { entryType = clazz; } else { entryType = getContainerType(clazz, value).orElse(ObjectValue.class); } return forClass(entryType); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessVariablesMapSerializer.java
1
请在Spring Boot框架中完成以下Java代码
public String getLevel() { return this.level; } public void setLevel(String level) { this.level = level; } public int getLogDiskSpaceLimit() { return this.logDiskSpaceLimit; } public void setLogDiskSpaceLimit(int logDiskSpaceLimit) { this.logDiskSpaceLimit = logDiskSpaceLimit; } public String getLogFile() {
return this.logFile; } public void setLogFile(String logFile) { this.logFile = logFile; } public int getLogFileSizeLimit() { return this.logFileSizeLimit; } public void setLogFileSizeLimit(int logFileSizeLimit) { this.logFileSizeLimit = logFileSizeLimit; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\LoggingProperties.java
2
请完成以下Java代码
public void onContextCheckIn(final Properties ctxNew, final Properties ctxOld) { activeContexts.remove(ctxOld); activeContexts.add(ctxNew); } public String[] getActiveContextsInfo() { final List<Properties> activeContextsCopy = new ArrayList<>(activeContexts); final int count = activeContextsCopy.size(); final List<String> activeContextsInfo = new ArrayList<>(count); int index = 1; for (final Properties ctx : activeContextsCopy) { if (ctx == null) { continue; } final String ctxInfo = index + "/" + count + ". " + toInfoString(ctx); activeContextsInfo.add(ctxInfo); index++; } return activeContextsInfo.toArray(new String[activeContextsInfo.size()]); } private String toInfoString(final Properties ctx) { final String threadName = (String)ctx.get(CTXNAME_ThreadName); final String threadId = (String)ctx.get(CTXNAME_ThreadId); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx); final int adUserId = Env.getAD_User_ID(ctx); final int adRoleId = Env.getAD_Role_ID(ctx); final int adSessionId = Env.getAD_Session_ID(ctx);
return "Thread=" + threadName + "(" + threadId + ")" // + "\n" + ", Client/Org=" + adClientId + "/" + adOrgId + ", User/Role=" + adUserId + "/" + adRoleId + ", SessionId=" + adSessionId // + "\n" + ", id=" + System.identityHashCode(ctx) + ", " + ctx.getClass() // + "\n" + ", " + ctx.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\TraceContextProviderListener.java
1
请完成以下Java代码
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobManager() .findDeploymentIdMappingsByQueryCriteria(this); } //getters ////////////////////////////////////////// public Set<String> getIds() { return ids; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getProcessInstanceId() { return processInstanceId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable;
} public Date getNow() { return ClockUtil.getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public boolean getAcquired() { return acquired; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java
1
请完成以下Java代码
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; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAvoidEntityInDtoViaConstructor\src\main\java\com\bookstore\entity\Book.java
1
请在Spring Boot框架中完成以下Java代码
public class DocTypeQuery { public static final DocSubType DOCSUBTYPE_Any = DocSubType.ANY; public static final DocSubType DOCSUBTYPE_NONE = DocSubType.NONE; @NonNull DocBaseType docBaseType; @NonNull @Default DocSubType docSubType = DOCSUBTYPE_Any; @NonNull Integer adClientId; /** * Even if specified, the system will still try to fallback to {@code AD_Org_ID=0} if there is no doctype with a matching org-id. */ @Default int adOrgId = Env.CTXVALUE_AD_Org_ID_System; @Nullable Boolean isSOTrx; @Nullable Boolean defaultDocType; @Nullable String name; // // // public static class DocTypeQueryBuilder { public DocTypeQueryBuilder docBaseType(@NonNull final String docBaseType) { return docBaseType(DocBaseType.ofCode(docBaseType)); } public DocTypeQueryBuilder docBaseType(@NonNull final DocBaseType docBaseType) { this.docBaseType = docBaseType; return this; }
public DocTypeQueryBuilder docSubTypeAny() { return docSubType(DOCSUBTYPE_Any); } public DocTypeQueryBuilder docSubTypeNone() { return docSubType(DOCSUBTYPE_NONE); } public DocTypeQueryBuilder clientAndOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { return clientAndOrgId(clientAndOrgId.getClientId(), clientAndOrgId.getOrgId()); } public DocTypeQueryBuilder clientAndOrgId(@NonNull final ClientId clientId, @NonNull final OrgId orgId) { adClientId(clientId.getRepoId()); adOrgId(orgId.getRepoId()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\DocTypeQuery.java
2
请完成以下Java代码
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findWidgetsBundleById(tenantId, new WidgetsBundleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(widgetsBundleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.WIDGETS_BUNDLE; }
private final PaginatedRemover<TenantId, WidgetsBundle> tenantWidgetsBundleRemover = new PaginatedRemover<>() { @Override protected PageData<WidgetsBundle> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return widgetsBundleDao.findTenantWidgetsBundlesByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, WidgetsBundle entity) { deleteWidgetsBundle(tenantId, new WidgetsBundleId(entity.getUuidId())); } }; }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\widget\WidgetsBundleServiceImpl.java
1
请完成以下Java代码
protected AbstractSetStateCmd getNextCommand() { return null; } /** * @return the id of the associated deployment, only necessary if the command * can potentially be executed in a scheduled way (i.e. if an * {@link #executionDate} can be set) so the job executor responsible * for that deployment can execute the resulting job */ protected String getDeploymentId(CommandContext commandContext) { return null; } protected abstract void checkAuthorization(CommandContext commandContext); protected abstract void checkParameters(CommandContext commandContext); protected abstract void updateSuspensionState(CommandContext commandContext, SuspensionState suspensionState); protected abstract void logUserOperation(CommandContext commandContext); protected abstract String getLogEntryOperation(); protected abstract SuspensionState getNewSuspensionState(); protected String getDeploymentIdByProcessDefinition(CommandContext commandContext, String processDefinitionId) { ProcessDefinitionEntity definition = commandContext.getProcessDefinitionManager().getCachedResourceDefinitionEntity(processDefinitionId); if (definition == null) { definition = commandContext.getProcessDefinitionManager().findLatestDefinitionById(processDefinitionId); } if (definition != null) { return definition.getDeploymentId(); } return null; }
protected String getDeploymentIdByProcessDefinitionKey(CommandContext commandContext, String processDefinitionKey, boolean tenantIdSet, String tenantId) { ProcessDefinitionEntity definition = null; if (tenantIdSet) { definition = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKeyAndTenantId(processDefinitionKey, tenantId); } else { // randomly use a latest process definition's deployment id from one of the tenants List<ProcessDefinitionEntity> definitions = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionsByKey(processDefinitionKey); definition = definitions.isEmpty() ? null : definitions.get(0); } if (definition != null) { return definition.getDeploymentId(); } return null; } protected String getDeploymentIdByJobDefinition(CommandContext commandContext, String jobDefinitionId) { JobDefinitionManager jobDefinitionManager = commandContext.getJobDefinitionManager(); JobDefinitionEntity jobDefinition = jobDefinitionManager.findById(jobDefinitionId); if (jobDefinition != null) { if (jobDefinition.getProcessDefinitionId() != null) { return getDeploymentIdByProcessDefinition(commandContext, jobDefinition.getProcessDefinitionId()); } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetStateCmd.java
1
请完成以下Java代码
public void setOrderedData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(ic); final ConditionTypeSpecificInvoiceCandidateHandler handler = getSpecificHandler(term); ic.setDateOrdered(handler.calculateDateOrdered(ic)); final Quantity calculateQtyOrdered = handler.calculateQtyEntered(ic); ic.setQtyEntered(calculateQtyOrdered.toBigDecimal()); ic.setC_UOM_ID(calculateQtyOrdered.getUomId().getRepoId()); final ProductId productId = ProductId.ofRepoId(term.getM_Product_ID()); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(calculateQtyOrdered, productId); ic.setQtyOrdered(qtyInProductUOM.toBigDecimal()); } /** * <ul> * <li>QtyDelivered := QtyOrdered * <li>DeliveryDate := DateOrdered * <li>M_InOut_ID: untouched * </ul> * * @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate) */ @Override public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic) { HandlerTools.setDeliveredData(ic); } @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(ic);
final ConditionTypeSpecificInvoiceCandidateHandler handler = getSpecificHandler(term); return handler.calculatePriceAndTax(ic); } @Override public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { HandlerTools.setBPartnerData(ic); } @Override public void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(ic); final ConditionTypeSpecificInvoiceCandidateHandler handler = getSpecificHandler(term); final Consumer<I_C_Invoice_Candidate> defaultImplementation = super::setInvoiceScheduleAndDateToInvoice; handler.getInvoiceScheduleSetterFunction(defaultImplementation) .accept(ic); } private ConditionTypeSpecificInvoiceCandidateHandler getSpecificHandler(@NonNull final I_C_Flatrate_Term term) { final ConditionTypeSpecificInvoiceCandidateHandler handlerOrNull = conditionTypeSpecificInvoiceCandidateHandlers.get(term.getType_Conditions()); return Check.assumeNotNull(handlerOrNull, "The given term's condition-type={} has a not-null ConditionTypeSpecificInvoiceCandidateHandler; term={}", term.getType_Conditions(), term); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoicecandidate\FlatrateTerm_Handler.java
1
请完成以下Java代码
public boolean isInvoiceable() { return get_ValueAsBoolean(COLUMNNAME_IsInvoiceable); } @Override public void setLength (final @Nullable BigDecimal Length) { set_Value (COLUMNNAME_Length, Length); } @Override public BigDecimal getLength() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxLoadWeight (final @Nullable BigDecimal MaxLoadWeight) { set_Value (COLUMNNAME_MaxLoadWeight, MaxLoadWeight); } @Override public BigDecimal getMaxLoadWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxLoadWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID) { if (M_HU_PackingMaterial_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID); } @Override public int getM_HU_PackingMaterial_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setStackabilityFactor (final int StackabilityFactor) { set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor); } @Override public int getStackabilityFactor() { return get_ValueAsInt(COLUMNNAME_StackabilityFactor); } @Override public void setWidth (final @Nullable BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java
1
请完成以下Java代码
boolean empty() { return _units.empty(); } /** * 1的数量 * @return */ int numOnes() { return _numOnes; } /** * 大小 * @return */ int size() { return _size; } /** * 在末尾追加 */ void append() { if ((_size % UNIT_SIZE) == 0) { _units.add(0); } ++_size; } /** * 构建 */ void build() { _ranks = new int[_units.size()]; _numOnes = 0; for (int i = 0; i < _units.size(); ++i) { _ranks[i] = _numOnes; _numOnes += popCount(_units.get(i)); } } /** * 清空 */ void clear() { _units.clear(); _ranks = null; } /** * 整型大小 */
private static final int UNIT_SIZE = 32; // sizeof(int) * 8 /** * 1的数量 * @param unit * @return */ private static int popCount(int unit) { unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555); unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333); unit = ((unit >>> 4) + unit) & 0x0F0F0F0F; unit += unit >>> 8; unit += unit >>> 16; return unit & 0xFF; } /** * 储存空间 */ private AutoIntPool _units = new AutoIntPool(); /** * 是每个元素的1的个数的累加 */ private int[] _ranks; /** * 1的数量 */ private int _numOnes; /** * 大小 */ private int _size; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
1
请在Spring Boot框架中完成以下Java代码
static class SpringBootJdbcConfiguration extends AbstractJdbcConfiguration { private final ApplicationContext applicationContext; private final DataJdbcProperties properties; SpringBootJdbcConfiguration(ApplicationContext applicationContext, DataJdbcProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @Override protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException { return new EntityScanner(this.applicationContext).scan(Table.class); } @Override @Bean @ConditionalOnMissingBean public RelationalManagedTypes jdbcManagedTypes() throws ClassNotFoundException { return super.jdbcManagedTypes(); } @Override @Bean @ConditionalOnMissingBean public JdbcMappingContext jdbcMappingContext(Optional<NamingStrategy> namingStrategy, JdbcCustomConversions customConversions, RelationalManagedTypes jdbcManagedTypes) { return super.jdbcMappingContext(namingStrategy, customConversions, jdbcManagedTypes); } @Override @Bean @ConditionalOnMissingBean public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations, @Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, JdbcDialect dialect) { return super.jdbcConverter(mappingContext, operations, relationResolver, conversions, dialect); } @Override
@Bean @ConditionalOnMissingBean public JdbcCustomConversions jdbcCustomConversions() { return super.jdbcCustomConversions(); } @Override @Bean @ConditionalOnMissingBean public JdbcAggregateTemplate jdbcAggregateTemplate(ApplicationContext applicationContext, JdbcMappingContext mappingContext, JdbcConverter converter, DataAccessStrategy dataAccessStrategy) { return super.jdbcAggregateTemplate(applicationContext, mappingContext, converter, dataAccessStrategy); } @Override @Bean @ConditionalOnMissingBean public DataAccessStrategy dataAccessStrategyBean(NamedParameterJdbcOperations operations, JdbcConverter jdbcConverter, JdbcMappingContext context, JdbcDialect dialect) { return super.dataAccessStrategyBean(operations, jdbcConverter, context, dialect); } @Override @Bean @ConditionalOnMissingBean public JdbcDialect jdbcDialect(NamedParameterJdbcOperations operations) { DataJdbcDatabaseDialect dialect = this.properties.getDialect(); return (dialect != null) ? dialect.getJdbcDialect(operations.getJdbcOperations()) : super.jdbcDialect(operations); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-jdbc\src\main\java\org\springframework\boot\data\jdbc\autoconfigure\DataJdbcRepositoriesAutoConfiguration.java
2
请完成以下Java代码
public boolean isOpen() { return IncidentState.DEFAULT.getStateCode() == incidentState; } public boolean isDeleted() { return IncidentState.DELETED.getStateCode() == incidentState; } public boolean isResolved() { return IncidentState.RESOLVED.getStateCode() == incidentState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getFailedActivityId() { return failedActivityId;
} public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java
1
请完成以下Java代码
public static void defineNamedPersistenceManagerFactory(String pmfName) { pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); pm = pmf.getPersistenceManager(); } public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) { pmf = JDOHelper.getPersistenceManagerFactory(filePath); pm = pmf.getPersistenceManager(); } public static void closePersistenceManager() { if (pm != null && !pm.isClosed()) { pm.close(); } } public static void persistObject(Object obj) { Transaction tx = pm.currentTransaction(); try { tx.begin(); pm.makePersistent(obj); tx.commit(); } finally {
if (tx.isActive()) { tx.rollback(); } } } public static void queryPersonsInXML() { Query<Person> query = pm.newQuery(Person.class); List<Person> result = query.executeList(); System.out.println("name: " + result.get(0).getFirstName()); } public static void queryAnnotatedPersonsInXML() { Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class); List<AnnotadedPerson> result = query.executeList(); System.out.println("name: " + result.get(0).getFirstName()); } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\xml\MyApp.java
1
请完成以下Java代码
public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceEndTime() { orderBy(HistoricActivityInstanceQueryProperty.END); return this; } @Override public HistoricActivityInstanceQueryImpl orderByExecutionId() { orderBy(HistoricActivityInstanceQueryProperty.EXECUTION_ID); return this; } @Override public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceId() { orderBy(HistoricActivityInstanceQueryProperty.HISTORIC_ACTIVITY_INSTANCE_ID); return this; } @Override public HistoricActivityInstanceQueryImpl orderByProcessDefinitionId() { orderBy(HistoricActivityInstanceQueryProperty.PROCESS_DEFINITION_ID); return this; } @Override public HistoricActivityInstanceQueryImpl orderByProcessInstanceId() { orderBy(HistoricActivityInstanceQueryProperty.PROCESS_INSTANCE_ID); return this; } @Override public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceStartTime() { orderBy(HistoricActivityInstanceQueryProperty.START); return this; } @Override public HistoricActivityInstanceQuery orderByActivityId() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_ID); return this; } @Override public HistoricActivityInstanceQueryImpl orderByActivityName() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_NAME); return this; } @Override public HistoricActivityInstanceQueryImpl orderByActivityType() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_TYPE); return this; } @Override public HistoricActivityInstanceQueryImpl orderByTenantId() { orderBy(HistoricActivityInstanceQueryProperty.TENANT_ID); return this; } @Override public HistoricActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() {
return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public String getAssignee() { return assignee; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class MembershipContractRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); public Set<FlatrateTermId> retrieveMembershipSubscriptionIds( @NonNull final BPartnerId bpartnerId, @NonNull final Instant orgChangeDate, @NonNull final OrgId orgId) { return queryMembershipRunningSubscription(bpartnerId, orgChangeDate, orgId) .idsAsSet(FlatrateTermId::ofRepoId); } public IQuery<I_C_Flatrate_Term> queryMembershipRunningSubscription( @NonNull final BPartnerId bPartnerId, @NonNull final Instant orgChangeDate, @NonNull final OrgId orgId) { final IQuery<I_M_Product> membershipProductQuery = queryMembershipProducts(orgId); return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId) .addInSubQueryFilter(I_C_Flatrate_Term.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, membershipProductQuery) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, CompareQueryFilter.Operator.GREATER, orgChangeDate) .create(); } public IQuery<I_M_Product> queryMembershipProducts(@NonNull final OrgId orgId) { return queryBL.createQueryBuilder(I_M_Product.class) .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Org_ID, orgId) .addNotEqualsFilter(I_M_Product.COLUMNNAME_C_CompensationGroup_Schema_ID, null) .addNotEqualsFilter(I_M_Product.COLUMNNAME_C_CompensationGroup_Schema_Category_ID, null) .create(); }
public ImmutableSet<OrderId> retrieveMembershipOrderIds( @NonNull final OrgId orgId, @NonNull final Instant orgChangeDate) { final IQuery<I_M_Product> membershipProductQuery = queryMembershipProducts(orgId); return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId) .addInSubQueryFilter(I_C_Flatrate_Term.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, membershipProductQuery) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, CompareQueryFilter.Operator.GREATER, orgChangeDate) .andCollect(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, I_C_Order.class) .addEqualsFilter(I_C_Order.COLUMNNAME_AD_Org_ID, orgId) .create() .idsAsSet(OrderId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\repository\MembershipContractRepository.java
2
请完成以下Java代码
public OrderUserNotifications notifyOrderCompleted(@NonNull final I_C_Order order) { final NotificationRequest request = NotificationRequest.builder() .order(order).build(); return notifyOrderCompleted(request); } public OrderUserNotifications notifyOrderCompleted(@NonNull final NotificationRequest request) { final I_C_Order order = request.getOrder(); final Set<UserId> recipientUserIds = Optional .ofNullable(request.getRecipientUserIds()) .orElse(extractRecipientUserIdsFromOrder(order)); final ADMessageAndParams adMessageAndParams = Optional .ofNullable(request.getAdMessageAndParams()) .orElse(extractOrderCompletedADMessageAndParams(order)); try { postNotifications(createOrderCompletedEvents( order, recipientUserIds, adMessageAndParams)); } catch (final Exception ex) { logger.warn("Failed creating event for " + order + ". Ignored.", ex); } return this; } private List<UserNotificationRequest> createOrderCompletedEvents( @NonNull final I_C_Order order, @NonNull final Set<UserId> recipientUserIds, @NonNull final ADMessageAndParams adMessageAndParams) { Check.assumeNotEmpty(recipientUserIds, "recipientUserIds is not empty"); return recipientUserIds.stream() .filter(Objects::nonNull) .map(recipientUserId -> newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(adMessageAndParams.getAdMessage()) .contentADMessageParams(adMessageAndParams.getParams()) .targetAction(TargetRecordAction.of(TableRecordReference.of(order))) .build()) .collect(ImmutableList.toImmutableList()); }
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC); } private static ADMessageAndParams extractOrderCompletedADMessageAndParams(final I_C_Order order) { final I_C_BPartner bpartner = Services.get(IOrderBL.class).getBPartner(order); return ADMessageAndParams.builder() .adMessage(order.isSOTrx() ? MSG_SalesOrderCompleted : MSG_PurchaseOrderCompleted) .param(TableRecordReference.of(order)) .param(bpartner.getValue()) .param(bpartner.getName()) .build(); } private static Set<UserId> extractRecipientUserIdsFromOrder(final I_C_Order order) { final Integer createdBy = InterfaceWrapperHelper.getValueOrNull(order, "CreatedBy"); final UserId recipientUserId = createdBy == null ? null : UserId.ofRepoIdOrNull(createdBy); return recipientUserId != null ? ImmutableSet.of(recipientUserId) : ImmutableSet.of(); } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } @Value @Builder public static class NotificationRequest { @NonNull I_C_Order order; @Nullable Set<UserId> recipientUserIds; @Nullable ADMessageAndParams adMessageAndParams; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\event\OrderUserNotifications.java
1
请在Spring Boot框架中完成以下Java代码
public static void setOfficeExportNotesValue(Boolean officeExportNotes) { ConfigConstants.officeExportNotes = officeExportNotes; } public static Boolean getOfficeDocumentOpenPasswords() { return officeDocumentOpenPasswords; } @Value("${office.documentopenpasswords:true}") public void setDocumentOpenPasswords(Boolean officeDocumentOpenPasswords) { setOfficeDocumentOpenPasswordsValue(officeDocumentOpenPasswords); } public static void setOfficeDocumentOpenPasswordsValue(Boolean officeDocumentOpenPasswords) { ConfigConstants.officeDocumentOpenPasswords = officeDocumentOpenPasswords; } /** * 以下为首页显示 */ public static String getBeian() { return beian; } @Value("${beian:default}") public void setBeian(String beian) { setBeianValue(beian); } public static void setBeianValue(String beian) { ConfigConstants.beian = beian; } public static String getHomePageNumber() { return homePageNumber; } @Value("${home.pagenumber:1}") public void setHomePageNumber(String homePageNumber) { setHomePageNumberValue(homePageNumber); } public static void setHomePageNumberValue(String homePageNumber) { ConfigConstants.homePageNumber = homePageNumber; } public static String getHomePagination() {
return homePagination; } @Value("${home.pagination:true}") public void setHomePagination(String homePagination) { setHomePaginationValue(homePagination); } public static void setHomePaginationValue(String homePagination) { ConfigConstants.homePagination = homePagination; } public static String getHomePageSize() { return homePageSize; } @Value("${home.pagesize:15}") public void setHomePageSize(String homePageSize) { setHomePageSizeValue(homePageSize); } public static void setHomePageSizeValue(String homePageSize) { ConfigConstants.homePageSize = homePageSize; } public static String getHomeSearch() { return homeSearch; } @Value("${home.search:1}") public void setHomeSearch(String homeSearch) { setHomeSearchValue(homeSearch); } public static void setHomeSearchValue(String homeSearch) { ConfigConstants.homeSearch = homeSearch; } }
repos\kkFileView-master\server\src\main\java\cn\keking\config\ConfigConstants.java
2
请完成以下Java代码
public void execute(DelegateExecution execution) { ActivityExecution activityExecution = (ActivityExecution) execution; ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) { ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(scriptTaskId, execution.getProcessDefinitionId()); if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT)) { String overrideScript = taskElementProperties.get(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT).asString(); if (StringUtils.isNotEmpty(overrideScript) && !overrideScript.equals(script)) { script = overrideScript; } } } boolean noErrors = true; try { Object result = scriptingEngines.evaluate(script, language, execution, storeScriptVariables); if (resultVariable != null) { execution.setVariable(resultVariable, result); } } catch (ActivitiException e) { LOGGER.warn("Exception while executing {} : {}", activityExecution.getActivity().getId(), e.getMessage());
noErrors = false; Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause instanceof BpmnError) { ErrorPropagation.propagateError((BpmnError) rootCause, activityExecution); } else { throw e; } } if (noErrors) { leave(activityExecution); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\ScriptTaskActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) { return null; } /** * init --HeaderStyle * * @param workbook * @return */ private CellStyle initHeaderStyle(Workbook workbook) { CellStyle style = getBaseCellStyle(workbook); style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true)); return style; } /** * init-TitleStyle * * @param workbook * @return */ private CellStyle initTitleStyle(Workbook workbook) { CellStyle style = getBaseCellStyle(workbook); style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false)); // ForegroundColor style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); return style; } /** * BaseCellStyle * * @return */ private CellStyle getBaseCellStyle(Workbook workbook) { CellStyle style = workbook.createCellStyle(); style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setWrapText(true); return style; } /** * Font * * @param size * @param isBold * @return */ private Font getFont(Workbook workbook, short size, boolean isBold) { Font font = workbook.createFont(); font.setFontName("宋体"); font.setBold(isBold); font.setFontHeightInPoints(size); return font; } }
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\service\ExcelExportStyler.java
2
请完成以下Java代码
public class WordInfo { /** * 左邻接字集合 */ Map<Character, int[]> left; /** * 右邻接字集合 */ Map<Character, int[]> right; /** * 词语 */ public String text; /** * 词频 */ public int frequency; float p; float leftEntropy; float rightEntropy; /** * 互信息 */ public float aggregation; /** * 信息熵 */ public float entropy; WordInfo(String text) { this.text = text; left = new TreeMap<Character, int[]>(); right = new TreeMap<Character, int[]>(); aggregation = Float.MAX_VALUE; } private static void increaseFrequency(char c, Map<Character, int[]> storage) { int[] freq = storage.get(c); if (freq == null) { freq = new int[]{1}; storage.put(c, freq); } else { ++freq[0]; } } private float computeEntropy(Map<Character, int[]> storage) { float sum = 0; for (Map.Entry<Character, int[]> entry : storage.entrySet()) { float p = entry.getValue()[0] / (float) frequency; sum -= p * Math.log(p); } return sum; } void update(char left, char right) { ++frequency; increaseFrequency(left, this.left); increaseFrequency(right, this.right);
} void computeProbabilityEntropy(int length) { p = frequency / (float) length; leftEntropy = computeEntropy(left); rightEntropy = computeEntropy(right); entropy = Math.min(leftEntropy, rightEntropy); } void computeAggregation(Map<String, WordInfo> word_cands) { if (text.length() == 1) { aggregation = (float) Math.sqrt(p); return; } for (int i = 1; i < text.length(); ++i) { aggregation = Math.min(aggregation, p / word_cands.get(text.substring(0, i)).p / word_cands.get(text.substring(i)).p); } } @Override public String toString() { return text; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\WordInfo.java
1
请完成以下Java代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { boolean alreadyPrefixed = exchange.getAttributeOrDefault(GATEWAY_ALREADY_PREFIXED_ATTR, false); if (alreadyPrefixed) { return chain.filter(exchange); } exchange.getAttributes().put(GATEWAY_ALREADY_PREFIXED_ATTR, true); ServerHttpRequest req = exchange.getRequest(); addOriginalRequestUrl(exchange, req.getURI()); Map<String, String> uriVariables = getUriTemplateVariables(exchange); URI uri = uriTemplate.expand(uriVariables); String newPath = uri.getRawPath() + req.getURI().getRawPath(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri); ServerHttpRequest request = req.mutate().path(newPath).build(); if (log.isTraceEnabled()) { log.trace("Prefixed URI with: " + config.prefix + " -> " + request.getURI()); } return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() {
return filterToStringCreator(PrefixPathGatewayFilterFactory.this).append("prefix", config.getPrefix()) .toString(); } }; } public static class Config { private @Nullable String prefix; public @Nullable String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\PrefixPathGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
private static String buildReportFilename(@NonNull final JasperPrint jasperPrint, @NonNull final OutputType outputType) { final String fileBasename = FileUtil.stripIllegalCharacters(jasperPrint.getName()); return FileUtil.changeFileExtension(fileBasename, outputType.getFileExtension()); } private ReportResult exportAsJasperPrint(final JasperPrint jasperPrint) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(jasperPrint); return ReportResult.builder() .outputType(OutputType.JasperPrint) .reportFilename(buildReportFilename(jasperPrint, OutputType.JasperPrint)) .reportContentBase64(Util.encodeBase64(out.toByteArray())) .build(); } private ReportResult exportAsExcel(final JasperPrint jasperPrint) throws JRException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final MetasJRXlsExporter exporter = new MetasJRXlsExporter(); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out); // Output exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); // Input // Make sure our cells will be locked by default // and assume that cells which shall not be locked are particularly specified. jasperPrint.setProperty(XlsReportConfiguration.PROPERTY_CELL_LOCKED, "true"); // there are cases when we don't want the cells to be blocked by password // in those cases we put in jrxml the password property with empty value, which will indicate we don't want password // if there is no such property we take default password. If empty we set no password and if set, we use that password from the report //noinspection StatementWithEmptyBody
if (jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD) == null) { // do nothing; } else if (jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD).isEmpty()) { exporter.setParameter(JRXlsAbstractExporterParameter.PASSWORD, null); } else { exporter.setParameter(JRXlsAbstractExporterParameter.PASSWORD, jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD)); } exporter.exportReport(); return ReportResult.builder() .outputType(OutputType.XLS) .reportContentBase64(Util.encodeBase64(out.toByteArray())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JasperEngine.java
2
请在Spring Boot框架中完成以下Java代码
public class FlowJobDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job flowJob() { return jobBuilderFactory.get("flowJob") .start(flow()) .next(step3()) .end() .build(); } private Step step1() { return stepBuilderFactory.get("step1") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤一操作。。。"); return RepeatStatus.FINISHED; }).build(); }
private Step step2() { return stepBuilderFactory.get("step2") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤二操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step3() { return stepBuilderFactory.get("step3") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤三操作。。。"); return RepeatStatus.FINISHED; }).build(); } // 创建一个flow对象,包含若干个step private Flow flow() { return new FlowBuilder<Flow>("flow") .start(step1()) .next(step2()) .build(); } }
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\FlowJobDemo.java
2
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Usable Life - Months. @param UseLifeMonths Months of the usable life of the asset */ public void setUseLifeMonths (int UseLifeMonths) { set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths)); } /** Get Usable Life - Months. @return Months of the usable life of the asset */ public int getUseLifeMonths () { Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths); if (ii == null) return 0; return ii.intValue(); }
/** Set Usable Life - Years. @param UseLifeYears Years of the usable life of the asset */ public void setUseLifeYears (int UseLifeYears) { set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears)); } /** Get Usable Life - Years. @return Years of the usable life of the asset */ public int getUseLifeYears () { Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears); 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_A_Asset_Group_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public ClientProviderType getClientProviderType() { return this.clientProviderType; } public void setClientProviderType(ClientProviderType clientProviderType) { this.clientProviderType = clientProviderType; } public @Nullable String getApiKey() { return this.apiKey; } public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; }
public @Nullable String getAccountId() { return this.accountId; } public void setAccountId(@Nullable String accountId) { this.accountId = accountId; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicProperties.java
2
请完成以下Java代码
public String getTour() { return tour; } /** * Sets the value of the tour property. * * @param value * allowed object is * {@link String } * */ public void setTour(String value) { this.tour = value; } /** * Gets the value of the grund property. * * @return * possible object is * {@link VerfuegbarkeitDefektgrund } * */ public VerfuegbarkeitDefektgrund getGrund() {
return grund; } /** * Sets the value of the grund property. * * @param value * allowed object is * {@link VerfuegbarkeitDefektgrund } * */ public void setGrund(VerfuegbarkeitDefektgrund value) { this.grund = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitAnteil.java
1
请完成以下Java代码
public synchronized boolean isEmpty() { return false; } @Override public synchronized Enumeration<Object> keys() { // TODO: implement for GridField values too return ctx.keys(); } @Override public Set<Object> keySet() { // TODO: implement for GridField values too return ctx.keySet(); } @Override public synchronized Object put(Object key, Object value) { if (gridTab == null) throw new IllegalStateException("Method not supported (gridTab is null)"); if (gridTab.getCurrentRow() != row) { return ctx.put(key, value); } String columnName = getColumnName(key); if (columnName == null) { return ctx.put(key, value); } GridField field = gridTab.getField(columnName); if (field == null) { return ctx.put(key, value); } Object valueOld = field.getValue(); field.setValue(value, false); // inserting=false return valueOld; } @Override public synchronized void putAll(Map<? extends Object, ? extends Object> t) { for (Map.Entry<? extends Object, ? extends Object> e : t.entrySet()) put(e.getKey(), e.getValue()); }
@Override public synchronized Object remove(Object key) { // TODO: implement for GridField values too return ctx.remove(key); } @Override public synchronized int size() { // TODO: implement for GridField values too return ctx.size(); } @Override public synchronized String toString() { // TODO: implement for GridField values too return ctx.toString(); } @Override public Collection<Object> values() { return ctx.values(); } @Override public String getProperty(String key) { // I need to override this method, because Properties.getProperty method // is calling super.get() instead of get() Object oval = get(key); return oval == null ? null : oval.toString(); } @Override public String get_ValueAsString(String variableName) { final int windowNo = getWindowNo(); final int tabNo = getTabNo(); // Check value at Tab level, fallback to Window level final String value = Env.getContext(this, windowNo, tabNo, variableName, Scope.Window); return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\GridRowCtx.java
1
请完成以下Java代码
public String getMovieName() { return movieName; } public void setMovieName(String movieName) { this.movieName = movieName; } public Integer getReleaseYear() { return releaseYear; } public void setReleaseYear(Integer releaseYear) { this.releaseYear = releaseYear; } public String getLanguage() { return language;
} public void setLanguage(String language) { this.language = language; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\pojo\Movie.java
1
请完成以下Java代码
public void setClientId(String clientId) { this.clientId = clientId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getApprovedScopes() { return approvedScopes; } public void setApprovedScopes(String approvedScopes) { this.approvedScopes = approvedScopes; }
public String getRedirectUri() { return redirectUri; } public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } public LocalDateTime getExpirationDate() { return expirationDate; } public void setExpirationDate(LocalDateTime expirationDate) { this.expirationDate = expirationDate; } }
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\model\AuthorizationCode.java
1
请完成以下Java代码
private void removeDuplicatePIResultsWithoutPartner(final I_M_HU_PI_Item_Product originalHUPIItemProduct, final List<I_M_HU_PI_Item_Product> availableHUPIItemProducts) { final Iterator<I_M_HU_PI_Item_Product> it = availableHUPIItemProducts.iterator(); while (it.hasNext()) // scan if we have duplicates of the original with a C_BPartner & remove them { final I_M_HU_PI_Item_Product availableHUPIItemProduct = it.next(); final I_M_HU_PI_Version availableHUPIVersion = availableHUPIItemProduct.getM_HU_PI_Item().getM_HU_PI_Version(); final I_M_HU_PI_Version originalHUPIVersion = originalHUPIItemProduct.getM_HU_PI_Item().getM_HU_PI_Version(); if (availableHUPIVersion.getName().equals(originalHUPIVersion.getName()) && availableHUPIItemProduct.getM_Product_ID() == originalHUPIItemProduct.getM_Product_ID() && availableHUPIItemProduct.getC_UOM_ID() == originalHUPIItemProduct.getC_UOM_ID() && isSameQty(availableHUPIItemProduct, originalHUPIItemProduct)) { it.remove(); } } } /** * @return true if both {@link I_M_HU_PI_Item_Product}s have infinite capacity or if they have matching quantities */ private boolean isSameQty(final I_M_HU_PI_Item_Product piip1, final I_M_HU_PI_Item_Product piip2) { if (piip1.isInfiniteCapacity() != piip2.isInfiniteCapacity()) { return false; } final boolean isInfiniteCapacity = piip1.isInfiniteCapacity(); if (isInfiniteCapacity) { return true; } final BigDecimal piip1Qty = piip1.getQty(); final BigDecimal piip2Qty = piip2.getQty(); return piip1Qty != null && piip1Qty.compareTo(piip2Qty) == 0; } @Override public Optional<I_M_HU_PI_Item_Product> retrieveDefaultForProduct( @NonNull final ProductId productId, @Nullable final BPartnerId bpartnerId, @NonNull final ZonedDateTime date) { final IHUPIItemProductQuery query = createHUPIItemProductQuery(); query.setBPartnerId(bpartnerId);
query.setProductId(productId); query.setDate(date); query.setDefaultForProduct(true); final I_M_HU_PI_Item_Product huPIItemProduct = retrieveFirst(Env.getCtx(), query, ITrx.TRXNAME_None); return Optional.ofNullable(huPIItemProduct); } @Override public Optional<HUPIItemProductId> retrieveDefaultIdForProduct( @NonNull final ProductId productId, @Nullable final BPartnerId bpartnerId, @NonNull final ZonedDateTime date) { return retrieveDefaultForProduct(productId, bpartnerId, date) .map(huPiItemProduct -> HUPIItemProductId.ofRepoIdOrNull(huPiItemProduct.getM_HU_PI_Item_Product_ID())); } @Override @Nullable public I_M_HU_PI_Item_Product retrieveDefaultForProduct( @NonNull final ProductId productId, @NonNull final ZonedDateTime date) { final IHUPIItemProductQuery query = createHUPIItemProductQuery(); query.setProductId(productId); query.setDate(date); query.setDefaultForProduct(true); return retrieveFirst(Env.getCtx(), query, ITrx.TRXNAME_None); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductDAO.java
1
请完成以下Java代码
public class WebClientTimeoutProvider { public static WebClient defaultWebClient() { HttpClient httpClient = HttpClient.create(); return buildWebClient(httpClient); } public WebClient responseTimeoutClient() { HttpClient httpClient = HttpClient.create() .responseTimeout(Duration.ofSeconds(1)); return buildWebClient(httpClient); } public WebClient connectionTimeoutClient() { HttpClient httpClient = HttpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); return buildWebClient(httpClient); } public WebClient connectionTimeoutWithKeepAliveClient() { HttpClient httpClient = HttpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .option(EpollChannelOption.TCP_KEEPIDLE, 300) .option(EpollChannelOption.TCP_KEEPINTVL, 60) .option(EpollChannelOption.TCP_KEEPCNT, 8); return buildWebClient(httpClient); } public WebClient readWriteTimeoutClient() { HttpClient httpClient = HttpClient.create() .doOnConnected(conn -> conn .addHandler(new ReadTimeoutHandler(5, TimeUnit.SECONDS)) .addHandler(new WriteTimeoutHandler(5))); return buildWebClient(httpClient); }
public WebClient sslTimeoutClient() { HttpClient httpClient = HttpClient.create() .secure(spec -> spec .sslContext(SslContextBuilder.forClient()) .defaultConfiguration(SslProvider.DefaultConfigurationType.TCP) .handshakeTimeout(Duration.ofSeconds(30)) .closeNotifyFlushTimeout(Duration.ofSeconds(10)) .closeNotifyReadTimeout(Duration.ofSeconds(10))); return buildWebClient(httpClient); } public WebClient proxyTimeoutClient() { HttpClient httpClient = HttpClient.create() .proxy(spec -> spec .type(ProxyProvider.Proxy.HTTP) .host("http://proxy") .port(8080) .connectTimeoutMillis(3000)); return buildWebClient(httpClient); } private WebClient buildWebClient(HttpClient httpClient) { return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\timeout\WebClientTimeoutProvider.java
1
请完成以下Java代码
public class Book { private Long id; private String name; private BigDecimal price; public Book() { } public Book(Long id, String name, BigDecimal price) { this.id = id; this.name = name; this.price = price; } public Book(String name, BigDecimal price) { this.name = name; this.price = price; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}'; } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\Book.java
1
请完成以下Java代码
public static final boolean is08793_HUSelectModel_ResetCacheBeforeProcess() { final String SYSCONFIG_08793_HUSelectModel_ResetCacheBeforeProcess = "de.metas.handlingunits.client.terminal.select.model.AbstractHUSelectModel.ResetCacheBeforeProcess"; final boolean DEFAULT_08793_HUSelectModel_ResetCacheBeforeProcess = false; final boolean resetCacheBeforeProcessing = Services.get(ISysConfigBL.class).getBooleanValue( SYSCONFIG_08793_HUSelectModel_ResetCacheBeforeProcess, DEFAULT_08793_HUSelectModel_ResetCacheBeforeProcess); return resetCacheBeforeProcessing; } private static final String SYSCONFIG_AttributeStorageFailOnDisposed = "de.metas.handlingunits.attribute.storage.IAttributeStorage.FailOnDisposed"; private static final boolean DEFAULT_AttributeStorageFailOnDisposed = true; public static final boolean isAttributeStorageFailOnDisposed() {
return Services.get(ISysConfigBL.class).getBooleanValue( SYSCONFIG_AttributeStorageFailOnDisposed, DEFAULT_AttributeStorageFailOnDisposed); } public static final String DIM_PP_Order_ProductAttribute_To_Transfer = "PP_Order_ProductAttribute_Transfer"; public static final String DIM_Barcode_Attributes = "DIM_Barcode_Attributes"; /** * @task http://dewiki908/mediawiki/index.php/09106_Material-Vorgangs-ID_nachtr%C3%A4glich_erfassen_%28101556035702%29 */ public static final String PARAM_CHANGE_HU_MAterial_Tracking_ID = M_Material_Tracking_CreateOrUpdate_ID.class.getSimpleName() + ".CHANGE_HUs"; }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUConstants.java
1
请完成以下Java代码
public ExternalTaskQueryTopicBuilder variables(String... variables) { // don't use plain Arrays.asList since this returns an instance of a different list class // that is private and may mess mybatis queries up if (variables != null) { currentInstruction.setVariablesToFetch(new ArrayList<String>(Arrays.asList(variables))); } return this; } public ExternalTaskQueryTopicBuilder variables(List<String> variables) { currentInstruction.setVariablesToFetch(variables); return this; } public ExternalTaskQueryTopicBuilder processInstanceVariableEquals(Map<String, Object> variables) { currentInstruction.setFilterVariables(variables); return this; } public ExternalTaskQueryTopicBuilder processInstanceVariableEquals(String name, Object value) { currentInstruction.addFilterVariable(name, value); return this; } public ExternalTaskQueryTopicBuilder businessKey(String businessKey) { currentInstruction.setBusinessKey(businessKey); return this; } public ExternalTaskQueryTopicBuilder processDefinitionId(String processDefinitionId) { currentInstruction.setProcessDefinitionId(processDefinitionId); return this; } public ExternalTaskQueryTopicBuilder processDefinitionIdIn(String... processDefinitionIds) { currentInstruction.setProcessDefinitionIds(processDefinitionIds); return this; } public ExternalTaskQueryTopicBuilder processDefinitionKey(String processDefinitionKey) { currentInstruction.setProcessDefinitionKey(processDefinitionKey); return this; } public ExternalTaskQueryTopicBuilder processDefinitionKeyIn(String... processDefinitionKeys) { currentInstruction.setProcessDefinitionKeys(processDefinitionKeys); return this;
} public ExternalTaskQueryTopicBuilder processDefinitionVersionTag(String processDefinitionVersionTag) { currentInstruction.setProcessDefinitionVersionTag(processDefinitionVersionTag); return this; } public ExternalTaskQueryTopicBuilder withoutTenantId() { currentInstruction.setTenantIds(null); return this; } public ExternalTaskQueryTopicBuilder tenantIdIn(String... tenantIds) { currentInstruction.setTenantIds(tenantIds); return this; } protected void submitCurrentInstruction() { if (currentInstruction != null) { this.instructions.put(currentInstruction.getTopicName(), currentInstruction); } } public ExternalTaskQueryTopicBuilder enableCustomObjectDeserialization() { currentInstruction.setDeserializeVariables(true); return this; } public ExternalTaskQueryTopicBuilder localVariables() { currentInstruction.setLocalVariables(true); return this; } public ExternalTaskQueryTopicBuilder includeExtensionProperties() { currentInstruction.setIncludeExtensionProperties(true); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\ExternalTaskQueryTopicBuilderImpl.java
1
请完成以下Java代码
public void setC_BPartner_Customer_ID (int C_BPartner_Customer_ID) { if (C_BPartner_Customer_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Customer_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Customer_ID, Integer.valueOf(C_BPartner_Customer_ID)); } @Override public int getC_BPartner_Customer_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Customer_ID); } @Override public void setDateProjected (java.sql.Timestamp DateProjected) { set_ValueNoCheck (COLUMNNAME_DateProjected, DateProjected); } @Override public java.sql.Timestamp getDateProjected() { return get_ValueAsTimestamp(COLUMNNAME_DateProjected); } @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() {
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public java.math.BigDecimal getQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStorageAttributesKey (java.lang.String StorageAttributesKey) { set_ValueNoCheck (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_ATP_QueryResult.java
1
请完成以下Java代码
private static final String buildMsg(final String message, final Object documentLineModel, final I_M_HU hu) { final StringBuilder sb = new StringBuilder(); if (!Check.isEmpty(message, true)) { sb.append(message.trim()); } // // Document Line Info if (documentLineModel != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append("@Line@: ").append(documentLineModel);
} // // HU Info if (hu != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append("@M_HU_ID@: ").append(hu.getValue()).append(" (ID=").append(hu.getM_HU_ID()).append(")"); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\exceptions\HUNotAssignableException.java
1
请完成以下Java代码
public BigDecimal getQtySupply_PP_Order_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_PP_Order_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupply_PurchaseOrder_AtDate (final @Nullable BigDecimal QtySupply_PurchaseOrder_AtDate) { set_Value (COLUMNNAME_QtySupply_PurchaseOrder_AtDate, QtySupply_PurchaseOrder_AtDate); } @Override public BigDecimal getQtySupply_PurchaseOrder_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_PurchaseOrder_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyRequired_AtDate (final @Nullable BigDecimal QtySupplyRequired_AtDate) { set_Value (COLUMNNAME_QtySupplyRequired_AtDate, QtySupplyRequired_AtDate); } @Override public BigDecimal getQtySupplyRequired_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyRequired_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplySum_AtDate (final @Nullable BigDecimal QtySupplySum_AtDate)
{ set_Value (COLUMNNAME_QtySupplySum_AtDate, QtySupplySum_AtDate); } @Override public BigDecimal getQtySupplySum_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplySum_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyToSchedule_AtDate (final @Nullable BigDecimal QtySupplyToSchedule_AtDate) { set_Value (COLUMNNAME_QtySupplyToSchedule_AtDate, QtySupplyToSchedule_AtDate); } @Override public BigDecimal getQtySupplyToSchedule_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyToSchedule_AtDate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit.java
1
请在Spring Boot框架中完成以下Java代码
public static class App2ConfigurationAdapter { @Bean public SecurityFilterChain filterChainApp2(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.securityMatcher("/user/**") .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(mvcMatcherBuilder.pattern("/user/**")).hasRole("USER")) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginProcessingUrl("/user/login") .failureUrl("/userLogin?error=loginError") .defaultSuccessUrl("/user/myUserPage")) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/user/logout") .logoutSuccessUrl("/multipleHttpLinks") .deleteCookies("JSESSIONID")) .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.defaultAuthenticationEntryPointFor(loginUrlauthenticationEntryPointWithWarning(), new AntPathRequestMatcher("/user/private/**")) .defaultAuthenticationEntryPointFor(loginUrlauthenticationEntryPoint(), new AntPathRequestMatcher("/user/general/**")) .accessDeniedPage("/403")) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public AuthenticationEntryPoint loginUrlauthenticationEntryPoint(){ return new LoginUrlAuthenticationEntryPoint("/userLogin"); }
@Bean public AuthenticationEntryPoint loginUrlauthenticationEntryPointWithWarning(){ return new LoginUrlAuthenticationEntryPoint("/userLoginWithWarning"); } } @Configuration @Order(3) public static class App3ConfigurationAdapter { @Bean public SecurityFilterChain filterChainApp3(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.securityMatcher("/guest/**") .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(mvcMatcherBuilder.pattern("/guest/**")).permitAll()); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\multipleentrypoints\MultipleEntryPointsSecurityConfig.java
2
请完成以下Java代码
public class AstBracket extends AstProperty { protected final AstNode property; public AstBracket(AstNode base, AstNode property, boolean lvalue, boolean strict) { this(base, property, lvalue, strict, false); } public AstBracket(AstNode base, AstNode property, boolean lvalue, boolean strict, boolean ignoreReturnType) { super(base, lvalue, strict, ignoreReturnType); this.property = property; } @Override protected Object getProperty(Bindings bindings, ELContext context) throws ELException { return property.eval(bindings, context); } @Override public String toString() { return "[...]";
} @Override public void appendStructure(StringBuilder b, Bindings bindings) { getChild(0).appendStructure(b, bindings); b.append("["); getChild(1).appendStructure(b, bindings); b.append("]"); } public int getCardinality() { return 2; } @Override public AstNode getChild(int i) { return i == 1 ? property : super.getChild(i); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstBracket.java
1
请完成以下Java代码
public void setValueMax (String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Value. @return Maximum Value for a field */ public String getValueMax () { return (String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Value. @param ValueMin Minimum Value for a field */ public void setValueMin (String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Value. @return Minimum Value for a field */ public String getValueMin () { return (String)get_Value(COLUMNNAME_ValueMin); }
/** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public void setVFormat (String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public String getVFormat () { return (String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute.java
1
请完成以下Java代码
public void setQtyShipped_CatchWeight (final @Nullable BigDecimal QtyShipped_CatchWeight) { set_Value (COLUMNNAME_QtyShipped_CatchWeight, QtyShipped_CatchWeight); } @Override public BigDecimal getQtyShipped_CatchWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped_CatchWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyShipped_CatchWeight_UOM_ID (final int QtyShipped_CatchWeight_UOM_ID) { if (QtyShipped_CatchWeight_UOM_ID < 1) set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, null); else set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, QtyShipped_CatchWeight_UOM_ID); } @Override public int getQtyShipped_CatchWeight_UOM_ID() { return get_ValueAsInt(COLUMNNAME_QtyShipped_CatchWeight_UOM_ID); } @Override public void setRecord_ID (final int Record_ID)
{ if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setReplicationTrxErrorMsg (final @Nullable java.lang.String ReplicationTrxErrorMsg) { throw new IllegalArgumentException ("ReplicationTrxErrorMsg is virtual column"); } @Override public java.lang.String getReplicationTrxErrorMsg() { return get_ValueAsString(COLUMNNAME_ReplicationTrxErrorMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCand.java
1
请完成以下Java代码
public Builder displayName(@NonNull final ITranslatableString displayName) { this.displayName = TranslatableStrings.copyOf(displayName); return this; } public Builder displayName(final String displayName) { this.displayName = TranslatableStrings.constant(displayName); return this; } public Builder displayName(final AdMessageKey displayName) { return displayName(TranslatableStrings.adMessage(displayName)); } public ITranslatableString getDisplayName() { return displayName; } public Builder lookupDescriptor(@NonNull final Optional<LookupDescriptor> lookupDescriptor)
{ this.lookupDescriptor = lookupDescriptor; return this; } public Builder lookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor) { return lookupDescriptor(Optional.ofNullable(lookupDescriptor)); } public Builder lookupDescriptor(@NonNull final UnaryOperator<LookupDescriptor> mapper) { if (this.lookupDescriptor!= null) // don't replace with isPresent() since it could be null at this point { return lookupDescriptor(this.lookupDescriptor.map(mapper)); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParamDescriptor.java
1
请完成以下Java代码
public boolean isOverwriteUser1 () { Object oo = get_Value(COLUMNNAME_OverwriteUser1); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Overwrite User2. @param OverwriteUser2 Overwrite the account segment User 2 with the value specified */ @Override public void setOverwriteUser2 (boolean OverwriteUser2) { set_Value (COLUMNNAME_OverwriteUser2, Boolean.valueOf(OverwriteUser2)); } /** Get Overwrite User2. @return Overwrite the account segment User 2 with the value specified */ @Override public boolean isOverwriteUser2 () { Object oo = get_Value(COLUMNNAME_OverwriteUser2); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Percent. @param Percent Percentage */ @Override public void setPercent (java.math.BigDecimal Percent) { set_Value (COLUMNNAME_Percent, Percent); } /** Get Percent. @return Percentage */ @Override public java.math.BigDecimal getPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent); if (bd == null) return Env.ZERO; return bd; } @Override public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override
public void setUser1(org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } /** Set Nutzer 1. @param User1_ID User defined list element #1 */ @Override public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get Nutzer 1. @return User defined list element #1 */ @Override public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } /** Set Nutzer 2. @param User2_ID User defined list element #2 */ @Override public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get Nutzer 2. @return User defined list element #2 */ @Override public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_DistributionLine.java
1
请完成以下Java代码
public IReceiptScheduleProducerFactory registerProducer(final String tableName, final Class<? extends IReceiptScheduleProducer> producerClass) { Check.assumeNotEmpty(tableName, "tableName not empty"); Check.assumeNotNull(producerClass, "producerClass not null"); producerClasses .computeIfAbsent(tableName, tableNameKey -> new CopyOnWriteArrayList<>()) .addIfAbsent(producerClass); return this; } @Override public IReceiptScheduleWarehouseDestProvider getWarehouseDestProvider() { return warehouseDestProviders; } @Override public IReceiptScheduleProducerFactory registerWarehouseDestProvider(final IReceiptScheduleWarehouseDestProvider provider) { warehouseDestProviders.addProvider(provider); return this; } /** * Mutable composite {@link IReceiptScheduleWarehouseDestProvider} */ private static final class CompositeReceiptScheduleWarehouseDestProvider implements IReceiptScheduleWarehouseDestProvider { private final IReceiptScheduleWarehouseDestProvider defaultProvider; private final CopyOnWriteArrayList<IReceiptScheduleWarehouseDestProvider> providers = new CopyOnWriteArrayList<>(); private CompositeReceiptScheduleWarehouseDestProvider(final IReceiptScheduleWarehouseDestProvider defaultProvider) { super(); Check.assumeNotNull(defaultProvider, "Parameter defaultProvider is not null"); this.defaultProvider = defaultProvider;
} @Override public String toString() { return MoreObjects.toStringHelper(this) .add("providers", providers) .add("defaultProvider", defaultProvider) .toString(); } private void addProvider(final IReceiptScheduleWarehouseDestProvider provider) { Check.assumeNotNull(provider, "Parameter provider is not null"); providers.add(provider); } @Override public Optional<WarehouseId> getWarehouseDest(final IContext context) { return Stream.concat(providers.stream(), Stream.of(defaultProvider)) .map(provider -> provider.getWarehouseDest(context)) .map(warehouseDest -> warehouseDest.orElse(null)) .filter(Objects::nonNull) .findFirst(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleProducerFactory.java
1
请完成以下Java代码
public Observable<LogAggregate> call(Context context, Observable<MantisGroup<String, LogEvent>> mantisGroup) { return mantisGroup .window(duration, TimeUnit.MILLISECONDS) .flatMap(o -> o.groupBy(MantisGroup::getKeyValue) .flatMap(group -> group.reduce(0, (count, value) -> count = count + 1) .map((count) -> new LogAggregate(count, group.getKey())) )); } public static GroupToScalar.Config<String, LogEvent, LogAggregate> config(){ return new GroupToScalar.Config<String, LogEvent, LogAggregate>() .description("sum events for a log level") .codec(JacksonCodecs.pojo(LogAggregate.class)) .withParameters(getParameters()); }
public static List<ParameterDefinition<?>> getParameters() { List<ParameterDefinition<?>> params = new ArrayList<>(); params.add(new IntParameter() .name("LogAggregationDuration") .description("window size for aggregation in milliseconds") .validator(Validators.range(100, 10000)) .defaultValue(5000) .build()) ; return params; } }
repos\tutorials-master\netflix-modules\mantis\src\main\java\com\baeldung\netflix\mantis\stage\CountLogStage.java
1
请在Spring Boot框架中完成以下Java代码
public class RatingCacheRepository implements InitializingBean { @Autowired private LettuceConnectionFactory cacheConnectionFactory; private StringRedisTemplate redisTemplate; private ValueOperations<String, String> valueOps; private SetOperations<String, String> setOps; private ObjectMapper jsonMapper; public List<Rating> findCachedRatingsByBookId(Long bookId) { return setOps.members("book-" + bookId) .stream() .map(rtId -> { try { return jsonMapper.readValue(valueOps.get(rtId), Rating.class); } catch (IOException ex) { return null; } }) .collect(Collectors.toList()); } public Rating findCachedRatingById(Long ratingId) { try { return jsonMapper.readValue(valueOps.get("rating-" + ratingId), Rating.class); } catch (IOException e) { return null; } } public List<Rating> findAllCachedRatings() { List<Rating> ratings = null; ratings = redisTemplate.keys("rating*") .stream() .map(rtId -> { try { return jsonMapper.readValue(valueOps.get(rtId), Rating.class); } catch (IOException e) { return null; } }) .collect(Collectors.toList()); return ratings; } public boolean createRating(Rating persisted) { try { valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted)); setOps.add("book-" + persisted.getBookId(), "rating-" + persisted.getId()); return true;
} catch (JsonProcessingException ex) { return false; } } public boolean updateRating(Rating persisted) { try { valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted)); return true; } catch (JsonProcessingException e) { e.printStackTrace(); } return false; } public boolean deleteRating(Long ratingId) { Rating toDel; try { toDel = jsonMapper.readValue(valueOps.get("rating-" + ratingId), Rating.class); setOps.remove("book-" + toDel.getBookId(), "rating-" + ratingId); redisTemplate.delete("rating-" + ratingId); return true; } catch (IOException e) { e.printStackTrace(); } return false; } @Override public void afterPropertiesSet() throws Exception { this.redisTemplate = new StringRedisTemplate(cacheConnectionFactory); this.valueOps = redisTemplate.opsForValue(); this.setOps = redisTemplate.opsForSet(); jsonMapper = new ObjectMapper(); jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingCacheRepository.java
2
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Exclude. @param IsExclude Exclude access to the data - if not selected Include access to the data */ public void setIsExclude (boolean IsExclude) { set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude)); } /** Get Exclude. @return Exclude access to the data - if not selected Include access to the data */ public boolean isExclude () { Object oo = get_Value(COLUMNNAME_IsExclude); if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessProfile.java
1
请完成以下Java代码
public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return Env.ZERO; return bd; } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return Env.ZERO; return bd; } /** Set Gültig ab. @param ValidFrom Valid from including this date (first day) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Valid from including this date (first day) */
@Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Valid to including this date (last day) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Valid to including this date (last day) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Conversion_Rate.java
1
请完成以下Java代码
protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } /* * ------------------- GETTERS AND SETTERS ------------------- */ public List<ChannelDefinitionEntity> getChannelDefinitions() { return channelDefinitions; }
public EventDeploymentEntity getDeployment() { return deployment; } public void setDeployment(EventDeploymentEntity deployment) { this.deployment = deployment; } public ChannelModel getChannelModel() { return channelModel; } public void setChannelModel(ChannelModel channelModel) { this.channelModel = channelModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\parser\ChannelDefinitionParse.java
1
请完成以下Java代码
public ResponseEntity<Object> createQuartzJob(@Validated @RequestBody QuartzJob resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } // 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义 checkBean(resources.getBeanName()); quartzJobService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改定时任务") @ApiOperation("修改定时任务") @PutMapping @PreAuthorize("@el.check('timing:edit')") public ResponseEntity<Object> updateQuartzJob(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){ // 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义 checkBean(resources.getBeanName()); quartzJobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("更改定时任务状态") @ApiOperation("更改定时任务状态") @PutMapping(value = "/{id}") @PreAuthorize("@el.check('timing:edit')") public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id){ quartzJobService.updateIsPause(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("执行定时任务") @ApiOperation("执行定时任务") @PutMapping(value = "/exec/{id}") @PreAuthorize("@el.check('timing:edit')") public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id){ quartzJobService.execution(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} @Log("删除定时任务") @ApiOperation("删除定时任务") @DeleteMapping @PreAuthorize("@el.check('timing:del')") public ResponseEntity<Object> deleteQuartzJob(@RequestBody Set<Long> ids){ quartzJobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } private void checkBean(String beanName){ // 避免调用攻击者可以从SpringContextHolder获得控制jdbcTemplate类 // 并使用getDeclaredMethod调用jdbcTemplate的queryForMap函数,执行任意sql命令。 if(!SpringBeanHolder.getAllServiceBeanName().contains(beanName)){ throw new BadRequestException("非法的 Bean,请重新输入!"); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\rest\QuartzJobController.java
1