instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void deleteMobileApplicationAccess(@NonNull final MobileApplicationRepoId applicationId) { mobileApplicationPermissionsRepository.deleteMobileApplicationAccess(applicationId); } @Override public void deleteUserOrgAccessByUserId(final UserId userId) { queryBL.createQueryBuilder(I_AD_User_OrgAccess.class) .addEqualsFilter(I_AD_User_OrgAccess.COLUMNNAME_AD_User_ID, userId) .create() .delete(); } @Override public void deleteUserOrgAssignmentByUserId(final UserId userId) { queryBL.createQueryBuilder(I_C_OrgAssignment.class) .addEqualsFilter(I_C_OrgAssignment.COLUMNNAME_AD_User_ID, userId) .create() .delete(); }
@Value(staticConstructor = "of") private static class RoleOrgPermissionsCacheKey { RoleId roleId; AdTreeId adTreeOrgId; } @Value(staticConstructor = "of") private static class UserOrgPermissionsCacheKey { UserId userId; AdTreeId adTreeOrgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsDAO.java
1
请完成以下Java代码
private static final class NoHintsRequired implements MethodParameterRuntimeHintsRegistrar { @Override public void apply(RuntimeHints runtimeHints) { // no runtime hints are required for this type of argument } } private static class ArgumentBindingHints implements MethodParameterRuntimeHintsRegistrar { private final MethodParameter methodParameter; ArgumentBindingHints(MethodParameter methodParameter) { this.methodParameter = methodParameter; } @Override public void apply(RuntimeHints runtimeHints) { Type parameterType = this.methodParameter.getGenericParameterType(); if (ArgumentValue.class.isAssignableFrom(this.methodParameter.getParameterType())) { parameterType = this.methodParameter.nested().getNestedGenericParameterType(); } bindingRegistrar.registerReflectionHints(runtimeHints.reflection(), parameterType); } } private static class DataLoaderHints implements MethodParameterRuntimeHintsRegistrar { private final MethodParameter methodParameter; DataLoaderHints(MethodParameter methodParameter) { this.methodParameter = methodParameter; }
@Override public void apply(RuntimeHints hints) { bindingRegistrar.registerReflectionHints( hints.reflection(), this.methodParameter.nested().getNestedGenericParameterType()); } } private static class ProjectedPayloadHints implements MethodParameterRuntimeHintsRegistrar { private final MethodParameter methodParameter; ProjectedPayloadHints(MethodParameter methodParameter) { this.methodParameter = methodParameter; } @Override public void apply(RuntimeHints hints) { Class<?> parameterType = this.methodParameter.nestedIfOptional().getNestedParameterType(); hints.reflection().registerType(parameterType); hints.proxies().registerJdkProxy(parameterType, TargetAware.class, SpringProxy.class, DecoratingProxy.class); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\SchemaMappingBeanFactoryInitializationAotProcessor.java
1
请完成以下Java代码
public class JavaUUIDCreatorBenchmark { public static void main(String[] args) throws InterruptedException { int threadCount = 128; int iterationCount = 100_000; Map<UUID, Long> uuidMap = new ConcurrentHashMap<>(); AtomicLong collisionCount = new AtomicLong(); long startNanos = System.nanoTime(); CountDownLatch endLatch = new CountDownLatch(threadCount); for (long i = 0; i < threadCount; i++) { long threadId = i; new Thread(() -> { for (long j = 0; j < iterationCount; j++) { UUID uuid = Generators.timeBasedGenerator().generate();
Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j); if(existingUUID != null) { collisionCount.incrementAndGet(); } } endLatch.countDown(); }).start(); } endLatch.await(); System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms"); } }
repos\tutorials-master\core-java-modules\core-java-uuid-generation\src\main\java\com\baeldung\timebaseduuid\JavaUUIDCreatorBenchmark.java
1
请完成以下Java代码
static void removeWithWhileLoopStoringFirstOccurrenceIndex(List<Integer> list, Integer element) { int index; while ((index = list.indexOf(element)) >= 0) { list.remove(index); } } static void removeWithCallingRemoveUntilModifies(List<Integer> list, Integer element) { while (list.remove(element)) ; } static void removeWithStandardForLoopUsingIndex(List<Integer> list, int element) { for (int i = 0; i < list.size(); i++) { if (Objects.equals(element, list.get(i))) { list.remove(i); } } } static void removeWithForLoopDecrementOnRemove(List<Integer> list, int element) { for (int i = 0; i < list.size(); i++) { if (Objects.equals(element, list.get(i))) { list.remove(i); i--; } } } static void removeWithForLoopIncrementIfRemains(List<Integer> list, int element) { for (int i = 0; i < list.size();) { if (Objects.equals(element, list.get(i))) { list.remove(i); } else { i++; } } } static void removeWithForEachLoop(List<Integer> list, int element) { for (Integer number : list) { if (Objects.equals(number, element)) { list.remove(number); } } } static void removeWithIterator(List<Integer> list, int element) { for (Iterator<Integer> i = list.iterator(); i.hasNext();) { Integer number = i.next(); if (Objects.equals(number, element)) {
i.remove(); } } } static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) { List<Integer> remainingElements = new ArrayList<>(); for (Integer number : list) { if (!Objects.equals(number, element)) { remainingElements.add(number); } } return remainingElements; } static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) { List<Integer> remainingElements = new ArrayList<>(); for (Integer number : list) { if (!Objects.equals(number, element)) { remainingElements.add(number); } } list.clear(); list.addAll(remainingElements); } static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) { return list.stream() .filter(e -> !Objects.equals(e, element)) .collect(Collectors.toList()); } static void removeWithRemoveIf(List<Integer> list, Integer element) { list.removeIf(n -> Objects.equals(n, element)); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\removeall\RemoveAll.java
1
请在Spring Boot框架中完成以下Java代码
class AtlasRepositoryFragment<T> implements AtlasRepository<T>, RepositoryMetadataAccess { private final MongoOperations mongoOperations; public AtlasRepositoryFragment(@Autowired MongoOperations mongoOperations) { this.mongoOperations = mongoOperations; } @Override @SuppressWarnings("unchecked") public List<T> vectorSearch(String index, String path, List<Double> vector) { RepositoryMethodContext methodContext = RepositoryMethodContext.getContext(); Class<?> domainType = resolveDomainType(methodContext.getMetadata()); VectorSearchOperation $vectorSearch = VectorSearchOperation.search(index).path(path).vector(vector) .limit(Limit.of(10)).numCandidates(150);
Aggregation aggregation = Aggregation.newAggregation($vectorSearch); return (List<T>) mongoOperations.aggregate(aggregation, mongoOperations.getCollectionName(domainType), domainType).getMappedResults(); } @SuppressWarnings("unchecked") private static <T> Class<T> resolveDomainType(RepositoryMetadata metadata) { // resolve the actual generic type argument of the AtlasRepository<T>. return (Class<T>) ResolvableType.forClass(metadata.getRepositoryInterface()) .as(AtlasRepository.class) .getGeneric(0) .resolve(); } }
repos\spring-data-examples-main\mongodb\fragment-spi\atlas-api\src\main\java\com\example\spi\mongodb\atlas\AtlasRepositoryFragment.java
2
请在Spring Boot框架中完成以下Java代码
class UsersController { @Autowired private UsersService usersService; @GetMapping("/{id}") public UserResponse getUser(@PathVariable("id") String id) { var user = usersService.getUserById(id); return buildResponse(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable("id") String id) { usersService.deleteUserById(id); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public UserResponse createUser(@RequestBody CreateUserRequest body) { var user = usersService.createUser(body.name()); return buildResponse(user); }
@PatchMapping("/{id}") public UserResponse patchUser(@PathVariable("id") String id, @RequestBody PatchUserRequest body) { var user = usersService.updateUser(id, body.name()); return buildResponse(user); } private UserResponse buildResponse(final UserRecord user) { return new UserResponse(user.getId(), user.getName()); } @ExceptionHandler(UnknownUserException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public void handleUnknownUser() { } }
repos\tutorials-master\lightrun\lightrun-users-service\src\main\java\com\baeldung\usersservice\adapters\http\UsersController.java
2
请在Spring Boot框架中完成以下Java代码
public void setObservationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } } static class DefaultWebSecurityExpressionHandlerBeanFactory extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory { private DefaultHttpSecurityExpressionHandler handler = new DefaultHttpSecurityExpressionHandler(); @Override public DefaultHttpSecurityExpressionHandler getBean() { if (this.rolePrefix != null) { this.handler.setDefaultRolePrefix(this.rolePrefix); } return this.handler; }
} static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> { @Override public ObservationRegistry getObject() throws Exception { return ObservationRegistry.NOOP; } @Override public Class<?> getObjectType() { return ObservationRegistry.class; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\AuthorizationFilterParser.java
2
请完成以下Java代码
protected void setElementProperty(String id, String propertyName, String propertyValue, ObjectNode infoNode) { ObjectNode bpmnNode = createOrGetBpmnNode(infoNode); if (!bpmnNode.has(id)) { bpmnNode.set(id, processEngineConfiguration.getObjectMapper().createObjectNode()); } ((ObjectNode) bpmnNode.get(id)).put(propertyName, propertyValue); } protected void setElementProperty(String id, String propertyName, JsonNode propertyValue, ObjectNode infoNode) { ObjectNode bpmnNode = createOrGetBpmnNode(infoNode); if (!bpmnNode.has(id)) { bpmnNode.set(id, processEngineConfiguration.getObjectMapper().createObjectNode()); } ((ObjectNode) bpmnNode.get(id)).replace(propertyName, propertyValue); } protected ObjectNode createOrGetBpmnNode(ObjectNode infoNode) { if (!infoNode.has(BPMN_NODE)) { infoNode.set(BPMN_NODE, processEngineConfiguration.getObjectMapper().createObjectNode()); } return (ObjectNode) infoNode.get(BPMN_NODE); } protected ObjectNode getBpmnNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(BPMN_NODE); }
protected void setLocalizationProperty(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) { ObjectNode localizationNode = createOrGetLocalizationNode(infoNode); if (!localizationNode.has(language)) { localizationNode.set(language, processEngineConfiguration.getObjectMapper().createObjectNode()); } ObjectNode languageNode = (ObjectNode) localizationNode.get(language); if (!languageNode.has(id)) { languageNode.set(id, processEngineConfiguration.getObjectMapper().createObjectNode()); } ((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue); } protected ObjectNode createOrGetLocalizationNode(ObjectNode infoNode) { if (!infoNode.has(LOCALIZATION_NODE)) { infoNode.set(LOCALIZATION_NODE, processEngineConfiguration.getObjectMapper().createObjectNode()); } return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } protected ObjectNode getLocalizationNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\DynamicBpmnServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<TAMOU1> getTAMOU1() { if (tamou1 == null) { tamou1 = new ArrayList<TAMOU1>(); } return this.tamou1; } /** * Gets the value of the ttaxi1 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 ttaxi1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTTAXI1().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TTAXI1 } * * */ public List<TTAXI1> getTTAXI1() { if (ttaxi1 == null) { ttaxi1 = new ArrayList<TTAXI1>(); } return this.ttaxi1; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\TRAILR.java
2
请在Spring Boot框架中完成以下Java代码
public TaskBuilder formKey(String formKey) { this.formKey = formKey; return this; } @Override public TaskBuilder taskDefinitionId(String taskDefinitionId) { this.taskDefinitionId = taskDefinitionId; return this; } @Override public TaskBuilder taskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; return this; } @Override public TaskBuilder identityLinks(Set<? extends IdentityLinkInfo> identityLinks) { this.identityLinks = identityLinks; return this; } @Override public TaskBuilder scopeId(String scopeId) { this.scopeId = scopeId; return this; } @Override public TaskBuilder scopeType(String scopeType) { this.scopeType = scopeType; return this; } @Override public String getId() { return id; } @Override public String getName() { return name; } @Override public String getDescription() { return description; } @Override public int getPriority() { return priority; } @Override public String getOwner() { return ownerId; } @Override public String getAssignee() { return assigneeId; } @Override public String getTaskDefinitionId() { return taskDefinitionId;
} @Override public String getTaskDefinitionKey() { return taskDefinitionKey; } @Override public Date getDueDate() { return dueDate; } @Override public String getCategory() { return category; } @Override public String getParentTaskId() { return parentTaskId; } @Override public String getTenantId() { return tenantId; } @Override public String getFormKey() { return formKey; } @Override public Set<? extends IdentityLinkInfo> getIdentityLinks() { return identityLinks; } @Override public String getScopeId() { return this.scopeId; } @Override public String getScopeType() { return this.scopeType; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java
2
请完成以下Java代码
public String getLogDir() { return logDir; } public void setLogFilePrefix(final String logFilePrefix) { final String logFilePrefixNorm = normalizeLogDirPrefix(logFilePrefix); if (Objects.equals(this.logFilePrefix, logFilePrefixNorm)) { return; } this.logFilePrefix = logFilePrefixNorm; updateFileNamePattern(); } public String getLogFilePrefix() { return logFilePrefix; } public void setLogFileDatePattern(final String logFileDatePattern) { if (Objects.equals(this.logFileDatePattern, logFileDatePattern)) { return; } if (Check.isEmpty(logFileDatePattern, true)) { addError("Skip setting LogFileDatePattern to null"); return; } this.logFileDatePattern = logFileDatePattern; updateFileNamePattern(); } public String getLogFileDatePattern() { return logFileDatePattern; } private final void updateFileNamePattern() { final StringBuilder fileNamePatternBuilder = new StringBuilder(); final String logDir = getLogDir(); if (!Check.isEmpty(logDir, true)) { fileNamePatternBuilder.append(logDir); if (!logDir.endsWith("\\") && !logDir.endsWith("/")) { fileNamePatternBuilder.append(File.separator); } } final String logFilePrefix = getLogFilePrefix(); fileNamePatternBuilder.append(logFilePrefix); if (!Check.isEmpty(logFilePrefix)) { fileNamePatternBuilder.append("."); } fileNamePatternBuilder.append(getLogFileDatePattern()); fileNamePatternBuilder.append(logFileSuffix);
final String fileNamePattern = fileNamePatternBuilder.toString(); super.setFileNamePattern(fileNamePattern); // System.out.println("Using FileNamePattern: " + fileNamePattern); } @Override public void setFileNamePattern(final String fnp) { throw new UnsupportedOperationException("Setting FileNamePattern directly is not allowed"); } public File getLogDirAsFile() { if (logDir == null) { return null; } return new File(logDir); } public File getActiveFileOrNull() { try { final String filename = getActiveFileName(); if (filename == null) { return null; } final File file = new File(filename).getAbsoluteFile(); return file; } catch (Exception e) { addError("Failed fetching active file name", e); return null; } } public List<File> getLogFiles() { final File logDir = getLogDirAsFile(); if (logDir != null && logDir.isDirectory()) { final File[] logs = logDir.listFiles(logFileNameFilter); for (int i = 0; i < logs.length; i++) { try { logs[i] = logs[i].getCanonicalFile(); } catch (Exception e) { } } return ImmutableList.copyOf(logs); } return ImmutableList.of(); } public void flush() { // TODO } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshTimeBasedRollingPolicy.java
1
请完成以下Java代码
public Set<Entry<String, Object>> entrySet() { Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) { DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue()); entrySet.add(entry); } return entrySet; } protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> { protected final String key; protected final TypedValue typedValue; public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) { this.key = key; this.typedValue = typedValue; } @Override public String getKey() { return key; }
@Override public Object getValue() { if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object setValue(Object value) { throw new UnsupportedOperationException("decision output entry is immutable"); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java
1
请完成以下Java代码
public void setFindChildrenQuery(String findChildrenSql) { this.findChildrenSql = findChildrenSql; } public void setAclClassIdSupported(boolean aclClassIdSupported) { this.aclClassIdSupported = aclClassIdSupported; if (aclClassIdSupported) { // Change the default children select if it hasn't been overridden if (this.findChildrenSql.equals(DEFAULT_SELECT_ACL_WITH_PARENT_SQL)) { this.findChildrenSql = DEFAULT_SELECT_ACL_WITH_PARENT_SQL_WITH_CLASS_ID_TYPE; } else { log.debug("Find children statement has already been overridden, so not overridding the default"); } } }
public void setConversionService(ConversionService conversionService) { this.aclClassIdUtils = new AclClassIdUtils(conversionService); } public void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) { Assert.notNull(objectIdentityGenerator, "objectIdentityGenerator cannot be null"); this.objectIdentityGenerator = objectIdentityGenerator; } protected boolean isAclClassIdSupported() { return this.aclClassIdSupported; } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcAclService.java
1
请完成以下Java代码
public String getColumnName() { return columnName; } private int precision = -1; /** * Sets precision to be used in case it's a number. * * If not set, default displayType's precision will be used. * * @param precision * @return this */ public ColumnInfo setPrecision(final int precision) { this.precision = precision; return this; } /** * * @return precision to be used in case it's a number */ public int getPrecision() { return this.precision; } public ColumnInfo setSortNo(final int sortNo) {
this.sortNo = sortNo; return this; } /** * Gets SortNo. * * @return * @see I_AD_Field#COLUMNNAME_SortNo. */ public int getSortNo() { return sortNo; } @Override public String toString() { return ObjectUtils.toString(this); } } // infoColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\minigrid\ColumnInfo.java
1
请完成以下Java代码
public class RSSRomeExample { public static void main(String[] args) throws IOException, FeedException, URISyntaxException { SyndFeed feed = createFeed(); addEntryToFeed(feed); publishFeed(feed); readFeed(); } private static SyndFeed createFeed() { SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("rss_1.0"); feed.setTitle("Test title"); feed.setLink("http://www.somelink.com"); feed.setDescription("Basic description"); return feed; } private static void addEntryToFeed(SyndFeed feed) { SyndEntry entry = new SyndEntryImpl(); entry.setTitle("Entry title"); entry.setLink("http://www.somelink.com/entry1"); addDescriptionToEntry(entry); addCategoryToEntry(entry); feed.setEntries(Arrays.asList(entry)); } private static void addDescriptionToEntry(SyndEntry entry) { SyndContent description = new SyndContentImpl(); description.setType("text/html"); description.setValue("First entry"); entry.setDescription(description); }
private static void addCategoryToEntry(SyndEntry entry) { List<SyndCategory> categories = new ArrayList<>(); SyndCategory category = new SyndCategoryImpl(); category.setName("Sophisticated category"); categories.add(category); entry.setCategories(categories); } private static void publishFeed(SyndFeed feed) throws IOException, FeedException { Writer writer = new FileWriter("xyz.txt"); SyndFeedOutput syndFeedOutput = new SyndFeedOutput(); syndFeedOutput.output(feed, writer); writer.close(); } private static SyndFeed readFeed() throws IOException, FeedException, URISyntaxException { URL feedSource = new URI("http://rssblog.whatisrss.com/feed/").toURL(); SyndFeedInput input = new SyndFeedInput(); return input.build(new XmlReader(feedSource)); } }
repos\tutorials-master\web-modules\rome\src\main\java\com\baeldung\rome\RSSRomeExample.java
1
请完成以下Spring Boot application配置
# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 #
连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0
repos\spring-boot-quick-master\quick-vw-crawler\src\main\resources\application.properties
2
请完成以下Java代码
public MRegistrationAttribute[] getAttributes() { if (m_allAttributes == null) m_allAttributes = MRegistrationAttribute.getAll(getCtx()); return m_allAttributes; } // getAttributes /** * Get All active Self Service Attribute Values * @return Registration Attribute Values */ public MRegistrationValue[] getValues() { return getValues (true); } // getValues /** * Get All Attribute Values * @param onlySelfService only Active Self Service * @return sorted Registration Attribute Values */ public MRegistrationValue[] getValues (boolean onlySelfService) { createMissingValues(); // String sql = "SELECT * FROM A_RegistrationValue rv " + "WHERE A_Registration_ID=?"; if (onlySelfService) sql += " AND EXISTS (SELECT * FROM A_RegistrationAttribute ra WHERE rv.A_RegistrationAttribute_ID=ra.A_RegistrationAttribute_ID" + " AND ra.IsActive='Y' AND ra.IsSelfService='Y')"; // sql += " ORDER BY A_RegistrationAttribute_ID"; ArrayList<MRegistrationValue> list = new ArrayList<MRegistrationValue>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getA_Registration_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) list.add(new MRegistrationValue(getCtx(), rs, get_TrxName())); rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close(); pstmt = null; } catch (Exception e) { pstmt = null; } // Convert and Sort MRegistrationValue[] retValue = new MRegistrationValue[list.size()]; list.toArray(retValue); Arrays.sort(retValue); return retValue; } // getValues /**
* Create Missing Attribute Values */ private void createMissingValues() { String sql = "SELECT ra.A_RegistrationAttribute_ID " + "FROM A_RegistrationAttribute ra" + " LEFT OUTER JOIN A_RegistrationProduct rp ON (rp.A_RegistrationAttribute_ID=ra.A_RegistrationAttribute_ID)" + " LEFT OUTER JOIN A_Registration r ON (r.M_Product_ID=rp.M_Product_ID) " + "WHERE r.A_Registration_ID=?" // Not in Registration + " AND NOT EXISTS (SELECT A_RegistrationAttribute_ID FROM A_RegistrationValue v " + "WHERE ra.A_RegistrationAttribute_ID=v.A_RegistrationAttribute_ID AND r.A_Registration_ID=v.A_Registration_ID)"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getA_Registration_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { MRegistrationValue v = new MRegistrationValue (this, rs.getInt(1), "?"); v.save(); } rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.error(null, e); } try { if (pstmt != null) pstmt.close(); pstmt = null; } catch (Exception e) { pstmt = null; } } // createMissingValues } // MRegistration
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistration.java
1
请完成以下Java代码
public void put(Object key, Object value) { if (usedFirstCache) { caffeineCache.put(key, value); } redisCache.put(key, value); } @Override public ValueWrapper putIfAbsent(Object key, Object value) { if (usedFirstCache) { caffeineCache.putIfAbsent(key, value); } return redisCache.putIfAbsent(key, value); } @Override public void evict(Object key) { // 删除的时候要先删除二级缓存再删除一级缓存,否则有并发问题 redisCache.evict(key); if (usedFirstCache) { // 删除一级缓存需要用到redis的Pub/Sub(订阅/发布)模式,否则集群中其他服服务器节点的一级缓存数据无法删除 Map<String, Object> message = new HashMap<>(); message.put("cacheName", name); message.put("key", key); // 创建redis发布者 RedisPublisher redisPublisher = new RedisPublisher(redisOperations, ChannelTopicEnum.REDIS_CACHE_DELETE_TOPIC.getChannelTopic()); // 发布消息 redisPublisher.publisher(message); } } @Override public void clear() { redisCache.clear(); if (usedFirstCache) { // 清除一级缓存需要用到redis的订阅/发布模式,否则集群中其他服服务器节点的一级缓存数据无法删除 Map<String, Object> message = new HashMap<>(); message.put("cacheName", name); // 创建redis发布者 RedisPublisher redisPublisher = new RedisPublisher(redisOperations, ChannelTopicEnum.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic()); // 发布消息 redisPublisher.publisher(message); }
} @Override protected Object lookup(Object key) { Object value = null; if (usedFirstCache) { value = caffeineCache.get(key); logger.debug("查询一级缓存 key:{},返回值是:{}", key, JSON.toJSONString(value)); } if (value == null) { value = redisCache.get(key); logger.debug("查询二级缓存 key:{},返回值是:{}", key, JSON.toJSONString(value)); } return value; } /** * 查询二级缓存 * * @param key * @param valueLoader * @return */ private <T> Object getForSecondaryCache(Object key, Callable<T> valueLoader) { T value = redisCache.get(key, valueLoader); logger.debug("查询二级缓存 key:{},返回值是:{}", key, JSON.toJSONString(value)); return toStoreValue(value); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\layering\LayeringCache.java
1
请完成以下Java代码
public int getRecord_ID() { return asyncBatch.getC_Async_Batch_ID(); } @Override public EMail sendEMail(org.compiere.model.I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributesOld) { final I_AD_Client client = Services.get(IClientDAO.class).retriveClient(ctx, Env.getAD_Client_ID(ctx)); final BoilerPlateContext attributesEffective; { final BoilerPlateContext.Builder attributesBuilder = attributesOld.toBuilder(); attributesBuilder.setSourceDocumentFromObject(asyncBatch); // try to set language; take first from partner; if does not exists, take it from client final org.compiere.model.I_AD_User user = InterfaceWrapperHelper.create(ctx, asyncBatch.getCreatedBy(), I_AD_User.class, ITrx.TRXNAME_None); final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(user.getC_BPartner_ID()); final I_C_BPartner partner = bpartnerId != null ? Services.get(IBPartnerDAO.class).getById(bpartnerId) : null; String adLanguage = ""; if (partner != null && partner.getC_BPartner_ID() > 0) { adLanguage = partner.getAD_Language(); } if (Check.isEmpty(adLanguage, true)) { adLanguage = client.getAD_Language(); } attributesBuilder.setAD_Language(adLanguage); attributesEffective = attributesBuilder.build(); } // final String message = text.getTextSnippetParsed(attributesEffective); // if (Check.isEmpty(message, true)) { return null; // } Check.assume(asyncBatch.getCreatedBy() > 0, "CreatedBy > 0"); notificationBL.send(UserNotificationRequest.builder() .recipientUserId(UserId.ofRepoId(asyncBatch.getCreatedBy())) .subjectPlain(text.getSubject()) .contentPlain(message) .targetAction(TargetRecordAction.of(TableRecordReference.of(asyncBatch))) .build()); return null;
} }, false); isSent = true; } catch (Exception e) { isSent = false; } finally { final int asyncBatch_id = asyncBatch.getC_Async_Batch_ID(); final String toEmail = InterfaceWrapperHelper.create(ctx, asyncBatch.getCreatedBy(), I_AD_User.class, trxName).getEMail(); if (isSent) { logger.warn("Async batch {} was notified by email {}", asyncBatch_id, toEmail); } else { logger.warn("Async batch {} was not notified by email {} ", asyncBatch_id, toEmail); } } } /** * Send note to the user who created the async batch with the result */ public void sendNote(final I_C_Async_Batch asyncBatch) { asyncBatchBL.getAsyncBatchType(asyncBatch) .orElseThrow(() -> new AdempiereException("Async Batch type should not be null for async batch " + asyncBatch.getC_Async_Batch_ID())); asyncBatchListener.applyListener(asyncBatch); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\async\spi\impl\NotifyAsyncBatch.java
1
请在Spring Boot框架中完成以下Java代码
public String getNumber() { return number; } /** 菜单编号(用于显示时排序) **/ public void setNumber(String number) { this.number = number; } /** 是否为叶子节点 **/ public String getIsLeaf() { return isLeaf; } /** 是否为叶子节点 **/ public void setIsLeaf(String isLeaf) { this.isLeaf = isLeaf; } /** 菜单层级 **/ public Long getLevel() { return level; } /** 菜单层级 **/ public void setLevel(Long level) { this.level = level; }
/** 父节点:一级菜单为0 **/ public PmsMenu getParent() { return parent; } /** 父节点:一级菜单为0 **/ public void setParent(PmsMenu parent) { this.parent = parent; } /** 目标名称(用于DWZUI的NAVTABID) **/ public String getTargetName() { return targetName; } /** 目标名称(用于DWZUI的NAVTABID) **/ public void setTargetName(String targetName) { this.targetName = targetName; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsMenu.java
2
请完成以下Java代码
public static void setRootRecordReference(@NonNull final PO po, @Nullable final TableRecordReference rootRecordReference) { ATTR_RootRecordReference.setValue(po, rootRecordReference); } private static final ModelDynAttributeAccessor<PO, TableRecordReference> // ATTR_RootRecordReference = new ModelDynAttributeAccessor<>(ModelCacheInvalidationService.class.getName(), "RootRecordReference", TableRecordReference.class); private final PO po; POCacheSourceModel(@NonNull final PO po) { this.po = po; } @Override public String getTableName() { return po.get_TableName(); } @Override public int getRecordId() { return po.get_ID(); } @Override public TableRecordReference getRootRecordReferenceOrNull() {
return ATTR_RootRecordReference.getValue(po); } @Override public Integer getValueAsInt(final String columnName, final Integer defaultValue) { return po.get_ValueAsInt(columnName, defaultValue); } @Override public boolean isValueChanged(final String columnName) { return po.is_ValueChanged(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\POCacheSourceModel.java
1
请在Spring Boot框架中完成以下Java代码
public Tenant getByTenantId(String tenantId) { return getOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getTenantId, tenantId)); } @Override @Transactional(rollbackFor = Exception.class) public boolean saveTenant(Tenant tenant) { if (Func.isEmpty(tenant.getId())) { List<Tenant> tenants = baseMapper.selectList(Wrappers.<Tenant>query().lambda().eq(Tenant::getIsDeleted, BladeConstant.DB_NOT_DELETED)); List<String> codes = tenants.stream().map(Tenant::getTenantId).collect(Collectors.toList()); String tenantId = getTenantId(codes); tenant.setTenantId(tenantId); // 新建租户对应的默认角色 Role role = new Role(); role.setTenantId(tenantId); role.setParentId(0L); role.setRoleName("管理员"); role.setRoleAlias("admin"); role.setSort(2); role.setIsDeleted(0); roleMapper.insert(role); // 新建租户对应的默认部门 Dept dept = new Dept(); dept.setTenantId(tenantId); dept.setParentId(0L); dept.setDeptName(tenant.getTenantName()); dept.setFullName(tenant.getTenantName()); dept.setSort(2); dept.setIsDeleted(0); deptMapper.insert(dept); // 新建租户对应的默认岗位 Post post = new Post(); post.setTenantId(tenantId); post.setCategory(1); post.setPostCode("ceo"); post.setPostName("首席执行官"); post.setSort(1); postService.save(post); // 新建租户对应的默认管理用户 User user = new User(); user.setTenantId(tenantId); user.setName("admin"); user.setRealName("admin"); user.setAccount("admin"); user.setPassword(DigestUtil.encrypt("admin"));
user.setRoleId(String.valueOf(role.getId())); user.setDeptId(String.valueOf(dept.getId())); user.setPostId(String.valueOf(post.getId())); user.setBirthday(new Date()); user.setSex(1); user.setIsDeleted(BladeConstant.DB_NOT_DELETED); boolean temp = super.saveOrUpdate(tenant); R<Boolean> result = userClient.saveUser(user); if (!result.isSuccess()) { throw new ServiceException(result.getMsg()); } return temp; } return super.saveOrUpdate(tenant); } private String getTenantId(List<String> codes) { String code = tenantId.generate(); if (codes.contains(code)) { return getTenantId(codes); } return code; } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\TenantServiceImpl.java
2
请完成以下Java代码
public Set<QueuePackageProcessorId> getAssignedPackageProcessorIds() { return getQueue().getQueuePackageProcessorIds(); } @Override public QueueProcessorId getQueueProcessorId() { return getQueue().getQueueProcessorId(); } private boolean processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage) { boolean success = false; try { final IWorkpackageProcessor workPackageProcessor = getWorkpackageProcessor(workPackage); final PerformanceMonitoringService perfMonService = getPerfMonService(); final WorkpackageProcessorTask task = new WorkpackageProcessorTask(this, workPackageProcessor, workPackage, logsRepository, perfMonService); executeTask(task); success = true; return true; } finally { if (!success) { logger.info("Submitting for processing next workPackage failed. workPackage={}.", workPackage); getEventDispatcher().unregisterListeners(workPackage.getC_Queue_WorkPackage_ID()); } } } private IWorkpackageProcessor getWorkpackageProcessor(final I_C_Queue_WorkPackage workPackage) { final IWorkpackageProcessorFactory factory = getActualWorkpackageProcessorFactory(); final Properties ctx = InterfaceWrapperHelper.getCtx(workPackage);
final int packageProcessorId = workPackage.getC_Queue_PackageProcessor_ID(); return factory.getWorkpackageProcessor(ctx, packageProcessorId); } private PerformanceMonitoringService getPerfMonService() { PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService; if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService) { performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr( PerformanceMonitoringService.class, NoopPerformanceMonitoringService.INSTANCE); } return performanceMonitoringService; } private IQueueProcessorEventDispatcher getEventDispatcher() { return queueProcessorFactory.getQueueProcessorEventDispatcher(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\AbstractQueueProcessor.java
1
请完成以下Java代码
public void setRequestDefaults(I_R_Request request, I_RV_R_Group_Prospect contact) { request.setAD_Org_ID(contact.getAD_Org_ID()); request.setR_Group_ID(contact.getR_Group_ID()); request.setC_BPartner_ID(contact.getC_BPartner_ID()); request.setAD_User_ID(contact.getAD_User_ID()); request.setSalesRep_ID(Env.getAD_User_ID(m_ctx)); // MGroup group = MGroup.get(Env.getCtx(), contact.getR_Group_ID()); String summary = group.getDescription(); if (Check.isEmpty(summary)) { summary = group.getHelp(); } if (Check.isEmpty(summary)) { summary = group.getName(); } request.setSummary(summary); request.setR_RequestType_ID(getDefault_RequestType_ID()); request.setR_Category_ID(group.get_ValueAsInt(BundleUtil.R_Group_R_Category_ID)); } public void setContactPhoneNo(de.metas.callcenter.model.I_R_Request request, ContactPhoneNo phoneNo) { if (phoneNo == null) { return; } if (!Check.isEmpty(phoneNo.getPhoneNo())) { request.setCCM_PhoneActual(phoneNo.getPhoneNo()); if (phoneNo.getAD_User_ID() > 0) { request.setAD_User_ID(phoneNo.getAD_User_ID()); } } } public static String toString(I_RV_R_Group_Prospect c) { if (c == null) { return "null"; } StringBuffer sb = new StringBuffer(); sb.append("RV_R_Group_Prospect[") .append("C_BPartner_ID="+c.getBPValue()+"/"+c.getC_BPartner_ID()) .append(", R_Request_ID="+c.getR_Request_ID()) .append("]"); return sb.toString();
} public List<ContactPhoneNo> getContactPhoneNumbers() { final I_RV_R_Group_Prospect prospect = getRV_R_Group_Prospect(false); final ArrayList<ContactPhoneNo> list = new ArrayList<>(); if (prospect == null) { return list; } for (final I_AD_User contact : Services.get(IBPartnerDAO.class).retrieveContacts(prospect.getC_BPartner())) { if (!Check.isEmpty(contact.getPhone(), true)) { list.add(new ContactPhoneNo(contact.getPhone(), contact.getName(), contact.getAD_User_ID())); } if (!Check.isEmpty(contact.getPhone2(), true)) { list.add(new ContactPhoneNo(contact.getPhone2(), contact.getName(), contact.getAD_User_ID())); } } return list; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CallCenterModel.java
1
请完成以下Java代码
protected String getAlreadyFilteredAttributeName() { String name = getFilterName(); if (name == null) { name = getClass().getName().concat("-" + System.identityHashCode(this)); } return name + ALREADY_FILTERED_SUFFIX; } private void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { this.securityContextHolderStrategy.clearContext(); this.failureHandler.onAuthenticationFailure(request, response, failed); } private void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException { SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response);
this.successHandler.onAuthenticationSuccess(request, response, chain, authentication); } private @Nullable Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, ServletException { Authentication authentication = this.authenticationConverter.convert(request); if (authentication == null) { return null; } AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request); Authentication authenticationResult = authenticationManager.authenticate(authentication); if (authenticationResult == null) { throw new ServletException("AuthenticationManager should not return null Authentication object."); } return authenticationResult; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AuthenticationFilter.java
1
请在Spring Boot框架中完成以下Java代码
public AssetProfile find(AssetProfileId assetProfileId) { return assetProfileService.findAssetProfileById(TenantId.SYS_TENANT_ID, assetProfileId); } @Override public AssetProfile findOrCreateAssetProfile(TenantId tenantId, String profileName) { return assetProfileService.findOrCreateAssetProfile(tenantId, profileName); } @Override public void removeListener(TenantId tenantId, EntityId listenerId) { ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.remove(listenerId); } ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> assetListeners = assetProfileListeners.get(tenantId); if (assetListeners != null) { assetListeners.remove(listenerId); } }
private void notifyProfileListeners(AssetProfile profile) { ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(profile.getTenantId()); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(profile)); } } private void notifyAssetListeners(TenantId tenantId, AssetId assetId, AssetProfile profile) { if (profile != null) { ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> tenantListeners = assetProfileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(assetId, profile)); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbAssetProfileCache.java
2
请在Spring Boot框架中完成以下Java代码
public class productDao { @Autowired private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sf) { this.sessionFactory = sf; } @Transactional public List<Product> getProducts(){ return this.sessionFactory.getCurrentSession().createQuery("from PRODUCT").list(); } @Transactional public Product addProduct(Product product) { this.sessionFactory.getCurrentSession().save(product); return product; } @Transactional public Product getProduct(int id) {
return this.sessionFactory.getCurrentSession().get(Product.class, id); } public Product updateProduct(Product product){ this.sessionFactory.getCurrentSession().update(String.valueOf(Product.class),product); return product; } @Transactional public Boolean deletProduct(int id) { Session session = this.sessionFactory.getCurrentSession(); Object persistanceInstance = session.load(Product.class, id); if (persistanceInstance != null) { session.delete(persistanceInstance); return true; } return false; } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\dao\productDao.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrincipal() { return principal; } public void setPrincipal(String principal) { this.principal = principal; } public Instant getAuditEventDate() { return auditEventDate; } public void setAuditEventDate(Instant auditEventDate) { this.auditEventDate = auditEventDate; } public String getAuditEventType() { return auditEventType; } public void setAuditEventType(String auditEventType) { this.auditEventType = auditEventType; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data;
} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PersistentAuditEvent persistentAuditEvent = (PersistentAuditEvent) o; return !(persistentAuditEvent.getId() == null || getId() == null) && Objects.equals(getId(), persistentAuditEvent.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "PersistentAuditEvent{" + "principal='" + principal + '\'' + ", auditEventDate=" + auditEventDate + ", auditEventType='" + auditEventType + '\'' + '}'; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\PersistentAuditEvent.java
1
请完成以下Java代码
public void setCity (final @Nullable java.lang.String City) { set_Value (COLUMNNAME_City, City); } @Override public java.lang.String getCity() { return get_ValueAsString(COLUMNNAME_City); } @Override public void setDistrict (final @Nullable java.lang.String District) { set_Value (COLUMNNAME_District, District); } @Override public java.lang.String getDistrict() { return get_ValueAsString(COLUMNNAME_District); } @Override public void setIsManual (final boolean IsManual) { set_Value (COLUMNNAME_IsManual, IsManual); } @Override public boolean isManual() { return get_ValueAsBoolean(COLUMNNAME_IsManual); } @Override public void setIsValidDPD (final boolean IsValidDPD) { set_Value (COLUMNNAME_IsValidDPD, IsValidDPD); } @Override public boolean isValidDPD() { return get_ValueAsBoolean(COLUMNNAME_IsValidDPD); } @Override public void setNonStdAddress (final boolean NonStdAddress) { set_Value (COLUMNNAME_NonStdAddress, NonStdAddress); } @Override public boolean isNonStdAddress() { return get_ValueAsBoolean(COLUMNNAME_NonStdAddress); }
@Override public void setPostal (final @Nullable java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); } @Override public void setPostal_Add (final @Nullable java.lang.String Postal_Add) { set_Value (COLUMNNAME_Postal_Add, Postal_Add); } @Override public java.lang.String getPostal_Add() { return get_ValueAsString(COLUMNNAME_Postal_Add); } @Override public void setRegionName (final @Nullable java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } @Override public java.lang.String getRegionName() { return get_ValueAsString(COLUMNNAME_RegionName); } @Override public void setTownship (final @Nullable java.lang.String Township) { set_Value (COLUMNNAME_Township, Township); } @Override public java.lang.String getTownship() { return get_ValueAsString(COLUMNNAME_Township); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Postal.java
1
请完成以下Java代码
public String getSourceTable() { return I_M_InventoryLine.Table_Name; } @Override public boolean isUserInChargeUserEditable() { return false; } @Override public void setOrderedData(final I_C_Invoice_Candidate ic) { final I_M_InventoryLine inventoryLine = getM_InventoryLine(ic); final org.compiere.model.I_M_InOutLine originInOutLine = inventoryLine.getM_InOutLine(); Check.assumeNotNull(originInOutLine, "InventoryLine {0} must have an origin inoutline set", inventoryLine); final I_M_InOut inOut = originInOutLine.getM_InOut(); final I_C_Order order = inOut.getC_Order(); if (inOut.getC_Order_ID() > 0) { ic.setC_Order(order); // also set the order; even if the iol does not directly refer to an order line, it is there because of that order ic.setDateOrdered(order.getDateOrdered()); } else if (ic.getC_Order_ID() <= 0) { // don't attempt to "clear" the order data if it is already set/known. ic.setC_Order(null); ic.setDateOrdered(inOut.getMovementDate()); } final I_M_Inventory inventory = inventoryLine.getM_Inventory(); final DocStatus inventoryDocStatus = DocStatus.ofCode(inventory.getDocStatus()); if (inventoryDocStatus.isCompletedOrClosed()) { final BigDecimal qtyMultiplier = ONE.negate(); final BigDecimal qtyDelivered = inventoryLine.getQtyInternalUse().multiply(qtyMultiplier); ic.setQtyEntered(qtyDelivered); ic.setQtyOrdered(qtyDelivered); } else { // Corrected, voided etc document. Set qty to zero. ic.setQtyOrdered(ZERO);
ic.setQtyEntered(ZERO); } final IProductBL productBL = Services.get(IProductBL.class); final UomId stockingUOMId = productBL.getStockUOMId(inventoryLine.getM_Product_ID()); ic.setC_UOM_ID(UomId.toRepoId(stockingUOMId)); } @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { final BigDecimal qtyDelivered = ic.getQtyOrdered(); ic.setQtyDelivered(qtyDelivered); // when changing this, make sure to threat ProductType.Service specially final BigDecimal qtyInUOM = Services.get(IUOMConversionBL.class) .convertFromProductUOM( ProductId.ofRepoId(ic.getM_Product_ID()), UomId.ofRepoId(ic.getC_UOM_ID()), qtyDelivered); ic.setQtyDeliveredInUOM(qtyInUOM); ic.setDeliveryDate(ic.getDateOrdered()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\M_InventoryLine_Handler.java
1
请完成以下Java代码
public String getCamundaName() { return camundaNameAttribute.getValue(this); } public void setCamundaName(String camundaName) { camundaNameAttribute.setValue(this, camundaName); } public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaStringValue() { return camundaStringValueAttribute.getValue(this); }
public void setCamundaStringValue(String camundaStringValue) { camundaStringValueAttribute.setValue(this, camundaStringValue); } public CamundaString getCamundaString() { return camundaStringChild.getChild(this); } public void setCamundaString(CamundaString camundaString) { camundaStringChild.setChild(this, camundaString); } public CamundaExpression getCamundaExpressionChild() { return camundaExpressionChild.getChild(this); } public void setCamundaExpressionChild(CamundaExpression camundaExpression) { camundaExpressionChild.setChild(this, camundaExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFieldImpl.java
1
请完成以下Java代码
public boolean isRegistered () { Object oo = get_Value(COLUMNNAME_IsRegistered); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ 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 Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); 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); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Note. @param Note Optional additional user defined information */ public void setNote (String Note) {
set_Value (COLUMNNAME_Note, Note); } /** Get Note. @return Optional additional user defined information */ public String getNote () { return (String)get_Value(COLUMNNAME_Note); } /** 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 Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Registration.java
1
请在Spring Boot框架中完成以下Java代码
public class ConfProperties { @Value("${db.url}") private String url; @Value("${db.username}") private String username; @Value("${db.password}") private String password; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\tutorials-master\spring-boot-modules\spring-boot-environment\src\main\java\com\baeldung\properties\ConfProperties.java
2
请完成以下Java代码
private static JsonActualImportAsync toJson(@Nullable final AsyncImportRecordsResponse result) { if (result == null) { return null; } return JsonActualImportAsync.builder() .workpackageId(result.getWorkpackageId()) .build(); } private static JsonErrorItem toJsonErrorItem(final InsertIntoImportTableResult.Error error) { return JsonErrorItem.builder() .message(error.getMessage()) .parameter(ERROR_PARAM_WHERE, "source-file") .parameter("importLineNo", String.valueOf(error.getLineNo()))
.parameter("importLineContent", error.getLineContent()) .build(); } private static JsonErrorItem toJsonErrorItem(final ActualImportRecordsResult.Error error) { return JsonErrorItem.builder() .message(error.getMessage()) .adIssueId(JsonMetasfreshId.of(error.getAdIssueId().getRepoId())) .throwable(error.getException()) .stackTrace(error.getException() != null ? Trace.toOneLineStackTraceString(error.getException()) : null) .parameter(ERROR_PARAM_WHERE, "actual-import") .parameter("affectedRecordsCount", String.valueOf(error.getAffectedImportRecordsCount())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\data_import\DataImportRestController.java
1
请完成以下Java代码
public class Authorization { private final Authentication authentication; private final boolean granted; private String application; public Authorization(Authentication authentication, boolean granted) { this.authentication = authentication; this.granted = granted; } public Authentication getAuthentication() { return authentication; } public boolean isGranted() { return granted; } public Authorization forApplication(String application) { this.application = application; return this; } public void attachHeaders(HttpServletResponse response) { if (authentication != null) { // header != null checks required for websphere compatibility if (authentication.getIdentityId() != null) { response.addHeader("X-Authorized-User", authentication.getIdentityId()); } if (authentication.getProcessEngineName() != null) { response.addHeader("X-Authorized-Engine", authentication.getProcessEngineName()); } if (authentication instanceof UserAuthentication) { response.addHeader("X-Authorized-Apps", join(",", ((UserAuthentication) authentication).getAuthorizedApps())); } } // response.addHeader("X-Authorized", Boolean.toString(granted)); } public boolean isAuthenticated() { return authentication != null && authentication != Authentication.ANONYMOUS;
} public String getApplication() { return application; } ////// static helpers ////////////////////////////// public static Authorization granted(Authentication authentication) { return new Authorization(authentication, true); } public static Authorization denied(Authentication authentication) { return new Authorization(authentication, false); } public static Authorization grantedUnlessNull(Authentication authentication) { return authentication != null ? granted(authentication) : denied(authentication); } private static String join(String delimiter, Collection<?> collection) { StringBuilder builder = new StringBuilder(); for (Object o: collection) { if (builder.length() > 0) { builder.append(delimiter); } builder.append(o); } return builder.toString(); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\Authorization.java
1
请完成以下Java代码
public int getMaxQueryRecords() { // // Check if we have it set on Tab level final int maxQueryRecordsPerRole = constraint.getMaxQueryRecordsPerRole(); if (maxQueryRecordsPerRole > 0 && maxQueryRecordsPerTab > 0) { return Math.min(maxQueryRecordsPerTab, maxQueryRecordsPerRole); } else if (maxQueryRecordsPerTab > 0) { return maxQueryRecordsPerTab; } else { return Math.max(maxQueryRecordsPerRole, 0); } } /** * Gets the maximum allowed records to be presented to user, without asking him to confirm/refine the initial query. * * @return maximum allowed records to be presented to user, without asking him to confirm/refine the initial query. */ public int getConfirmQueryRecords() { return constraint.getConfirmQueryRecords(); } /** * Converts the given <code>maxQueryRecords</code> restriction to an actual number of rows. * * If there was NO maximum number of rows configured, then ZERO will be returned. * * @return maximum number of rows allowed to be presented to a user in a window. */ public int resolve(final GridTabMaxRows maxQueryRecords) { // Case: we were asked to use the default if (maxQueryRecords != null && maxQueryRecords.isDefault()) { return getMaxQueryRecords(); } // Case: we were asked to not enforce at all else if (maxQueryRecords == null || maxQueryRecords.isNoRestriction()) { return 0; } // Case: we got a specific maximum number of records we shall display else { return maxQueryRecords.getMaxRows(); } } public static class Builder { private IUserRolePermissions userRolePermissions; private GridTab gridTab; private Integer maxQueryRecordsPerTab = null; private Builder() { super(); } public final GridTabMaxRowsRestrictionChecker build() { return new GridTabMaxRowsRestrictionChecker(this); } public Builder setUserRolePermissions(final IUserRolePermissions userRolePermissions) { this.userRolePermissions = userRolePermissions;
return this; } private WindowMaxQueryRecordsConstraint getConstraint() { return getUserRolePermissions() .getConstraint(WindowMaxQueryRecordsConstraint.class) .orElse(WindowMaxQueryRecordsConstraint.DEFAULT); } private IUserRolePermissions getUserRolePermissions() { if (userRolePermissions != null) { return userRolePermissions; } return Env.getUserRolePermissions(); } public Builder setAD_Tab(final GridTab gridTab) { this.gridTab = gridTab; return this; } public Builder setMaxQueryRecordsPerTab(final int maxQueryRecordsPerTab) { this.maxQueryRecordsPerTab = maxQueryRecordsPerTab; return this; } private int getMaxQueryRecordsPerTab() { if (maxQueryRecordsPerTab != null) { return maxQueryRecordsPerTab; } else if (gridTab != null) { return gridTab.getMaxQueryRecords(); } return 0; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\GridTabMaxRowsRestrictionChecker.java
1
请在Spring Boot框架中完成以下Java代码
public class TBRedisSentinelConfiguration extends TBRedisCacheConfiguration { @Value("${redis.sentinel.master:}") private String master; @Value("${redis.sentinel.sentinels:}") private String sentinels; @Value("${redis.sentinel.password:}") private String sentinelPassword; @Value("${redis.sentinel.useDefaultPoolConfig:true}") private boolean useDefaultPoolConfig; @Value("${redis.db:}") private Integer database; @Value("${redis.ssl.enabled:false}") private boolean useSsl; @Value("${redis.username:}") private String username; @Value("${redis.password:}") private String password; public JedisConnectionFactory loadFactory() { RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration(); redisSentinelConfiguration.setMaster(master); redisSentinelConfiguration.setSentinels(getNodes(sentinels)); redisSentinelConfiguration.setSentinelPassword(sentinelPassword); redisSentinelConfiguration.setUsername(username); redisSentinelConfiguration.setPassword(password); redisSentinelConfiguration.setDatabase(database); return new JedisConnectionFactory(redisSentinelConfiguration, buildClientConfig()); }
private JedisClientConfiguration buildClientConfig() { JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfigurationBuilder = JedisClientConfiguration.builder(); if (!useDefaultPoolConfig) { jedisClientConfigurationBuilder .usePooling() .poolConfig(buildPoolConfig()); } if (useSsl) { jedisClientConfigurationBuilder .useSsl() .sslSocketFactory(createSslSocketFactory()); } return jedisClientConfigurationBuilder.build(); } }
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\TBRedisSentinelConfiguration.java
2
请完成以下Java代码
public List<IFacetCategory> getFacetCategories() { return facetCategories; } @Override public Set<IFacet<ModelType>> getFacets() { return facets; } @Override public Set<IFacet<ModelType>> getFacetsByCategory(IFacetCategory facetCategory) { Check.assumeNotNull(facetCategory, "facetCategory not null"); // TODO optimize final ImmutableSet.Builder<IFacet<ModelType>> facetsForCategory = ImmutableSet.builder(); for (final IFacet<ModelType> facet : facets) { if (!facetCategory.equals(facet.getFacetCategory())) { continue; } facetsForCategory.add(facet); } return facetsForCategory.build(); } public static class Builder<ModelType> { private final Set<IFacetCategory> facetCategories = new LinkedHashSet<>(); private final LinkedHashSet<IFacet<ModelType>> facets = new LinkedHashSet<>(); private Builder() { super(); } public IFacetCollectorResult<ModelType> build() { // If there was nothing added to this builder, return the empty instance (optimization) if (isEmpty()) { return EmptyFacetCollectorResult.getInstance(); } return new FacetCollectorResult<>(this); } /** @return true if this builder is empty */
private final boolean isEmpty() { return facets.isEmpty() && facetCategories.isEmpty(); } public Builder<ModelType> addFacetCategory(final IFacetCategory facetCategory) { Check.assumeNotNull(facetCategory, "facetCategory not null"); facetCategories.add(facetCategory); return this; } public Builder<ModelType> addFacet(final IFacet<ModelType> facet) { Check.assumeNotNull(facet, "facet not null"); facets.add(facet); facetCategories.add(facet.getFacetCategory()); return this; } public Builder<ModelType> addFacets(final Iterable<IFacet<ModelType>> facets) { Check.assumeNotNull(facets, "facet not null"); for (final IFacet<ModelType> facet : facets) { addFacet(facet); } return this; } /** @return true if there was added at least one facet */ public boolean hasFacets() { return !facets.isEmpty(); } public Builder<ModelType> addFacetCollectorResult(final IFacetCollectorResult<ModelType> facetCollectorResult) { // NOTE: we need to add the categories first, to make sure we preserve the order of categories this.facetCategories.addAll(facetCollectorResult.getFacetCategories()); this.facets.addAll(facetCollectorResult.getFacets()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCollectorResult.java
1
请完成以下Java代码
public class C_Invoice_AddTo_VerificationSet extends JavaProcess implements IProcessPrecondition { private final IInvoiceVerificationBL invoiceVerificationDAO = Services.get(IInvoiceVerificationBL.class); private final IQueryBL queryBL = Services.get(IQueryBL.class); @Param(parameterName = I_C_Invoice_Verification_Set.COLUMNNAME_C_Invoice_Verification_Set_ID, mandatory = true) private int verificationSetId; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { return context.isNoSelection() ? ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal() : ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception
{ final InvoiceVerificationSetId invoiceVerificationSetId = InvoiceVerificationSetId.ofRepoId(verificationSetId); invoiceVerificationDAO.createVerificationSetLines(invoiceVerificationSetId, getSelectedInvoiceIds()); return MSG_OK; } protected final List<InvoiceId> getSelectedInvoiceIds() { final IQueryFilter<I_C_Invoice> queryFilter = getProcessInfo().getQueryFilterOrElseFalse(); return queryBL.createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .filter(queryFilter) .create() .stream() .map(I_C_Invoice::getC_Invoice_ID) .map(InvoiceId::ofRepoId) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_AddTo_VerificationSet.java
1
请在Spring Boot框架中完成以下Java代码
class ApplicationConfiguration { @Bean BeforeConvertCallback<Customer> idGeneratingCallback(DatabaseClient databaseClient) { return (customer, sqlIdentifier) -> { if (customer.id() == null) { return databaseClient.sql("SELECT NEXT VALUE FOR primary_key") // .map(row -> row.get(0, Long.class)) // .first() // .map(customer::withId); } return Mono.just(customer);
}; } @Bean ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) { var initializer = new ConnectionFactoryInitializer(); initializer.setConnectionFactory(connectionFactory); initializer.setDatabasePopulator(new ResourceDatabasePopulator(new ByteArrayResource(("CREATE SEQUENCE primary_key;" + "DROP TABLE IF EXISTS customer;" + "CREATE TABLE customer (id INT PRIMARY KEY, firstname VARCHAR(100) NOT NULL, lastname VARCHAR(100) NOT NULL);") .getBytes()))); return initializer; } }
repos\spring-data-examples-main\r2dbc\example\src\main\java\example\springdata\r2dbc\entitycallback\ApplicationConfiguration.java
2
请完成以下Java代码
public List<IOParameter> getEventInParameters() { return eventInParameters; } public void setEventInParameters(List<IOParameter> eventInParameters) { this.eventInParameters = eventInParameters; } public List<IOParameter> getEventOutParameters() { return eventOutParameters; } public void setEventOutParameters(List<IOParameter> eventOutParameters) { this.eventOutParameters = eventOutParameters; } @Override public SendEventServiceTask clone() { SendEventServiceTask clone = new SendEventServiceTask(); clone.setValues(this); return clone; }
public void setValues(SendEventServiceTask otherElement) { super.setValues(otherElement); setEventType(otherElement.getEventType()); setTriggerEventType(otherElement.getTriggerEventType()); setSendSynchronously(otherElement.isSendSynchronously()); eventInParameters = new ArrayList<>(); if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getEventInParameters()) { eventInParameters.add(parameter.clone()); } } eventOutParameters = new ArrayList<>(); if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getEventOutParameters()) { eventOutParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SendEventServiceTask.java
1
请完成以下Java代码
public int getSAP_GLJournal_ID() { return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID); } @Override public void setTotalCr (final BigDecimal TotalCr) { set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr); } @Override public BigDecimal getTotalCr() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalCr);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalDr (final BigDecimal TotalDr) { set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr); } @Override public BigDecimal getTotalDr() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalDr); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournal.java
1
请完成以下Java代码
public String getName() { return name; } public int getBooks() { return books; } public static class LibraryStatistics { public static int getAverageBooks(Library[] libraries) { int total = 0; for (Library library : libraries) { total += library.books; } return libraries.length > 0 ? total / libraries.length : 0; } } public static class Book { private final String title; private final String author;
public Book(String title, String author) { this.title = title; this.author = author; } public void displayBookDetails() { LOGGER.info("Book Title: " + title); LOGGER.info("Book Author: " + author); } } public record BookRecord(String title, String author) { } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\statickeyword\Library.java
1
请完成以下Java代码
public void setHandOver_Location_Value_ID(final int HandOver_Location_Value_ID) { delegate.setHandOver_Location_Value_ID(HandOver_Location_Value_ID); } @Override public int getHandOver_User_ID() { return delegate.getHandOver_User_ID(); } @Override public void setHandOver_User_ID(final int HandOver_User_ID) { delegate.setHandOver_User_ID(HandOver_User_ID); } @Override public String getHandOverAddress() { return delegate.getHandOverAddress(); } @Override public void setHandOverAddress(final String address) { delegate.setHandOverAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddress(from);
} @Override public I_C_Order getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public OrderHandOverLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new OrderHandOverLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class)); } public void setFromHandOverLocation(@NonNull final I_C_Order from) { final BPartnerId bpartnerId = BPartnerId.ofRepoId(from.getHandOver_Partner_ID()); final BPartnerInfo bpartnerInfo = BPartnerInfo.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, from.getHandOver_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, from.getHandOver_User_ID())) .build(); setFrom(bpartnerInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderHandOverLocationAdapter.java
1
请完成以下Java代码
public void setRestartFrequency (final @Nullable java.lang.String RestartFrequency) { set_Value (COLUMNNAME_RestartFrequency, RestartFrequency); } @Override public java.lang.String getRestartFrequency() { return get_ValueAsString(COLUMNNAME_RestartFrequency); } @Override public void setStartNo (final int StartNo) { set_Value (COLUMNNAME_StartNo, StartNo); } @Override public int getStartNo() { return get_ValueAsInt(COLUMNNAME_StartNo); } @Override public void setSuffix (final @Nullable java.lang.String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } @Override public java.lang.String getSuffix()
{ return get_ValueAsString(COLUMNNAME_Suffix); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence.java
1
请在Spring Boot框架中完成以下Java代码
private List<I_C_PaySchedule> getPayScheduleRecords(@NonNull final PaymentTermId paymentTermId) { return CollectionUtils.getOrLoad(this.scheduleRecordsById, paymentTermId, this::retrievePayScheduleRecords); } @NonNull private Map<PaymentTermId, List<I_C_PaySchedule>> retrievePayScheduleRecords(@NonNull final Set<PaymentTermId> paymentTermIds) { if (paymentTermIds.isEmpty()) { return ImmutableMap.of(); } final Map<PaymentTermId, List<I_C_PaySchedule>> result = queryBL.createQueryBuilder(I_C_PaySchedule.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_PaySchedule.COLUMNNAME_C_PaymentTerm_ID, paymentTermIds) .stream() .collect(Collectors.groupingBy(PayScheduleConverter::extractPaymentTermId, Collectors.toList())); return CollectionUtils.fillMissingKeys(result, paymentTermIds, ImmutableList.of()); } private PaymentTerm fromRecord(final I_C_PaymentTerm record) { @NonNull final PaymentTermId paymentTermId = PaymentTermConverter.extractId(record); @NonNull final List<I_C_PaymentTerm_Break> breakRecords = getPaymentTermBreakRecords(paymentTermId); @NonNull final List<I_C_PaySchedule> payScheduleRecords = getPayScheduleRecords(paymentTermId); return PaymentTermConverter.fromRecord(record, breakRecords, payScheduleRecords); } private void saveToDB(final I_C_PaymentTerm record) { InterfaceWrapperHelper.saveRecord(record); } public void syncStateToDatabase(final Set<PaymentTermId> paymentTermIds)
{ if (paymentTermIds.isEmpty()) {return;} trxManager.runInThreadInheritedTrx(() -> { warmUpByIds(paymentTermIds); for (final PaymentTermId paymentTermId : paymentTermIds) { final PaymentTerm paymentTerm = loadById(paymentTermId); saveToDB(paymentTerm); } }); } private void saveToDB(@NonNull final PaymentTerm paymentTerm) { final PaymentTermId paymentTermId = paymentTerm.getId(); final I_C_PaymentTerm record = getRecordById(paymentTermId); PaymentTermConverter.updateRecord(record, paymentTerm); saveToDB(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PaymentTermLoaderAndSaver.java
2
请在Spring Boot框架中完成以下Java代码
public void addField(String field) { this.fields.add(field); } public String getName() { return name; } public Set<String> getFields() { return new HashSet<>(fields); } public void setName(String name) { this.name = name; } public void setFields(Set<String> fields) { this.fields = fields; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public boolean isAll() { return all; } public void setAll(boolean all) { this.all = all; } /** * 判断是否有相同字段 * * @param fieldControlString * @return */ public boolean isAllFieldsValid(String fieldControlString) { //如果白名单中没有配置字段,则返回false String[] controlFields = fieldControlString.split(","); if (oConvertUtils.isEmpty(fieldControlString)) { return false;
} for (String queryField : fields) { if (oConvertUtils.isIn(queryField, controlFields)) { log.warn("字典表白名单校验,表【" + name + "】中字段【" + queryField + "】无权限查询"); return false; } } return true; } @Override public String toString() { return "QueryTable{" + "name='" + name + '\'' + ", alias='" + alias + '\'' + ", fields=" + fields + ", all=" + all + '}'; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\firewall\SqlInjection\SysDictTableWhite.java
2
请完成以下Java代码
protected void deleteExecutionEntities( ExecutionEntityManager executionEntityManager, ExecutionEntity rootExecutionEntity, String deleteReason ) { List<ExecutionEntity> childExecutions = executionEntityManager.collectChildren(rootExecutionEntity); for (int i = childExecutions.size() - 1; i >= 0; i--) { executionEntityManager.cancelExecutionAndRelatedData(childExecutions.get(i), deleteReason); } executionEntityManager.cancelExecutionAndRelatedData(rootExecutionEntity, deleteReason); } protected void sendProcessInstanceCancelledEvent(DelegateExecution execution, FlowElement terminateEndEvent) { if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { if (execution.isProcessInstanceType() && execution instanceof ExecutionEntity) { Context.getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createProcessCancelledEvent( ((ExecutionEntity) execution).getProcessInstance(), createDeleteReason(terminateEndEvent.getId()) ) ); } } dispatchExecutionCancelled(execution, terminateEndEvent); } protected void dispatchExecutionCancelled(DelegateExecution execution, FlowElement terminateEndEvent) { ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager(); // subprocesses for (DelegateExecution subExecution : executionEntityManager.findChildExecutionsByParentExecutionId( execution.getId() )) { dispatchExecutionCancelled(subExecution, terminateEndEvent); } // call activities ExecutionEntity subProcessInstance = Context.getCommandContext()
.getExecutionEntityManager() .findSubProcessInstanceBySuperExecutionId(execution.getId()); if (subProcessInstance != null) { dispatchExecutionCancelled(subProcessInstance, terminateEndEvent); } } public static String createDeleteReason(String activityId) { return activityId != null ? DeleteReason.TERMINATE_END_EVENT + ": " + activityId : DeleteReason.TERMINATE_END_EVENT; } public boolean isTerminateAll() { return terminateAll; } public void setTerminateAll(boolean terminateAll) { this.terminateAll = terminateAll; } public boolean isTerminateMultiInstance() { return terminateMultiInstance; } public void setTerminateMultiInstance(boolean terminateMultiInstance) { this.terminateMultiInstance = terminateMultiInstance; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\TerminateEndEventActivityBehavior.java
1
请完成以下Java代码
public static void main(String[] args) { double a = 13.22; double b = 4.88; double c = 21.45; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); double sum_ab = a + b; System.out.println("a + b = " + sum_ab); double abc = a + b + c; System.out.println("a + b + c = " + abc); double ab_c = sum_ab + c; System.out.println("ab + c = " + ab_c); double sum_ac = a + c; System.out.println("a + c = " + sum_ac); double acb = a + c + b; System.out.println("a + c + b = " + acb); double ac_b = sum_ac + b; System.out.println("ac + b = " + ac_b); double ab = 18.1;
double ac = 34.67; double sum_ab_c = ab + c; double sum_ac_b = ac + b; System.out.println("ab + c = " + sum_ab_c); System.out.println("ac + b = " + sum_ac_b); BigDecimal d = new BigDecimal(String.valueOf(a)); BigDecimal e = new BigDecimal(String.valueOf(b)); BigDecimal f = new BigDecimal(String.valueOf(c)); BigDecimal def = d.add(e).add(f); BigDecimal dfe = d.add(f).add(e); System.out.println("d + e + f = " + def); System.out.println("d + f + e = " + dfe); } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\maths\FloatingPointArithmetic.java
1
请完成以下Java代码
public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public boolean isUseLocalScopeForResultVariable() { return useLocalScopeForResultVariable; } public void setUseLocalScopeForResultVariable(boolean useLocalScopeForResultVariable) { this.useLocalScopeForResultVariable = useLocalScopeForResultVariable; } public boolean isTriggerable() { return triggerable; } public void setTriggerable(boolean triggerable) { this.triggerable = triggerable; } public boolean isStoreResultVariableAsTransient() { return storeResultVariableAsTransient; } public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) { this.storeResultVariableAsTransient = storeResultVariableAsTransient; } @Override public ServiceTask clone() { ServiceTask clone = new ServiceTask(); clone.setValues(this); return clone; } public void setValues(ServiceTask otherElement) { super.setValues(otherElement); setImplementation(otherElement.getImplementation()); setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName()); setType(otherElement.getType()); setOperationRef(otherElement.getOperationRef()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); setUseLocalScopeForResultVariable(otherElement.isUseLocalScopeForResultVariable()); setTriggerable(otherElement.isTriggerable()); setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient()); fieldExtensions = new ArrayList<>(); if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherElement.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } customProperties = new ArrayList<>(); if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) { for (CustomProperty property : otherElement.getCustomProperties()) { customProperties.add(property.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ServiceTask.java
1
请在Spring Boot框架中完成以下Java代码
public ApiUsageStateValue getFeatureValue(ApiFeature feature) { switch (feature) { case TRANSPORT: return apiUsageState.getTransportState(); case RE: return apiUsageState.getReExecState(); case DB: return apiUsageState.getDbStorageState(); case JS: return apiUsageState.getJsExecState(); case TBEL: return apiUsageState.getTbelExecState(); case EMAIL: return apiUsageState.getEmailExecState(); case SMS: return apiUsageState.getSmsExecState(); case ALARM: return apiUsageState.getAlarmExecState(); default: return ApiUsageStateValue.ENABLED; } } public boolean setFeatureValue(ApiFeature feature, ApiUsageStateValue value) { ApiUsageStateValue currentValue = getFeatureValue(feature); switch (feature) { case TRANSPORT: apiUsageState.setTransportState(value); break; case RE: apiUsageState.setReExecState(value); break; case DB: apiUsageState.setDbStorageState(value); break; case JS: apiUsageState.setJsExecState(value); break; case TBEL: apiUsageState.setTbelExecState(value); break; case EMAIL: apiUsageState.setEmailExecState(value); break; case SMS: apiUsageState.setSmsExecState(value); break; case ALARM: apiUsageState.setAlarmExecState(value);
break; } return !currentValue.equals(value); } public abstract EntityType getEntityType(); public TenantId getTenantId() { return getApiUsageState().getTenantId(); } public EntityId getEntityId() { return getApiUsageState().getEntityId(); } @Override public String toString() { return "BaseApiUsageState{" + "apiUsageState=" + apiUsageState + ", currentCycleTs=" + currentCycleTs + ", nextCycleTs=" + nextCycleTs + ", currentHourTs=" + currentHourTs + '}'; } @Data @Builder public static class StatsCalculationResult { private final long newValue; private final boolean valueChanged; private final long newHourlyValue; private final boolean hourlyValueChanged; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\BaseApiUsageState.java
2
请在Spring Boot框架中完成以下Java代码
class AuthTokenResolver implements BearerTokenResolver { private static final Pattern AUTHORIZATION_PATTERN = Pattern.compile("^Token (?<token>[a-zA-Z0-9-._~+/]+=*)$", Pattern.CASE_INSENSITIVE); private static final String ACCESS_TOKEN_PARAM = "access_token"; @Override public String resolve(HttpServletRequest request) { String authorizationHeaderToken = resolveFromAuthorizationHeader(request); String parameterToken = isParameterTokenSupportedForRequest(request) ? resolveFromRequestParameters(request) : null; if (authorizationHeaderToken != null) { if (parameterToken != null) { throw new OAuth2AuthenticationException( BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request")); } return authorizationHeaderToken; } return parameterToken; } private String resolveFromAuthorizationHeader(HttpServletRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); if (!StringUtils.startsWithIgnoreCase(authorization, "token")) { return null; } Matcher matcher = AUTHORIZATION_PATTERN.matcher(authorization); if (!matcher.matches()) { throw new OAuth2AuthenticationException(BearerTokenErrors.invalidToken("Bearer token is malformed")); } return matcher.group("token"); } private boolean isParameterTokenSupportedForRequest(HttpServletRequest request) { return (("POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType())) || "GET".equals(request.getMethod())); } private String resolveFromRequestParameters(HttpServletRequest request) { String[] values = request.getParameterValues(ACCESS_TOKEN_PARAM); if (values == null || values.length == 0) { return null; } if (values.length == 1) { return values[0]; } throw new OAuth2AuthenticationException( BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request")); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthTokenResolver.java
2
请完成以下Java代码
public void initialize(ModelValidationEngine engine, MClient client) { if (client != null) m_AD_Client_ID = client.getAD_Client_ID(); engine.addModelChange(I_C_Invoice_Candidate_Agg.Table_Name, this); } @Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; } @Override public String modelChange(final PO po, final int type) throws Exception { if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE) { if (po.is_ValueChanged(I_C_Invoice_Candidate_Agg.COLUMNNAME_Classname))
{ final I_C_Invoice_Candidate_Agg icAgg = InterfaceWrapperHelper.create(po, I_C_Invoice_Candidate_Agg.class); Services.get(IAggregationBL.class).evalClassName(icAgg); } // Note: we invalidate *every* candidate, so there is no need to use the different IInvoiceCandidateHandler implementations. final IInvoiceCandDAO invoiceCandDB = Services.get(IInvoiceCandDAO.class); invoiceCandDB.invalidateAllCands(po.getCtx(), po.get_TrxName()); } return null; } @Override public String docValidate(final PO po, final int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_Invoice_Candidate_Agg.java
1
请在Spring Boot框架中完成以下Java代码
public static class Singlelogout { /** * Location where SAML2 LogoutRequest gets sent to. */ private @Nullable String url; /** * Location where SAML2 LogoutResponse gets sent to. */ private @Nullable String responseUrl; /** * Whether to redirect or post logout requests. */ private @Nullable Saml2MessageBinding binding; public @Nullable String getUrl() { return this.url; } public void setUrl(@Nullable String url) { this.url = url; } public @Nullable String getResponseUrl() {
return this.responseUrl; } public void setResponseUrl(@Nullable String responseUrl) { this.responseUrl = responseUrl; } public @Nullable Saml2MessageBinding getBinding() { return this.binding; } public void setBinding(@Nullable Saml2MessageBinding binding) { this.binding = binding; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyProperties.java
2
请完成以下Java代码
public double getLatitude() { return lattitude; } public void setLatitude(double latitude) { this.lattitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Hotel hotel = (Hotel) o; if (Double.compare(hotel.lattitude, lattitude) != 0) return false; if (Double.compare(hotel.longitude, longitude) != 0) return false; if (deleted != hotel.deleted) return false; if (!Objects.equals(id, hotel.id)) return false; if (!Objects.equals(name, hotel.name)) return false; if (!Objects.equals(rating, hotel.rating)) return false; if (!Objects.equals(city, hotel.city)) return false; return Objects.equals(address, hotel.address); } }
repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\ttl\model\Hotel.java
1
请完成以下Java代码
public class TransactionPrice2Choice { @XmlElement(name = "DealPric") protected ActiveOrHistoricCurrencyAndAmount dealPric; @XmlElement(name = "Prtry") protected List<ProprietaryPrice2> prtry; /** * Gets the value of the dealPric property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getDealPric() { return dealPric; } /** * Sets the value of the dealPric property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setDealPric(ActiveOrHistoricCurrencyAndAmount value) { this.dealPric = 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 ProprietaryPrice2 } * * */ public List<ProprietaryPrice2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryPrice2>(); } 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_02\TransactionPrice2Choice.java
1
请完成以下Java代码
private void notifyEMail(final MADBoilerPlate text, final I_AD_User user) { MADBoilerPlate.sendEMail(new IEMailEditor() { @Override public Object getBaseObject() { return user; } @Override public int getAD_Table_ID() { return InterfaceWrapperHelper.getModelTableId(user); } @Override public int getRecord_ID() { return user.getAD_User_ID(); } @Override public EMail sendEMail(final I_AD_User from, final String toEmail, final String subject, final BoilerPlateContext attributes) { final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder() .clientId(getClientId()) .orgId(getOrgId()) .adProcessId(getProcessInfo().getAdProcessId()) .fromUserId(getFromUserId()) .build()); return mailService.sendEMail(EMailRequest.builder() .mailbox(mailbox) .toList(toEMailAddresses(toEmail)) .subject(text.getSubject()) .message(text.getTextSnippetParsed(attributes)) .html(true) .build()); } }); }
private void createNote(MADBoilerPlate text, I_AD_User user, Exception e) { final AdMessageId adMessageId = Services.get(IMsgBL.class).getIdByAdMessage(AD_Message_UserNotifyError) .orElseThrow(() -> new AdempiereException("@NotFound@ @AD_Message_ID@ " + AD_Message_UserNotifyError)); // final IMsgBL msgBL = Services.get(IMsgBL.class); final String reference = msgBL.parseTranslation(getCtx(), "@AD_BoilerPlate_ID@: " + text.get_Translation(MADBoilerPlate.COLUMNNAME_Name)) + ", " + msgBL.parseTranslation(getCtx(), "@AD_User_ID@: " + user.getName()) // +", "+Msg.parseTranslation(getCtx(), "@AD_PInstance_ID@: "+getAD_PInstance_ID()) ; final MNote note = new MNote(getCtx(), adMessageId.getRepoId(), getFromUserId().getRepoId(), InterfaceWrapperHelper.getModelTableId(user), user.getAD_User_ID(), reference, e.getLocalizedMessage(), get_TrxName()); note.setAD_Org_ID(0); note.saveEx(); m_count_notes++; } static List<EMailAddress> toEMailAddresses(final String string) { final StringTokenizer st = new StringTokenizer(string, " ,;", false); final ArrayList<EMailAddress> result = new ArrayList<>(); while (st.hasMoreTokens()) { result.add(EMailAddress.ofString(st.nextToken())); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToUsers.java
1
请在Spring Boot框架中完成以下Java代码
public class JobApiController { @Resource private AdminBiz adminBiz; /** * api * * @param uri * @param data * @return */ @RequestMapping("/{uri}") @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> api(HttpServletRequest request, @PathVariable("uri") String uri, @RequestBody(required = false) String data) { // valid if (!"POST".equalsIgnoreCase(request.getMethod())) { return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, HttpMethod not support."); } if (uri==null || uri.trim().length()==0) { return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping empty."); } if (XxlJobAdminConfig.getAdminConfig().getAccessToken()!=null && XxlJobAdminConfig.getAdminConfig().getAccessToken().trim().length()>0 && !XxlJobAdminConfig.getAdminConfig().getAccessToken().equals(request.getHeader(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN))) { return new ReturnT<String>(ReturnT.FAIL_CODE, "The access token is wrong."); } // services mapping
if ("callback".equals(uri)) { List<HandleCallbackParam> callbackParamList = GsonTool.fromJson(data, List.class, HandleCallbackParam.class); return adminBiz.callback(callbackParamList); } else if ("registry".equals(uri)) { RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class); return adminBiz.registry(registryParam); } else if ("registryRemove".equals(uri)) { RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class); return adminBiz.registryRemove(registryParam); } else { return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping("+ uri +") not found."); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobApiController.java
2
请在Spring Boot框架中完成以下Java代码
public User post(@RequestBody User user) { log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam"); return user; } @PostMapping("/multipar") @ApiOperation(value = "添加用户(DONE)") public List<User> multipar(@RequestBody List<User> user) { log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam"); return user; } @PostMapping("/array") @ApiOperation(value = "添加用户(DONE)") public User[] array(@RequestBody User[] user) { log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user; } @PutMapping("/{id}") @ApiOperation(value = "修改用户(DONE)") public void put(@PathVariable Long id, @RequestBody User user) { log.info("如果你不想写 @ApiImplicitParam 那么 swagger 也会使用默认的参数名作为描述信息 "); } @PostMapping("/{id}/file") @ApiOperation(value = "文件上传(DONE)") public String file(@PathVariable Long id, @RequestParam("file") MultipartFile file) { log.info(file.getContentType()); log.info(file.getName()); log.info(file.getOriginalFilename()); return file.getOriginalFilename(); } }
repos\spring-boot-demo-master\demo-swagger\src\main\java\com\xkcoding\swagger\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public String getFilesUrlPrefix() { return filesUrlPrefix; } public void setFilesUrlPrefix(String filesUrlPrefix) { this.filesUrlPrefix = filesUrlPrefix; } public String getFilesPath() { return filesPath; } public void setFilesPath(String filesPath) { this.filesPath = filesPath; } public Integer getHeartbeatTimeout() { return heartbeatTimeout; } public void setHeartbeatTimeout(Integer heartbeatTimeout) { this.heartbeatTimeout = heartbeatTimeout; }
public String getPicsPath() { return picsPath; } public void setPicsPath(String picsPath) { this.picsPath = picsPath; } public String getPosapiUrlPrefix() { return posapiUrlPrefix; } public void setPosapiUrlPrefix(String posapiUrlPrefix) { this.posapiUrlPrefix = posapiUrlPrefix; } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\properties\MyProperties.java
2
请完成以下Java代码
public boolean add(T t) { if (!contains(t)) { performAddOperation(referenceSourceElement, t); } return true; } public boolean remove(Object o) { ModelUtil.ensureInstanceOf(o, ModelElementInstanceImpl.class); performRemoveOperation(referenceSourceElement, o); return true; } public boolean containsAll(Collection<?> c) { Collection<T> modelElementCollection = ModelUtil.getModelElementCollection(getView(referenceSourceElement), (ModelInstanceImpl) referenceSourceElement.getModelInstance()); return modelElementCollection.containsAll(c); } public boolean addAll(Collection<? extends T> c) { boolean result = false; for (T o: c) { result |= add(o); } return result; } public boolean removeAll(Collection<?> c) { boolean result = false; for (Object o: c) { result |= remove(o); } return result; } public boolean retainAll(Collection<?> c) { throw new UnsupportedModelOperationException("retainAll()", "not implemented"); } public void clear() { performClearOperation(referenceSourceElement);
} }; } protected void performClearOperation(ModelElementInstance referenceSourceElement) { setReferenceIdentifier(referenceSourceElement, ""); } @Override protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) { if (referenceIdentifier != null && !referenceIdentifier.isEmpty()) { super.setReferenceIdentifier(referenceSourceElement, referenceIdentifier); } else { referenceSourceAttribute.removeAttribute(referenceSourceElement); } } /** * @param referenceSourceElement * @param o */ protected void performRemoveOperation(ModelElementInstance referenceSourceElement, Object o) { removeReference(referenceSourceElement, (ModelElementInstance) o); } protected void performAddOperation(ModelElementInstance referenceSourceElement, T referenceTargetElement) { String identifier = getReferenceIdentifier(referenceSourceElement); List<String> references = StringUtil.splitListBySeparator(identifier, separator); String targetIdentifier = getTargetElementIdentifier(referenceTargetElement); references.add(targetIdentifier); identifier = StringUtil.joinList(references, separator); setReferenceIdentifier(referenceSourceElement, identifier); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\type\reference\AttributeReferenceCollection.java
1
请完成以下Java代码
public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; }
public boolean isAndChildren() { return andChildren; } public void setAndChildren(boolean andChildren) { this.andChildren = andChildren; } public String getRootCause() { return rootCause; } public void setRootCause(String rootCause) { this.rootCause = rootCause; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MapExceptionEntry.java
1
请完成以下Java代码
public class DeptrackApiServerDeploymentResource extends CRUDKubernetesDependentResource<Deployment, DeptrackResource> { public static final String COMPONENT = "api-server"; private Deployment template; public DeptrackApiServerDeploymentResource() { super(Deployment.class); this.template = BuilderHelper.loadTemplate(Deployment.class, "templates/api-server-deployment.yaml"); } @Override protected Deployment desired(DeptrackResource primary, Context<DeptrackResource> context) { ObjectMeta meta = fromPrimary(primary,COMPONENT) .build(); return new DeploymentBuilder(template) .withMetadata(meta) .withSpec(buildSpec(primary, meta)) .build(); } private DeploymentSpec buildSpec(DeptrackResource primary, ObjectMeta primaryMeta) { return new DeploymentSpecBuilder() .withSelector(buildSelector(primaryMeta.getLabels())) .withReplicas(1) // Dependenty track does not support multiple pods (yet) .withTemplate(buildPodTemplate(primary,primaryMeta)) .build(); } private LabelSelector buildSelector(Map<String, String> labels) { return new LabelSelectorBuilder() .addToMatchLabels(labels) .build(); } private PodTemplateSpec buildPodTemplate(DeptrackResource primary, ObjectMeta primaryMeta) {
return new PodTemplateSpecBuilder() .withMetadata(primaryMeta) .withSpec(buildPodSpec(primary)) .build(); } private PodSpec buildPodSpec(DeptrackResource primary) { // Check for version override String imageVersion = StringUtils.hasText(primary.getSpec().getApiServerVersion())? ":" + primary.getSpec().getApiServerVersion().trim():""; // Check for image override String imageName = StringUtils.hasText(primary.getSpec().getApiServerImage())? primary.getSpec().getApiServerImage().trim(): Constants.DEFAULT_API_SERVER_IMAGE; //@formatter:off return new PodSpecBuilder(template.getSpec().getTemplate().getSpec()) .editContainer(0) // Assumes we have a single container .withImage(imageName + imageVersion) .and() .build(); //@formatter:on } static class Discriminator extends ResourceIDMatcherDiscriminator<Deployment,DeptrackResource> { public Discriminator() { super(COMPONENT, (p) -> new ResourceID(p.getMetadata() .getName() + "-" + COMPONENT, p.getMetadata() .getNamespace())); } } }
repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackApiServerDeploymentResource.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isAP() {return multiplier.isAP();} public boolean isAPAdjusted() {return multiplier.isAPAdjusted();} public boolean isCreditMemo() {return multiplier.isCreditMemo();} public boolean isCMAdjusted() {return multiplier.isCreditMemoAdjusted();} public InvoiceTotal withAPAdjusted(final boolean isAPAdjusted) { return isAPAdjusted ? withAPAdjusted() : withoutAPAdjusted(); } public InvoiceTotal withAPAdjusted() { if (multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(true)); } } public InvoiceTotal withoutAPAdjusted() { if (!multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(false));
} } public InvoiceTotal withCMAdjusted(final boolean isCMAdjusted) { return isCMAdjusted ? withCMAdjusted() : withoutCMAdjusted(); } public InvoiceTotal withCMAdjusted() { if (multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(true)); } } public InvoiceTotal withoutCMAdjusted() { if (!multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(false)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceTotal.java
2
请完成以下Java代码
public class CopyFromProject extends JavaProcess { private int m_C_Project_ID = 0; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("C_Project_ID")) m_C_Project_ID = ((BigDecimal)para[i].getParameter()).intValue(); else log.error("prepare - Unknown Parameter: " + name); } } // prepare /** * Perform process. * @return Message (clear text) * @throws Exception if not successful */
protected String doIt() throws Exception { int To_C_Project_ID = getRecord_ID(); log.info("doIt - From C_Project_ID=" + m_C_Project_ID + " to " + To_C_Project_ID); if (To_C_Project_ID == 0) throw new IllegalArgumentException("Target C_Project_ID == 0"); if (m_C_Project_ID == 0) throw new IllegalArgumentException("Source C_Project_ID == 0"); MProject from = new MProject (getCtx(), m_C_Project_ID, get_TrxName()); MProject to = new MProject (getCtx(), To_C_Project_ID, get_TrxName()); // int no = to.copyDetailsFrom (from); return "@Copied@=" + no; } // doIt } // CopyFromProject
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\CopyFromProject.java
1
请完成以下Java代码
public void setP_Number (java.math.BigDecimal P_Number) { set_Value (COLUMNNAME_P_Number, P_Number); } /** Get Process Number. @return Prozess-Parameter */ @Override public java.math.BigDecimal getP_Number () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Process String. @param P_String Prozess-Parameter */ @Override public void setP_String (java.lang.String P_String) { set_Value (COLUMNNAME_P_String, P_String); }
/** Get Process String. @return Prozess-Parameter */ @Override public java.lang.String getP_String () { return (java.lang.String)get_Value(COLUMNNAME_P_String); } /** Set Parameter Name. @param ParameterName Parameter Name */ @Override public void setParameterName (java.lang.String ParameterName) { set_ValueNoCheck (COLUMNNAME_ParameterName, ParameterName); } /** Get Parameter Name. @return Parameter Name */ @Override public java.lang.String getParameterName () { return (java.lang.String)get_Value(COLUMNNAME_ParameterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Param.java
1
请完成以下Java代码
public static ClonableRabbit createRabbitUsingClone(ClonableRabbit originalRabbit) throws CloneNotSupportedException { ClonableRabbit clonedRabbit = (ClonableRabbit) originalRabbit.clone(); return clonedRabbit; } public static SerializableRabbit createRabbitUsingDeserialization(File file) throws IOException, ClassNotFoundException { try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis);) { return (SerializableRabbit) ois.readObject(); } } public static Rabbit createRabbitUsingSupplier() { Supplier<Rabbit> rabbitSupplier = Rabbit::new;
Rabbit rabbit = rabbitSupplier.get(); return rabbit; } public static Rabbit[] createRabbitArray() { Rabbit[] rabbitArray = new Rabbit[10]; return rabbitArray; } public static RabbitType createRabbitTypeEnum() { return RabbitType.PET; //any RabbitType could be returned here, PET is just an example. } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-constructors-2\src\main\java\com\baeldung\objectcreation\utils\CreateRabbits.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Class<?> getFieldNamingStrategy() { return this.fieldNamingStrategy; } public void setFieldNamingStrategy(@Nullable Class<?> fieldNamingStrategy) { this.fieldNamingStrategy = fieldNamingStrategy; } public Gridfs getGridfs() { return this.gridfs; } public Representation getRepresentation() { return this.representation; } public static class Gridfs { /** * GridFS database name. */ private @Nullable String database; /** * GridFS bucket name. */ private @Nullable String bucket; public @Nullable String getDatabase() { return this.database; } public void setDatabase(@Nullable String database) { this.database = database; } public @Nullable String getBucket() { return this.bucket; }
public void setBucket(@Nullable String bucket) { this.bucket = bucket; } } public static class Representation { /** * Representation to use when converting a BigDecimal. */ private @Nullable BigDecimalRepresentation bigDecimal = BigDecimalRepresentation.UNSPECIFIED; public @Nullable BigDecimalRepresentation getBigDecimal() { return this.bigDecimal; } public void setBigDecimal(@Nullable BigDecimalRepresentation bigDecimal) { this.bigDecimal = bigDecimal; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoProperties.java
2
请完成以下Java代码
public long getLogNumber() { return logNumber; } public void setLogNumber(long logNumber) { this.logNumber = logNumber; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; }
public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public String getLockTime() { return lockTime; } public void setLockTime(String lockTime) { this.lockTime = lockTime; } public int getProcessed() { return isProcessed; } public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Prefix. @param Prefix Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Start No. @param StartNo Starting number/position */ public void setStartNo (int StartNo)
{ set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java
1
请完成以下Java代码
public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name) { set_ValueNoCheck (COLUMNNAME_SalesRep_Name, SalesRep_Name); } @Override public java.lang.String getSalesRep_Name() { return get_ValueAsString(COLUMNNAME_SalesRep_Name); } @Override public void setTaxID (final java.lang.String TaxID) {
set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Header_v.java
1
请完成以下Java代码
public void setCollectionElementVariable(String collectionElementVariable) { this.collectionElementVariable = collectionElementVariable; } public String getCollectionElementIndexVariable() { return collectionElementIndexVariable; } public void setCollectionElementIndexVariable(String collectionElementIndexVariable) { this.collectionElementIndexVariable = collectionElementIndexVariable; } public void setInnerActivityBehavior(ActivityBehavior innerActivityBehavior) { this.innerActivityBehavior = innerActivityBehavior; if (innerActivityBehavior instanceof org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior) { ((org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior) innerActivityBehavior).setV5MultiInstanceActivityBehavior(this); } else { ((AbstractBpmnActivityBehavior) this.innerActivityBehavior).setMultiInstanceActivityBehavior(this); } } public ActivityBehavior getInnerActivityBehavior() { return innerActivityBehavior; } /** * ACT-1339. Calling ActivityEndListeners within an {@link AtomicOperation} so that an executionContext is present. * * @author Aris Tzoumas
* @author Joram Barrez */ private static final class CallActivityListenersOperation implements AtomicOperation { private List<ExecutionListener> listeners; private CallActivityListenersOperation(List<ExecutionListener> listeners) { this.listeners = listeners; } @Override public void execute(InterpretableExecution execution) { for (ExecutionListener executionListener : listeners) { try { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new ExecutionListenerInvocation(executionListener, execution)); } catch (Exception e) { throw new ActivitiException("Couldn't execute listener", e); } } } @Override public boolean isAsync(InterpretableExecution execution) { return false; } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
1
请完成以下Java代码
private void callExternalSystem(final IExternalSystemChildConfigId childConfigId, final ManufacturingJob job) { final PPOrderId ppOrderId = job.getPpOrderId(); final PInstanceId pInstanceId = adPInstanceDAO.createSelectionId(); exportToExternalSystemService.exportToExternalSystem( childConfigId, TableRecordReference.of(I_PP_Order.Table_Name, ppOrderId), pInstanceId); } @NonNull private IExternalSystemChildConfigId getExternalSystemChildConfigId(@NonNull final GlobalQRCode scannedQRCode) { if (ResourceQRCode.isTypeMatching(scannedQRCode)) { return getExternalSystemChildConfigId(ResourceQRCode.ofGlobalQRCode(scannedQRCode)); } else if (ExternalSystemConfigQRCode.isTypeMatching(scannedQRCode)) { final ExternalSystemConfigQRCode configQRCode = ExternalSystemConfigQRCode.ofGlobalQRCode(scannedQRCode); return configQRCode.getChildConfigId(); } else {
throw new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY); } } @NonNull private IExternalSystemChildConfigId getExternalSystemChildConfigId(@NonNull final ResourceQRCode resourceQRCode) { final Resource externalSystemResource = resourceService.getById(resourceQRCode.getResourceId()); if (!externalSystemResource.isExternalSystem()) { throw new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY); } return ExternalSystemParentConfigId.ofRepoIdOptional(externalSystemResource.getExternalSystemParentConfigId()) .flatMap(externalSystemConfigRepo::getChildByParentId) .map(IExternalSystemChildConfig::getId) .orElseThrow(() -> new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\callExternalSystem\CallExternalSystemActivityHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Feed atom() { Feed feed = new Feed(); feed.setFeedType("atom_1.0"); feed.setTitle("HBLOG"); feed.setId("http://www.liuhaihua.cn"); Content subtitle = new Content(); subtitle.setType("text/plain"); subtitle.setValue("recents post"); feed.setSubtitle(subtitle); Date postDate = new Date(); feed.setUpdated(postDate); Entry entry = new Entry(); Link link = new Link(); link.setHref("http://www.liuhaihua.cn/archives/710608.html"); entry.setAlternateLinks(Collections.singletonList(link)); SyndPerson author = new Person(); author.setName("HBLOG"); entry.setAuthors(Collections.singletonList(author));
entry.setCreated(postDate); entry.setPublished(postDate); entry.setUpdated(postDate); entry.setId("710608"); entry.setTitle("Spring Boot integrated banner quick start demo"); Category category = new Category(); category.setTerm("CORS"); entry.setCategories(Collections.singletonList(category)); Content summary = new Content(); summary.setType("text/plain"); summary.setValue("Spring Boot Banner is a feature for displaying custom ASCII art and information at application startup. This ASCII art usually includes the project name, version number, author information"); entry.setSummary(summary); feed.setEntries(Collections.singletonList(entry)); //add different topic return feed; } }
repos\springboot-demo-master\rss\src\main\java\com\et\rss\controller\FeedController.java
2
请完成以下Java代码
class ALayoutCollection extends HashMap<Object,Object> { /** * */ private static final long serialVersionUID = -2906536401026546141L; /** * Create Collection */ public ALayoutCollection() { super(); } // ALayoutCollection /** * Add a Component. * If constraint is null, it is added to the last row as additional column * @param constraint * @param component * @return component * @throws IllegalArgumentException if component is not a Component */ public Object put (Object constraint, Object component) { if (!(component instanceof Component)) throw new IllegalArgumentException ("ALayoutCollection can only add Component values"); if (constraint != null && !containsKey(constraint) && constraint instanceof ALayoutConstraint) { // Log.trace(this,Log.l6_Database, "ALayoutCollection.put", constraint.toString()); return super.put (constraint, component); } // We need to create constraint if (super.size() == 0) { // Log.trace(this,Log.l6_Database, "ALayoutCollection.put - first"); return super.put(new ALayoutConstraint(0,0), component); } // Add to end of list int row = getMaxRow(); if (row == -1) row = 0; int col = getMaxCol(row) + 1; ALayoutConstraint next = new ALayoutConstraint(row, col); // Log.trace(this,Log.l6_Database, "ALayoutCollection.put - addEnd", next.toString()); return super.put(next, component); } // put /** * Get Maximum Row Number * @return max row no - or -1 if no row */ public int getMaxRow () { int maxRow = -1; //
Iterator i = keySet().iterator(); while (i.hasNext()) { ALayoutConstraint c = (ALayoutConstraint)i.next(); maxRow = Math.max(maxRow, c.getRow()); } return maxRow; } // getMaxRow /** * Get Maximum Column Number * @return max col no - or -1 if no column */ public int getMaxCol () { int maxCol = -1; // Iterator i = keySet().iterator(); while (i.hasNext()) { ALayoutConstraint c = (ALayoutConstraint)i.next(); maxCol = Math.max(maxCol, c.getCol()); } return maxCol; } // getMaxCol /** * Get Maximum Column Number for Row * @param row * @return max col no for row - or -1 if no col in row */ public int getMaxCol (int row) { int maxCol = -1; // Iterator i = keySet().iterator(); while (i.hasNext()) { ALayoutConstraint c = (ALayoutConstraint)i.next(); if (c.getRow() == row) maxCol = Math.max(maxCol, c.getCol()); } return maxCol; } // getMaxCol } // ALayoutCollection
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayoutCollection.java
1
请在Spring Boot框架中完成以下Java代码
private static String getErrorMessage(@NonNull final Collection<TrxImportStatus> progress) { return progress.stream() .map(TrxImportStatus::getErrorMessage) .filter(Check::isNotBlank) .collect(Collectors.joining("\n")); } @Value @Builder public static class TrxImportStatus { boolean ok; @Nullable String errorMessage; @NonNull
public static EcosioOrdersRouteContext.TrxImportStatus ok() { return TrxImportStatus.builder() .ok(true) .build(); } @NonNull public static EcosioOrdersRouteContext.TrxImportStatus error(@NonNull final String errorMessage) { return TrxImportStatus.builder() .ok(false) .errorMessage(errorMessage) .build(); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\ecosio\EcosioOrdersRouteContext.java
2
请完成以下Java代码
public class CryptReadInterceptor extends CryptInterceptor implements Interceptor { private static final String MAPPED_STATEMENT = "mappedStatement"; public CryptReadInterceptor(Encrypt encrypt) { super(encrypt); log.info("init CryptReadInterceptor"); } @Override public Object intercept(Invocation invocation) throws Throwable { final List<Object> results = (List<Object>) invocation.proceed(); if (results.isEmpty()) { return results; } final ResultSetHandler statementHandler = PluginUtils.realTarget(invocation.getTarget()); final MetaObject metaObject = SystemMetaObject.forObject(statementHandler); final MappedStatement mappedStatement = (MappedStatement) metaObject.getValue(MAPPED_STATEMENT); final ResultMap resultMap = mappedStatement.getResultMaps().isEmpty() ? null : mappedStatement.getResultMaps().get(0); Object result = results.get(0); CryptEntity cryptEntity = result.getClass().getAnnotation(CryptEntity.class); if (cryptEntity == null || resultMap == null) { return results; } List<String> cryptFieldList = getCryptField(resultMap); log.info("CryptReadInterceptor cryptFieldList: {}", cryptFieldList); cryptFieldList.forEach(item -> { results.forEach(x -> { MetaObject objMetaObject = SystemMetaObject.forObject(x); Object value = objMetaObject.getValue(item); if (Objects.nonNull(value)) { objMetaObject.setValue(item, encrypt.decrypt(value.toString())); } }); }); return results; } /** * 获取需要加密的属性 * * @param resultMap * @return */ private List<String> getCryptField(ResultMap resultMap) { Class<?> clazz = resultMap.getType(); log.info("clazz: {}", clazz); List<String> fieldList = ENTITY_FILED_ANN_MAP.get(clazz.getName());
if (Objects.isNull(fieldList)) { fieldList = new ArrayList<>(); for (Field declaredField : clazz.getDeclaredFields()) { CryptField cryptField = declaredField.getAnnotation(CryptField.class); if (cryptField != null) { fieldList.add(declaredField.getName()); } } ENTITY_FILED_ANN_MAP.put(clazz.getName(), fieldList); } return fieldList; } @Override public Object plugin(Object target) { if (target instanceof ResultSetHandler) { return Plugin.wrap(target, this); } return target; } @Override public void setProperties(Properties properties) { } }
repos\spring-boot-quick-master\mybatis-crypt-plugin\src\main\java\com\quick\db\crypt\intercept\CryptReadInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getLOCATIONCODE() { return locationcode; } /** * Sets the value of the locationcode property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONCODE(String value) { this.locationcode = value; } /** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the hrfad1 property. * * @return * possible object is
* {@link HRFAD1 } * */ public HRFAD1 getHRFAD1() { return hrfad1; } /** * Sets the value of the hrfad1 property. * * @param value * allowed object is * {@link HRFAD1 } * */ public void setHRFAD1(HRFAD1 value) { this.hrfad1 = value; } /** * Gets the value of the hctad1 property. * * @return * possible object is * {@link HCTAD1 } * */ public HCTAD1 getHCTAD1() { return hctad1; } /** * Sets the value of the hctad1 property. * * @param value * allowed object is * {@link HCTAD1 } * */ public void setHCTAD1(HCTAD1 value) { this.hctad1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\HADRE1.java
2
请完成以下Java代码
public void setValue(final ModelType model, @Nullable final AttributeType attributeValue) { InterfaceWrapperHelper.setDynAttribute(model, attributeName, attributeValue); } public IAutoCloseable temporarySetValue(final ModelType model, final AttributeType value) { final AttributeType valueOld = getValue(model); setValue(model, value); return () -> setValue(model, valueOld); } public boolean isSet(final ModelType model) { final Object attributeValue = InterfaceWrapperHelper.getDynAttribute(model, attributeName); return attributeValue != null; } public boolean isNull(final ModelType model) { final Object attributeValue = InterfaceWrapperHelper.getDynAttribute(model, attributeName);
return attributeValue == null; } /** * @return true if given <code>model</code>'s attribute equals with <code>expectedValue</code> */ public boolean is(final ModelType model, final AttributeType expectedValue) { final Object attributeValue = InterfaceWrapperHelper.getDynAttribute(model, attributeName); return Objects.equals(attributeValue, expectedValue); } public void reset(final ModelType model) { setValue(model, null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelDynAttributeAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public class GenericEntityController { private List<GenericEntity> entityList = new ArrayList<>(); { entityList.add(new GenericEntity(1l, "entity_1")); entityList.add(new GenericEntity(2l, "entity_2")); entityList.add(new GenericEntity(3l, "entity_3")); entityList.add(new GenericEntity(4l, "entity_4")); } @GetMapping("/entity/all") public List<GenericEntity> findAll() { return entityList; } @PostMapping("/entity")
public GenericEntity addEntity(GenericEntity entity) { entityList.add(entity); return entity; } @GetMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); } @GetMapping("/entity/findbydate/{date}") public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { return entityList.stream().findFirst().get(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-simple\src\main\java\com\baeldung\starter\controller\GenericEntityController.java
2
请完成以下Java代码
public final class DocumentLUTUConfigurationManager<T> implements IDocumentLUTUConfigurationManager { private final IDocumentLUTUConfigurationHandler<T> handler; private final T _documentLine; public DocumentLUTUConfigurationManager(final T documentLine, final IDocumentLUTUConfigurationHandler<T> handler) { super(); Check.assumeNotNull(handler, "handler not null"); this.handler = handler; Check.assumeNotNull(documentLine, "documentLine not null"); this._documentLine = documentLine; } @Override public I_M_HU_LUTU_Configuration createAndEdit(final Function<I_M_HU_LUTU_Configuration, I_M_HU_LUTU_Configuration> lutuConfigurationEditor) { final ILUTUConfigurationEditor editor = startEditing(); editor.updateFromModel(); if (lutuConfigurationEditor != null) { editor.edit(lutuConfigurationEditor); if (!editor.isEditing()) { return null; } } // Save the edited configuration and push it back to model editor.pushBackToModel(); return editor.getLUTUConfiguration(); } @Override public ILUTUConfigurationEditor startEditing() { return new LUTUConfigurationEditor(this); } @Override public I_M_HU_LUTU_Configuration getCreateLUTUConfiguration() { // // If there is an already existing configuration, return it without any changes final I_M_HU_LUTU_Configuration lutuConfigurationExisting = getCurrentLUTUConfigurationOrNull(); if (lutuConfigurationExisting != null && lutuConfigurationExisting.getM_HU_LUTU_Configuration_ID() > 0) { return lutuConfigurationExisting; } // // Create a new LU/TU configuration and return it return createNewLUTUConfiguration(); } @Override public I_M_HU_LUTU_Configuration getCurrentLUTUConfigurationOrNull() { final T documentLine = getDocumentLine(); return handler.getCurrentLUTUConfigurationOrNull(documentLine); } @Override
public void setCurrentLUTUConfigurationAndSave(final I_M_HU_LUTU_Configuration lutuConfiguration) { // Update the document line final T documentLine = getDocumentLine(); handler.setCurrentLUTUConfiguration(documentLine, lutuConfiguration); // Save it handler.save(documentLine); } protected I_M_HU_LUTU_Configuration createNewLUTUConfiguration() { final T documentLine = getDocumentLine(); return handler.createNewLUTUConfiguration(documentLine); } private T getDocumentLine() { return _documentLine; } @Override public void updateLUTUConfigurationFromModel(final I_M_HU_LUTU_Configuration lutuConfiguration) { final T documentLine = getDocumentLine(); handler.updateLUTUConfigurationFromDocumentLine(lutuConfiguration, documentLine); } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product() { final T documentLine = getDocumentLine(); return handler.getM_HU_PI_Item_Product(documentLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\DocumentLUTUConfigurationManager.java
1
请完成以下Java代码
public void setPrice_Old (java.math.BigDecimal Price_Old) { set_Value (COLUMNNAME_Price_Old, Price_Old); } /** Get Preis (old). @return Preis (old) */ @Override public java.math.BigDecimal getPrice_Old () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price_Old); if (bd == null) { return Env.ZERO; } return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Produkt UUID. @param Product_UUID Produkt UUID */ @Override public void setProduct_UUID (java.lang.String Product_UUID) { set_Value (COLUMNNAME_Product_UUID, Product_UUID); } /** Get Produkt UUID. @return Produkt UUID */ @Override public java.lang.String getProduct_UUID () { return (java.lang.String)get_Value(COLUMNNAME_Product_UUID); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) { return Env.ZERO; } return bd; } /** Set Menge (old). @param Qty_Old Menge (old) */ @Override
public void setQty_Old (java.math.BigDecimal Qty_Old) { set_Value (COLUMNNAME_Qty_Old, Qty_Old); } /** Get Menge (old). @return Menge (old) */ @Override public java.math.BigDecimal getQty_Old () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty_Old); if (bd == null) { return Env.ZERO; } return bd; } /** * Type AD_Reference_ID=540660 * Reference name: PMM_RfQResponse_ChangeEvent_Type */ public static final int TYPE_AD_Reference_ID=540660; /** Price = P */ public static final String TYPE_Price = "P"; /** Quantity = Q */ public static final String TYPE_Quantity = "Q"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_RfQResponse_ChangeEvent.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Posted. @param Posted Posting status */ public void setPosted (boolean Posted) { set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted)); } /** Get Posted. @return Posting status */ public boolean isPosted () { Object oo = get_Value(COLUMNNAME_Posted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set 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; } public org.eevolution.model.I_HR_Process getReversal() throws RuntimeException { return (org.eevolution.model.I_HR_Process)MTable.get(getCtx(), org.eevolution.model.I_HR_Process.Table_Name) .getPO(getReversal_ID(), get_TrxName()); } /** Set Reversal ID. @param Reversal_ID ID of document reversal */ public void setReversal_ID (int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID)); } /** Get Reversal ID. @return ID of document reversal */ public int getReversal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Process.java
1
请在Spring Boot框架中完成以下Java代码
public void stop() { this.lifecycleLock.lock(); try { if (this.running) { try { if (this.kafkaStreams != null) { this.kafkaStreams.close(new KafkaStreams.CloseOptions() .timeout(this.closeTimeout) .leaveGroup(this.leaveGroupOnClose) ); if (this.cleanupConfig.cleanupOnStop()) { this.kafkaStreams.cleanUp(); } for (Listener listener : this.listeners) { listener.streamsRemoved(this.beanName, this.kafkaStreams); } this.kafkaStreams = null; } } catch (Exception e) { LOGGER.error(e, "Failed to stop streams"); } finally { this.running = false; } } } finally { this.lifecycleLock.unlock(); } } @Override public boolean isRunning() { this.lifecycleLock.lock(); try { return this.running; } finally { this.lifecycleLock.unlock(); } } @Override public void afterSingletonsInstantiated() { try { this.topology = getObject().build(this.properties); this.infrastructureCustomizer.configureTopology(this.topology); TopologyDescription description = this.topology.describe(); LOGGER.debug(description::toString); } catch (Exception e) { throw new RuntimeException(e); } } private StreamsBuilder createStreamBuilder() { if (this.properties == null) { return new StreamsBuilder(); } else {
StreamsConfig streamsConfig = new StreamsConfig(this.properties); TopologyConfig topologyConfig = new TopologyConfig(streamsConfig); return new StreamsBuilder(topologyConfig); } } /** * Called whenever a {@link KafkaStreams} is added or removed. * * @since 2.5.3 * */ public interface Listener { /** * A new {@link KafkaStreams} was created. * @param id the streams id (factory bean name). * @param streams the streams; */ default void streamsAdded(String id, KafkaStreams streams) { } /** * An existing {@link KafkaStreams} was removed. * @param id the streams id (factory bean name). * @param streams the streams; */ default void streamsRemoved(String id, KafkaStreams streams) { } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\StreamsBuilderFactoryBean.java
2
请完成以下Java代码
public MLocation getLocation (Object key, String trxName) { if (key == null) return null; int C_Location_ID = 0; if (key instanceof Integer) C_Location_ID = ((Integer)key).intValue(); else if (key != null) C_Location_ID = Integer.parseInt(key.toString()); // return getLocation(C_Location_ID, trxName); } // getLocation /** * Get Location * @param C_Location_ID id * @param trxName transaction * @return Location */ public MLocation getLocation (int C_Location_ID, String trxName) { return MLocation.get(m_ctx, C_Location_ID, trxName); } // getC_Location_ID @Override public String getTableName() { return I_C_Location.Table_Name; } @Override public String getColumnName() { return I_C_Location.Table_Name + "." + I_C_Location.COLUMNNAME_C_Location_ID; } // getColumnName
@Override public String getColumnNameNotFQ() { return I_C_Location.COLUMNNAME_C_Location_ID; } /** * Return data as sorted Array - not implemented * @param mandatory mandatory * @param onlyValidated only validated * @param onlyActive only active * @param temporary force load for temporary display * @return null */ @Override public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { log.error("not implemented"); return null; } // getArray } // MLocation
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocationLookup.java
1
请完成以下Java代码
public byte[] listen(String in) { log.info(in); if (in.equals("\"getAThing\"")) { return ("{\"thingProp\":\"someValue\"}").getBytes(); } if (in.equals("\"getThings\"")) { return ("[{\"thingProp\":\"someValue1\"},{\"thingProp\":\"someValue2\"}]").getBytes(); } return in.toUpperCase().getBytes(); } public static class Thing { private String thingProp; public String getThingProp() { return this.thingProp; }
public void setThingProp(String thingProp) { this.thingProp = thingProp; } @Override public String toString() { return "Thing [thingProp=" + this.thingProp + "]"; } } }
repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\requestreply\Application.java
1
请完成以下Java代码
public class Item { @Id private String _id; private String name; private double price; public Item(String name, double price) { this.name = name; this.price = price; } public Item() { } public String get_id() { return _id; } public String getName() { return name; } public void setName(String name) {
this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Item{" + "id='" + _id + '\'' + ", name='" + name + '\'' + ", price=" + price + '}'; } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\caching\Item.java
1
请完成以下Java代码
public boolean contains(Object value) { return getDelegate().contains(value); } @Override public boolean containsValue(Object value) { return getDelegate().containsValue(value); } @Override public boolean containsKey(Object key) { return getDelegate().containsKey(key); } @Override public Object get(Object key) { return getDelegate().get(key); } @Override public void load(InputStream inStream) throws IOException { getDelegate().load(inStream); } @Override public Object put(Object key, Object value) { return getDelegate().put(key, value); } @Override public Object remove(Object key) { return getDelegate().remove(key); } @Override public void putAll(Map<? extends Object, ? extends Object> t) { getDelegate().putAll(t); } @Override public void clear() { getDelegate().clear(); } @Override public Object clone() { return getDelegate().clone(); } @Override public String toString() { return getDelegate().toString(); } @Override public Set<Object> keySet() { return getDelegate().keySet(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { return getDelegate().entrySet(); } @Override public Collection<Object> values() { return getDelegate().values(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); }
@SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
public Long getWorkTimeInMillis() { if (endTime == null || claimTime == null) { return null; } return endTime.getTime() - claimTime.getTime(); } public Map<String, Object> getTaskLocalVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() != null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void processRestApiCallToRuleEngine(TenantId tenantId, UUID requestId, TbMsg request, boolean useQueueFromTbMsg, Consumer<TbMsg> responseConsumer) { log.trace("[{}] Processing REST API call to rule engine: [{}] for entity: [{}]", tenantId, requestId, request.getOriginator()); requests.put(requestId, responseConsumer); sendRequestToRuleEngine(tenantId, request, useQueueFromTbMsg); scheduleTimeout(request, requestId, requests); } @Override public void onQueueMsg(TransportProtos.RestApiCallResponseMsgProto restApiCallResponseMsg, TbCallback callback) { UUID requestId = new UUID(restApiCallResponseMsg.getRequestIdMSB(), restApiCallResponseMsg.getRequestIdLSB()); Consumer<TbMsg> consumer = requests.remove(requestId); if (consumer != null) { consumer.accept(TbMsg.fromProto(null, restApiCallResponseMsg.getResponseProto(), restApiCallResponseMsg.getResponse(), TbMsgCallback.EMPTY)); } else { log.trace("[{}] Unknown or stale rest api call response received", requestId); } callback.onSuccess(); }
private void sendRequestToRuleEngine(TenantId tenantId, TbMsg msg, boolean useQueueFromTbMsg) { clusterService.pushMsgToRuleEngine(tenantId, msg.getOriginator(), msg, useQueueFromTbMsg, null); } private void scheduleTimeout(TbMsg request, UUID requestId, ConcurrentMap<UUID, Consumer<TbMsg>> requestsMap) { long expirationTime = Long.parseLong(request.getMetaData().getValue("expirationTime")); long timeout = Math.max(0, expirationTime - System.currentTimeMillis()); log.trace("[{}] processing the request: [{}]", this.hashCode(), requestId); executor.schedule(() -> { Consumer<TbMsg> consumer = requestsMap.remove(requestId); if (consumer != null) { log.trace("[{}] request timeout detected: [{}]", this.hashCode(), requestId); consumer.accept(null); } }, timeout, TimeUnit.MILLISECONDS); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ruleengine\DefaultRuleEngineCallService.java
2
请在Spring Boot框架中完成以下Java代码
public static ServiceName forMscRuntimeContainerJobExecutorService(String jobExecutorName) { return JOB_EXECUTOR.append(jobExecutorName); } /** * @return the {@link ServiceName} of the {@link MscBpmPlatformPlugins} */ public static ServiceName forBpmPlatformPlugins() { return BPM_PLATFORM_PLUGINS; } /** * @return the {@link ServiceName} of the {@link ProcessApplicationStopService} */ public static ServiceName forProcessApplicationStopService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("STOP"); }
/** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.BoundedQueueThreadPoolService} */ public static ServiceName forManagedThreadPool(String threadPoolName) { return JOB_EXECUTOR.append(threadPoolName); } /** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.ThreadFactoryService} */ public static ServiceName forThreadFactoryService(String threadFactoryName) { return ThreadsServices.threadFactoryName(threadFactoryName); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ServiceNames.java
2
请完成以下Java代码
public Integer getRoleId() { return roleId; } /** * 设置 角色ID. * * @param roleId 角色ID. */ public void setRoleId(Integer roleId) { this.roleId = roleId; } /** * 获取 创建时间. * * @return 创建时间. */ public Date getCreatedTime() { return createdTime; } /** * 设置 创建时间. * * @param createdTime 创建时间. */ public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; }
/** * 获取 更新时间. * * @return 更新时间. */ public Date getUpdatedTime() { return updatedTime; } /** * 设置 更新时间. * * @param updatedTime 更新时间. */ public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } protected Serializable pkVal() { return this.id; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\ManagerRole.java
1
请完成以下Java代码
public class CompositeModelInterceptor implements IModelInterceptor, IUserLoginListener { private final CopyOnWriteArrayList<IModelInterceptor> interceptors = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<IUserLoginListener> userLoginListeners = new CopyOnWriteArrayList<>(); private int adClientId = -1; public void addModelInterceptor(final IModelInterceptor interceptor) { Check.assumeNotNull(interceptor, "interceptor not null"); interceptors.addIfAbsent(interceptor); if (interceptor instanceof IUserLoginListener) { userLoginListeners.addIfAbsent((IUserLoginListener)interceptor); } } public void removeModelInterceptor(final IModelInterceptor interceptor) { Check.assumeNotNull(interceptor, "interceptor not null"); interceptors.remove(interceptor); if (interceptor instanceof IUserLoginListener) { userLoginListeners.remove(interceptor); } } @Override public void initialize(final IModelValidationEngine engine, final I_AD_Client client) { if (client != null) { adClientId = client.getAD_Client_ID(); } for (final IModelInterceptor interceptor : interceptors) { interceptor.initialize(engine, client); } } @Override public int getAD_Client_ID() { return adClientId; } @Override public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception { for (final IModelInterceptor interceptor : interceptors) { interceptor.onModelChange(model, changeType); } } @Override public void onDocValidate(final Object model, final DocTimingType timing) throws Exception { for (final IModelInterceptor interceptor : interceptors) { interceptor.onDocValidate(model, timing);
} } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // NOTE: we use "interceptors" instead of userLoginListeners because the "onUserLogin" it's implemented on IModelInterceptor level for (final IModelInterceptor interceptor : interceptors) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); } } @Override public void beforeLogout(final MFSession session) { for (final IUserLoginListener listener : userLoginListeners) { listener.beforeLogout(session); } } @Override public void afterLogout(final MFSession session) { for (final IUserLoginListener listener : userLoginListeners) { listener.afterLogout(session); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\CompositeModelInterceptor.java
1
请完成以下Java代码
public EntityTypeEntry getByEntityTypeOrNull(final String entityType) { Check.assumeNotEmpty(entityType, "entityType not empty"); // fail because in most of the cases is a development error return entries.get(entityType); } public EntityTypeEntry getByEntityType(final String entityType) { final EntityTypeEntry entry = getByEntityTypeOrNull(entityType); if (entry == null) { final AdempiereException ex = new AdempiereException("No EntityType entry found for entity type: " + entityType + "\n Available EntityTypes are: " + getEntityTypeNames()); logger.warn("", ex); } return entry; } public boolean isActive(final String entityType) { return getByEntityTypeOrNull(entityType) != null; } public boolean isDisplayedInUI(final String entityType) { final EntityTypeEntry entry = getByEntityTypeOrNull(entityType); if (entry == null) { return false; } return entry.isDisplayedInUI(); } public String getModelPackage(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return null; } return entry.getModelPackage(); } public String getWebUIServletListenerClass(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return null; } return entry.getWebUIServletListenerClass(); } public boolean isSystemMaintained(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return false; } return entry.isSystemMaintained();
} } @Value @VisibleForTesting public static final class EntityTypeEntry { private final String entityType; private final String modelPackage; private final boolean displayedInUI; private final boolean systemMaintained; private final String webUIServletListenerClass; @Builder private EntityTypeEntry( final String entityType, final String modelPackage, final boolean displayedInUI, final boolean systemMaintained, final String webUIServletListenerClass) { super(); this.entityType = entityType; this.modelPackage = modelPackage; this.displayedInUI = displayedInUI; this.systemMaintained = systemMaintained; this.webUIServletListenerClass = webUIServletListenerClass; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\EntityTypesCache.java
1
请完成以下Java代码
public DynamicUserTaskBuilder assignee(String assignee) { this.assignee = assignee; return this; } public DynamicUserTaskCallback getDynamicUserTaskCallback() { return dynamicUserTaskCallback; } public void setDynamicUserTaskCallback(DynamicUserTaskCallback dynamicUserTaskCallback) { this.dynamicUserTaskCallback = dynamicUserTaskCallback; } public DynamicUserTaskBuilder dynamicUserTaskCallback(DynamicUserTaskCallback dynamicUserTaskCallback) { this.dynamicUserTaskCallback = dynamicUserTaskCallback; return this; } public String getDynamicTaskId() { return dynamicTaskId; } public void setDynamicTaskId(String dynamicTaskId) { this.dynamicTaskId = dynamicTaskId; } public String nextSubProcessId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicSubProcess", flowElementMap); } public String nextTaskId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicTask", flowElementMap); } public String nextFlowId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicFlow", flowElementMap); } public String nextForkGatewayId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicForkGateway", flowElementMap); } public String nextJoinGatewayId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicJoinGateway", flowElementMap); }
public String nextStartEventId(Map<String, FlowElement> flowElementMap) { return nextId("startEvent", flowElementMap); } public String nextEndEventId(Map<String, FlowElement> flowElementMap) { return nextId("endEvent", flowElementMap); } protected String nextId(String prefix, Map<String, FlowElement> flowElementMap) { String nextId = null; boolean nextIdNotFound = true; while (nextIdNotFound) { if (!flowElementMap.containsKey(prefix + counter)) { nextId = prefix + counter; nextIdNotFound = false; } counter++; } return nextId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\DynamicUserTaskBuilder.java
1
请完成以下Java代码
public boolean isMaterial(@Nullable final PPOrderBOMLineId orderBOMLineId) { return isMaterialReceipt() || isAnyComponentIssueOrCoProduct(orderBOMLineId); } public boolean isMaterialReceipt() { return this == MaterialReceipt; } public boolean isMaterialReceiptOrCoProduct() { return isMaterialReceipt() || isCoOrByProductReceipt(); } public boolean isComponentIssue() { return this == ComponentIssue; } public boolean isAnyComponentIssueOrCoProduct(@Nullable final PPOrderBOMLineId orderBOMLineId) { return isAnyComponentIssue(orderBOMLineId) || isCoOrByProductReceipt(); } public boolean isAnyComponentIssue(@Nullable final PPOrderBOMLineId orderBOMLineId) { return isComponentIssue() || isMaterialMethodChangeVariance(orderBOMLineId); } public boolean isActivityControl() { return this == ActivityControl; } public boolean isVariance() { return this == MethodChangeVariance || this == UsageVariance || this == RateVariance || this == MixVariance; } public boolean isCoOrByProductReceipt() { return this == MixVariance; } public boolean isUsageVariance() { return this == UsageVariance; }
public boolean isMaterialUsageVariance(@Nullable final PPOrderBOMLineId orderBOMLineId) { return this == UsageVariance && orderBOMLineId != null; } public boolean isResourceUsageVariance(@Nullable final PPOrderRoutingActivityId activityId) { return this == UsageVariance && activityId != null; } public boolean isRateVariance() { return this == RateVariance; } public boolean isMethodChangeVariance() { return this == MethodChangeVariance; } public boolean isMaterialMethodChangeVariance(@Nullable final PPOrderBOMLineId orderBOMLineId) { return this == MethodChangeVariance && orderBOMLineId != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\CostCollectorType.java
1
请完成以下Java代码
public SAPGLJournalLineId getIdNotNull() { if (id == null) { throw new AdempiereException("Line ID not yet available: " + this); } return id; } @Nullable public SAPGLJournalLineId getIdOrNull() { return id; } public void assignId(@NonNull final SAPGLJournalLineId id) { if (this.id != null && !SAPGLJournalLineId.equals(this.id, id)) { throw new AdempiereException("Line has already assigned a different ID: " + this); } this.id = id; } public boolean isGeneratedTaxLine() { return parentId != null && taxId != null; } /** * This logic expects, that tax lines always generated from an base account with tax set (included or not)
*/ public boolean isTaxLine() { return taxId != null && (determineTaxBaseSAP || parentId != null); } public boolean isTaxLineGeneratedForBaseLine(@NonNull final SAPGLJournalLine taxBaseLine) { return isTaxLine() && parentId != null && SAPGLJournalLineId.equals(parentId, taxBaseLine.getIdOrNull()); } public boolean isBaseTaxLine() { return parentId == null && taxId != null && !determineTaxBaseSAP; } @NonNull public Optional<SAPGLJournalLine> getReverseChargeCounterPart( @NonNull final SAPGLJournalTaxProvider taxProvider, @NonNull final AcctSchemaId acctSchemaId) { return Optional.ofNullable(taxId) .filter(taxProvider::isReverseCharge) .map(reverseChargeTaxId -> toBuilder() .postingSign(getPostingSign().reverse()) .account(taxProvider.getTaxAccount(reverseChargeTaxId, acctSchemaId, getPostingSign().reverse())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\SAPGLJournalLine.java
1
请在Spring Boot框架中完成以下Java代码
public class SessionFilter implements Filter { protected Logger log = LoggerFactory.getLogger(SessionFilter.class); // 不登陆也可以访问的资源 private static Set<String> GreenUrlSet = new HashSet<String>(); public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) srequest; String uri = request.getRequestURI(); sresponse.setCharacterEncoding("UTF-8");//设置响应编码格式 sresponse.setContentType("text/html;charset=UTF-8");//设置响应编码格式 if (uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".jpg") || uri.endsWith(".gif") || uri.endsWith(".png") || uri.endsWith(".ico")) { log.debug("security filter, pass, " + request.getRequestURI()); filterChain.doFilter(srequest, sresponse); return; } System.out.println("request uri is : "+uri); //不处理指定的action, jsp if (GreenUrlSet.contains(uri) || uri.contains("/verified/")) { log.debug("security filter, pass, " + request.getRequestURI()); filterChain.doFilter(srequest, sresponse); return; } String id=(String)request.getSession().getAttribute(WebConfiguration.LOGIN_KEY); if(StringUtils.isBlank(id)){ String html = "<script type=\"text/javascript\">window.location.href=\"/toLogin\"</script>"; sresponse.getWriter().write(html); }else { filterChain.doFilter(srequest, sresponse);
} } public void destroy() { } @Override public void init(FilterConfig filterconfig) throws ServletException { GreenUrlSet.add("/toRegister"); GreenUrlSet.add("/toLogin"); GreenUrlSet.add("/login"); GreenUrlSet.add("/loginOut"); GreenUrlSet.add("/register"); GreenUrlSet.add("/verified"); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\config\SessionFilter.java
2
请完成以下Java代码
public void setMSV3_Bestellung_Transaction_ID (int MSV3_Bestellung_Transaction_ID) { if (MSV3_Bestellung_Transaction_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Bestellung_Transaction_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Bestellung_Transaction_ID, Integer.valueOf(MSV3_Bestellung_Transaction_ID)); } /** Get MSV3_Bestellung_Transaction. @return MSV3_Bestellung_Transaction */ @Override public int getMSV3_Bestellung_Transaction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Bestellung_Transaction_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_BestellungAntwort getMSV3_BestellungAntwort() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_BestellungAntwort_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_BestellungAntwort.class); } @Override public void setMSV3_BestellungAntwort(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_BestellungAntwort MSV3_BestellungAntwort) { set_ValueFromPO(COLUMNNAME_MSV3_BestellungAntwort_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_BestellungAntwort.class, MSV3_BestellungAntwort); } /** Set MSV3_BestellungAntwort. @param MSV3_BestellungAntwort_ID MSV3_BestellungAntwort */ @Override public void setMSV3_BestellungAntwort_ID (int MSV3_BestellungAntwort_ID) { if (MSV3_BestellungAntwort_ID < 1) set_Value (COLUMNNAME_MSV3_BestellungAntwort_ID, null); else set_Value (COLUMNNAME_MSV3_BestellungAntwort_ID, Integer.valueOf(MSV3_BestellungAntwort_ID)); } /** Get MSV3_BestellungAntwort. @return MSV3_BestellungAntwort */ @Override public int getMSV3_BestellungAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwort_ID); if (ii == null) return 0;
return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo getMSV3_FaultInfo() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_FaultInfo_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo.class); } @Override public void setMSV3_FaultInfo(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo MSV3_FaultInfo) { set_ValueFromPO(COLUMNNAME_MSV3_FaultInfo_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo.class, MSV3_FaultInfo); } /** Set MSV3_FaultInfo. @param MSV3_FaultInfo_ID MSV3_FaultInfo */ @Override public void setMSV3_FaultInfo_ID (int MSV3_FaultInfo_ID) { if (MSV3_FaultInfo_ID < 1) set_Value (COLUMNNAME_MSV3_FaultInfo_ID, null); else set_Value (COLUMNNAME_MSV3_FaultInfo_ID, Integer.valueOf(MSV3_FaultInfo_ID)); } /** Get MSV3_FaultInfo. @return MSV3_FaultInfo */ @Override public int getMSV3_FaultInfo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_FaultInfo_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Bestellung_Transaction.java
1
请完成以下Java代码
public <T> T getAdditionalInfoField(String field, Function<JsonNode, T> mapper, T defaultValue) { JsonNode additionalInfo = getAdditionalInfo(); if (additionalInfo != null && additionalInfo.has(field)) { return mapper.apply(additionalInfo.get(field)); } return defaultValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; BaseDataWithAdditionalInfo<?> that = (BaseDataWithAdditionalInfo<?>) o; return Arrays.equals(additionalInfoBytes, that.additionalInfoBytes); } @Override public int hashCode() { return Objects.hash(super.hashCode(), additionalInfoBytes); } public static JsonNode getJson(Supplier<JsonNode> jsonData, Supplier<byte[]> binaryData) { JsonNode json = jsonData.get(); if (json != null) { return json;
} else { byte[] data = binaryData.get(); if (data != null) { try { return mapper.readTree(new ByteArrayInputStream(data)); } catch (IOException e) { log.warn("Can't deserialize json data: ", e); return null; } } else { return null; } } } public static void setJson(JsonNode json, Consumer<JsonNode> jsonConsumer, Consumer<byte[]> bytesConsumer) { jsonConsumer.accept(json); try { bytesConsumer.accept(mapper.writeValueAsBytes(json)); } catch (JsonProcessingException e) { log.warn("Can't serialize json data: ", e); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseDataWithAdditionalInfo.java
1