instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
private void updateSubCnt(Long menuId){ if(menuId != null){ int count = menuRepository.countByPid(menuId); menuRepository.updateSubCntById(count, menuId); } } /** * 清理缓存 * @param id 菜单ID */ public void delCaches(Long id){ List<User> users = userRepository.findByMenuId(id); redisUtils.del(CacheKey.MENU_ID + id); redisUtils.delByKeys(CacheKey.MENU_USER, users.stream().map(User::getId).collect(Collectors.toSet())); // 清除 Role 缓存 List<Role> roles = roleService.findInMenuId(new ArrayList<Long>(){{ add(id); }}); redisUtils.delByKeys(CacheKey.ROLE_ID, roles.stream().map(Role::getId).collect(Collectors.toSet())); } /** * 构建前端路由 * @param menuDTO / * @param menuVo / * @return /
*/ private static MenuVo getMenuVo(MenuDto menuDTO, MenuVo menuVo) { MenuVo menuVo1 = new MenuVo(); menuVo1.setMeta(menuVo.getMeta()); // 非外链 if(!menuDTO.getIFrame()){ menuVo1.setPath("index"); menuVo1.setName(menuVo.getName()); menuVo1.setComponent(menuVo.getComponent()); } else { menuVo1.setPath(menuDTO.getPath()); } return menuVo1; } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\MenuServiceImpl.java
2
请完成以下Java代码
public class EOFDetection { public String readWithFileInputStream(String pathFile) throws IOException { try (FileInputStream fis = new FileInputStream(pathFile); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { int data; while ((data = fis.read()) != -1) { baos.write(data); } return baos.toString(); } } public String readWithBufferedReader(String pathFile) throws IOException { try (FileInputStream fis = new FileInputStream(pathFile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader reader = new BufferedReader(isr)) { StringBuilder actualContent = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { actualContent.append(line); } return actualContent.toString(); } } public String readWithScanner(String pathFile) throws IOException { File file = new File(pathFile); Scanner scanner = new Scanner(file);
StringBuilder actualContent = new StringBuilder(); while (scanner.hasNext()) { String line = scanner.nextLine(); actualContent.append(line); } scanner.close(); return actualContent.toString(); } public String readFileWithFileChannelAndByteBuffer(String pathFile) throws IOException { try (FileInputStream fis = new FileInputStream(pathFile); FileChannel channel = fis.getChannel()) { ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); while (channel.read(buffer) != -1) { buffer.flip(); buffer.clear(); } return StandardCharsets.UTF_8.decode(buffer).toString(); } } }
repos\tutorials-master\core-java-modules\core-java-io-apis-2\src\main\java\com\baeldung\eofdetections\EOFDetection.java
1
请完成以下Java代码
public RedisCacheManager getInstance() { if (redisCacheManager == null) { redisCacheManager = SpringContextUtils.getBean(RedisCacheManager.class); } return redisCacheManager; } /** * 获取过期时间 * * @return */ public long getExpirationSecondTime(String name) { if (StringUtils.isEmpty(name)) { return 0; } CacheTime cacheTime = null; if (!CollectionUtils.isEmpty(cacheTimes)) { cacheTime = cacheTimes.get(name); } Long expiration = cacheTime != null ? cacheTime.getExpirationSecondTime() : defaultExpiration; return expiration < 0 ? 0 : expiration; } /** * 获取自动刷新时间 * * @return */ private long getPreloadSecondTime(String name) { // 自动刷新时间,默认是0 CacheTime cacheTime = null; if (!CollectionUtils.isEmpty(cacheTimes)) { cacheTime = cacheTimes.get(name); } Long preloadSecondTime = cacheTime != null ? cacheTime.getPreloadSecondTime() : 0; return preloadSecondTime < 0 ? 0 : preloadSecondTime; } /** * 创建缓存 * * @param cacheName 缓存名称 * @return */ @Override public CustomizedRedisCache getMissingCache(String cacheName) { // 有效时间,初始化获取默认的有效时间 Long expirationSecondTime = getExpirationSecondTime(cacheName); // 自动刷新时间,默认是0 Long preloadSecondTime = getPreloadSecondTime(cacheName); logger.info("缓存 cacheName:{},过期时间:{}, 自动刷新时间:{}", cacheName, expirationSecondTime, preloadSecondTime); // 是否在运行时创建Cache Boolean dynamic = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_DYNAMIC); // 是否允许存放NULL Boolean cacheNullValues = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_CACHENULLVALUES); return dynamic ? new CustomizedRedisCache(cacheName, (this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null), this.getRedisOperations(), expirationSecondTime, preloadSecondTime, cacheNullValues) : null; }
/** * 根据缓存名称设置缓存的有效时间和刷新时间,单位秒 * * @param cacheTimes */ public void setCacheTimess(Map<String, CacheTime> cacheTimes) { this.cacheTimes = (cacheTimes != null ? new ConcurrentHashMap<String, CacheTime>(cacheTimes) : null); } /** * 设置默认的过去时间, 单位:秒 * * @param defaultExpireTime */ @Override public void setDefaultExpiration(long defaultExpireTime) { super.setDefaultExpiration(defaultExpireTime); this.defaultExpiration = defaultExpireTime; } @Deprecated @Override public void setExpires(Map<String, Long> expires) { } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-2\src\main\java\com\xiaolyuh\redis\cache\CustomizedRedisCacheManager.java
1
请完成以下Java代码
public void deleteProcessedRequests() { final ApiRequestQuery apiRequestQuery = ApiRequestQuery.builder() .apiRequestStatusSet(ImmutableSet.of(Status.ERROR, Status.PROCESSED)) .build(); final ApiRequestIterator processedApiRequests = apiRequestAuditRepository.getByQuery(apiRequestQuery); if (!processedApiRequests.hasNext()) { return; } final ApiAuditConfigShortTimeIndex apiAuditConfigShortTimeIndex = new ApiAuditConfigShortTimeIndex(apiAuditConfigRepository); final Consumer<ApiRequestAudit> deleteIfTime = (apiRequestAudit) -> { if (isReadyForCleanup(apiRequestAudit, apiAuditConfigShortTimeIndex)) { deleteProcessedRequestInNewTrx(apiRequestAudit); } }; processedApiRequests.forEach(deleteIfTime); } private void deleteProcessedRequestInNewTrx(@NonNull final ApiRequestAudit apiRequestAudit) { trxManager.runInNewTrx(() -> deleteProcessedRequest(apiRequestAudit)); } private void deleteProcessedRequest(@NonNull final ApiRequestAudit apiRequestAudit) { apiAuditRequestLogDAO.deleteLogsByApiRequestId(apiRequestAudit.getIdNotNull()); apiResponseAuditRepository.getByRequestId(apiRequestAudit.getIdNotNull()) .stream() .map(ApiResponseAudit::getIdNotNull) .forEach(apiResponseAuditRepository::delete); apiRequestAuditRepository.deleteRequestAudit(apiRequestAudit.getIdNotNull()); } private boolean isReadyForCleanup( @NonNull final ApiRequestAudit apiRequestAudit, @NonNull final ApiAuditConfigShortTimeIndex apiAuditConfigIndex) { final ApiAuditConfig apiAuditConfig = apiAuditConfigIndex.getConfig(apiRequestAudit.getApiAuditConfigId()); final long daysSinceLastUpdate = (Instant.now().getEpochSecond() - apiRequestAudit.getTime().getEpochSecond()) / (60 * 60 * 24);
final boolean deleteProcessedRequest = (apiRequestAudit.isErrorAcknowledged() || Status.PROCESSED.equals(apiRequestAudit.getStatus())) && daysSinceLastUpdate > apiAuditConfig.getKeepRequestDays(); final boolean deleteErroredRequest = Status.ERROR.equals(apiRequestAudit.getStatus()) && daysSinceLastUpdate > apiAuditConfig.getKeepErroredRequestDays(); return deleteErroredRequest || deleteProcessedRequest; } @Value private static class ApiAuditConfigShortTimeIndex { Map<ApiAuditConfigId, ApiAuditConfig> configId2Config = new HashMap<>(); ApiAuditConfigRepository apiAuditConfigRepository; public ApiAuditConfigShortTimeIndex(final ApiAuditConfigRepository apiAuditConfigRepository) { this.apiAuditConfigRepository = apiAuditConfigRepository; } @NonNull public ApiAuditConfig getConfig(@NonNull final ApiAuditConfigId apiAuditConfigId) { return configId2Config.computeIfAbsent(apiAuditConfigId, apiAuditConfigRepository::getConfigById); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\ApiAuditCleanUpService.java
1
请完成以下Java代码
public void setC_Order_MFGWarehouse_Report(de.metas.fresh.model.I_C_Order_MFGWarehouse_Report C_Order_MFGWarehouse_Report) { set_ValueFromPO(COLUMNNAME_C_Order_MFGWarehouse_Report_ID, de.metas.fresh.model.I_C_Order_MFGWarehouse_Report.class, C_Order_MFGWarehouse_Report); } /** Set Order / MFG Warehouse report. @param C_Order_MFGWarehouse_Report_ID Order / MFG Warehouse report */ @Override public void setC_Order_MFGWarehouse_Report_ID (int C_Order_MFGWarehouse_Report_ID) { if (C_Order_MFGWarehouse_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Order_MFGWarehouse_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Order_MFGWarehouse_Report_ID, Integer.valueOf(C_Order_MFGWarehouse_Report_ID)); } /** Get Order / MFG Warehouse report. @return Order / MFG Warehouse report */ @Override public int getC_Order_MFGWarehouse_Report_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_MFGWarehouse_Report_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Order / MFG Warehouse report line. @param C_Order_MFGWarehouse_ReportLine_ID Order / MFG Warehouse report line */ @Override public void setC_Order_MFGWarehouse_ReportLine_ID (int C_Order_MFGWarehouse_ReportLine_ID) { if (C_Order_MFGWarehouse_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Order_MFGWarehouse_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Order_MFGWarehouse_ReportLine_ID, Integer.valueOf(C_Order_MFGWarehouse_ReportLine_ID)); } /** Get Order / MFG Warehouse report line. @return Order / MFG Warehouse report line */ @Override public int getC_Order_MFGWarehouse_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_MFGWarehouse_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); }
/** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Order_MFGWarehouse_ReportLine.java
1
请完成以下Java代码
public void init() { // @formatter:off personRepository = new ArrayList<>(Arrays.asList( new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), new Person(5, "Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)), new Person(6, "Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)))); // @formatter:on } @GetMapping("/person/{id}") @ResponseBody public Person findById(@PathVariable final int id) { return personRepository.get(id); }
@PostMapping("/person") @ResponseStatus(HttpStatus.OK) @ResponseBody public boolean insertPerson(@RequestBody final Person person) { return personRepository.add(person); } @GetMapping("/person") @ResponseBody public List<Person> findAll() { return personRepository; } }
repos\tutorials-master\spring-5\src\main\java\com\baeldung\jsonb\PersonController.java
1
请完成以下Java代码
Collection<String> getCommonNames() { return this.factories.keySet().stream().map(CommonStructuredLogFormat::getId).toList(); } @Nullable StructuredLogFormatter<E> get(Instantiator<?> instantiator, String format) { CommonStructuredLogFormat commonFormat = CommonStructuredLogFormat.forId(format); CommonFormatterFactory<E> factory = (commonFormat != null) ? this.factories.get(commonFormat) : null; return (factory != null) ? factory.createFormatter(instantiator) : null; } } /** * Factory used to create a {@link StructuredLogFormatter} for a given * {@link CommonStructuredLogFormat}. * * @param <E> the log event type */ @FunctionalInterface public interface CommonFormatterFactory<E> { /** * Create the {@link StructuredLogFormatter} instance. * @param instantiator instantiator that can be used to obtain arguments * @return a new {@link StructuredLogFormatter} instance */ StructuredLogFormatter<E> createFormatter(Instantiator<?> instantiator); } /** * {@link StructuredLoggingJsonMembersCustomizer.Builder} implementation. */ class JsonMembersCustomizerBuilder implements StructuredLoggingJsonMembersCustomizer.Builder<E> { private final @Nullable StructuredLoggingJsonProperties properties; private boolean nested; JsonMembersCustomizerBuilder(@Nullable StructuredLoggingJsonProperties properties) { this.properties = properties; }
@Override public JsonMembersCustomizerBuilder nested(boolean nested) { this.nested = nested; return this; } @Override public StructuredLoggingJsonMembersCustomizer<E> build() { return (members) -> { List<StructuredLoggingJsonMembersCustomizer<?>> customizers = new ArrayList<>(); if (this.properties != null) { customizers.add(new StructuredLoggingJsonPropertiesJsonMembersCustomizer( StructuredLogFormatterFactory.this.instantiator, this.properties, this.nested)); } customizers.addAll(loadStructuredLoggingJsonMembersCustomizers()); invokeCustomizers(members, customizers); }; } @SuppressWarnings({ "unchecked", "rawtypes" }) private List<StructuredLoggingJsonMembersCustomizer<?>> loadStructuredLoggingJsonMembersCustomizers() { return (List) StructuredLogFormatterFactory.this.factoriesLoader.load( StructuredLoggingJsonMembersCustomizer.class, ArgumentResolver.from(StructuredLogFormatterFactory.this.instantiator::getArg)); } @SuppressWarnings("unchecked") private void invokeCustomizers(Members<E> members, List<StructuredLoggingJsonMembersCustomizer<?>> customizers) { LambdaSafe.callbacks(StructuredLoggingJsonMembersCustomizer.class, customizers, members) .withFilter(LambdaSafe.Filter.allowAll()) .invoke((customizer) -> customizer.customize(members)); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\StructuredLogFormatterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class BankStatementLineAmounts { public static BankStatementLineAmounts of(@NonNull final I_C_BankStatementLine bsl) { return BankStatementLineAmounts.builder() .stmtAmt(bsl.getStmtAmt()) .trxAmt(bsl.getTrxAmt()) .bankFeeAmt(bsl.getBankFeeAmt()) .chargeAmt(bsl.getChargeAmt()) .interestAmt(bsl.getInterestAmt()) .build(); } BigDecimal stmtAmt; BigDecimal trxAmt; BigDecimal bankFeeAmt; BigDecimal chargeAmt; BigDecimal interestAmt; BigDecimal differenceAmt; @Builder(toBuilder = true) private BankStatementLineAmounts( @NonNull final BigDecimal stmtAmt, final BigDecimal trxAmt, final BigDecimal bankFeeAmt, final BigDecimal chargeAmt, final BigDecimal interestAmt) { this.stmtAmt = stmtAmt; this.trxAmt = trxAmt != null ? trxAmt : BigDecimal.ZERO; this.bankFeeAmt = bankFeeAmt != null ? bankFeeAmt : BigDecimal.ZERO; this.chargeAmt = chargeAmt != null ? chargeAmt : BigDecimal.ZERO; this.interestAmt = interestAmt != null ? interestAmt : BigDecimal.ZERO; // final BigDecimal stmtAmtComputed = this.trxAmt .subtract(this.bankFeeAmt) .add(this.chargeAmt) .add(this.interestAmt); this.differenceAmt = this.stmtAmt.subtract(stmtAmtComputed); } public boolean hasDifferences() { return differenceAmt.signum() != 0; } public BankStatementLineAmounts assertNoDifferences() { if (differenceAmt.signum() != 0) { throw new AdempiereException("Amounts are not completelly balanced: " + this); } return this; } public BankStatementLineAmounts addDifferenceToTrxAmt() {
if (differenceAmt.signum() == 0) { return this; } return toBuilder() .trxAmt(this.trxAmt.add(differenceAmt)) .build(); } public BankStatementLineAmounts withTrxAmt(@NonNull final BigDecimal trxAmt) { return !this.trxAmt.equals(trxAmt) ? toBuilder().trxAmt(trxAmt).build() : this; } public BankStatementLineAmounts addDifferenceToBankFeeAmt() { if (differenceAmt.signum() == 0) { return this; } return toBuilder() .bankFeeAmt(this.bankFeeAmt.subtract(differenceAmt)) .build(); } public BankStatementLineAmounts withBankFeeAmt(@NonNull final BigDecimal bankFeeAmt) { return !this.bankFeeAmt.equals(bankFeeAmt) ? toBuilder().bankFeeAmt(bankFeeAmt).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\BankStatementLineAmounts.java
2
请完成以下Java代码
public static void retrieveValueUsingFind() { DB database = mongoClient.getDB(databaseName); DBCollection collection = database.getCollection(testCollectionName); BasicDBObject queryFilter = new BasicDBObject(); BasicDBObject projection = new BasicDBObject(); projection.put("passengerId", 1); projection.put("_id", 0); DBCursor dbCursor = collection.find(queryFilter, projection); while (dbCursor.hasNext()) { System.out.println(dbCursor.next()); } } public static void retrieveValueUsingAggregation() { ArrayList<Document> response = new ArrayList<>(); ArrayList<Bson> pipeline = new ArrayList<>(Arrays.asList( project(fields(Projections.exclude("_id"), Projections.include("passengerId"))))); database = mongoClient.getDatabase(databaseName); database.getCollection(testCollectionName) .aggregate(pipeline) .allowDiskUse(true) .into(response); System.out.println("response:- " + response); } public static void retrieveValueAggregationUsingDocument() { ArrayList<Document> response = new ArrayList<>(); ArrayList<Document> pipeline = new ArrayList<>(Arrays.asList(new Document("$project", new Document("passengerId", 1L)))); database = mongoClient.getDatabase(databaseName); database.getCollection(testCollectionName) .aggregate(pipeline) .allowDiskUse(true) .into(response);
System.out.println("response:- " + response); } public static void main(String args[]) { // // Connect to cluster (default is localhost:27017) // setUp(); // // Fetch the data using find query with projected fields // retrieveValueUsingFind(); // // Fetch the data using aggregate pipeline query with projected fields // retrieveValueUsingAggregation(); // // Fetch the data using aggregate pipeline document query with projected fields // retrieveValueAggregationUsingDocument(); } }
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\RetrieveValue.java
1
请完成以下Java代码
public Mono<CompromisedPasswordDecision> check(@Nullable String password) { return getHash(password).map((hash) -> new String(Hex.encode(hash))) .flatMap(this::findLeakedPassword) .defaultIfEmpty(Boolean.FALSE) .map(CompromisedPasswordDecision::new); } private Mono<Boolean> findLeakedPassword(String encodedPassword) { String prefix = encodedPassword.substring(0, PREFIX_LENGTH).toUpperCase(Locale.ROOT); String suffix = encodedPassword.substring(PREFIX_LENGTH).toUpperCase(Locale.ROOT); return getLeakedPasswordsForPrefix(prefix).any((leakedPw) -> leakedPw.startsWith(suffix)); } private Flux<String> getLeakedPasswordsForPrefix(String prefix) { return this.webClient.get().uri(prefix).retrieve().bodyToMono(String.class).flatMapMany((body) -> { if (StringUtils.hasText(body)) { return Flux.fromStream(body.lines()); } return Flux.empty(); }) .doOnError((ex) -> this.logger.error("Request for leaked passwords failed", ex)) .onErrorResume(WebClientResponseException.class, (ex) -> Flux.empty()); } /**
* Sets the {@link WebClient} to use when making requests to Have I Been Pwned REST * API. By default, a {@link WebClient} with a base URL of {@link #API_URL} is used. * @param webClient the {@link WebClient} to use */ public void setWebClient(WebClient webClient) { Assert.notNull(webClient, "webClient cannot be null"); this.webClient = webClient; } private Mono<byte[]> getHash(@Nullable String rawPassword) { return Mono.justOrEmpty(rawPassword) .map((password) -> this.sha1Digest.digest(password.getBytes(StandardCharsets.UTF_8))) .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()); } private static MessageDigest getSha1Digest() { try { return MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex.getMessage()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\password\HaveIBeenPwnedRestApiReactivePasswordChecker.java
1
请完成以下Java代码
byte getKeyByte(int keyId, int byteId) { if (byteId >= _keys[keyId].length) { return 0; } return _keys[keyId][byteId]; } /** * 是否含有值 * @return */ boolean hasValues() { return _values != null; } /** * 根据下标获取值 * @param id * @return */ int getValue(int id) {
if (hasValues()) { return _values[id]; } return id; } /** * 键 */ private byte[][] _keys; /** * 值 */ private int _values[]; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\Keyset.java
1
请完成以下Java代码
class NestedByteChannel implements SeekableByteChannel { private long position; private final Resources resources; private final Cleanable cleanup; private final long size; private volatile boolean closed; NestedByteChannel(Path path, String nestedEntryName) throws IOException { this(path, nestedEntryName, Cleaner.instance); } NestedByteChannel(Path path, String nestedEntryName, Cleaner cleaner) throws IOException { this.resources = new Resources(path, nestedEntryName); this.cleanup = cleaner.register(this, this.resources); this.size = this.resources.getData().size(); } @Override public boolean isOpen() { return !this.closed; } @Override public void close() throws IOException { if (this.closed) { return; } this.closed = true; try { this.cleanup.clean(); } catch (UncheckedIOException ex) { throw ex.getCause(); } } @Override public int read(ByteBuffer dst) throws IOException { assertNotClosed(); int total = 0; while (dst.remaining() > 0) { int count = this.resources.getData().read(dst, this.position); if (count <= 0) { return (total != 0) ? 0 : count; } total += count; this.position += count; } return total; } @Override public int write(ByteBuffer src) throws IOException { throw new NonWritableChannelException(); } @Override public long position() throws IOException { assertNotClosed(); return this.position; } @Override public SeekableByteChannel position(long position) throws IOException { assertNotClosed(); if (position < 0 || position >= this.size) { throw new IllegalArgumentException("Position must be in bounds"); } this.position = position;
return this; } @Override public long size() throws IOException { assertNotClosed(); return this.size; } @Override public SeekableByteChannel truncate(long size) throws IOException { throw new NonWritableChannelException(); } private void assertNotClosed() throws ClosedChannelException { if (this.closed) { throw new ClosedChannelException(); } } /** * Resources used by the channel and suitable for registration with a {@link Cleaner}. */ static class Resources implements Runnable { private final ZipContent zipContent; private final CloseableDataBlock data; Resources(Path path, String nestedEntryName) throws IOException { this.zipContent = ZipContent.open(path, nestedEntryName); this.data = this.zipContent.openRawZipData(); } DataBlock getData() { return this.data; } @Override public void run() { releaseAll(); } private void releaseAll() { IOException exception = null; try { this.data.close(); } catch (IOException ex) { exception = ex; } try { this.zipContent.close(); } catch (IOException ex) { if (exception != null) { ex.addSuppressed(exception); } exception = ex; } if (exception != null) { throw new UncheckedIOException(exception); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
1
请完成以下Java代码
public class ErrorDetails { private Date timestamp; private String message; private String details; public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }
public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public ErrorDetails(Date timestamp, String message, String details){ super(); this.timestamp = timestamp; this.details = details; this.message = message; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringRestDB\src\main\java\spring\restdb\exception\ErrorDetails.java
1
请完成以下Java代码
public int getIMP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Days to keep Log. @param KeepLogDays Number of days to keep the log entries */ public void setKeepLogDays (int KeepLogDays) { set_Value (COLUMNNAME_KeepLogDays, Integer.valueOf(KeepLogDays)); } /** Get Days to keep Log. @return Number of days to keep the log entries */ public int getKeepLogDays () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays); if (ii == null) return 0; return ii.intValue(); } /** 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); } /** Set Password Info. @param PasswordInfo Password Info */ public void setPasswordInfo (String PasswordInfo) { set_Value (COLUMNNAME_PasswordInfo, PasswordInfo); } /** Get Password Info. @return Password Info */ public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_Port); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ 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 Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_Processor.java
1
请完成以下Java代码
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; } public Date getStartedAfter() {
return startedAfter; } public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public ActivityInstanceState getActivityInstanceState() { return activityInstanceState; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class M_InOut { private static final AdMessageKey ERR_ShipmentDeclaration = AdMessageKey.of("de.metas.shipment.model.interceptor.M_InOut.ERR_ShipmentDeclaration"); private final ShipmentDeclarationCreator shipmentDeclarationCreator; private final ShipmentDeclarationRepository shipmentDeclarationRepo; private final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); private final IInOutBL inOutBL = Services.get(IInOutBL.class); public M_InOut(@NonNull final ShipmentDeclarationCreator shipmentDeclarationCreator, @NonNull final ShipmentDeclarationRepository shipmentDeclarationRepo) { this.shipmentDeclarationCreator = shipmentDeclarationCreator; this.shipmentDeclarationRepo = shipmentDeclarationRepo; } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void createShipmentDeclarationIfNeeded(final I_M_InOut inout) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inout)) { if (!inout.isSOTrx()) { // Only applies to shipments return; } final InOutId shipmentId = InOutId.ofRepoId(inout.getM_InOut_ID()); shipmentDeclarationCreator.createShipmentDeclarationsIfNeeded(shipmentId); } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void createRequestIfConfigured(final I_M_InOut inout) { if (docTypeBL.hasRequestType(DocTypeId.ofRepoId(inout.getC_DocType_ID()))) { inOutBL.createRequestFromInOut(inout); } } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE }) public void forbidReactivateOnCompletedShipmentDeclaration(final I_M_InOut inout) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inout)) { if (!inout.isSOTrx()) { // Only applies to shipments return; }
final InOutId shipmentId = InOutId.ofRepoId(inout.getM_InOut_ID()); if (shipmentDeclarationRepo.existCompletedShipmentDeclarationsForShipmentId(shipmentId)) { throw new AdempiereException(ERR_ShipmentDeclaration).markAsUserValidationError(); } } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE, }, ifColumnsChanged = { I_M_InOut.COLUMNNAME_DropShip_Location_ID, I_M_InOut.COLUMNNAME_C_BPartner_Location_ID }) public void onBPartnerLocation(final I_M_InOut inout) { if (InterfaceWrapperHelper.isUIAction(inout)) { inOutBL.setShipperId(inout); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\model\interceptor\M_InOut.java
2
请在Spring Boot框架中完成以下Java代码
public class SecSecurityConfig { @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user1 = User.withUsername("user1") .password(passwordEncoder().encode("user1Pass")) .roles("USER") .build(); UserDetails user2 = User.withUsername("user2") .password(passwordEncoder().encode("user2Pass")) .roles("USER") .build(); UserDetails admin = User.withUsername("admin") .password(passwordEncoder().encode("adminPass")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user1, user2, admin); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests() .antMatchers("/admin/**") .hasRole("ADMIN") .antMatchers("/anonymous*") .anonymous() .antMatchers("/login*") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .loginPage("/login.html")
.loginProcessingUrl("/perform_login") .defaultSuccessUrl("/homepage.html", true) // .failureUrl("/login.html?error=true") .failureHandler(authenticationFailureHandler()) .and() .logout() .logoutUrl("/perform_logout") .deleteCookies("JSESSIONID") .logoutSuccessHandler(logoutSuccessHandler()); // .and() // .exceptionHandling().accessDeniedPage("/accessDenied"); // .exceptionHandling().accessDeniedHandler(accessDeniedHandler()); return http.build(); } @Bean public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } @Bean public AccessDeniedHandler accessDeniedHandler() { return new CustomAccessDeniedHandler(); } @Bean public AuthenticationFailureHandler authenticationFailureHandler() { return new CustomAuthenticationFailureHandler(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-login\src\main\java\com\baeldung\security\config\SecSecurityConfig.java
2
请完成以下Java代码
public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_InventoryLineMA. @param M_InventoryLineMA_ID M_InventoryLineMA */ @Override public void setM_InventoryLineMA_ID (int M_InventoryLineMA_ID) { if (M_InventoryLineMA_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, Integer.valueOf(M_InventoryLineMA_ID)); } /** Get M_InventoryLineMA. @return M_InventoryLineMA */ @Override public int getM_InventoryLineMA_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLineMA_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bewegungs-Menge. @param MovementQty Quantity of a product moved. */ @Override public void setMovementQty (java.math.BigDecimal MovementQty)
{ set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Bewegungs-Menge. @return Quantity of a product moved. */ @Override public java.math.BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLineMA.java
1
请完成以下Java代码
public String getActivityInstanceId() { return activityInstanceId; } @Override public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getExecutionId() { return executionId; } @Override
public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public Date getTime() { return time; } @Override public void setTime(Date time) { this.time = time; } @Override public String getDetailType() { return detailType; } @Override public void setDetailType(String detailType) { this.detailType = detailType; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailEntityImpl.java
1
请完成以下Java代码
public void onOccur(CmmnActivityExecution execution) { ensureTransitionAllowed(execution, AVAILABLE, COMPLETED, "occur"); } // suspension //////////////////////////////////////////////////////////// public void onSuspension(CmmnActivityExecution execution) { ensureTransitionAllowed(execution, AVAILABLE, SUSPENDED, "suspend"); performSuspension(execution); } public void onParentSuspension(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("parentSuspend", execution); } // resume //////////////////////////////////////////////////////////////// public void onResume(CmmnActivityExecution execution) { ensureTransitionAllowed(execution, SUSPENDED, AVAILABLE, "resume"); CmmnActivityExecution parent = execution.getParent(); if (parent != null) { if (!parent.isActive()) { String id = execution.getId(); throw LOG.resumeInactiveCaseException("resume", id); } } resuming(execution); }
public void onParentResume(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("parentResume", execution); } // re-activation //////////////////////////////////////////////////////// public void onReactivation(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("reactivate", execution); } // sentry /////////////////////////////////////////////////////////////// protected boolean isAtLeastOneExitCriterionSatisfied(CmmnActivityExecution execution) { return false; } public void fireExitCriteria(CmmnActivityExecution execution) { throw LOG.criteriaNotAllowedForEventListenerOrMilestonesException("exit", execution.getId()); } // helper //////////////////////////////////////////////////////////////// protected CaseIllegalStateTransitionException createIllegalStateTransitionException(String transition, CmmnActivityExecution execution) { String id = execution.getId(); return LOG.illegalStateTransitionException(transition, id, getTypeName()); } protected abstract String getTypeName(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerOrMilestoneActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public class ModificationBatchConfiguration extends BatchConfiguration { protected List<AbstractProcessInstanceModificationCommand> instructions; protected boolean skipCustomListeners; protected boolean skipIoMappings; protected String processDefinitionId; public ModificationBatchConfiguration(List<String> ids, String processDefinitionId, List<AbstractProcessInstanceModificationCommand> instructions, boolean skipCustomListeners, boolean skipIoMappings) { this(ids, null, processDefinitionId, instructions, skipCustomListeners, skipIoMappings); } public ModificationBatchConfiguration(List<String> ids, DeploymentMappings mappings, String processDefinitionId, List<AbstractProcessInstanceModificationCommand> instructions, boolean skipCustomListeners, boolean skipIoMappings) { super(ids, mappings); this.instructions = instructions; this.processDefinitionId = processDefinitionId; this.skipCustomListeners = skipCustomListeners; this.skipIoMappings = skipIoMappings; } public List<AbstractProcessInstanceModificationCommand> getInstructions() { return instructions;
} public String getProcessDefinitionId() { return processDefinitionId; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBatchConfiguration.java
2
请完成以下Java代码
public BigDecimal getQM_QtyDeliveredAvg() { return ppOrder.getQM_QtyDeliveredAvg(); } @Override public Object getModel() { return ppOrder; } @Override public String getVariantGroup() { return null; } @Override public BOMComponentType getComponentType() { return null; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo()
{ if (!_handlingUnitsInfoLoaded) { _handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder); _handlingUnitsInfoLoaded = true; } return _handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { // there is no substitute for a produced material return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java
1
请完成以下Java代码
/* package */ InvoiceLineAggregationRequest build() { return new InvoiceLineAggregationRequest(this); } private Builder() { } @Override public String toString() { return ObjectUtils.toString(this); } public Builder setC_Invoice_Candidate(final I_C_Invoice_Candidate invoiceCandidate) { this.invoiceCandidate = invoiceCandidate; return this; } public Builder setC_InvoiceCandidate_InOutLine(final I_C_InvoiceCandidate_InOutLine iciol) { this.iciol = iciol; return this; } /** * Adds an additional element to be considered part of the line aggregation key.
* <p> * NOTE: basically this shall be always empty because everything which is related to line aggregation * shall be configured from aggregation definition, * but we are also leaving this door open in case we need to implement some quick/hot fixes. * * @deprecated This method will be removed because we shall go entirely with standard aggregation definition. */ @Deprecated public Builder addLineAggregationKeyElement(@NonNull final Object aggregationKeyElement) { aggregationKeyElements.add(aggregationKeyElement); return this; } public void addInvoiceLineAttributes(@NonNull final Collection<IInvoiceLineAttribute> invoiceLineAttributes) { this.attributesFromInoutLines.addAll(invoiceLineAttributes); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineAggregationRequest.java
1
请完成以下Java代码
public static CostAmountAndQtyDetailed of(@NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final CostAmountType type) { final CostAmountAndQty amtAndQty = CostAmountAndQty.of(amt, qty); return of(type, amtAndQty); } private static CostAmountAndQtyDetailed of(final @NonNull CostAmountType type, @NonNull final CostAmountAndQty amtAndQty) { final CostAmountAndQtyDetailed costAmountAndQtyDetailed; switch (type) { case MAIN: costAmountAndQtyDetailed = builder().main(amtAndQty).build(); break; case ADJUSTMENT: costAmountAndQtyDetailed = builder().costAdjustment(amtAndQty).build(); break; case ALREADY_SHIPPED: costAmountAndQtyDetailed = builder().alreadyShipped(amtAndQty).build(); break; default: throw new IllegalArgumentException(); } return costAmountAndQtyDetailed; } public static CostAmountAndQtyDetailed zero(@NonNull final CurrencyId currencyId, @NonNull final UomId uomId) { final CostAmountAndQty zero = CostAmountAndQty.zero(currencyId, uomId); return new CostAmountAndQtyDetailed(zero, zero, zero); } public CostAmountAndQtyDetailed add(@NonNull final CostAmountAndQtyDetailed other) { return builder() .main(main.add(other.main)) .costAdjustment(costAdjustment.add(other.costAdjustment)) .alreadyShipped(alreadyShipped.add(other.alreadyShipped)) .build(); } public CostAmountAndQtyDetailed negateIf(final boolean condition) { return condition ? negate() : this; } public CostAmountAndQtyDetailed negate() { return builder() .main(main.negate()) .costAdjustment(costAdjustment.negate()) .alreadyShipped(alreadyShipped.negate()) .build(); } public CostAmountAndQty getAmtAndQty(final CostAmountType type)
{ final CostAmountAndQty costAmountAndQty; switch (type) { case MAIN: costAmountAndQty = main; break; case ADJUSTMENT: costAmountAndQty = costAdjustment; break; case ALREADY_SHIPPED: costAmountAndQty = alreadyShipped; break; default: throw new IllegalArgumentException(); } return costAmountAndQty; } public CostAmountDetailed getAmt() { return CostAmountDetailed.builder() .mainAmt(main.getAmt()) .costAdjustmentAmt(costAdjustment.getAmt()) .alreadyShippedAmt(alreadyShipped.getAmt()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostAmountAndQtyDetailed.java
1
请完成以下Java代码
private SaveDecoupledHUAttributesDAO getDelegate() { final String trxName = trxManager.getThreadInheritedTrxName(); final ITrx trx = trxManager.getTrx(trxName); Check.assumeNotNull(trx, "trx not null for trxName={}", trxName); // // Get an existing storage DAO from transaction. // If no storage DAO exists => create a new one return trx.getProperty(TRX_PROPERTY_SaveDecoupledHUAttributesDAO, () -> { // Create a new attributes storage final SaveDecoupledHUAttributesDAO huAttributesDAO = new SaveDecoupledHUAttributesDAO(dbHUAttributesDAO); // Listen this transaction for COMMIT events // Before committing the transaction, this listener makes sure we are also saving all storages trx.getTrxListenerManager() .newEventListener(TrxEventTiming.BEFORE_COMMIT) .registerHandlingMethod(innerTrx -> { // Get and remove the save-decoupled HU Storage DAO final SaveDecoupledHUAttributesDAO innerHuAttributesDAO = innerTrx.setProperty(TRX_PROPERTY_SaveDecoupledHUAttributesDAO, null); if (innerHuAttributesDAO == null) { // shall not happen, because this handlerMethod is invoked only once, // but silently ignore it return; } // Save everything to database innerHuAttributesDAO.flush(); }); return huAttributesDAO; }); } @Override public I_M_HU_Attribute newHUAttribute(final Object contextProvider) { final SaveDecoupledHUAttributesDAO delegate = getDelegate(); return delegate.newHUAttribute(contextProvider); } @Override
public void save(final I_M_HU_Attribute huAttribute) { final SaveDecoupledHUAttributesDAO delegate = getDelegate(); delegate.save(huAttribute); } @Override public void delete(final I_M_HU_Attribute huAttribute) { final SaveDecoupledHUAttributesDAO delegate = getDelegate(); delegate.delete(huAttribute); } @Override public List<I_M_HU_Attribute> retrieveAllAttributesNoCache(final Collection<HuId> huIds) { final SaveDecoupledHUAttributesDAO delegate = getDelegate(); return delegate.retrieveAllAttributesNoCache(huIds); } @Override public HUAndPIAttributes retrieveAttributesOrdered(final I_M_HU hu) { final SaveDecoupledHUAttributesDAO delegate = getDelegate(); return delegate.retrieveAttributesOrdered(hu); } @Override public I_M_HU_Attribute retrieveAttribute(final I_M_HU hu, final AttributeId attributeId) { final SaveDecoupledHUAttributesDAO delegate = getDelegate(); return delegate.retrieveAttribute(hu, attributeId); } @Override public void flush() { final SaveDecoupledHUAttributesDAO attributesDAO = getDelegateOrNull(); if (attributesDAO != null) { attributesDAO.flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\SaveOnCommitHUAttributesDAO.java
1
请完成以下Java代码
public PMM_GenerateOrdersEnqueuer confirmRecordsToProcess(final ConfirmationCallback confirmationCallback) { this.confirmationCallback = confirmationCallback; return this; } /** * @return number of records enqueued */ public int enqueue() { final IQuery<I_PMM_PurchaseCandidate> query = createRecordsToProcessQuery(); if (!confirmRecordsToProcess(query)) { return 0; } final List<I_PMM_PurchaseCandidate> candidates = query.list(); if (candidates.isEmpty()) { throw new AdempiereException("@NoSelection@"); } final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName()); final ILockCommand elementsLocker = lockManager.lock() .setOwner(lockOwner) .setAutoCleanup(false); workPackageQueueFactory .getQueueForEnqueuing(Env.getCtx(), PMM_GenerateOrders.class) .newWorkPackage() .setElementsLocker(elementsLocker) .addElements(candidates) .buildAndEnqueue(); return candidates.size(); } private boolean confirmRecordsToProcess(final IQuery<I_PMM_PurchaseCandidate> query) { if (confirmationCallback == null) { return true; // OK, autoconfirmed } // // Fail if there is nothing to update final int countToProcess = query.count(); if (countToProcess <= 0) { throw new AdempiereException("@NoSelection@"); }
// // Ask the callback if we shall process return confirmationCallback.confirmRecordsToProcess(countToProcess); } private IQuery<I_PMM_PurchaseCandidate> createRecordsToProcessQuery() { final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder = queryBL.createQueryBuilder(I_PMM_PurchaseCandidate.class); if (candidatesFilter != null) { queryBuilder.filter(candidatesFilter); } return queryBuilder .addOnlyActiveRecordsFilter() .filter(lockManager.getNotLockedFilter(I_PMM_PurchaseCandidate.class)) .addCompareFilter(I_PMM_PurchaseCandidate.COLUMNNAME_QtyToOrder, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .orderBy() .addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_AD_Org_ID) .addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_M_Warehouse_ID) .addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_C_BPartner_ID) .addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised) .addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_M_PricingSystem_ID) .addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_C_Currency_ID) .endOrderBy() // .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\async\PMM_GenerateOrdersEnqueuer.java
1
请完成以下Java代码
public DeploymentCache<CaseDefinitionCacheEntry> getCaseDefinitionCache() { return caseDefinitionCache; } public void setCaseDefinitionCache(DeploymentCache<CaseDefinitionCacheEntry> caseDefinitionCache) { this.caseDefinitionCache = caseDefinitionCache; } public CmmnEngineConfiguration getCaseEngineConfiguration() { return cmmnEngineConfiguration; } public void setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; } public CaseDefinitionEntityManager getCaseDefinitionEntityManager() {
return caseDefinitionEntityManager; } public void setCaseDefinitionEntityManager(CaseDefinitionEntityManager caseDefinitionEntityManager) { this.caseDefinitionEntityManager = caseDefinitionEntityManager; } public CmmnDeploymentEntityManager getDeploymentEntityManager() { return deploymentEntityManager; } public void setDeploymentEntityManager(CmmnDeploymentEntityManager deploymentEntityManager) { this.deploymentEntityManager = deploymentEntityManager; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\CmmnDeploymentManager.java
1
请完成以下Java代码
private static Language extractLanguageFromDraftInOut(@NonNull final Properties ctx, @Nullable final TableRecordReference recordRef) { final boolean isUseLoginLanguage = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_UseLoginLanguageForDraftDocuments, true); // in case the sys config is not set, there is no need to continue if (!isUseLoginLanguage) { return null; } if (recordRef == null) { return null; } final IDocumentBL docActionBL = Services.get(IDocumentBL.class); final boolean isDocument = docActionBL.isDocumentTable(recordRef.getTableName()); // fails for processes // Make sure the process is for a document if (!isDocument) { return null; } final Object document = recordRef.getModel(PlainContextAware.newWithThreadInheritedTrx(ctx)); if (document == null) { return null; } final I_C_DocType doctype = docActionBL.getDocTypeOrNull(document); // make sure the document has a doctype if (doctype == null) { return null; // this shall never happen } final String docBaseType = doctype.getDocBaseType(); // make sure the doctype has a base doctype if (docBaseType == null) { return null; }
// Nothing to do if not dealing with a sales inout. if (!X_C_DocType.DOCBASETYPE_MaterialDelivery.equals(docBaseType)) { return null; } // Nothing to do if the document is not a draft or in progress. if (!docActionBL.issDocumentDraftedOrInProgress(document)) { return null; } // If all the conditions described above are fulfilled, take the language from the login final String languageString = Env.getAD_Language(ctx); return Language.getLanguage(languageString); } } // ProcessInfoBuilder } // ProcessInfo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfo.java
1
请完成以下Java代码
public FormType getType() { return type; } public void setType(AbstractFormFieldType type) { this.type = type; } public boolean isReadable() { return isReadable; } public void setReadable(boolean isReadable) { this.isReadable = isReadable; } public boolean isRequired() { return isRequired; } public void setRequired(boolean isRequired) { this.isRequired = isRequired; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } public Expression getVariableExpression() { return variableExpression; }
public void setVariableExpression(Expression variableExpression) { this.variableExpression = variableExpression; } public Expression getDefaultExpression() { return defaultExpression; } public void setDefaultExpression(Expression defaultExpression) { this.defaultExpression = defaultExpression; } public boolean isWritable() { return isWritable; } public void setWritable(boolean isWritable) { this.isWritable = isWritable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\FormPropertyHandler.java
1
请完成以下Java代码
public <T> T mapOnParams(@Nullable final CostCalculationMethodParams params, @NonNull final ParamsMapper<T> mapper) { if (this == CostCalculationMethod.FixedAmount) { return mapper.fixedAmount(castParams(params, FixedAmountCostCalculationMethodParams.class)); } else if (this == CostCalculationMethod.PercentageOfAmount) { return mapper.percentageOfAmount(castParams(params, PercentageCostCalculationMethodParams.class)); } else { throw new AdempiereException("Calculation method not handled: " + this); } } public <T extends CostCalculationMethodParams> T castParams(@Nullable final CostCalculationMethodParams params, @NonNull final Class<T> type) { if (params == null) { throw new AdempiereException("No calculation method parameters provided for " + type.getSimpleName()); } return type.cast(params); }
public interface CaseMapper<T> { T fixedAmount(); T percentageOfAmount(); } public <T> T map(@NonNull final CaseMapper<T> mapper) { if (this == CostCalculationMethod.FixedAmount) { return mapper.fixedAmount(); } else if (this == CostCalculationMethod.PercentageOfAmount) { return mapper.percentageOfAmount(); } else { throw new AdempiereException("Calculation method not handled: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\calculation_methods\CostCalculationMethod.java
1
请完成以下Java代码
public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value;
this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceAreaProductRelationExample.java
1
请在Spring Boot框架中完成以下Java代码
public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return true; } @Override public Object getValue(ValueFields valueFields) { BigDecimal bigDecimal = null; String textValue = valueFields.getTextValue(); if (textValue != null && !textValue.isEmpty()) { bigDecimal = new BigDecimal(textValue); } return bigDecimal; } @Override
public void setValue(Object value, ValueFields valueFields) { if (value != null) { valueFields.setTextValue(((BigDecimal) value).toPlainString()); } else { valueFields.setTextValue(null); } } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return BigDecimal.class.isAssignableFrom(value.getClass()); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\BigDecimalType.java
2
请完成以下Java代码
public String getTaskId() { return taskId; } public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public String getTenantId() { return tenantId; } public Date getCreateTime() { return createTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public Boolean getRequired() { return required; } public Boolean getAvailable() { return available; } public Boolean getEnabled() { return enabled; } public Boolean getDisabled() { return disabled; }
public Boolean getActive() { return active; } public Boolean getCompleted() { return completed; } public Boolean getTerminated() { return terminated; } public static HistoricCaseActivityInstanceDto fromHistoricCaseActivityInstance(HistoricCaseActivityInstance historicCaseActivityInstance) { HistoricCaseActivityInstanceDto dto = new HistoricCaseActivityInstanceDto(); dto.id = historicCaseActivityInstance.getId(); dto.parentCaseActivityInstanceId = historicCaseActivityInstance.getParentCaseActivityInstanceId(); dto.caseActivityId = historicCaseActivityInstance.getCaseActivityId(); dto.caseActivityName = historicCaseActivityInstance.getCaseActivityName(); dto.caseActivityType = historicCaseActivityInstance.getCaseActivityType(); dto.caseDefinitionId = historicCaseActivityInstance.getCaseDefinitionId(); dto.caseInstanceId = historicCaseActivityInstance.getCaseInstanceId(); dto.caseExecutionId = historicCaseActivityInstance.getCaseExecutionId(); dto.taskId = historicCaseActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicCaseActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicCaseActivityInstance.getCalledCaseInstanceId(); dto.tenantId = historicCaseActivityInstance.getTenantId(); dto.createTime = historicCaseActivityInstance.getCreateTime(); dto.endTime = historicCaseActivityInstance.getEndTime(); dto.durationInMillis = historicCaseActivityInstance.getDurationInMillis(); dto.required = historicCaseActivityInstance.isRequired(); dto.available = historicCaseActivityInstance.isAvailable(); dto.enabled = historicCaseActivityInstance.isEnabled(); dto.disabled = historicCaseActivityInstance.isDisabled(); dto.active = historicCaseActivityInstance.isActive(); dto.completed = historicCaseActivityInstance.isCompleted(); dto.terminated = historicCaseActivityInstance.isTerminated(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseActivityInstanceDto.java
1
请完成以下Java代码
public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */ public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() { return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); } @Override public void setQty (final @Nullable BigDecimal Qty) {
set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectTask.java
1
请完成以下Java代码
public Party6Choice getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Party6Choice } * */ public void setId(Party6Choice value) { this.id = value; } /** * Gets the value of the ctryOfRes property. * * @return * possible object is * {@link String } * */ public String getCtryOfRes() { return ctryOfRes; } /** * Sets the value of the ctryOfRes property. * * @param value * allowed object is * {@link String } * */ public void setCtryOfRes(String value) { this.ctryOfRes = value; }
/** * Gets the value of the ctctDtls property. * * @return * possible object is * {@link ContactDetails2 } * */ public ContactDetails2 getCtctDtls() { return ctctDtls; } /** * Sets the value of the ctctDtls property. * * @param value * allowed object is * {@link ContactDetails2 } * */ public void setCtctDtls(ContactDetails2 value) { this.ctctDtls = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PartyIdentification32.java
1
请在Spring Boot框架中完成以下Java代码
public PollerMetadata pollerMetadata() { return Pollers.fixedDelay(5000) .advice(transactionInterceptor()) .transactionSynchronizationFactory(transactionSynchronizationFactory) .get(); } private TransactionInterceptor transactionInterceptor() { return new TransactionInterceptorBuilder().transactionManager(txManager).build(); } @Bean public TransactionSynchronizationFactory transactionSynchronizationFactory() { ExpressionEvaluatingTransactionSynchronizationProcessor processor = new ExpressionEvaluatingTransactionSynchronizationProcessor(); SpelExpressionParser spelParser = new SpelExpressionParser(); processor.setAfterCommitExpression( spelParser.parseExpression( "payload.renameTo(new java.io.File(payload.absolutePath + '.PASSED'))")); processor.setAfterRollbackExpression( spelParser.parseExpression( "payload.renameTo(new java.io.File(payload.absolutePath + '.FAILED'))")); return new DefaultTransactionSynchronizationFactory(processor); } @Bean @Transformer(inputChannel = "inputChannel", outputChannel = "toServiceChannel") public FileToStringTransformer fileToStringTransformer() { return new FileToStringTransformer(); } @ServiceActivator(inputChannel = "toServiceChannel") public void serviceActivator(String payload) { jdbcTemplate.update("insert into STUDENT values(?)", payload); if (payload.toLowerCase().startsWith("fail")) { log.error("Service failure. Test result: {} ", payload); throw new RuntimeException("Service failure."); } log.info("Service success. Test result: {}", payload); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean
public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath:table.sql") .build(); } @Bean public DataSourceTransactionManager txManager() { return new DataSourceTransactionManager(dataSource); } public static void main(final String... args) { final AbstractApplicationContext context = new AnnotationConfigApplicationContext(TxIntegrationConfig.class); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); System.out.print("Integration flow is running. Type q + <enter> to quit "); while (true) { final String input = scanner.nextLine(); if ("q".equals(input.trim())) { context.close(); scanner.close(); break; } } System.exit(0); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\tx\TxIntegrationConfig.java
2
请完成以下Java代码
public void setCdtrAcct(CashAccount24 value) { this.cdtrAcct = value; } /** * Gets the value of the ultmtCdtr property. * * @return * possible object is * {@link PartyIdentification43 } * */ public PartyIdentification43 getUltmtCdtr() { return ultmtCdtr; } /** * Sets the value of the ultmtCdtr property. * * @param value * allowed object is * {@link PartyIdentification43 } * */ public void setUltmtCdtr(PartyIdentification43 value) { this.ultmtCdtr = value; } /** * Gets the value of the tradgPty property. * * @return * possible object is * {@link PartyIdentification43 } * */ public PartyIdentification43 getTradgPty() { return tradgPty; } /** * Sets the value of the tradgPty property. * * @param value * allowed object is * {@link PartyIdentification43 } * */ public void setTradgPty(PartyIdentification43 value) { this.tradgPty = value; }
/** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryParty3 } * * */ public List<ProprietaryParty3> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryParty3>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionParties3.java
1
请在Spring Boot框架中完成以下Java代码
public List<Author> fetchAllAuthors() { return authorRepository.fetchAll(); } public Author fetchAuthorByNameAndAge() { return authorRepository.fetchByNameAndAge("Joana Nimar", 34); } /* causes exception public List<Author> fetchAuthorsViaSort() { return authorRepository.fetchViaSort(Sort.by(Direction.DESC, "name")); } */ /* causes exception public List<Author> fetchAuthorsViaSortWhere() { return authorRepository.fetchViaSortWhere(30, Sort.by(Direction.DESC, "name")); } */ public Page<Author> fetchAuthorsPageSort() { return authorRepository.fetchPageSort(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Page<Author> fetchAuthorsPageSortWhere() { return authorRepository.fetchPageSortWhere(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSort() { return authorRepository.fetchSliceSort(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortWhere() { return authorRepository.fetchSliceSortWhere(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public List<Author> fetchAllAuthorsNative() { return authorRepository.fetchAllNative(); }
public Author fetchAuthorByNameAndAgeNative() { return authorRepository.fetchByNameAndAgeNative("Joana Nimar", 34); } /* causes exception public List<Author> fetchAuthorsViaSortNative() { return authorRepository.fetchViaSortNative(Sort.by(Direction.DESC, "name")); } */ /* causes exception public List<Author> fetchAuthorsViaSortWhereNative() { return authorRepository.fetchViaSortWhereNative(30, Sort.by(Direction.DESC, "name")); } */ public Page<Author> fetchAuthorsPageSortNative() { return authorRepository.fetchPageSortNative(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Page<Author> fetchAuthorsPageSortWhereNative() { return authorRepository.fetchPageSortWhereNative(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortNative() { return authorRepository.fetchSliceSortNative(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortWhereNative() { return authorRepository.fetchSliceSortWhereNative(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedQueriesInOrmXml\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
void jbInit() throws Exception { this.setResizable(false); textLabel.setIcon(new ImageIcon(net.sf.memoranda.ui.htmleditor.HTMLEditor.class.getResource("resources/icons/findbig.png"))) ; textLabel.setIconTextGap(10); border1 = BorderFactory.createEmptyBorder(5, 5, 5, 5); border2 = BorderFactory.createEmptyBorder(); panel1.setLayout(borderLayout1); cancelB.setText(Local.getString("Cancel")); cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { cancelB_actionPerformed(e); } }); // cancelB.setFocusable(false); yesAllB.setText(Local.getString("Yes to all")); yesAllB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { yesAllB_actionPerformed(e); } }); //yesAllB.setFocusable(false); buttonsPanel.setLayout(flowLayout1); panel1.setBorder(border1); areaPanel.setLayout(borderLayout3); areaPanel.setBorder(border2); borderLayout3.setHgap(5); borderLayout3.setVgap(5); textLabel.setHorizontalAlignment(SwingConstants.CENTER); yesB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { yesB_actionPerformed(e); } }); yesB.setText(Local.getString("Yes")); //yesB.setFocusable(false); this.getRootPane().setDefaultButton(yesB);
noB.setText(Local.getString("No")); noB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { noB_actionPerformed(e); } }); // noB.setFocusable(false); buttonsPanel.add(yesB, null); getContentPane().add(panel1); panel1.add(areaPanel, BorderLayout.CENTER); areaPanel.add(textLabel, BorderLayout.WEST); panel1.add(buttonsPanel, BorderLayout.SOUTH); buttonsPanel.add(yesAllB, null); buttonsPanel.add(noB, null); buttonsPanel.add(cancelB, null); } void yesAllB_actionPerformed(ActionEvent e) { option = YES_TO_ALL_OPTION; this.dispose(); } void cancelB_actionPerformed(ActionEvent e) { option = CANCEL_OPTION; this.dispose(); } void yesB_actionPerformed(ActionEvent e) { option = YES_OPTION; this.dispose(); } void noB_actionPerformed(ActionEvent e) { option = NO_OPTION; this.dispose(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\ReplaceOptionsDialog.java
1
请在Spring Boot框架中完成以下Java代码
class CreditMemoInvoiceCopyHandler implements IDocCopyHandler<I_C_Invoice, I_C_InvoiceLine> { private final InvoiceCreditContext creditCtx; public CreditMemoInvoiceCopyHandler(final InvoiceCreditContext creditCtx) { this.creditCtx = creditCtx; } @Override public void copyPreliminaryValues(final I_C_Invoice from, final I_C_Invoice to) { // do nothing. this is already done by the default copy handler } @Override public void copyValues(@NonNull final I_C_Invoice from, @NonNull final I_C_Invoice to) { final de.metas.adempiere.model.I_C_Invoice invoice = InterfaceWrapperHelper.create(from, de.metas.adempiere.model.I_C_Invoice.class); final de.metas.adempiere.model.I_C_Invoice creditMemo = InterfaceWrapperHelper.create(to, de.metas.adempiere.model.I_C_Invoice.class); if (creditCtx.isReferenceInvoice()) { creditMemo.setRef_Invoice_ID(invoice.getC_Invoice_ID()); } creditMemo.setIsCreditedInvoiceReinvoicable(creditCtx.isCreditedInvoiceReinvoicable()); // task 08927 completeAndAllocateCreditMemo(invoice, creditMemo); } @Override public CreditMemoInvoiceLineCopyHandler getDocLineCopyHandler() { return CreditMemoInvoiceLineCopyHandler.getInstance();
} private void completeAndAllocateCreditMemo(final de.metas.adempiere.model.I_C_Invoice invoice, final de.metas.adempiere.model.I_C_Invoice creditMemo) { if (!creditCtx.isCompleteAndAllocate()) { Services.get(IDocumentBL.class).processEx(creditMemo, IDocument.ACTION_Prepare, IDocument.STATUS_InProgress); // nothing left to do return; } Services.get(IDocumentBL.class).processEx(creditMemo, IDocument.ACTION_Complete, IDocument.STATUS_Completed); // allocate invoice against credit memo will be done in the model validator of creditmemo complete } /** * Returns the header item class, i.e. <code>I_C_Invoice</code>. */ @Override public Class<I_C_Invoice> getSupportedItemsClass() { return I_C_Invoice.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\CreditMemoInvoiceCopyHandler.java
2
请完成以下Java代码
public BigDecimal getQtyItemCapacityInternal() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacityInternal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyShipped (final @Nullable BigDecimal QtyShipped) { set_Value (COLUMNNAME_QtyShipped, QtyShipped); } @Override public BigDecimal getQtyShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override 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
请在Spring Boot框架中完成以下Java代码
public Result<IPage<SysUserRoleCountVo>> queryPageRoleCount(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) { Result<IPage<SysUserRoleCountVo>> result = new Result<>(); LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>(); //------------------------------------------------------------------------------------------------ //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】 if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){ query.eq(SysRole::getTenantId, oConvertUtils.getInt(TenantContext.getTenant(), 0)); } //------------------------------------------------------------------------------------------------ Page<SysRole> page = new Page<>(pageNo, pageSize); IPage<SysRole> pageList = sysRoleService.page(page, query); List<SysRole> records = pageList.getRecords(); IPage<SysUserRoleCountVo> sysRoleCountPage = new PageDTO<>(); List<SysUserRoleCountVo> sysCountVoList = new ArrayList<>(); //循环角色数据获取每个角色下面对应的角色数量 for (SysRole role:records) { LambdaQueryWrapper<SysUserRole> countQuery = new LambdaQueryWrapper<>();
countQuery.eq(SysUserRole::getRoleId,role.getId()); long count = sysUserRoleService.count(countQuery); SysUserRoleCountVo countVo = new SysUserRoleCountVo(); BeanUtils.copyProperties(role,countVo); countVo.setCount(count); sysCountVoList.add(countVo); } sysRoleCountPage.setRecords(sysCountVoList); sysRoleCountPage.setTotal(pageList.getTotal()); sysRoleCountPage.setSize(pageList.getSize()); result.setSuccess(true); result.setResult(sysRoleCountPage); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysRoleController.java
2
请在Spring Boot框架中完成以下Java代码
public class ReconciliationDataGetBiz { private static final Log LOG = LogFactory.getLog(ReconciliationDataGetBiz.class); @Autowired private RpTradePaymentQueryService rpTradePaymentQueryService; /** * 获取平台指定支付渠道、指定订单日下[所有成功]的数据 * * @param billDate * 账单日 * @param interfaceCode * 支付渠道 * @return */ public List<RpTradePaymentRecord> getSuccessPlatformDateByBillDate(Date billDate, String interfaceCode) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String billDateStr = sdf.format(billDate); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("billDate", billDateStr); paramMap.put("interfaceCode", interfaceCode); paramMap.put("status", TradeStatusEnum.SUCCESS.name()); LOG.info("开始查询平台支付成功的数据:billDate[" + billDateStr + "],支付方式为[" + interfaceCode + "]"); List<RpTradePaymentRecord> recordList = rpTradePaymentQueryService.listPaymentRecord(paramMap); if (recordList == null) { recordList = new ArrayList<RpTradePaymentRecord>(); } LOG.info("查询得到的数据count[" + recordList.size() + "]"); return recordList;
} /** * 获取平台指定支付渠道、指定订单日下[所有]的数据 * * @param billDate * 账单日 * @param interfaceCode * 支付渠道 * @return */ public List<RpTradePaymentRecord> getAllPlatformDateByBillDate(Date billDate, String interfaceCode) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String billDateStr = sdf.format(billDate); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("billDate", billDateStr); paramMap.put("interfaceCode", interfaceCode); LOG.info("开始查询平台支付所有的数据:billDate[" + billDateStr + "],支付方式为[" + interfaceCode + "]"); List<RpTradePaymentRecord> recordList = rpTradePaymentQueryService.listPaymentRecord(paramMap); if (recordList == null) { recordList = new ArrayList<RpTradePaymentRecord>(); } LOG.info("查询得到的数据count[" + recordList.size() + "]"); return recordList; } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\biz\ReconciliationDataGetBiz.java
2
请完成以下Java代码
public void loadDataSource() { configAttributeMap = dynamicSecurityService.loadDataSource(); } public void clearDataSource() { configAttributeMap.clear(); configAttributeMap = null; } @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { if (configAttributeMap == null) this.loadDataSource(); List<ConfigAttribute> configAttributes = new ArrayList<>(); //获取当前访问的路径 String url = ((FilterInvocation) o).getRequestUrl(); String path = URLUtil.getPath(url); PathMatcher pathMatcher = new AntPathMatcher(); Iterator<String> iterator = configAttributeMap.keySet().iterator(); //获取访问该路径所需资源 while (iterator.hasNext()) { String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) { configAttributes.add(configAttributeMap.get(pattern)); } } // 未设置操作请求权限,返回空集合 return configAttributes; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> aClass) { return true; } }
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\component\DynamicSecurityMetadataSource.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; }
public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Priority getPriority() { return priority; } public void setPriority(Priority priority) { this.priority = priority; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\enums\Article.java
1
请完成以下Java代码
public void setType_Clearing (final java.lang.String Type_Clearing) { set_Value (COLUMNNAME_Type_Clearing, Type_Clearing); } @Override public java.lang.String getType_Clearing() { return get_ValueAsString(COLUMNNAME_Type_Clearing); } /** * Type_Conditions AD_Reference_ID=540271 * Reference name: Type_Conditions */ public static final int TYPE_CONDITIONS_AD_Reference_ID=540271; /** FlatFee = FlatFee */ public static final String TYPE_CONDITIONS_FlatFee = "FlatFee"; /** HoldingFee = HoldingFee */ public static final String TYPE_CONDITIONS_HoldingFee = "HoldingFee"; /** Subscription = Subscr */ public static final String TYPE_CONDITIONS_Subscription = "Subscr"; /** Refundable = Refundable */ public static final String TYPE_CONDITIONS_Refundable = "Refundable"; /** QualityBasedInvoicing = QualityBsd */ public static final String TYPE_CONDITIONS_QualityBasedInvoicing = "QualityBsd"; /** Procurement = Procuremnt */ public static final String TYPE_CONDITIONS_Procurement = "Procuremnt"; /** Refund = Refund */ public static final String TYPE_CONDITIONS_Refund = "Refund"; /** Commission = Commission */ public static final String TYPE_CONDITIONS_Commission = "Commission"; /** MarginCommission = MarginCommission */ public static final String TYPE_CONDITIONS_MarginCommission = "MarginCommission"; /** Mediated commission = MediatedCommission */ public static final String TYPE_CONDITIONS_MediatedCommission = "MediatedCommission"; /** LicenseFee = LicenseFee */ public static final String TYPE_CONDITIONS_LicenseFee = "LicenseFee"; /** CallOrder = CallOrder */ public static final String TYPE_CONDITIONS_CallOrder = "CallOrder"; @Override public void setType_Conditions (final java.lang.String Type_Conditions)
{ set_ValueNoCheck (COLUMNNAME_Type_Conditions, Type_Conditions); } @Override public java.lang.String getType_Conditions() { return get_ValueAsString(COLUMNNAME_Type_Conditions); } /** * Type_Flatrate AD_Reference_ID=540264 * Reference name: Type_Flatrate */ public static final int TYPE_FLATRATE_AD_Reference_ID=540264; /** NONE = NONE */ public static final String TYPE_FLATRATE_NONE = "NONE"; /** Corridor_Percent = LIPE */ public static final String TYPE_FLATRATE_Corridor_Percent = "LIPE"; /** Reported Quantity = RPTD */ public static final String TYPE_FLATRATE_ReportedQuantity = "RPTD"; @Override public void setType_Flatrate (final java.lang.String Type_Flatrate) { set_Value (COLUMNNAME_Type_Flatrate, Type_Flatrate); } @Override public java.lang.String getType_Flatrate() { return get_ValueAsString(COLUMNNAME_Type_Flatrate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Conditions.java
1
请完成以下Java代码
public Builder setKeyColumn(final boolean keyColumn) { this.keyColumn = keyColumn; return this; } public Builder setEncrypted(final boolean encrypted) { this.encrypted = encrypted; return this; } /** * Sets ORDER BY priority and direction (ascending/descending) * * @param priority priority; if positive then direction will be ascending; if negative then direction will be descending */ public Builder setDefaultOrderBy(final int priority)
{ if (priority >= 0) { orderByPriority = priority; orderByAscending = true; } else { orderByPriority = -priority; orderByAscending = false; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java
1
请完成以下Java代码
protected void postProcess(final boolean success) { invalidateView(); invalidateParentView(); } private HuId getSelectedHUId() { return getSingleSelectedRow().getHuId(); } private boolean checkSourceHuPreconditionIncludingEmptyHUs() { final HuId huId = getSelectedHUId(); final Collection<HuId> sourceHUs = sourceHUsRepository.retrieveMatchingSourceHUIds(huId); return !sourceHUs.isEmpty(); } private List<ProductId> getProductIds() { return getHUProductStorages() .stream() .filter(productStorage -> !productStorage.isEmpty()) .map(IProductStorage::getProductId) .distinct() .collect(ImmutableList.toImmutableList()); } private Quantity getHUStorageQty(@NonNull final ProductId productId) { return getHUProductStorages() .stream()
.filter(productStorage -> ProductId.equals(productStorage.getProductId(), productId)) .map(IHUProductStorage::getQty) .findFirst() .orElseThrow(() -> new AdempiereException("No Qty found for " + productId)); } private ImmutableList<IHUProductStorage> getHUProductStorages() { ImmutableList<IHUProductStorage> huProductStorage = _huProductStorages; if (huProductStorage == null) { final HuId huId = getSelectedHUId(); final I_M_HU hu = handlingUnitsBL.getById(huId); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); huProductStorage = _huProductStorages = ImmutableList.copyOf(storageFactory .getStorage(hu) .getProductStorages()); } return huProductStorage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_ReturnQtyToSourceHU.java
1
请完成以下Java代码
public double getImageableHeight (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getImageableWidth(); return super.getImageableHeight(); } /** * Get Image Width in 1/72 inch * @param orientationCorrected correct for orientation * @return imagable width */ public double getImageableWidth (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getImageableHeight(); return super.getImageableWidth();
} /** * Get Margin * @param orientationCorrected correct for orientation * @return margin */ public Insets getMargin (boolean orientationCorrected) { return new Insets ((int)getImageableY(orientationCorrected), // top (int)getImageableX(orientationCorrected), // left (int)(getHeight(orientationCorrected)-getImageableY(orientationCorrected)-getImageableHeight(orientationCorrected)), // bottom (int)(getWidth(orientationCorrected)-getImageableX(orientationCorrected)-getImageableWidth(orientationCorrected))); // right } // getMargin } // CPapaer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\CPaper.java
1
请完成以下Java代码
public final String toString() { if ( getCodeset() != null ) return (html.toString(getCodeset())); else return(html.toString()); } /** Override the toString() method so that it prints something meaningful. */ public final String toString(String codeset) { return(html.toString(codeset));
} /** Allows the XhtmlFrameSetDocument to be cloned. Doesn't return an instanceof XhtmlFrameSetDocument returns instance of html. */ public Object clone() { return(html.clone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlFrameSetDocument.java
1
请在Spring Boot框架中完成以下Java代码
Output resizeBilinear(Output images, Output size) { return binaryOp("ResizeBilinear", images, size); } Output expandDims(Output input, Output dim) { return binaryOp("ExpandDims", input, dim); } Output cast(Output value, DataType dtype) { return g.opBuilder("Cast", "Cast", scope).addInput(value).setAttr("DstT", dtype).build().output(0); } Output decodeJpeg(Output contents, long channels) { return g.opBuilder("DecodeJpeg", "DecodeJpeg", scope) .addInput(contents) .setAttr("channels", channels) .build() .output(0); } Output<? extends TType> constant(String name, Tensor t) { return g.opBuilder("Const", name, scope) .setAttr("dtype", t.dataType()) .setAttr("value", t) .build() .output(0); } private Output binaryOp(String type, Output in1, Output in2) { return g.opBuilder(type, type, scope).addInput(in1).addInput(in2).build().output(0);
} private final Graph g; } @PreDestroy public void close() { session.close(); } @Data @NoArgsConstructor @AllArgsConstructor public static class LabelWithProbability { private String label; private float probability; private long elapsed; } }
repos\springboot-demo-master\Tensorflow\src\main\java\com\et\tf\service\ClassifyImageService.java
2
请完成以下Java代码
public VEditor createEditor(final boolean tableEditor) { // Reset lookup state // background: the lookup implements MutableComboBoxModel which stores the selected item. // If this lookup was previously used somewhere, the selected item is retained from there and we will get unexpected results. final Lookup lookup = gridField.getLookup(); if (lookup != null) { lookup.setSelectedItem(null); } // // Create a new editor VEditor editor = swingEditorFactory.getEditor(gridField, tableEditor); if (editor == null && tableEditor) { editor = new VString(); } // // Configure the new editor if (editor != null) { editor.setMandatory(false); editor.setReadWrite(true); } return editor; } public CLabel createEditorLabel() { return swingEditorFactory.getLabel(gridField); } @Override public Object convertValueToFieldType(final Object valueObj) { return UserQueryFieldHelper.parseValueObjectByColumnDisplayType(valueObj, getDisplayType(), getColumnName()); } @Override public String getValueDisplay(final Object value) { String infoDisplay = value == null ? "" : value.toString(); if (isLookup()) { final Lookup lookup = getLookup(); if (lookup != null) { infoDisplay = lookup.getDisplay(value); } } else if (getDisplayType() == DisplayType.YesNo) { final IMsgBL msgBL = Services.get(IMsgBL.class); infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay); } return infoDisplay; }
@Override public boolean matchesColumnName(final String columnName) { if (columnName == null || columnName.isEmpty()) { return false; } if (columnName.equals(getColumnName())) { return true; } if (gridField.isVirtualColumn()) { if (columnName.equals(gridField.getColumnSQL(false))) { return true; } if (columnName.equals(gridField.getColumnSQL(true))) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
1
请完成以下Java代码
protected PurchaseOrderFromItemFactory createGroup( @NonNull final Object itemHashKey, final PurchaseOrderItem item_NOTUSED) { final PurchaseOrderAggregationKey orderAggregationKey = PurchaseOrderAggregationKey.cast(itemHashKey); return PurchaseOrderFromItemFactory.builder() .orderAggregationKey(orderAggregationKey) .userNotifications(userNotifications) .docType(docType) .build(); } @Override protected void closeGroup(@NonNull final PurchaseOrderFromItemFactory orderFactory) { final I_C_Order newPurchaseOrder = orderFactory.createAndComplete(); createdPurchaseOrders.add(newPurchaseOrder);
} @Override protected void addItemToGroup( @NonNull final PurchaseOrderFromItemFactory orderFactory, @NonNull final PurchaseOrderItem candidate) { orderFactory.addCandidate(candidate); } @VisibleForTesting List<I_C_Order> getCreatedPurchaseOrders() { return ImmutableList.copyOf(createdPurchaseOrders); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseOrderFromItemsAggregator.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<JsonPurchaseCandidateCreateItem> mapRowToRequestItem(@NonNull final PurchaseOrderRow purchaseOrderRow) { if (hasMissingFields(purchaseOrderRow)) { pInstanceLogger.logMessage("Skipping row due to missing mandatory information, see row: " + purchaseOrderRow); return Optional.empty(); } final JsonPurchaseCandidateCreateItem requestItem = JsonPurchaseCandidateCreateItem.builder() .orgCode(externalSystemRequest.getOrgCode()) .externalSystemCode(externalSystemRequest.getExternalSystemName().getName()) .productIdentifier(ExternalId.ofId(purchaseOrderRow.getProductIdentifier()).toExternalIdentifierString()) .warehouseIdentifier(ExternalId.ofId(purchaseOrderRow.getWarehouseIdentifier()).toExternalIdentifierString()) .vendor(JsonVendor.builder() .bpartnerIdentifier(ExternalId.ofId(purchaseOrderRow.getBpartnerIdentifier()).toExternalIdentifierString()) .build()) .externalHeaderId(purchaseOrderRow.getExternalHeaderId()) .externalLineId(purchaseOrderRow.getExternalLineId()) .poReference(purchaseOrderRow.getPoReference()) .qty(JsonQuantity.builder() .qty(purchaseOrderRow.getQty()) .uomCode(DEFAULT_UOM_X12DE355_CODE) .build()) .isManualPrice(true) .isPrepared(true) .price(JsonPrice.builder() .value(purchaseOrderRow.getPrice()) .currencyCode(DEFAULT_CURRENCY_CODE) .priceUomCode(DEFAULT_UOM_X12DE355_CODE) .build()) .purchaseDateOrdered(Optional.ofNullable(StringUtils.trimBlankToNull(purchaseOrderRow.getDateOrdered())) .map(UpsertPurchaseCandidateProcessor::parseDateTime) .orElse(null)) .purchaseDatePromised(Optional.ofNullable(StringUtils.trimBlankToNull(purchaseOrderRow.getDatePromised())) .map(UpsertPurchaseCandidateProcessor::parseDateTime) .orElse(null)) .build();
return Optional.of(requestItem); } private static boolean hasMissingFields(@NonNull final PurchaseOrderRow orderRow) { return Check.isBlank(orderRow.getProductIdentifier()) || Check.isBlank(orderRow.getBpartnerIdentifier()) || Check.isBlank(orderRow.getWarehouseIdentifier()) || Check.isBlank(orderRow.getPoReference()) || Check.isBlank(orderRow.getExternalHeaderId()) || Check.isBlank(orderRow.getExternalLineId()) || orderRow.getPrice() == null || orderRow.getQty() == null; } @NonNull private static ZonedDateTime parseDateTime(@NonNull final String dateString) { final LocalDateTime localDateTime = LocalDateTime.parse(dateString, LOCAL_DATE_TIME_FORMATTER); return localDateTime.atZone(EUROPE_BERLIN); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\UpsertPurchaseCandidateProcessor.java
2
请完成以下Java代码
public IdentityOperationResult deleteTenant(String tenantId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.deleteTenant(tenantId); } @Override public IdentityOperationResult createMembership(String userId, String groupId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.createMembership(userId, groupId); } @Override public IdentityOperationResult deleteMembership(String userId, String groupId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.deleteMembership(userId, groupId); } @Override public IdentityOperationResult createTenantUserMembership(String tenantId, String userId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.createTenantUserMembership(tenantId, userId); }
@Override public IdentityOperationResult createTenantGroupMembership(String tenantId, String groupId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.createTenantGroupMembership(tenantId, groupId); } @Override public IdentityOperationResult deleteTenantUserMembership(String tenantId, String userId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.deleteTenantUserMembership(tenantId, userId); } @Override public IdentityOperationResult deleteTenantGroupMembership(String tenantId, String groupId) { if (springSecurityAuthentication()) { unsupportedOperationForOAuth2(); } return super.deleteTenantGroupMembership(tenantId, groupId); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\OAuth2IdentityProvider.java
1
请完成以下Java代码
private final Method findMethodImplementationOrNull(final Method interfaceMethod) { try { final String name = interfaceMethod.getName(); final Class<?>[] parameterTypes = interfaceMethod.getParameterTypes(); final Method implMethod = implClass.getMethod(name, parameterTypes); return implMethod; } catch (SecurityException e) { throw new IllegalStateException("Cannot get implementation method for " + implClass + ", interfaceMethod=" + interfaceMethod, e); } catch (NoSuchMethodException e) { return null; } } public Method getMethodImplementation(final Method interfaceMethod)
{ try { final Method implMethod = interfaceMethod2implMethod.get(interfaceMethod); if (implMethod == null || implMethod == NullMethod.NULL) { return null; } return implMethod; } catch (ExecutionException e) { // NOTE: shall not happen final String message = "Error while trying to find implementation method" + "\n Interface method: " + interfaceMethod + "\n Implementation class: " + implClass; throw new RuntimeException(message, e.getCause()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\ProxyClassMethodBindings.java
1
请完成以下Java代码
public class PrintEvenOddWaitNotify { public static void main(String... args) { Printer print = new Printer(); Thread t1 = new Thread(new TaskEvenOdd(print, 10, false), "Odd"); Thread t2 = new Thread(new TaskEvenOdd(print, 10, true), "Even"); t1.start(); t2.start(); } } class TaskEvenOdd implements Runnable { private final int max; private final Printer print; private final boolean isEvenNumber; TaskEvenOdd(Printer print, int max, boolean isEvenNumber) { this.print = print; this.max = max; this.isEvenNumber = isEvenNumber; } @Override public void run() { int number = isEvenNumber ? 2 : 1; while (number <= max) { if (isEvenNumber) { print.printEven(number); } else { print.printOdd(number); } number += 2; } } } class Printer { private volatile boolean isOdd; synchronized void printEven(int number) {
while (!isOdd) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println(Thread.currentThread().getName() + ":" + number); isOdd = false; notify(); } synchronized void printOdd(int number) { while (isOdd) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println(Thread.currentThread().getName() + ":" + number); isOdd = true; notify(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\evenandodd\PrintEvenOddWaitNotify.java
1
请完成以下Java代码
public void exportDunnings(@NonNull final ImmutableList<DunningDocId> dunningDocIds) { for (final DunningDocId dunningDocId : dunningDocIds) { final List<DunningToExport> dunningsToExport = dunningToExportFactory.getCreateForId(dunningDocId); for (final DunningToExport dunningToExport : dunningsToExport) { exportDunning(dunningToExport); } } } private void exportDunning(@NonNull final DunningToExport dunningToExport) { final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); final List<DunningExportClient> exportClients = dunningExportServiceRegistry.createExportClients(dunningToExport); if (exportClients.isEmpty()) { loggable.addLog("DunningExportService - Found no DunningExportClient implementors for dunningDocId={}; dunningToExport={}", dunningToExport.getId(), dunningToExport); return; // nothing more to do } final List<AttachmentEntryCreateRequest> attachmentEntryCreateRequests = new ArrayList<>(); for (final DunningExportClient exportClient : exportClients) { final List<DunningExportResult> exportResults = exportClient.export(dunningToExport); for (final DunningExportResult exportResult : exportResults) { attachmentEntryCreateRequests.add(createAttachmentRequest(exportResult)); } } for (final AttachmentEntryCreateRequest attachmentEntryCreateRequest : attachmentEntryCreateRequests) { attachmentEntryService.createNewAttachment( TableRecordReference.of(I_C_DunningDoc.Table_Name, dunningToExport.getId()), attachmentEntryCreateRequest);
loggable.addLog("DunningExportService - Attached export data to dunningDocId={}; attachment={}", dunningToExport.getId(), attachmentEntryCreateRequest); } } private AttachmentEntryCreateRequest createAttachmentRequest(@NonNull final DunningExportResult exportResult) { byte[] byteArrayData; try { byteArrayData = ByteStreams.toByteArray(exportResult.getData()); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } final AttachmentTags attachmentTags = AttachmentTags.builder() .tag(AttachmentTags.TAGNAME_IS_DOCUMENT, StringUtils.ofBoolean(true)) // other than the "input" xml with was more or less just a template, this is a document .tag(AttachmentTags.TAGNAME_BPARTNER_RECIPIENT_ID, Integer.toString(exportResult.getRecipientId().getRepoId())) .tag(DunningExportClientFactory.ATTATCHMENT_TAGNAME_EXPORT_PROVIDER, exportResult.getDunningExportProviderId()) .build(); final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest .builderFromByteArray( exportResult.getFileName(), byteArrayData) .tags(attachmentTags) .build(); return attachmentEntryCreateRequest; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\export\DunningExportService.java
1
请完成以下Java代码
private static DirContext connectToServer(Hashtable<String, String> env) throws NamingException { String url = env.get(Context.PROVIDER_URL); System.out.println("connecting to " + url + "..."); DirContext context = new InitialDirContext(env); System.out.println("successfully connected to " + url); return context; } private static void executeQuery(DirContext context, String query) throws NamingException { Attributes attributes = context.getAttributes(query); NamingEnumeration<? extends Attribute> all = attributes.getAll(); while (all.hasMoreElements()) { Attribute next = all.next(); String key = next.getID(); Object value = next.get(); System.out.println(key + "=" + value); } } private static Hashtable<String, String> createEnvironmentFromProperties() { String factory = System.getProperty("factory", "com.sun.jndi.ldap.LdapCtxFactory"); String authType = System.getProperty("authType", "none"); String url = System.getProperty("url"); String user = System.getProperty("user"); String password = System.getProperty("password"); String query = System.getProperty(QUERY, user); if (url == null) { throw new IllegalArgumentException("please provide 'url' system property"); } Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, factory); env.put("com.sun.jndi.ldap.read.timeout", "5000"); env.put("com.sun.jndi.ldap.connect.timeout", "5000"); env.put(Context.SECURITY_AUTHENTICATION, authType); env.put(Context.PROVIDER_URL, url); if (query != null) { env.put(LdapConnectionTool.QUERY, query); } if (user != null) { if (password == null) { throw new IllegalArgumentException("please provide 'password' system property"); } env.put(Context.SECURITY_PRINCIPAL, user); env.put(Context.SECURITY_CREDENTIALS, password); } return env; } }
repos\tutorials-master\core-java-modules\core-java-jndi\src\main\java\com\baeldung\jndi\ldap\connection\tool\LdapConnectionTool.java
1
请完成以下Java代码
public void setValueAt(Object aValue, int row, int column) { @SuppressWarnings("rawtypes") final Vector rowVector = (Vector)dataVector.elementAt(row); // Check if value was really changed. If not, do nothing final Object valueOld = rowVector.get(column); if (Check.equals(valueOld, aValue)) { return; } boolean valueSet = false; try {
rowVector.setElementAt(aValue, column); fireTableCellUpdated(row, column); valueSet = true; } finally { // Rollback changes if (!valueSet) { rowVector.setElementAt(valueOld, column); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\minigrid\MiniTableModel.java
1
请完成以下Java代码
public boolean isLimited() { return !isNoLimit(); } public boolean isNoLimit() { return isNoLimit(value); } private static boolean isNoLimit(final int value) { return value <= 0; } public QueryLimit ifNoLimitUse(final int limit) { return isNoLimit() ? ofInt(limit) : this; } @SuppressWarnings("unused") public QueryLimit ifNoLimitUse(@NonNull final QueryLimit limit) { return isNoLimit() ? limit : this; } public boolean isLessThanOrEqualTo(final int other) { return isLimited() && value <= other; } public boolean isLimitHitOrExceeded(@NonNull final Collection<?> collection) { return isLimitHitOrExceeded(collection.size()); } public boolean isLimitHitOrExceeded(@NonNull final MutableInt countHolder) { return isLimitHitOrExceeded(countHolder.getValue());
} public boolean isLimitHitOrExceeded(final int count) { return isLimited() && value <= count; } public boolean isBelowLimit(@NonNull final Collection<?> collection) { return isNoLimit() || value > collection.size(); } public QueryLimit minusSizeOf(@NonNull final Collection<?> collection) { if (isNoLimit() || collection.isEmpty()) { return this; } else { final int collectionSize = collection.size(); final int newLimitInt = value - collectionSize; if (newLimitInt <= 0) { throw new AdempiereException("Invalid collection size. It shall be less than " + value + " but it was " + collectionSize); } return ofInt(newLimitInt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\QueryLimit.java
1
请完成以下Java代码
public void logModelHTTLLongerThanGlobalConfiguration(String definitionKey) { logWarn( "017", "definitionKey: {}; " + "The specified Time To Live (TTL) in the model is longer than the global TTL configuration. " + "The historic data related to this model will be cleaned up at later point comparing to the other processes.", definitionKey); } public NotValidException logErrorNoTTLConfigured() { return new NotValidException(exceptionMessage("018", "History Time To Live (TTL) cannot be null. " + "TTL is necessary for the History Cleanup to work. The following options are possible:\n" + "* Set historyTimeToLive in the model\n" + "* Set a default historyTimeToLive as a global process engine configuration\n" + "* (Not recommended) Deactivate the enforceTTL config to disable this check")); }
public ProcessEngineException invalidTransactionIsolationLevel(String transactionIsolationLevel) { return new ProcessEngineException(exceptionMessage("019", "The transaction isolation level set for the database is '{}' which differs from the recommended value. " + "Please change the isolation level to 'READ_COMMITTED' or set property 'skipIsolationLevelCheck' to true. " + "Please keep in mind that some levels are known to cause deadlocks and other unexpected behaviours.", transactionIsolationLevel)); } public void logSkippedIsolationLevelCheck(String transactionIsolationLevel) { logWarn("020", "The transaction isolation level set for the database is '{}' which differs from the recommended value " + "and property skipIsolationLevelCheck is enabled. " + "Please keep in mind that levels different from 'READ_COMMITTED' are known to cause deadlocks and other unexpected behaviours.", transactionIsolationLevel); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ConfigurationLogger.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricTaskLogEntriesByScopeDefinitionId(String scopeType, String scopeDefinitionId) { Map<String, String> params = new HashMap<>(2); params.put("scopeDefinitionId", scopeDefinitionId); params.put("scopeType", scopeType); getDbSqlSession().delete("deleteHistoricTaskLogEntriesByScopeDefinitionId", params, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByTaskId(String taskId) { getDbSqlSession().delete("deleteHistoricTaskLogEntriesByTaskId", taskId, HistoricTaskLogEntryEntityImpl.class); } @Override public void bulkDeleteHistoricTaskLogEntriesForTaskIds(Collection<String> taskIds) { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForTaskIds", createSafeInValuesList(taskIds), HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesForNonExistingProcessInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances", null, HistoricTaskLogEntryEntityImpl.class); }
@Override public void deleteHistoricTaskLogEntriesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances", null, HistoricTaskLogEntryEntityImpl.class); } @Override public long findHistoricTaskLogEntriesCountByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricTaskLogEntriesCountByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override public List<HistoricTaskLogEntry> findHistoricTaskLogEntriesByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return getDbSqlSession().selectListWithRawParameter("selectHistoricTaskLogEntriesByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override protected IdGenerator getIdGenerator() { return taskServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MyBatisHistoricTaskLogEntryDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the street property. * * @return * possible object is * {@link String } * */ public String getStreet() { return street; } /** * Sets the value of the street property. * * @param value * allowed object is * {@link String } * */ public void setStreet(String value) { this.street = value; } /** * Gets the value of the zip property. * * @return * possible object is * {@link String } * */ public String getZIP() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link String } * */ public void setZIP(String value) { this.zip = value; } /** * Gets the value of the town property. * * @return * possible object is * {@link String } * */ public String getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is
* {@link String } * */ public void setTown(String value) { this.town = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link String } * */ public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */ public void setCountry(String value) { this.country = value; } /** * Details about the contact person at the delivery point. * * @return * possible object is * {@link ContactType } * */ public ContactType getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link ContactType } * */ public void setContact(ContactType value) { this.contact = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DeliveryPointDetails.java
2
请在Spring Boot框架中完成以下Java代码
public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime;
} public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobResponse.java
2
请完成以下Java代码
public Capacity multiply(final int multiplier) { Check.assume(multiplier >= 0, "multiplier = {} needs to be 0", multiplier); // If capacity is infinite, there is no point to multiply it if (infiniteCapacity) { return this; } final BigDecimal capacityNew = capacity.multiply(BigDecimal.valueOf(multiplier)); return createCapacity( capacityNew, productId, uom, allowNegativeCapacity); } public I_C_UOM getC_UOM() { return uom; } @Override public String toString() { return "Capacity [" + "infiniteCapacity=" + infiniteCapacity + ", capacity(qty)=" + capacity
+ ", product=" + productId + ", uom=" + (uom == null ? "null" : uom.getUOMSymbol()) + ", allowNegativeCapacity=" + allowNegativeCapacity + "]"; } public Quantity computeQtyCUs(final int qtyTUs) { if (qtyTUs < 0) { throw new AdempiereException("@QtyPacks@ < 0"); } return multiply(qtyTUs).toQuantity(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Capacity.java
1
请完成以下Java代码
public class ChatResponse { private List<Choice> choices; public static class Choice { private int index; private Message message; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public Message getMessage() { return message;
} public void setMessage(Message message) { this.message = message; } } public List<Choice> getChoices() { return choices; } public void setChoices(List<Choice> choices) { this.choices = choices; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-2\src\main\java\com\baeldung\openai\dto\ChatResponse.java
1
请完成以下Java代码
protected AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() { return this.authenticationDetailsSource; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource cannot be null"); this.authenticationDetailsSource = authenticationDetailsSource; } /** * Sets the strategy to be used to validate the {@code UserDetails} object obtained * for the user when processing a remember-me cookie to automatically log in a user. * @param userDetailsChecker the strategy which will be passed the user object to * allow it to be rejected if account should not be allowed to authenticate (if it is * locked, for example). Defaults to a {@code AccountStatusUserDetailsChecker} * instance. * */ public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { this.userDetailsChecker = userDetailsChecker; } public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { this.authoritiesMapper = authoritiesMapper; } /** * @since 5.5 */
@Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } /** * Sets the {@link Consumer}, allowing customization of cookie. * @param cookieCustomizer customize for cookie * @since 6.4 */ public void setCookieCustomizer(Consumer<Cookie> cookieCustomizer) { Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null"); this.cookieCustomizer = cookieCustomizer; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\AbstractRememberMeServices.java
1
请完成以下Java代码
public class ProblemDto { protected String message; protected int line; protected int column; protected String mainElementId; protected List<String> еlementIds; // transformer ///////////////////////////// public static ProblemDto fromProblem(Problem problem) { ProblemDto dto = new ProblemDto(); dto.setMessage(problem.getMessage()); dto.setLine(problem.getLine()); dto.setColumn(problem.getColumn()); dto.setMainElementId(problem.getMainElementId()); dto.setЕlementIds(problem.getElementIds()); return dto; } // getter / setters //////////////////////// public String getMessage() { return message; } public void setMessage(String errorMessage) { this.message = errorMessage; } public int getLine() { return line; } public void setLine(int line) { this.line = line; } public int getColumn() { return column; }
public void setColumn(int column) { this.column = column; } public String getMainElementId() { return mainElementId; } public void setMainElementId(String mainElementId) { this.mainElementId = mainElementId; } public List<String> getЕlementIds() { return еlementIds; } public void setЕlementIds(List<String> elementIds) { this.еlementIds = elementIds; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ProblemDto.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getExecutionJson() { return executionJson; } @Override public void setExecutionJson(String executionJson) { this.executionJson = executionJson; } @Override public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; }
@Override public String getDecisionName() { return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } @Override public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } @Override public String toString() { return "HistoricDecisionExecutionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java
1
请完成以下Java代码
private static GroupCompensationType extractGroupCompensationType(final I_M_Product product) { return GroupCompensationType.ofAD_Ref_List_Value( StringUtils.trimBlankToOptional(product.getGroupCompensationType()) .orElse(X_C_OrderLine.GROUPCOMPENSATIONTYPE_Discount)); } private static GroupCompensationAmtType extractGroupCompensationAmtType(final I_M_Product product) { return GroupCompensationAmtType.ofAD_Ref_List_Value( StringUtils.trimBlankToOptional(product.getGroupCompensationAmtType()) .orElse(X_C_OrderLine.GROUPCOMPENSATIONAMTTYPE_Percent)); } private Percent calculateDefaultDiscountPercentage(final GroupTemplateCompensationLine templateLine, final Group group) { if (templateLine.getPercentage() != null) { return templateLine.getPercentage(); } return retrieveDiscountPercentageFromPricing(templateLine, group); } private Percent retrieveDiscountPercentageFromPricing(final GroupTemplateCompensationLine templateLine, final Group group) { final IEditablePricingContext pricingCtx = pricingBL.createPricingContext(); pricingCtx.setProductId(templateLine.getProductId()); pricingCtx.setBPartnerId(group.getBpartnerId());
pricingCtx.setSOTrx(group.getSoTrx()); pricingCtx.setDisallowDiscount(false);// just to be sure pricingCtx.setQty(BigDecimal.ONE); final IPricingResult pricingResult = pricingBL.createInitialResult(pricingCtx); pricingResult.setCalculated(true); // important, else the Discount rule does not react pricingResult.setPriceStd(group.getTotalNetAmt()); final Discount discountRule = new Discount(); discountRule.calculate(pricingCtx, pricingResult); return pricingResult.getDiscount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupCompensationLineCreateRequestFactory.java
1
请在Spring Boot框架中完成以下Java代码
public MatchResult matcher(HttpServletRequest request) { return this.matcher.matcher(request); } } static final class AuthnRequestParameters { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final AuthnRequest authnRequest; AuthnRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration, AuthnRequest authnRequest) { this.request = request; this.registration = registration; this.authnRequest = authnRequest;
} HttpServletRequest getRequest() { return this.request; } RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } AuthnRequest getAuthnRequest() { return this.authnRequest; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\authentication\BaseOpenSamlAuthenticationRequestResolver.java
2
请在Spring Boot框架中完成以下Java代码
public class League { @Id private int id; private String name; @OneToMany(mappedBy = "league") private List<Player> players = new ArrayList<>(); public League() { } public League(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public List<Player> getPlayers() { return players; } public void setPlayers(List<Player> players) { this.players = players; } @Override public String toString() { return "League{" + "id=" + id + ", name='" + name + '\'' + ", players=" + players.size() + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\joinfetchcriteriaquery\model\League.java
2
请在Spring Boot框架中完成以下Java代码
public int create(List<SmsFlashPromotionProductRelation> relationList) { for (SmsFlashPromotionProductRelation relation : relationList) { relationMapper.insert(relation); } return relationList.size(); } @Override public int update(Long id, SmsFlashPromotionProductRelation relation) { relation.setId(id); return relationMapper.updateByPrimaryKey(relation); } @Override public int delete(Long id) { return relationMapper.deleteByPrimaryKey(id); } @Override
public SmsFlashPromotionProductRelation getItem(Long id) { return relationMapper.selectByPrimaryKey(id); } @Override public List<SmsFlashPromotionProduct> list(Long flashPromotionId, Long flashPromotionSessionId, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); return relationDao.getList(flashPromotionId,flashPromotionSessionId); } @Override public long getCount(Long flashPromotionId, Long flashPromotionSessionId) { SmsFlashPromotionProductRelationExample example = new SmsFlashPromotionProductRelationExample(); example.createCriteria() .andFlashPromotionIdEqualTo(flashPromotionId) .andFlashPromotionSessionIdEqualTo(flashPromotionSessionId); return relationMapper.countByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsFlashPromotionProductRelationServiceImpl.java
2
请完成以下Java代码
public String getKey() { return underlyingEntry.getKey(); } public Object getValue() { return underlyingEntry.getValue().getValue(); } public Object setValue(Object value) { TypedValue typedValue = Variables.untypedValue(value); return underlyingEntry.setValue(typedValue); } public final boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public final int hashCode() { String key = getKey(); Object value = getValue(); return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } }; } public void remove() { iterator.remove(); } }; } public int size() { return variables.size(); }
}; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("{\n"); for (Entry<String, TypedValue> variable : variables.entrySet()) { stringBuilder.append(" "); stringBuilder.append(variable.getKey()); stringBuilder.append(" => "); stringBuilder.append(variable.getValue()); stringBuilder.append("\n"); } stringBuilder.append("}"); return stringBuilder.toString(); } public boolean equals(Object obj) { return asValueMap().equals(obj); } public int hashCode() { return asValueMap().hashCode(); } public Map<String, Object> asValueMap() { return new HashMap<String, Object>(this); } public TypedValue resolve(String variableName) { return getValueTyped(variableName); } public boolean containsVariable(String variableName) { return containsKey(variableName); } public VariableContext asVariableContext() { return this; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\VariableMapImpl.java
1
请在Spring Boot框架中完成以下Java代码
public boolean await(long packProcessingTimeout, TimeUnit milliseconds) throws InterruptedException { return processingTimeoutLatch.await(packProcessingTimeout, milliseconds); } public void onSuccess(UUID id) { boolean empty = false; T msg = ackMap.remove(id); if (msg != null) { empty = pendingCount.decrementAndGet() == 0; } if (empty) { processingTimeoutLatch.countDown(); } else { if (log.isTraceEnabled()) { log.trace("Items left: {}", ackMap.size()); for (T t : ackMap.values()) { log.trace("left item: {}", t); } } } } public void onFailure(UUID id, Throwable t) { boolean empty = false; T msg = ackMap.remove(id); if (msg != null) { empty = pendingCount.decrementAndGet() == 0; failedMap.put(id, msg); if (log.isTraceEnabled()) { log.trace("Items left: {}", ackMap.size()); for (T v : ackMap.values()) { log.trace("left item: {}", v); }
} } if (empty) { processingTimeoutLatch.countDown(); } } public ConcurrentMap<UUID, T> getAckMap() { return ackMap; } public ConcurrentMap<UUID, T> getFailedMap() { return failedMap; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbPackProcessingContext.java
2
请完成以下Java代码
public NamePair getNullValue() { return getAttributeValuesMap().getNullValue(); } @Override public boolean isHighVolume() { if (_highVolume == null) { _highVolume = attribute.isHighVolumeValuesList(); } return _highVolume; } @Immutable private static final class AttributeValuesMap { @Getter private final NamePair nullValue; private final ImmutableMap<String, NamePair> valuesByKey; private final ImmutableList<NamePair> valuesList; private final ImmutableMap<String, AttributeValueId> attributeValueIdByKey; private AttributeValuesMap(final Attribute attribute, final Collection<AttributeListValue> attributeValues) { final ImmutableMap.Builder<String, NamePair> valuesByKey = ImmutableMap.builder(); final ImmutableMap.Builder<String, AttributeValueId> attributeValueIdByKey = ImmutableMap.builder(); NamePair nullValue = null; for (final AttributeListValue av : attributeValues) { if (!av.isActive()) { continue; } final ValueNamePair vnp = toValueNamePair(av); valuesByKey.put(vnp.getValue(), vnp); attributeValueIdByKey.put(vnp.getValue(), av.getId()); // // Null placeholder value (if defined) if (av.isNullFieldValue()) { Check.assumeNull(nullValue, "Only one null value shall be defined for {}, but we found: {}, {}", attribute.getDisplayName().getDefaultValue(), nullValue, av); nullValue = vnp; } } this.valuesByKey = valuesByKey.build(); this.valuesList = ImmutableList.copyOf(this.valuesByKey.values()); this.attributeValueIdByKey = attributeValueIdByKey.build();
this.nullValue = nullValue; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("values", valuesList) .add("nullValue", nullValue) .toString(); } public List<NamePair> getValues() { return valuesList; } public NamePair getValueByKeyOrNull(final String key) { return valuesByKey.get(key); } public AttributeValueId getAttributeValueId(final String valueKey) { final AttributeValueId attributeValueId = attributeValueIdByKey.get(valueKey); if (attributeValueId == null) { throw new AdempiereException("No M_AttributeValue_ID found for '" + valueKey + "'"); } return attributeValueId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\spi\impl\DefaultAttributeValuesProvider.java
1
请完成以下Java代码
public LocatorQRCode getLocatorQRCode(@NonNull final LocatorId locatorId) { final I_M_Locator locator = warehouseDAO.getLocatorById(locatorId); return LocatorQRCode.ofLocator(locator); } @Override @NonNull public ExplainedOptional<LocatorQRCode> getLocatorQRCodeByValue(@NonNull String locatorValue) { final List<I_M_Locator> locators = getActiveLocatorsByValue(locatorValue); if (locators.isEmpty()) { return ExplainedOptional.emptyBecause(AdempiereException.MSG_NotFound); } else if (locators.size() > 1) { return ExplainedOptional.emptyBecause(DBMoreThanOneRecordsFoundException.MSG_QueryMoreThanOneRecordsFound);
} else { final I_M_Locator locator = locators.get(0); return ExplainedOptional.of(LocatorQRCode.ofLocator(locator)); } } @Override public List<I_M_Locator> getActiveLocatorsByValue(final @NotNull String locatorValue) { return warehouseDAO.retrieveActiveLocatorsByValue(locatorValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseBL.java
1
请在Spring Boot框架中完成以下Java代码
private static void verifyCandidateType(final Candidate demandCandidate) { final CandidateType candidateType = demandCandidate.getType(); Preconditions.checkArgument(candidateType == CandidateType.DEMAND || candidateType == CandidateType.STOCK_UP, "Given parameter demandCandidate needs to have DEMAND or STOCK_UP as type; demandCandidate=%s", demandCandidate); } @NonNull public static SupplyRequiredDescriptor createSupplyRequiredDescriptor( @NonNull final Candidate demandCandidate, @NonNull final BigDecimal requiredAdditionalQty, @Nullable final CandidateId supplyCandidateId) { final SupplyRequiredDescriptorBuilder descriptorBuilder = createAndInitSupplyRequiredDescriptor( demandCandidate, requiredAdditionalQty); if (supplyCandidateId != null) { descriptorBuilder.supplyCandidateId(supplyCandidateId.getRepoId()); } if (demandCandidate.getDemandDetail() != null) { final DemandDetail demandDetail = demandCandidate.getDemandDetail(); descriptorBuilder .shipmentScheduleId(IdConstants.toRepoId(demandDetail.getShipmentScheduleId())) .forecastId(IdConstants.toRepoId(demandDetail.getForecastId())) .forecastLineId(IdConstants.toRepoId(demandDetail.getForecastLineId())) .orderId(IdConstants.toRepoId(demandDetail.getOrderId())) .orderLineId(IdConstants.toRepoId(demandDetail.getOrderLineId())) .subscriptionProgressId(IdConstants.toRepoId(demandDetail.getSubscriptionProgressId())); } return descriptorBuilder.build(); } @NonNull private static SupplyRequiredDescriptorBuilder createAndInitSupplyRequiredDescriptor(
@NonNull final Candidate candidate, @NonNull final BigDecimal qty) { final PPOrderRef ppOrderRef = candidate.getBusinessCaseDetail(ProductionDetail.class) .map(ProductionDetail::getPpOrderRef) .orElse(null); return SupplyRequiredDescriptor.builder() .demandCandidateId(candidate.getId().getRepoId()) .eventDescriptor(EventDescriptor.ofClientOrgAndTraceId(candidate.getClientAndOrgId(), candidate.getTraceId())) .materialDescriptor(candidate.getMaterialDescriptor().withQuantity(qty)) .fullDemandQty(candidate.getQuantity()) .ppOrderRef(ppOrderRef) .simulated(candidate.isSimulated()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\SupplyRequiredEventCreator.java
2
请完成以下Java代码
public void updateHUAttribute(@NonNull final HuId huId, @NonNull final AttributeCode attributeCode, @Nullable final Object attributeValue) { final I_M_Attribute attribute = attributeDAO.retrieveActiveAttributeByValueOrNull(attributeCode); if (attribute == null) { logger.debug("M_Attribute with Value={} does not exist or it is inactive; -> do nothing", attributeCode.getCode()); return; } final I_M_HU hu = handlingUnitsDAO.getById(huId); huTrxBL.createHUContextProcessorExecutor().run(huContext -> { final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory(); final IAttributeStorage attributeStorage = attributeStorageFactory.getAttributeStorage(hu); if (attributeStorage.hasAttribute(attribute)) { attributeStorage.setValue(attribute, attributeValue); } attributeStorage.saveChangesIfNeeded(); }); } @Override @Nullable public String getHUAttributeValue(@NonNull final I_M_HU hu, @NonNull final AttributeCode attributeCode) { return Optional.ofNullable(attributeDAO.retrieveActiveAttributeIdByValueOrNull(attributeCode)) .map(atrId -> huAttributesDAO.retrieveAttribute(hu, atrId))
.map(I_M_HU_Attribute::getValue) .orElse(null); } @Override @Nullable public IAttributeValue getAttributeValue(@NonNull final I_M_HU hu, @NonNull final AttributeCode attributeCode) { final IMutableHUContext huContext = handlingUnitsBL .createMutableHUContext(PlainContextAware.newWithThreadInheritedTrx()); final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory(); final IAttributeStorage attributeStorage = attributeStorageFactory.getAttributeStorage(hu); return attributeStorage.getAttributeValue(attributeCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUAttributesBL.java
1
请完成以下Java代码
public void setUnitsPerPack (final int UnitsPerPack) { set_Value (COLUMNNAME_UnitsPerPack, UnitsPerPack); } @Override public int getUnitsPerPack() { return get_ValueAsInt(COLUMNNAME_UnitsPerPack); } @Override public void setUnitsPerPallet (final @Nullable BigDecimal UnitsPerPallet) { set_Value (COLUMNNAME_UnitsPerPallet, UnitsPerPallet); } @Override public BigDecimal getUnitsPerPallet() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_UnitsPerPallet); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVersionNo (final @Nullable java.lang.String VersionNo) { set_Value (COLUMNNAME_VersionNo, VersionNo); } @Override public java.lang.String getVersionNo() { return get_ValueAsString(COLUMNNAME_VersionNo); } @Override public void setVolume (final @Nullable BigDecimal Volume) { set_Value (COLUMNNAME_Volume, Volume); } @Override public BigDecimal getVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setWarehouse_temperature (final @Nullable java.lang.String Warehouse_temperature) { set_Value (COLUMNNAME_Warehouse_temperature, Warehouse_temperature); } @Override public java.lang.String getWarehouse_temperature() { return get_ValueAsString(COLUMNNAME_Warehouse_temperature); } @Override public void setWeight (final @Nullable BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } @Override public BigDecimal getWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeight_UOM_ID (final int Weight_UOM_ID) { if (Weight_UOM_ID < 1) set_Value (COLUMNNAME_Weight_UOM_ID, null); else set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID); } @Override public int getWeight_UOM_ID() { return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product.java
1
请完成以下Java代码
public String getCaseActivityType() { return caseActivityType; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public String getTaskId() { return taskId; } public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public String getTenantId() { return tenantId; } public Date getCreateTime() { return createTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public Boolean getRequired() { return required; } public Boolean getAvailable() { return available; } public Boolean getEnabled() {
return enabled; } public Boolean getDisabled() { return disabled; } public Boolean getActive() { return active; } public Boolean getCompleted() { return completed; } public Boolean getTerminated() { return terminated; } public static HistoricCaseActivityInstanceDto fromHistoricCaseActivityInstance(HistoricCaseActivityInstance historicCaseActivityInstance) { HistoricCaseActivityInstanceDto dto = new HistoricCaseActivityInstanceDto(); dto.id = historicCaseActivityInstance.getId(); dto.parentCaseActivityInstanceId = historicCaseActivityInstance.getParentCaseActivityInstanceId(); dto.caseActivityId = historicCaseActivityInstance.getCaseActivityId(); dto.caseActivityName = historicCaseActivityInstance.getCaseActivityName(); dto.caseActivityType = historicCaseActivityInstance.getCaseActivityType(); dto.caseDefinitionId = historicCaseActivityInstance.getCaseDefinitionId(); dto.caseInstanceId = historicCaseActivityInstance.getCaseInstanceId(); dto.caseExecutionId = historicCaseActivityInstance.getCaseExecutionId(); dto.taskId = historicCaseActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicCaseActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicCaseActivityInstance.getCalledCaseInstanceId(); dto.tenantId = historicCaseActivityInstance.getTenantId(); dto.createTime = historicCaseActivityInstance.getCreateTime(); dto.endTime = historicCaseActivityInstance.getEndTime(); dto.durationInMillis = historicCaseActivityInstance.getDurationInMillis(); dto.required = historicCaseActivityInstance.isRequired(); dto.available = historicCaseActivityInstance.isAvailable(); dto.enabled = historicCaseActivityInstance.isEnabled(); dto.disabled = historicCaseActivityInstance.isDisabled(); dto.active = historicCaseActivityInstance.isActive(); dto.completed = historicCaseActivityInstance.isCompleted(); dto.terminated = historicCaseActivityInstance.isTerminated(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseActivityInstanceDto.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** 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); } /** Set Process Now. @param Processing Process Now */ 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 Test Export Model. @param TestExportModel Test Export Model */ public void setTestExportModel (String TestExportModel) { set_Value (COLUMNNAME_TestExportModel, TestExportModel); } /** Get Test Export Model. @return Test Export Model */ public String getTestExportModel () { return (String)get_Value(COLUMNNAME_TestExportModel); } /** Set Test Import Model. @param TestImportModel Test Import Model */ public void setTestImportModel (String TestImportModel) { set_Value (COLUMNNAME_TestImportModel, TestImportModel); } /** Get Test Import Model. @return Test Import Model */ public String getTestImportModel () { return (String)get_Value(COLUMNNAME_TestImportModel); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) {
set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Version. @param Version Version of the table definition */ public void setVersion (String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ public String getVersion () { return (String)get_Value(COLUMNNAME_Version); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Format.java
1
请完成以下Java代码
public boolean isUsePosixGroups() { return usePosixGroups; } public void setUsePosixGroups(boolean usePosixGroups) { this.usePosixGroups = usePosixGroups; } public SearchControls getSearchControls() { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setTimeLimit(30000); return searchControls; } public String getGroupTypeAttribute() { return groupTypeAttribute; } public void setGroupTypeAttribute(String groupTypeAttribute) { this.groupTypeAttribute = groupTypeAttribute; } public boolean isAllowAnonymousLogin() { return allowAnonymousLogin; } public void setAllowAnonymousLogin(boolean allowAnonymousLogin) { this.allowAnonymousLogin = allowAnonymousLogin; } public boolean isAuthorizationCheckEnabled() { return authorizationCheckEnabled; }
public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) { this.authorizationCheckEnabled = authorizationCheckEnabled; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public boolean isPasswordCheckCatchAuthenticationException() { return passwordCheckCatchAuthenticationException; } public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) { this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java
1
请完成以下Java代码
default Instant getClientIdIssuedAt() { return getClaimAsInstant(OAuth2ClientMetadataClaimNames.CLIENT_ID_ISSUED_AT); } /** * Returns the Client Secret {@code (client_secret)}. * @return the Client Secret */ default String getClientSecret() { return getClaimAsString(OAuth2ClientMetadataClaimNames.CLIENT_SECRET); } /** * Returns the time at which the {@code client_secret} will expire * {@code (client_secret_expires_at)}. * @return the time at which the {@code client_secret} will expire */ default Instant getClientSecretExpiresAt() { return getClaimAsInstant(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT); } /** * Returns the name of the Client to be presented to the End-User * {@code (client_name)}. * @return the name of the Client to be presented to the End-User */ default String getClientName() { return getClaimAsString(OAuth2ClientMetadataClaimNames.CLIENT_NAME); } /** * Returns the redirection {@code URI} values used by the Client * {@code (redirect_uris)}. * @return the redirection {@code URI} values used by the Client */ default List<String> getRedirectUris() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.REDIRECT_URIS); } /** * Returns the authentication method used by the Client for the Token Endpoint * {@code (token_endpoint_auth_method)}. * @return the authentication method used by the Client for the Token Endpoint */ default String getTokenEndpointAuthenticationMethod() {
return getClaimAsString(OAuth2ClientMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHOD); } /** * Returns the OAuth 2.0 {@code grant_type} values that the Client will restrict * itself to using {@code (grant_types)}. * @return the OAuth 2.0 {@code grant_type} values that the Client will restrict * itself to using */ default List<String> getGrantTypes() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.GRANT_TYPES); } /** * Returns the OAuth 2.0 {@code response_type} values that the Client will restrict * itself to using {@code (response_types)}. * @return the OAuth 2.0 {@code response_type} values that the Client will restrict * itself to using */ default List<String> getResponseTypes() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.RESPONSE_TYPES); } /** * Returns the OAuth 2.0 {@code scope} values that the Client will restrict itself to * using {@code (scope)}. * @return the OAuth 2.0 {@code scope} values that the Client will restrict itself to * using */ default List<String> getScopes() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.SCOPE); } /** * Returns the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)}. * @return the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)} */ default URL getJwkSetUrl() { return getClaimAsURL(OAuth2ClientMetadataClaimNames.JWKS_URI); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2ClientMetadataClaimAccessor.java
1
请完成以下Java代码
public DocumentFilterDescriptorsProvider createFiltersProvider(@NonNull final CreateFiltersProviderContext context) { if (!isValidTable(context.getTableName())) { return NullDocumentFilterDescriptorsProvider.instance; } return ImmutableDocumentFilterDescriptorsProvider.of( DocumentFilterDescriptor.builder() .setFilterId(BPartnerExportFilterConverter.FILTER_ID) .setFrequentUsed(true) // TODO ??? .setDisplayName(msgBL.translatable("Postal")) // .addParameter(DocumentFilterParamDescriptor.builder() .mandatory(true) .fieldName(BPartnerExportFilterConverter.PARAM_POSTAL_FROM) .displayName(msgBL.translatable(BPartnerExportFilterConverter.PARAM_POSTAL_FROM)) .widgetType(DocumentFieldWidgetType.Text)
) .addParameter(DocumentFilterParamDescriptor.builder() .mandatory(true) .fieldName(BPartnerExportFilterConverter.PARAM_POSTAL_TO) .displayName(msgBL.translatable(BPartnerExportFilterConverter.PARAM_POSTAL_TO)) .widgetType(DocumentFieldWidgetType.Text) ) // .build() ); } private boolean isValidTable(@Nullable final String tableName) { return C_BPARTNER_EXPORT_TABLE.equals(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bpartner\filter\BPartnerExportFilterDescriptionProviderFactory.java
1
请完成以下Java代码
public void setPublished(LocalDate published) { this.published = published; } public Integer getQuantity() { return quantity; } public Book quantity(Integer quantity) { this.quantity = quantity; return this; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Double getPrice() { return price; } public Book price(Double price) { this.price = price; return this; } public void setPrice(Double price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} Book book = (Book) o; if (book.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), book.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Book{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", author='" + getAuthor() + "'" + ", published='" + getPublished() + "'" + ", quantity=" + getQuantity() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\Book.java
1
请完成以下Java代码
public class WEBUI_Picking_TU_Label extends PickingSlotViewBasedProcess { private final HULabelService huLabelService = SpringContextHolder.instance.getBean(HULabelService.class); private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PickingSlotRow pickingSlotRow = getSingleSelectedRow(); if (!pickingSlotRow.isPickedHURow()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU)); } if (!pickingSlotRow.isTopLevelHU()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU)); } if (pickingSlotRow.getHuQtyCU().signum() <= 0) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_PICK_SOMETHING)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() {
final PickingSlotRow rowToProcess = getSingleSelectedRow(); printPickingLabel(rowToProcess.getHuId()); return MSG_OK; } protected void printPickingLabel(@NonNull final HuId huId) { huLabelService.print(HULabelPrintRequest.builder() .sourceDocType(HULabelSourceDocType.Picking) .hu(HUToReportWrapper.of(handlingUnitsDAO.getById(huId))) .onlyIfAutoPrint(false) .failOnMissingLabelConfig(true) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_TU_Label.java
1
请在Spring Boot框架中完成以下Java代码
public DeviceConfig.Builder setRequestClassnamesSupplier(final IDeviceRequestClassnamesSupplier requestClassnamesSupplier) { this.requestClassnamesSupplier = requestClassnamesSupplier; return this; } private IDeviceRequestClassnamesSupplier getRequestClassnamesSupplier() { Check.assumeNotNull(requestClassnamesSupplier, "Parameter requestClassnamesSupplier is not null"); return requestClassnamesSupplier; } public DeviceConfig.Builder setAssignedWarehouseIds(final Set<WarehouseId> assignedWareouseIds) { this.assignedWareouseIds = assignedWareouseIds; return this; } private ImmutableSet<WarehouseId> getAssignedWarehouseIds() { return assignedWareouseIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedWareouseIds); } @NonNull private ImmutableSet<LocatorId> getAssignedLocatorIds() { return assignedLocatorIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedLocatorIds); } @NonNull public DeviceConfig.Builder setAssignedLocatorIds(final Set<LocatorId> assignedLocatorIds) { this.assignedLocatorIds = assignedLocatorIds; return this; } @NonNull public DeviceConfig.Builder setBeforeHooksClassname(@NonNull final ImmutableList<String> beforeHooksClassname) {
this.beforeHooksClassname = beforeHooksClassname; return this; } @NonNull private ImmutableList<String> getBeforeHooksClassname() { return Optional.ofNullable(beforeHooksClassname).orElseGet(ImmutableList::of); } @NonNull public DeviceConfig.Builder setDeviceConfigParams(@NonNull final ImmutableMap<String, String> deviceConfigParams) { this.deviceConfigParams = deviceConfigParams; return this; } @NonNull private ImmutableMap<String, String> getDeviceConfigParams() { return deviceConfigParams == null ? ImmutableMap.of() : deviceConfigParams; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfig.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("entity", entityDescriptor) .add("layout", layout) .add("eTag", eTag) .toString(); } public DocumentLayoutDescriptor getLayout() { return layout; } public ViewLayout getViewLayout(final JSONViewDataType viewDataType) { switch (viewDataType) { case grid: { return layout.getGridViewLayout(); } case list: { return layout.getSideListViewLayout(); } default: { throw new IllegalArgumentException("Invalid viewDataType: " + viewDataType); } } } public DocumentEntityDescriptor getEntityDescriptor() { return entityDescriptor; } @Override public ETag getETag() { return eTag; } // public static final class Builder { private DocumentLayoutDescriptor layout; private DocumentEntityDescriptor entityDescriptor;
private Builder() { } public DocumentDescriptor build() { return new DocumentDescriptor(this); } public Builder setLayout(final DocumentLayoutDescriptor layout) { this.layout = layout; return this; } public Builder setEntityDescriptor(final DocumentEntityDescriptor entityDescriptor) { this.entityDescriptor = entityDescriptor; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/auth/login").permitAll() .antMatchers("/auth/logout").authenticated() .and() .apply(refreshTokenSecurityConfigurerAdapter()); } /** * A SecurityConfigurerAdapter to install a servlet filter that refreshes OAuth2 tokens. */ private RefreshTokenFilterConfigurer refreshTokenSecurityConfigurerAdapter() { return new RefreshTokenFilterConfigurer(uaaAuthenticationService(), tokenStore); } @Bean public OAuth2CookieHelper cookieHelper() { return new OAuth2CookieHelper(oAuth2Properties); } @Bean public OAuth2AuthenticationService uaaAuthenticationService() { return new OAuth2AuthenticationService(tokenEndpointClient, cookieHelper()); } /**
* Configure the ResourceServer security by installing a new TokenExtractor. */ @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenExtractor(tokenExtractor()); } /** * The new TokenExtractor can extract tokens from Cookies and Authorization headers. * * @return the CookieTokenExtractor bean. */ @Bean public TokenExtractor tokenExtractor() { return new CookieTokenExtractor(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2AuthenticationConfiguration.java
2
请完成以下Java代码
public class CallbackServlet extends AbstractServlet { @Inject private Config config; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientId = config.getValue("client.clientId", String.class); String clientSecret = config.getValue("client.clientSecret", String.class); //Error: String error = request.getParameter("error"); if (error != null) { request.setAttribute("error", error); dispatch("/", request, response); return; } String localState = (String) request.getSession().getAttribute("CLIENT_LOCAL_STATE"); if (!localState.equals(request.getParameter("state"))) { request.setAttribute("error", "The state attribute doesn't match !!"); dispatch("/", request, response); return;
} String code = request.getParameter("code"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); Form form = new Form(); form.param("grant_type", "authorization_code"); form.param("code", code); form.param("redirect_uri", config.getValue("client.redirectUri", String.class)); try { JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); request.getSession().setAttribute("tokenResponse", tokenResponse); } catch (Exception ex) { System.out.println(ex.getMessage()); request.setAttribute("error", ex.getMessage()); } dispatch("/", request, response); } }
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-client\src\main\java\com\baeldung\oauth2\client\CallbackServlet.java
1
请在Spring Boot框架中完成以下Java代码
public String uploadStatus() { return "uploadStatus"; } /** * @param multipartFile * @return * @throws IOException */ public String saveFile(MultipartFile multipartFile) throws IOException { String[] fileAbsolutePath={}; String fileName=multipartFile.getOriginalFilename(); String ext = fileName.substring(fileName.lastIndexOf(".") + 1); byte[] file_buff = null; InputStream inputStream=multipartFile.getInputStream(); if(inputStream!=null){ int len1 = inputStream.available(); file_buff = new byte[len1]; inputStream.read(file_buff);
} inputStream.close(); FastDFSFile file = new FastDFSFile(fileName, file_buff, ext); try { fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs } catch (Exception e) { logger.error("upload file Exception!",e); } if (fileAbsolutePath==null) { logger.error("upload file failed,please upload again!"); } String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1]; return path; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\controller\UploadController.java
2
请完成以下Java代码
public void error(final int WindowNo, final Throwable e) { final String AD_Message = "Error"; final String message = buildErrorMessage(e); // Log the error to console // NOTE: we need to do that because in case something went wrong we need the stacktrace to debug the actual issue // Before removing this please consider that you need to provide an alternative from where the support guys can grab their detailed exception info. logger.warn(message, e); error(WindowNo, AD_Message, message); } protected final String buildErrorMessage(final Throwable e) { String message = e == null ? "@UnknownError@" : e.getLocalizedMessage(); if (Check.isEmpty(message, true) && e != null) { message = e.toString(); } return message; } @Override public Thread createUserThread(final Runnable runnable, final String threadName) { final Thread thread; if (threadName == null) { thread = new Thread(runnable); } else { thread = new Thread(runnable, threadName); } thread.setDaemon(true); return thread; } @Override public final void executeLongOperation(final Object component, final Runnable runnable) { invoke() .setParentComponent(component) .setLongOperation(true) .setOnFail(OnFail.ThrowException) // backward compatibility .invoke(runnable); } @Override public void invokeLater(final int windowNo, final Runnable runnable) {
invoke() .setParentComponentByWindowNo(windowNo) .setInvokeLater(true) .setOnFail(OnFail.ThrowException) // backward compatibility .invoke(runnable); } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}. */ @Deprecated @Override public void hideBusyDialog() { // nothing } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#disableServerPush()}. */ @Deprecated @Override public void disableServerPush() { // nothing } /** * This method throws an UnsupportedOperationException. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#infoNoWait(int, String)}. * @throws UnsupportedOperationException */ @Deprecated @Override public void infoNoWait(int WindowNo, String AD_Message) { throw new UnsupportedOperationException("not implemented"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInstance.java
1
请在Spring Boot框架中完成以下Java代码
public class ConnectionUtil { private final static transient Logger logger = LogManager.getLogger(ConnectionUtil.class); /** * Can set up the database and rabbitmq connection at an early state, from commandline parameters. * It's assumed that if this method does not set up the connection, it is done later (currently via {@link CConnection#createInstance(CConnectionAttributes)}). * * Background: we use this to start metasfresh without a {@code }metasfresh.properties} file. */ public ConfigureConnectionsResult configureConnectionsIfArgsProvided(@Nullable final CommandLineOptions commandLineOptions) { if (commandLineOptions == null) { return new ConfigureConnectionsResult(false); } // CConnection ConfigureConnectionsResult result; if (Check.isNotBlank(commandLineOptions.getDbHost()) || commandLineOptions.getDbPort() != null) { final CConnectionAttributes connectionAttributes = CConnectionAttributes.builder() .dbHost(commandLineOptions.getDbHost()) .dbPort(commandLineOptions.getDbPort()) .dbName(coalesce(commandLineOptions.getDbName(), "metasfresh")) .dbUid(coalesce(commandLineOptions.getDbUser(), "metasfresh")) .dbPwd(coalesce(commandLineOptions.getDbPassword(), "metasfresh")) .build(); logger.info("!!!!!!!!!!!!!!!!\n" + "!! dbHost and/or dbPort were set from cmdline; -> will ignore DB-Settings from metasfresh.properties and connect to DB with {}\n" + "!!!!!!!!!!!!!!!!", connectionAttributes); CConnection.createInstance(connectionAttributes); result = new ConfigureConnectionsResult(true); } else { result = new ConfigureConnectionsResult(false); }
// RabbitMQ if (Check.isNotBlank(commandLineOptions.getRabbitHost())) { System.setProperty("spring.rabbitmq.host", commandLineOptions.getRabbitHost()); } if (commandLineOptions.getRabbitPort() != null) { System.setProperty("spring.rabbitmq.port", Integer.toString(commandLineOptions.getRabbitPort())); } if (Check.isNotBlank(commandLineOptions.getRabbitUser())) { System.setProperty("spring.rabbitmq.username", commandLineOptions.getRabbitUser()); } if (Check.isNotBlank(commandLineOptions.getRabbitPassword())) { System.setProperty("spring.rabbitmq.password", commandLineOptions.getRabbitPassword()); } return result; } @Value public static class ConfigureConnectionsResult { boolean cconnectionConfigured; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\de\metas\util\ConnectionUtil.java
2
请完成以下Java代码
private void forEachCostSegmentAndElement( final I_M_Product product, final Consumer<CostSegmentAndElement> consumer) { final ClientId clientId = ClientId.ofRepoId(product.getAD_Client_ID()); final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); final OrgId productOrgId = OrgId.ofRepoId(product.getAD_Org_ID()); final List<CostElement> costElements = costElementRepo.getByClientId(clientId); for (final AcctSchema as : acctSchemasRepo.getAllByClient(clientId)) { if (as.isDisallowPostingForOrg(productOrgId)) { continue; } final AcctSchemaId acctSchemaId = as.getId(); final CostTypeId costTypeId = as.getCosting().getCostTypeId(); final CostingLevel costingLevel = productCostingBL.getCostingLevel(product, as); // Create Std Costing if (costingLevel == CostingLevel.Client) { final CostSegment costSegment = CostSegment.builder() .costingLevel(costingLevel) .acctSchemaId(acctSchemaId) .costTypeId(costTypeId) .productId(productId) .clientId(clientId) .orgId(OrgId.ANY) .attributeSetInstanceId(AttributeSetInstanceId.NONE) .build(); costElements.forEach(costElement -> consumer.accept(costSegment.withCostElementId(costElement.getId()))); } else if (costingLevel == CostingLevel.Organization) { final Properties ctx = Env.getCtx(); for (final I_AD_Org org : MOrg.getOfClient(ctx, clientId.getRepoId())) { final CostSegment costSegment = CostSegment.builder() .costingLevel(costingLevel) .acctSchemaId(acctSchemaId) .costTypeId(costTypeId) .productId(productId) .clientId(clientId) .orgId(OrgId.ofRepoId(org.getAD_Org_ID())) .attributeSetInstanceId(AttributeSetInstanceId.NONE) .build(); costElements.forEach(costElement -> consumer.accept(costSegment.withCostElementId(costElement.getId()))); } }
else { logger.warn("{}'s costing Level {} not supported", product.getName(), costingLevel); } } // accounting schema loop } @Override public void updateCostRecord( @NonNull final CostSegmentAndElement costSegmentAndElement, @NonNull final Consumer<I_M_Cost> updater) { final I_M_Cost costRecord = getCostRecordOrNull(costSegmentAndElement); if (costRecord == null) { return; } updater.accept(costRecord); saveRecord(costRecord); } public boolean hasCostsInCurrency(final @NonNull AcctSchemaId acctSchemaId, @NonNull final CurrencyId currencyId) { return queryBL.createQueryBuilder(I_M_Cost.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_Cost.COLUMNNAME_C_AcctSchema_ID, acctSchemaId) .addEqualsFilter(I_M_Cost.COLUMNNAME_C_Currency_ID, currencyId) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CurrentCostsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public void setClock(Clock clock) { Assert.notNull(clock, "clock must not be null"); this.delegate.setClock(clock); } /** * Use this {@link Converter} to compute the RelayState * @param relayStateResolver the {@link Converter} to use * @since 6.1 */ public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { Assert.notNull(relayStateResolver, "relayStateResolver cannot be null"); this.delegate.setRelayStateResolver(relayStateResolver); } public static final class LogoutRequestParameters { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final Authentication authentication; private final LogoutRequest logoutRequest; public LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration, Authentication authentication, LogoutRequest logoutRequest) { this.request = request; this.registration = registration; this.authentication = authentication; this.logoutRequest = logoutRequest; } LogoutRequestParameters(BaseOpenSamlLogoutRequestResolver.LogoutRequestParameters parameters) { this(parameters.getRequest(), parameters.getRelyingPartyRegistration(), parameters.getAuthentication(), parameters.getLogoutRequest()); }
public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public Authentication getAuthentication() { return this.authentication; } public LogoutRequest getLogoutRequest() { return this.logoutRequest; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestResolver.java
2
请完成以下Java代码
public Resource getById(@NonNull final ResourceId id) { final Resource resource = byId.get(id); if (resource == null) { throw new AdempiereException("Resource not found by ID: " + id); } return resource; } public Stream<Resource> streamAllActive() { return allActive.stream(); } public List<Resource> getByIds(final Set<ResourceId> ids)
{ return ids.stream() .map(byId::get) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } public ImmutableSet<ResourceId> getActivePlantIds() { return streamAllActive() .filter(resource -> resource.isActive() && resource.isPlant()) .map(Resource::getResourceId) .collect(ImmutableSet.toImmutableSet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\ResourceRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class SAPGLJournalRepository { @NonNull public SAPGLJournal getById(@NonNull final SAPGLJournalId id) { final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); return loader.getById(id); } @NonNull public SAPGLJournal getByRecord(@NonNull final I_SAP_GLJournal record) { final SAPGLJournalId id = SAPGLJournalId.ofRepoId(record.getSAP_GLJournal_ID()); final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); loader.addToCacheAndAvoidSaving(record); return loader.getById(id); } public SeqNo getNextSeqNo(@NonNull final SAPGLJournalId glJournalId) { final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); return loader.getNextSeqNo(glJournalId); } public void updateWhileSaving( @NonNull final I_SAP_GLJournal record, @NonNull final Consumer<SAPGLJournal> consumer) { final SAPGLJournalId glJournalId = SAPGLJournalLoaderAndSaver.extractId(record); final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.addToCacheAndAvoidSaving(record); loaderAndSaver.updateById(glJournalId, consumer); } public void updateById( @NonNull final SAPGLJournalId glJournalId, @NonNull final Consumer<SAPGLJournal> consumer) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.updateById(glJournalId, consumer); } public <R> R updateById( @NonNull final SAPGLJournalId glJournalId, @NonNull final Function<SAPGLJournal, R> processor) {
final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); return loaderAndSaver.updateById(glJournalId, processor); } public DocStatus getDocStatus(final SAPGLJournalId glJournalId) { final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); return loader.getDocStatus(glJournalId); } @NonNull public SAPGLJournal create( @NonNull final SAPGLJournalCreateRequest createRequest, @NonNull final SAPGLJournalCurrencyConverter currencyConverter) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); return loaderAndSaver.create(createRequest, currencyConverter); } public void save(@NonNull final SAPGLJournal sapglJournal) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.save(sapglJournal); } public SAPGLJournalLineId acquireLineId(@NonNull final SAPGLJournalId sapGLJournalId) { final int lineRepoId = DB.getNextID(ClientId.METASFRESH.getRepoId(), I_SAP_GLJournalLine.Table_Name); return SAPGLJournalLineId.ofRepoId(sapGLJournalId, lineRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class HUConsolidationJobRepository { @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); // FIXME prototyping private final AtomicInteger nextJobId = new AtomicInteger(1000000); private final ConcurrentHashMap<HUConsolidationJobId, HUConsolidationJob> jobs = new ConcurrentHashMap<>(); public HUConsolidationJob create( @NonNull final HUConsolidationJobReference reference, @NonNull final UserId responsibleId) { final HUConsolidationJobId id = HUConsolidationJobId.ofRepoId(this.nextJobId.getAndIncrement()); final HUConsolidationJob job = HUConsolidationJob.builder() .id(id) .shipToBPLocationId(reference.getBpartnerLocationId()) .pickingSlotIds(reference.getPickingSlotIds()) .docStatus(HUConsolidationJobStatus.Drafted) .responsibleId(responsibleId) .build(); jobs.put(job.getId(), job); return job; } 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
2