instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static UsernamePasswordAuthenticationToken unauthenticated(@Nullable Object principal, @Nullable Object credentials) { return new UsernamePasswordAuthenticationToken(principal, credentials); } /** * This factory method can be safely used by any code that wishes to create a * authenticated <code>UsernamePasswordAuthenticationToken</code>. * @param principal * @param credentials * @return UsernamePasswordAuthenticationToken with true isAuthenticated() result * * @since 5.7 */ public static UsernamePasswordAuthenticationToken authenticated(Object principal, @Nullable Object credentials, Collection<? extends GrantedAuthority> authorities) { return new UsernamePasswordAuthenticationToken(principal, credentials, authorities); } @Override public @Nullable Object getCredentials() { return this.credentials; } @Override public @Nullable Object getPrincipal() { return this.principal; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); this.credentials = null; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link UsernamePasswordAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private @Nullable Object principal;
private @Nullable Object credentials; protected Builder(UsernamePasswordAuthenticationToken token) { super(token); this.principal = token.principal; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } @Override public B credentials(@Nullable Object credentials) { this.credentials = credentials; return (B) this; } @Override public UsernamePasswordAuthenticationToken build() { return new UsernamePasswordAuthenticationToken(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\UsernamePasswordAuthenticationToken.java
1
请完成以下Java代码
public void setMKTG_Consent_ID (int MKTG_Consent_ID) { if (MKTG_Consent_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Consent_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Consent_ID, Integer.valueOf(MKTG_Consent_ID)); } /** Get MKTG_Consent. @return MKTG_Consent */ @Override public int getMKTG_Consent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Consent_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); } @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */
@Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_Value (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_Value (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Consent.java
1
请完成以下Java代码
public @Nullable String getReplyToGroupId() { return this.replyToGroupId; } /** * See * {@link com.rabbitmq.stream.MessageBuilder.PropertiesBuilder#replyToGroupId(String)}. * @param replyToGroupId the reply to group id. */ public void setReplyToGroupId(String replyToGroupId) { this.replyToGroupId = replyToGroupId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(this.creationTime, this.groupId, this.groupSequence, this.replyToGroupId, this.subject, this.to); return result; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } StreamMessageProperties other = (StreamMessageProperties) obj; return this.creationTime == other.creationTime && Objects.equals(this.groupId, other.groupId) && this.groupSequence == other.groupSequence && Objects.equals(this.replyToGroupId, other.replyToGroupId) && Objects.equals(this.subject, other.subject) && Objects.equals(this.to, other.to); } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\support\StreamMessageProperties.java
1
请完成以下Java代码
public IntentEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public IntentEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public IntentEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public IntentEventListenerInstanceQuery asc() { innerQuery.asc(); return this; } @Override public IntentEventListenerInstanceQuery desc() { innerQuery.desc(); return this; } @Override public IntentEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public IntentEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return innerQuery.count();
} @Override public IntentEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return IntentEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<IntentEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<IntentEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<IntentEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(IntentEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceQueryImpl.java
1
请完成以下Java代码
private static final boolean isValueChanged(final GridTab tab, final String columnName, final boolean newRecord) { final GridTable table = tab.getTableModel(); final int index = table.findColumn(columnName); if (index == -1) { return false; } if (newRecord) { return true; } final Object valueOld = table.getOldValue(tab.getCurrentRow(), index); if (valueOld == null) { return false; } final Object value = tab.getValue(columnName); if (!valueOld.equals(value)) { return true; } return false; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MTableIndex["); sb.append(get_ID()).append("-").append(getName()).append( ",AD_Table_ID=").append(getAD_Table_ID()).append("]"); return sb.toString();
} private static class TableIndexesMap { private final ImmutableListMultimap<String, MIndexTable> indexesByTableName; private final ImmutableMap<String, MIndexTable> indexesByNameUC; public TableIndexesMap(final List<MIndexTable> indexes) { indexesByTableName = Multimaps.index(indexes, MIndexTable::getTableName); indexesByNameUC = Maps.uniqueIndex(indexes, index -> index.getName().toUpperCase()); } public ImmutableList<MIndexTable> getByTableName(@NonNull final String tableName) { return indexesByTableName.get(tableName); } public MIndexTable getByNameIgnoringCase(@NonNull final String name) { String nameUC = name.toUpperCase(); return indexesByNameUC.get(nameUC); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexTable.java
1
请在Spring Boot框架中完成以下Java代码
public static void validPermission(HttpServletRequest request, int jobGroup) { XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); if (!loginUser.validPermission(jobGroup)) { throw new RuntimeException(I18nUtil.getString("system_permission_limit") + "[username="+ loginUser.getUsername() +"]"); } } @RequestMapping("/pageList") @ResponseBody public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) { return xxlJobService.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author); } @RequestMapping("/add") @ResponseBody public ReturnT<String> add(XxlJobInfo jobInfo) { return xxlJobService.add(jobInfo); } @RequestMapping("/update") @ResponseBody public ReturnT<String> update(XxlJobInfo jobInfo) { return xxlJobService.update(jobInfo); } @RequestMapping("/remove") @ResponseBody public ReturnT<String> remove(int id) { return xxlJobService.remove(id); } @RequestMapping("/stop") @ResponseBody public ReturnT<String> pause(int id) { return xxlJobService.stop(id); } @RequestMapping("/start") @ResponseBody public ReturnT<String> start(int id) { return xxlJobService.start(id); } @RequestMapping("/trigger") @ResponseBody public ReturnT<String> triggerJob(HttpServletRequest request, int id, String executorParam, String addressList) { // login user XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); // trigger return xxlJobService.trigger(loginUser, id, executorParam, addressList); } @RequestMapping("/nextTriggerTime") @ResponseBody public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {
XxlJobInfo paramXxlJobInfo = new XxlJobInfo(); paramXxlJobInfo.setScheduleType(scheduleType); paramXxlJobInfo.setScheduleConf(scheduleConf); List<String> result = new ArrayList<>(); try { Date lastTime = new Date(); for (int i = 0; i < 5; i++) { lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime); if (lastTime != null) { result.add(DateUtil.formatDateTime(lastTime)); } else { break; } } } catch (Exception e) { logger.error(e.getMessage(), e); return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) + e.getMessage()); } return new ReturnT<List<String>>(result); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobInfoController.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringMvcConfiguration implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // Add Sentinel interceptor // addSentinelWebTotalInterceptor(registry); addSentinelWebInterceptor(registry); } private void addSentinelWebInterceptor(InterceptorRegistry registry) { // 创建 SentinelWebMvcConfig 对象 SentinelWebMvcConfig config = new SentinelWebMvcConfig(); config.setHttpMethodSpecify(true); // 是否包含请求方法。即基于 URL 创建的资源,是否包含 Method。 // config.setBlockExceptionHandler(new DefaultBlockExceptionHandler()); // 设置 BlockException 处理器。 // config.setOriginParser(new RequestOriginParser() { // 设置请求来源解析器。用于黑白名单控制功能。 // // @Override // public String parseOrigin(HttpServletRequest request) { // // 从 Header 中,获得请求来源 // String origin = request.getHeader("s-user"); // // 如果为空,给一个默认的 // if (StringUtils.isEmpty(origin)) { // origin = "default"; // } // return origin; // }
// // }); // 添加 SentinelWebInterceptor 拦截器 registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**"); } private void addSentinelWebTotalInterceptor(InterceptorRegistry registry) { // 创建 SentinelWebMvcTotalConfig 对象 SentinelWebMvcTotalConfig config = new SentinelWebMvcTotalConfig(); // 添加 SentinelWebTotalInterceptor 拦截器 registry.addInterceptor(new SentinelWebTotalInterceptor(config)).addPathPatterns("/**"); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SpringMvcConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { private final Logger logger = LoggerFactory.getLogger(getClass()); @PostMapping("/user/login") public Map<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password) { if ("yudaoyuanma".equals(username) && "123456".equals(password)) { Map<String, Object> tokenMap = new HashMap<>(); tokenMap.put("userId", 1); tokenMap.put("token", "token001"); return tokenMap; } throw new RuntimeException("小朋友,你的账号密码不正确哟!"); } @GetMapping("/user/get-current") public Map<String, Object> getCurrentUser(@RequestHeader("Authorization") String authorization, @RequestParam("full") boolean full) {
if ("token001".equals(authorization)) { Map<String, Object> userInfo = new HashMap<>(); userInfo.put("id", 1); // full 为 true 时,获得完整信息 if (full) { userInfo.put("nickname", "芋道源码"); userInfo.put("gender", 1); } return userInfo; } throw new RuntimeException("小朋友,你没有登录哟!"); } @PostMapping("/user/update") public Boolean update(@RequestBody UserUpdateVO updateVO) { logger.info("[update][收到更新请求:{}]", updateVO.toString()); return true; } }
repos\SpringBoot-Labs-master\lab-71-http-debug\lab-71-idea-http-client\src\main\java\cn\iocoder\springboot\lab71\controller\UserController.java
2
请完成以下Java代码
public class MapMax { public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) { Entry<K, V> maxEntry = null; for (Entry<K, V> entry : map.entrySet()) { if (maxEntry == null || entry.getValue() .compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } return maxEntry.getValue(); } public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) { Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() { public int compare(Entry<K, V> e1, Entry<K, V> e2) { return e1.getValue() .compareTo(e2.getValue()); } }); return maxEntry.getValue(); } public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) { Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.getValue(); } public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndMethodReference(Map<K, V> map) { Entry<K, V> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Entry::getValue)); return maxEntry.getValue(); } public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) { Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream() .max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.get() .getValue(); } public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) { Optional<Entry<K, V>> maxEntry = map.entrySet() .stream() .max(Comparator.comparing(Entry::getValue)); return maxEntry.get() .getValue(); } public <K, V extends Comparable<V>> K keyOfMaxUsingStream(Map<K, V> map) { return map.entrySet() .stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse(null); } public static void main(String[] args) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 3); map.put(2, 4); map.put(3, 5); map.put(4, 6); map.put(5, 7); MapMax mapMax = new MapMax(); System.out.println(mapMax.maxUsingIteration(map)); System.out.println(mapMax.maxUsingCollectionsMax(map)); System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); System.out.println(mapMax.maxUsingStreamAndLambda(map)); System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-2\src\main\java\com\baeldung\map\mapmax\MapMax.java
1
请完成以下Java代码
public static SecretKey getKeyForText(String secretText) throws GeneralSecurityException { byte[] keyBytes = secretText.getBytes(StandardCharsets.UTF_8); return new SecretKeySpec(keyBytes, "AES"); } /* * Allows us to generate a deterministic key, for the purposes of producing * reliable and consistent demo code & tests! For a random key, consider using * the generateKey method above. */ public static SecretKey getFixedKey() throws GeneralSecurityException { String secretText = "BaeldungIsASuperCoolSite"; return getKeyForText(secretText); } public static IvParameterSpec getIV() { SecureRandom secureRandom = new SecureRandom(); byte[] iv = new byte[128 / 8]; byte[] nonce = new byte[96 / 8]; secureRandom.nextBytes(nonce); System.arraycopy(nonce, 0, iv, 0, nonce.length); return new IvParameterSpec(nonce); } public static IvParameterSpec getIVSecureRandom(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException { SecureRandom random = SecureRandom.getInstanceStrong(); byte[] iv = new byte[Cipher.getInstance(algorithm).getBlockSize()]; random.nextBytes(iv); return new IvParameterSpec(iv); } public static IvParameterSpec getIVInternal(Cipher cipher) throws InvalidParameterSpecException { AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); return new IvParameterSpec(iv); } public static byte[] getRandomIVWithSize(int size) { byte[] nonce = new byte[size]; new SecureRandom().nextBytes(nonce); return nonce;
} public static byte[] encryptWithPadding(SecretKey key, byte[] bytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cipherTextBytes = cipher.doFinal(bytes); return cipherTextBytes; } public static byte[] decryptWithPadding(SecretKey key, byte[] cipherTextBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(cipherTextBytes); } }
repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\utils\CryptoUtils.java
1
请在Spring Boot框架中完成以下Java代码
public void setBuyerGTINCU(String value) { this.buyerGTINCU = value; } /** * Gets the value of the buyerEANCU property. * * @return * possible object is * {@link String } * */ public String getBuyerEANCU() { return buyerEANCU; } /** * Sets the value of the buyerEANCU property. * * @param value * allowed object is * {@link String } * */ public void setBuyerEANCU(String value) { this.buyerEANCU = value; } /** * Gets the value of the supplierGTINCU property.
* * @return * possible object is * {@link String } * */ public String getSupplierGTINCU() { return supplierGTINCU; } /** * Sets the value of the supplierGTINCU property. * * @param value * allowed object is * {@link String } * */ public void setSupplierGTINCU(String value) { this.supplierGTINCU = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EDICctopInvoic500VType.java
2
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Public. @param IsPublic Public can read entry */ public void setIsPublic (boolean IsPublic) { set_Value (COLUMNNAME_IsPublic, Boolean.valueOf(IsPublic)); } /** Get Public. @return Public can read entry */ public boolean isPublic () { Object oo = get_Value(COLUMNNAME_IsPublic); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Public Write. @param IsPublicWrite Public can write entries */ public void setIsPublicWrite (boolean IsPublicWrite) { set_Value (COLUMNNAME_IsPublicWrite, Boolean.valueOf(IsPublicWrite)); } /** Get Public Write. @return Public can write entries */ public boolean isPublicWrite () { Object oo = get_Value(COLUMNNAME_IsPublicWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Knowldge Type. @param K_Type_ID Knowledge Type */ public void setK_Type_ID (int K_Type_ID) { if (K_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Type_ID, Integer.valueOf(K_Type_ID)); } /** Get Knowldge Type. @return Knowledge Type */ public int getK_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Type_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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Type.java
1
请完成以下Java代码
private static Authentication getAuthenticationToken(Object principal) { return new AbstractAuthenticationToken(AuthorityUtils.NO_AUTHORITIES) { @Override public Object getCredentials() { return null; } @Override public Object getPrincipal() { return principal; } }; } class SpringSessionBackedReactiveSessionInformation extends ReactiveSessionInformation { SpringSessionBackedReactiveSessionInformation(S session) { super(resolvePrincipalName(session), session.getId(), session.getLastAccessedTime()); } private static String resolvePrincipalName(Session session) { String principalName = session .getAttribute(ReactiveFindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) {
return principalName; } SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT); if (securityContext != null && securityContext.getAuthentication() != null) { return securityContext.getAuthentication().getName(); } return ""; } @Override public Mono<Void> invalidate() { return super.invalidate() .then(Mono.defer(() -> SpringSessionBackedReactiveSessionRegistry.this.sessionRepository .deleteById(getSessionId()))); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedReactiveSessionRegistry.java
1
请完成以下Java代码
Iterator<WorkQueue> loadForTable(final Partition partition, final String tableName) { final IQueryBL queryBL = Services.get(IQueryBL.class); final int tableId = Services.get(IADTableDAO.class).retrieveTableId(tableName); final Iterator<I_DLM_Partition_Record_V> iterator = queryBL.createQueryBuilder(I_DLM_Partition_Record_V.class, PlainContextAware.newWithThreadInheritedTrx()) .addEqualsFilter(I_DLM_Partition_Record_V.COLUMN_DLM_Partition_ID, partition.getDLM_Partition_ID()) .addEqualsFilter(I_DLM_Partition_Record_V.COLUMN_AD_Table_ID, tableId) .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 5000) .iterate(I_DLM_Partition_Record_V.class); return new Iterator<WorkQueue>() { @Override public boolean hasNext() { return iterator.hasNext(); }
@Override public WorkQueue next() { return WorkQueue.of(TableRecordReference.ofReferencedOrNull(iterator.next())); } @Override public String toString() { return "PartitionerService.loadForTable() [partition=" + partition + "; tableName=" + tableName + ", iterator=" + iterator + "]"; } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\PartitionerService.java
1
请完成以下Java代码
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; }
public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
1
请在Spring Boot框架中完成以下Java代码
public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId;
} public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java
2
请完成以下Java代码
public WebClient connectionTimeoutClient() { HttpClient httpClient = HttpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); return buildWebClient(httpClient); } public WebClient connectionTimeoutWithKeepAliveClient() { HttpClient httpClient = HttpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .option(EpollChannelOption.TCP_KEEPIDLE, 300) .option(EpollChannelOption.TCP_KEEPINTVL, 60) .option(EpollChannelOption.TCP_KEEPCNT, 8); return buildWebClient(httpClient); } public WebClient readWriteTimeoutClient() { HttpClient httpClient = HttpClient.create() .doOnConnected(conn -> conn .addHandler(new ReadTimeoutHandler(5, TimeUnit.SECONDS)) .addHandler(new WriteTimeoutHandler(5))); return buildWebClient(httpClient); } public WebClient sslTimeoutClient() { HttpClient httpClient = HttpClient.create() .secure(spec -> spec .sslContext(SslContextBuilder.forClient()) .defaultConfiguration(SslProvider.DefaultConfigurationType.TCP) .handshakeTimeout(Duration.ofSeconds(30))
.closeNotifyFlushTimeout(Duration.ofSeconds(10)) .closeNotifyReadTimeout(Duration.ofSeconds(10))); return buildWebClient(httpClient); } public WebClient proxyTimeoutClient() { HttpClient httpClient = HttpClient.create() .proxy(spec -> spec .type(ProxyProvider.Proxy.HTTP) .host("http://proxy") .port(8080) .connectTimeoutMillis(3000)); return buildWebClient(httpClient); } private WebClient buildWebClient(HttpClient httpClient) { return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\timeout\WebClientTimeoutProvider.java
1
请完成以下Java代码
private ImmutableSet<FactAcctId> computeClearingFactAcctIds() { final ImmutableSet<FAOpenItemKey> openItemKeys = factAcctDAO.stream(FactAcctQuery.builder() .tableName(fromRecordRef.getTableName()) .recordId(fromRecordRef.getRecord_ID()) .isOpenItem(true) .openItemTrxType(FAOpenItemTrxType.OPEN_ITEM) .build()) .map(ClearingFactAcctsQuerySupplier::extractOpenItemKeyOrNull) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (openItemKeys.isEmpty()) { return ImmutableSet.of(); } return factAcctDAO.listIds(FactAcctQuery.builder() .tableName(I_SAP_GLJournal.Table_Name) .excludeRecordRef(fromRecordRef)
.isOpenItem(true) .openItemTrxType(FAOpenItemTrxType.CLEARING) .openItemsKeys(openItemKeys) .build()); } private static FAOpenItemKey extractOpenItemKeyOrNull(final I_Fact_Acct record) { try { return FAOpenItemKey.parseNullable(record.getOpenItemKey()).orElse(null); } catch (Exception ex) { logger.warn("Failed extracting open item key from {}. Returning null.", record, ex); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\open_items\related_documents\ClearingFactAcctsQuerySupplier.java
1
请完成以下Java代码
private void moveHUsToLocator(final @NonNull List<I_M_HU> husToMove, @NonNull final LocatorId locatorId) { final Map<Integer, List<HuId>> diffLocatorToHuIds = husToMove.stream() .filter(hu -> hu.getM_Locator_ID() != locatorId.getRepoId()) .collect(Collectors.groupingBy(I_M_HU::getM_Locator_ID, Collectors.mapping(hu -> HuId.ofRepoId(hu.getM_HU_ID()), Collectors.toList()))); if (diffLocatorToHuIds.isEmpty()) { return; } diffLocatorToHuIds.values() .forEach(huIdsSharingTheSameLocator -> huMovementBL.moveHUs(HUMovementGenerateRequest.builder() .toLocatorId(locatorId) .huIdsToMove(huIdsSharingTheSameLocator) .movementDate(SystemTime.asInstant()) .build())); } @NonNull private Optional<HuPackingInstructionsItemId> getNewLUPackingInstructionsForAggregateSplit(@NonNull final HuId tuId)
{ if (!target.isPlaceAggTUsOnNewLUAfterMove()) { return Optional.empty(); } final I_M_HU_PI tuPI = handlingUnitsBL.getEffectivePI(tuId); if (tuPI == null) { return Optional.empty(); } return handlingUnitsDAO.retrieveDefaultParentPIItemId(tuPI, X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit, null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\MoveHUCommand.java
1
请完成以下Java代码
public void setAge(final int age) { this.age = age; } public LocalDate getCreationDate() { return creationDate; } public List<Possession> getPossessionList() { return possessionList; } public void setPossessionList(List<Possession> possessionList) { this.possessionList = possessionList; } @Override public String toString() { return "User [name=" + name + ", id=" + id + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && age == user.age && Objects.equals(name, user.name) && Objects.equals(creationDate, user.creationDate) && Objects.equals(email, user.email) && Objects.equals(status, user.status);
} @Override public int hashCode() { return Objects.hash(id, name, creationDate, age, email, status); } public LocalDate getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(LocalDate lastLoginDate) { this.lastLoginDate = lastLoginDate; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\modifying\model\User.java
1
请完成以下Java代码
public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Accounting Schema. @return Rules for accounting */ public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getIntercompanyDueFrom_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getIntercompanyDueFrom_Acct(), get_TrxName()); } /** Set Intercompany Due From Acct. @param IntercompanyDueFrom_Acct Intercompany Due From / Receivables Account */ public void setIntercompanyDueFrom_Acct (int IntercompanyDueFrom_Acct) { set_Value (COLUMNNAME_IntercompanyDueFrom_Acct, Integer.valueOf(IntercompanyDueFrom_Acct)); } /** Get Intercompany Due From Acct. @return Intercompany Due From / Receivables Account
*/ public int getIntercompanyDueFrom_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueFrom_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getIntercompanyDueTo_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getIntercompanyDueTo_Acct(), get_TrxName()); } /** Set Intercompany Due To Acct. @param IntercompanyDueTo_Acct Intercompany Due To / Payable Account */ public void setIntercompanyDueTo_Acct (int IntercompanyDueTo_Acct) { set_Value (COLUMNNAME_IntercompanyDueTo_Acct, Integer.valueOf(IntercompanyDueTo_Acct)); } /** Get Intercompany Due To Acct. @return Intercompany Due To / Payable Account */ public int getIntercompanyDueTo_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueTo_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InterOrg_Acct.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper("Cached") .addValue(delegate) .toString(); } @Override public Optional<String> getLookupTableName() { return delegate.getLookupTableName(); } @Override public String getCachePrefix() { return cachePrefix; } @Override public boolean isCached() { return true; } @Override public void cacheInvalidate() { cache_retrieveEntities.reset(); cache_retrieveLookupValueById.reset(); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.<CCacheStats>builder() .add(cache_retrieveEntities.stats()) .add(cache_retrieveLookupValueById.stats()) .addAll(delegate.getCacheStats()) .build(); } @Override public boolean isNumericKey() { return delegate.isNumericKey(); } @Override public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return delegate.newContextForFetchingById(id); } @Override public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { return cache_retrieveLookupValueById.getOrLoad(evalCtx, () -> delegate.retrieveLookupValueById(evalCtx)); } @Override public LookupValuesList retrieveLookupValueByIdsInOrder(final @NonNull LookupDataSourceContext evalCtx) { cache_retrieveLookupValueById.getAllOrLoad( evalCtx.streamSingleIdContexts().collect(ImmutableSet.toImmutableSet()),
singleIdCtxs -> { final LookupDataSourceContext multipleIdsCtx = LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs); return delegate.retrieveLookupValueByIdsInOrder(LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs)) .getValues() .stream() .collect(ImmutableMap.toImmutableMap( lookupValue -> multipleIdsCtx.withIdToFilter(IdsToFilter.ofSingleValue(lookupValue.getId())), lookupValue -> lookupValue)); } ); return LookupDataSourceFetcher.super.retrieveLookupValueByIdsInOrder(evalCtx); } @Override public Builder newContextForFetchingList() { return delegate.newContextForFetchingList(); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { return cache_retrieveEntities.getOrLoad(evalCtx, delegate::retrieveEntities); } @Override public Optional<WindowId> getZoomIntoWindowId() { return delegate.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\CachedLookupDataSourceFetcherAdapter.java
1
请完成以下Java代码
public void setStmtAmt (final BigDecimal StmtAmt) { set_Value (COLUMNNAME_StmtAmt, StmtAmt); } @Override public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTrxAmt (final BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValutaDate (final java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLine.java
1
请完成以下Java代码
public <JSONType> ResponseEntity<JSONType> toJson(final BiFunction<R, JSONOptions, JSONType> toJsonMapper) { return toResponseEntity((responseBuilder, result) -> responseBuilder.body(toJsonMapper.apply(result, getJSONOptions()))); } public <JSONType> ResponseEntity<JSONType> toLayoutJson(final BiFunction<R, JSONDocumentLayoutOptions, JSONType> toJsonMapper) { return toResponseEntity((responseBuilder, result) -> responseBuilder.body(toJsonMapper.apply(result, getJSONLayoutOptions()))); } public <JSONType> ResponseEntity<JSONType> toDocumentJson(final BiFunction<R, JSONDocumentOptions, JSONType> toJsonMapper) { return toResponseEntity((responseBuilder, result) -> responseBuilder.body(toJsonMapper.apply(result, getJSONDocumentOptions()))); } public <BodyType> ResponseEntity<BodyType> toResponseEntity(final BiFunction<ResponseEntity.BodyBuilder, R, ResponseEntity<BodyType>> toJsonMapper) { // Check ETag final String etag = getETag().toETagString(); if (request.checkNotModified(etag)) { // Response: 304 Not Modified return newResponse(HttpStatus.NOT_MODIFIED, etag).build(); } // Get the result and convert it to JSON
final R result = this.result.get(); final ResponseEntity.BodyBuilder newResponse = newResponse(HttpStatus.OK, etag); return toJsonMapper.apply(newResponse, result); } private final ResponseEntity.BodyBuilder newResponse(final HttpStatus status, final String etag) { ResponseEntity.BodyBuilder response = ResponseEntity.status(status) .eTag(etag) .cacheControl(CacheControl.maxAge(cacheMaxAgeSec, TimeUnit.SECONDS)); final String adLanguage = getAdLanguage(); if (adLanguage != null && !adLanguage.isEmpty()) { final String contentLanguage = ADLanguageList.toHttpLanguageTag(adLanguage); response.header(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); response.header(HttpHeaders.VARY, HttpHeaders.ACCEPT_LANGUAGE); // advice browser to include ACCEPT_LANGUAGE in their caching key } return response; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\cache\ETagResponseEntityBuilder.java
1
请完成以下Java代码
public class SecureRandomFactoryBean implements FactoryBean<SecureRandom> { private String algorithm = "SHA1PRNG"; private @Nullable Resource seed; @Override public SecureRandom getObject() throws Exception { SecureRandom random = SecureRandom.getInstance(this.algorithm); // Request the next bytes, thus eagerly incurring the expense of default // seeding and to prevent the see from replacing the entire state random.nextBytes(new byte[1]); if (this.seed != null) { // Seed specified, so use it byte[] seedBytes = FileCopyUtils.copyToByteArray(this.seed.getInputStream()); random.setSeed(seedBytes); } return random; } @Override public Class<SecureRandom> getObjectType() { return SecureRandom.class; } @Override public boolean isSingleton() { return false; } /** * Allows the Pseudo Random Number Generator (PRNG) algorithm to be nominated. * Defaults to "SHA1PRNG". * @param algorithm to use (mandatory)
*/ public void setAlgorithm(String algorithm) { Assert.hasText(algorithm, "Algorithm required"); this.algorithm = algorithm; } /** * Allows the user to specify a resource which will act as a seed for the * {@link SecureRandom} instance. Specifically, the resource will be read into an * {@link InputStream} and those bytes presented to the * {@link SecureRandom#setSeed(byte[])} method. Note that this will simply supplement, * rather than replace, the existing seed. As such, it is always safe to set a seed * using this method (it never reduces randomness). * @param seed to use, or <code>null</code> if no additional seeding is needed */ public void setSeed(Resource seed) { this.seed = seed; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\token\SecureRandomFactoryBean.java
1
请完成以下Java代码
public int getC_Recurring_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document Date. @param DateDoc Date of the Document */ public void setDateDoc (Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Document Date. @return Date of the Document */ public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } public I_GL_JournalBatch getGL_JournalBatch() throws RuntimeException { return (I_GL_JournalBatch)MTable.get(getCtx(), I_GL_JournalBatch.Table_Name) .getPO(getGL_JournalBatch_ID(), get_TrxName()); } /** Set Journal Batch.
@param GL_JournalBatch_ID General Ledger Journal Batch */ public void setGL_JournalBatch_ID (int GL_JournalBatch_ID) { if (GL_JournalBatch_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, Integer.valueOf(GL_JournalBatch_ID)); } /** Get Journal Batch. @return General Ledger Journal Batch */ public int getGL_JournalBatch_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring_Run.java
1
请在Spring Boot框架中完成以下Java代码
public String getProductionDescription() { return productionDescription; } /** * Sets the value of the productionDescription property. * * @param value * allowed object is * {@link String } * */ public void setProductionDescription(String value) { this.productionDescription = value; } /** * Gets the value of the kanbanCardNumberRange1Start property. * * @return * possible object is * {@link String } * */ public String getKanbanCardNumberRange1Start() { return kanbanCardNumberRange1Start; } /** * Sets the value of the kanbanCardNumberRange1Start property. * * @param value * allowed object is * {@link String } * */ public void setKanbanCardNumberRange1Start(String value) { this.kanbanCardNumberRange1Start = value; } /** * Gets the value of the kanbanCardNumberRange1End property. * * @return * possible object is
* {@link String } * */ public String getKanbanCardNumberRange1End() { return kanbanCardNumberRange1End; } /** * Sets the value of the kanbanCardNumberRange1End property. * * @param value * allowed object is * {@link String } * */ public void setKanbanCardNumberRange1End(String value) { this.kanbanCardNumberRange1End = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PackagingIdentificationType.java
2
请完成以下Java代码
public PurposeSEPA getPurp() { return purp; } /** * Sets the value of the purp property. * * @param value * allowed object is * {@link PurposeSEPA } * */ public void setPurp(PurposeSEPA value) { this.purp = value; } /** * Gets the value of the rmtInf property. * * @return * possible object is
* {@link RemittanceInformationSEPA1Choice } * */ public RemittanceInformationSEPA1Choice getRmtInf() { return rmtInf; } /** * Sets the value of the rmtInf property. * * @param value * allowed object is * {@link RemittanceInformationSEPA1Choice } * */ public void setRmtInf(RemittanceInformationSEPA1Choice value) { this.rmtInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\DirectDebitTransactionInformationSDD.java
1
请完成以下Java代码
public String asi(final ICalloutField calloutField) { if (isCalloutActive()) { return NO_ERROR; } final I_M_InOutLine inoutLine = calloutField.getModel(I_M_InOutLine.class); final int asiId = inoutLine.getM_AttributeSetInstance_ID(); if (asiId <= 0) { return NO_ERROR; } // final I_M_InOut inout = inoutLine.getM_InOut(); final int M_Product_ID = inoutLine.getM_Product_ID(); final int M_Warehouse_ID = inout.getM_Warehouse_ID(); final int M_Locator_ID = inoutLine.getM_Locator_ID(); // TODO: Env.getContextAsInt(ctx, WindowNo, CTXNAME_M_Locator_ID); log.debug("M_Product_ID={}, M_ASI_ID={} - M_Warehouse_ID={}, M_Locator_ID={}", M_Product_ID, asiId, M_Warehouse_ID, M_Locator_ID); // // Check Selection final int selected_asiId = calloutField.getTabInfoContextAsInt(CTXNAME_M_AttributeSetInstance_ID); if (selected_asiId == asiId) { final int selectedM_Locator_ID = calloutField.getTabInfoContextAsInt(CTXNAME_M_Locator_ID); if (selectedM_Locator_ID > 0) { log.debug("Selected M_Locator_ID={}", selectedM_Locator_ID); inoutLine.setM_Locator_ID(selectedM_Locator_ID); } } //
// metas: make sure that MovementQty must be 1 for a product with a serial number. final I_M_AttributeSetInstance attributeSetInstance = inoutLine.getM_AttributeSetInstance(); if (attributeSetInstance != null) { final BigDecimal qtyEntered = inoutLine.getQtyEntered(); final String serNo = attributeSetInstance.getSerNo(); if (!Check.isEmpty(serNo, true) && (qtyEntered == null || qtyEntered.compareTo(BigDecimal.ONE) != 0)) { final int windowNo = calloutField.getWindowNo(); Services.get(IClientUI.class).info(windowNo, MSG_SERIALNO_QTY_ONE); inoutLine.setQtyEntered(BigDecimal.ONE); } } // metas end return NO_ERROR; } // asi } // CalloutInOut
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\CalloutInOut.java
1
请完成以下Java代码
public void setViewsRepository(@NonNull final IViewsRepository viewsRepository) { // nothing } @Override public IView createView(final @NonNull CreateViewRequest request) { throw new UnsupportedOperationException(); } @Override public ViewLayout getViewLayout( final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId) { Check.assumeEquals(windowId, WINDOW_ID, "windowId"); return ViewLayout.builder() .setWindowId(WINDOW_ID) .setCaption(TranslatableStrings.empty()) .setAllowOpeningRowDetails(false) .addElementsFromViewRowClass(PaymentToReconcileRow.class, viewDataType) .build(); } @Override public WindowId getWindowId() { return WINDOW_ID; } @Override public void put(final IView view) { throw new UnsupportedOperationException(); } @Nullable @Override public PaymentsToReconcileView getByIdOrNull(@NonNull final ViewId paymentsToReconcileViewId) { final ViewId bankStatementReconciliationViewId = toBankStatementReconciliationViewId(paymentsToReconcileViewId); final BankStatementReconciliationView bankStatementReconciliationView = banksStatementReconciliationViewFactory.getByIdOrNull(bankStatementReconciliationViewId); return bankStatementReconciliationView != null ? bankStatementReconciliationView.getPaymentsToReconcileView() : null; } private static ViewId toBankStatementReconciliationViewId(@NonNull final ViewId paymentsToReconcileViewId) {
return paymentsToReconcileViewId.withWindowId(BankStatementReconciliationViewFactory.WINDOW_ID); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { // nothing } @Override public Stream<IView> streamAllViews() { return banksStatementReconciliationViewFactory.streamAllViews() .map(BankStatementReconciliationView::cast) .map(BankStatementReconciliationView::getPaymentsToReconcileView); } @Override public void invalidateView(final ViewId paymentsToReconcileViewId) { final PaymentsToReconcileView paymentsToReconcileView = getByIdOrNull(paymentsToReconcileViewId); if (paymentsToReconcileView != null) { paymentsToReconcileView.invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentsToReconcileViewFactory.java
1
请完成以下Java代码
public final DDOrderUserNotificationProducer notifyGenerated(@NonNull final I_DD_Order order) { notifyGenerated(ImmutableList.of(order)); return this; } private UserNotificationRequest createUserNotification(@NonNull final I_DD_Order order) { final UserId recipientUserId = getNotificationRecipientUserId(order); final TableRecordReference orderRef = TableRecordReference.of(order); return newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(MSG_Event_DDOrderGenerated) .contentADMessageParam(orderRef) .targetAction(UserNotificationRequest.TargetRecordAction.of(orderRef)) .build(); }
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC); } private UserId getNotificationRecipientUserId(final I_DD_Order order) { return UserId.ofRepoId(order.getCreatedBy()); } private void postNotifications(final List<UserNotificationRequest> notifications) { notificationBL.sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\event\DDOrderUserNotificationProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class RpUserPayInfo extends BaseEntity implements Serializable { /** * 对应关系 * 微信:appid * 支付宝:partner */ private String appId; private String appSectet; /** * 对应关系 * 微信:merchantid * 支付宝:seller_id */ private String merchantId; private String appType; private String userNo; private String userName; /** * 对应关系 * 微信:partnerkey * 支付宝:key */ private String partnerKey; private String payWayCode; private String payWayName; /** * 支付宝线下产品appid */ private String offlineAppId; /** * 支付宝私钥 */ private String rsaPrivateKey; /** * 支付宝公钥 */ private String rsaPublicKey; public String getOfflineAppId() { return offlineAppId; } public void setOfflineAppId(String offlineAppId) { this.offlineAppId = offlineAppId; } public String getRsaPrivateKey() { return rsaPrivateKey; } public void setRsaPrivateKey(String rsaPrivateKey) { this.rsaPrivateKey = rsaPrivateKey; } public String getRsaPublicKey() { return rsaPublicKey; } public void setRsaPublicKey(String rsaPublicKey) { this.rsaPublicKey = rsaPublicKey; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode; } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName; } public String getPartnerKey() { return partnerKey; } public void setPartnerKey(String partnerKey) { this.partnerKey = partnerKey; } private static final long serialVersionUID = 1L; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId == null ? null : appId.trim(); } public String getAppSectet() { return appSectet; } public void setAppSectet(String appSectet) { this.appSectet = appSectet == null ? null : appSectet.trim(); } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId == null ? null : merchantId.trim(); } public String getAppType() { return appType; } public void setAppType(String appType) { this.appType = appType == null ? null : appType.trim(); } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayInfo.java
2
请完成以下Java代码
public final class ImmutableMoney { private final long amount; private final String currency; public ImmutableMoney(long amount, String currency) { this.amount = amount; this.currency = currency; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (amount ^ (amount >>> 32)); result = prime * result + ((currency == null) ? 0 : currency.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImmutableMoney other = (ImmutableMoney) obj; if (amount != other.amount) return false; if (currency == null) { if (other.currency != null)
return false; } else if (!currency.equals(other.currency)) return false; return true; } public long getAmount() { return amount; } public String getCurrency() { return currency; } @Override public String toString() { return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]"; } }
repos\tutorials-master\google-auto-project\src\main\java\com\baeldung\autovalue\ImmutableMoney.java
1
请完成以下Java代码
public void setDivideBy100 (boolean DivideBy100) { set_Value (COLUMNNAME_DivideBy100, Boolean.valueOf(DivideBy100)); } /** Get Durch 100 teilen. @return Divide number by 100 to get correct amount */ @Override public boolean isDivideBy100 () { Object oo = get_Value(COLUMNNAME_DivideBy100); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set End-Nr.. @param EndNo End-Nr. */ @Override public void setEndNo (int EndNo) { set_Value (COLUMNNAME_EndNo, Integer.valueOf(EndNo)); } /** Get End-Nr.. @return End-Nr. */ @Override public int getEndNo () { Integer ii = (Integer)get_Value(COLUMNNAME_EndNo); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Skript. @param Script Dynamic Java Language Script to calculate result */ @Override public void setScript (java.lang.String Script)
{ set_Value (COLUMNNAME_Script, Script); } /** Get Skript. @return Dynamic Java Language Script to calculate result */ @Override public java.lang.String getScript () { return (java.lang.String)get_Value(COLUMNNAME_Script); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Start No. @param StartNo Starting number/position */ @Override public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ @Override public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat_Row.java
1
请完成以下Java代码
private static PaymentToAllocate retrievePaymentToAllocateOrNull(@NonNull final ResultSet rs) throws SQLException { final CurrencyCode documentCurrencyCode = CurrencyCode.ofThreeLetterCode(rs.getString("currency_code")); final BigDecimal multiplierAP = rs.getBigDecimal("MultiplierAP"); // +1=Inbound Payment, -1=Outbound Payment final PaymentDirection paymentDirection = PaymentDirection.ofInboundPaymentFlag(multiplierAP.signum() > 0); // NOTE: we assume the amounts were already AP adjusted, so we are converting them back to relative values (i.e. not AP adjusted) final Amount payAmt = retrieveAmount(rs, "PayAmt", documentCurrencyCode).negateIf(paymentDirection.isOutboundPayment()); final Amount openAmt = retrieveAmount(rs, "OpenAmt", documentCurrencyCode).negateIf(paymentDirection.isOutboundPayment()); return PaymentToAllocate.builder() .paymentId(retrievePaymentId(rs)) .clientAndOrgId(ClientAndOrgId.ofClientAndOrg(rs.getInt("AD_Client_ID"), rs.getInt("AD_Org_ID"))) .documentNo(rs.getString("DocumentNo")) .bpartnerId(BPartnerId.ofRepoId(rs.getInt("C_BPartner_ID"))) .dateTrx(TimeUtil.asLocalDate(rs.getTimestamp("PaymentDate"))) .dateAcct(TimeUtil.asLocalDate(rs.getTimestamp("DateAcct"))) // task 09643 .paymentAmtMultiplier(PaymentAmtMultiplier.builder().paymentDirection(paymentDirection).isOutboundAdjusted(false).build().intern()) .payAmt(payAmt) .openAmt(openAmt) .paymentDirection(paymentDirection) .paymentCurrencyContext(extractPaymentCurrencyContext(rs)) .build(); } private static PaymentCurrencyContext extractPaymentCurrencyContext(@NonNull final ResultSet rs) throws SQLException { final PaymentCurrencyContext.PaymentCurrencyContextBuilder result = PaymentCurrencyContext.builder() .currencyConversionTypeId(CurrencyConversionTypeId.ofRepoIdOrNull(rs.getInt(I_C_ConversionType.COLUMNNAME_C_ConversionType_ID))); final CurrencyId sourceCurrencyId = CurrencyId.ofRepoIdOrNull(rs.getInt("FixedConversion_SourceCurrency_ID")); final BigDecimal currencyRate = rs.getBigDecimal("FixedConversion_Rate"); if (sourceCurrencyId != null && currencyRate != null
&& currencyRate.signum() != 0) { final CurrencyId paymentCurrencyId = CurrencyId.ofRepoId(rs.getInt("C_Currency_ID")); result.paymentCurrencyId(paymentCurrencyId) .sourceCurrencyId(sourceCurrencyId) .currencyRate(currencyRate); } return result.build(); } private static PaymentId retrievePaymentId(final ResultSet rs) throws SQLException { return PaymentId.ofRepoId(rs.getInt("C_Payment_ID")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\PaymentAllocationRepository.java
1
请完成以下Java代码
public class QueryValidators { public static class AdhocQueryValidator<T extends AbstractQuery<?, ?>> implements Validator<T> { @SuppressWarnings("rawtypes") public static final AdhocQueryValidator INSTANCE = new AdhocQueryValidator(); private AdhocQueryValidator() { } @Override public void validate(T query) { if (!Context.getProcessEngineConfiguration().isEnableExpressionsInAdhocQueries() && !query.getExpressions().isEmpty()) { throw new BadUserRequestException("Expressions are forbidden in adhoc queries. This behavior can be toggled" + " in the process engine configuration"); } } @SuppressWarnings("unchecked") public static <T extends AbstractQuery<?, ?>> AdhocQueryValidator<T> get() { return (AdhocQueryValidator<T>) INSTANCE; } } public static class StoredQueryValidator<T extends AbstractQuery<?, ?>> implements Validator<T> { @SuppressWarnings("rawtypes") public static final StoredQueryValidator INSTANCE = new StoredQueryValidator(); private StoredQueryValidator() { }
@Override public void validate(T query) { if (!Context.getProcessEngineConfiguration().isEnableExpressionsInStoredQueries() && !query.getExpressions().isEmpty()) { throw new BadUserRequestException("Expressions are forbidden in stored queries. This behavior can be toggled" + " in the process engine configuration"); } } @SuppressWarnings("unchecked") public static <T extends AbstractQuery<?, ?>> StoredQueryValidator<T> get() { return (StoredQueryValidator<T>) INSTANCE; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryValidators.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<TransactionResult> getLastTransactionResult(@NonNull final String paymentRule, @NonNull final BPartnerId bPartnerId) { final IQueryBL queryBL = Services.get(IQueryBL.class); final I_CS_Transaction_Result transactionResultRecord = queryBL .createQueryBuilder(I_CS_Transaction_Result.class) .addOnlyActiveRecordsFilter() .orderByDescending(I_CS_Transaction_Result.COLUMNNAME_RequestStartTime) .addEqualsFilter(I_CS_Transaction_Result.COLUMNNAME_PaymentRule, paymentRule) .addEqualsFilter(I_CS_Transaction_Result.COLUMNNAME_C_BPartner_ID, bPartnerId.getRepoId()) .create().first(); TransactionResult transactionResult = null; if (transactionResultRecord != null) { transactionResult = ofRecord(transactionResultRecord); }
return Optional.ofNullable(transactionResult); } private TransactionResult ofRecord(I_CS_Transaction_Result transactionResult) { return TransactionResult.builder() .resultCode(ResultCode.fromName(transactionResult.getResponseCode())) .resultCodeEffective(ResultCode.fromName(transactionResult.getResponseCodeEffective())) .resultCodeOverride(ResultCode.fromName(transactionResult.getResponseCodeOverride())) .requestDate(transactionResult.getRequestStartTime().toLocalDateTime()) .transactionResultId(TransactionResultId.ofRepoId(transactionResult.getCS_Transaction_Result_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\base\src\main\java\de\metas\vertical\creditscore\base\spi\repository\TransactionResultRepository.java
2
请完成以下Java代码
public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Integer getUseType() { return useType; } public void setUseType(Integer useType) { this.useType = useType; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getPublishCount() { return publishCount; } public void setPublishCount(Integer publishCount) { this.publishCount = publishCount; } public Integer getUseCount() { return useCount; } public void setUseCount(Integer useCount) { this.useCount = useCount; } public Integer getReceiveCount() { return receiveCount; } public void setReceiveCount(Integer receiveCount) { this.receiveCount = receiveCount; } public Date getEnableTime() { return enableTime; } public void setEnableTime(Date enableTime) { this.enableTime = enableTime; } public String getCode() { return code; } public void setCode(String code) {
this.code = code; } public Integer getMemberLevel() { return memberLevel; } public void setMemberLevel(Integer memberLevel) { this.memberLevel = memberLevel; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", type=").append(type); sb.append(", name=").append(name); sb.append(", platform=").append(platform); sb.append(", count=").append(count); sb.append(", amount=").append(amount); sb.append(", perLimit=").append(perLimit); sb.append(", minPoint=").append(minPoint); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", useType=").append(useType); sb.append(", note=").append(note); sb.append(", publishCount=").append(publishCount); sb.append(", useCount=").append(useCount); sb.append(", receiveCount=").append(receiveCount); sb.append(", enableTime=").append(enableTime); sb.append(", code=").append(code); sb.append(", memberLevel=").append(memberLevel); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCoupon.java
1
请在Spring Boot框架中完成以下Java代码
public class StartJcaExecutorServiceStep extends DeploymentOperationStep { protected ExecutorService executorService; private static final Logger LOGGER = Logger.getLogger(StartJcaExecutorServiceStep.class.getName()); public StartJcaExecutorServiceStep(ExecutorService executorService) { this.executorService = executorService; } public String getName() { return "Start JCA Executor Service"; } public void performOperationStep(DeploymentOperation operationContext) { BpmPlatformXml bpmPlatformXml = operationContext.getAttachment(Attachments.BPM_PLATFORM_XML); checkConfiguration(bpmPlatformXml.getJobExecutor()); final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
serviceContainer.startService(ServiceTypes.BPM_PLATFORM, RuntimeContainerDelegateImpl.SERVICE_NAME_EXECUTOR, new JcaExecutorServiceDelegate(executorService)); } /** * Checks the validation to see if properties are present, which will be ignored * in this environment so we can log a warning. */ private void checkConfiguration(JobExecutorXml jobExecutorXml) { Map<String, String> properties = jobExecutorXml.getProperties(); for (Entry<String, String> entry : properties.entrySet()) { LOGGER.warning("Property " + entry.getKey() + " with value " + entry.getValue() + " from bpm-platform.xml will be ignored for JobExecutor."); } } }
repos\camunda-bpm-platform-master\javaee\ejb-service\src\main\java\org\camunda\bpm\container\impl\ejb\deployment\StartJcaExecutorServiceStep.java
2
请完成以下Java代码
protected final void restoreModelsFromSnapshotsByParent(final ParentModelType parentModel) { final Map<Integer, SnapshotModelType> modelSnapshots = retrieveModelSnapshotsByParent(parentModel); final Map<Integer, ModelType> models = new HashMap<>(retrieveModelsByParent(parentModel)); // // Iterate model snapshots and try to restore the models from them for (final SnapshotModelType modelSnapshot : modelSnapshots.values()) { final int modelId = getModelId(modelSnapshot); ModelType model = models.remove(modelId); // // Handle the case when the model's parent was changed // In this case we retrieve the model directly from snapshot's link. if (model == null) { model = getModel(modelSnapshot); } restoreModelFromSnapshot(model, modelSnapshot); } // Iterate remaining models and delete/inactivate them. // NOTE: those are the models which were created after our snapshot. for (final ModelType model : models.values()) { final SnapshotModelType modelSnapshot = null; // no snapshot restoreModelFromSnapshot(model, modelSnapshot); } } /** * @param modelSnapshot * @return Model's ID from given snapshot */
protected abstract int getModelId(final SnapshotModelType modelSnapshot); /** * @param modelSnapshot * @return model retrieved using {@link #getModelId(Object)}. */ protected abstract ModelType getModel(final SnapshotModelType modelSnapshot); /** * * @param parentModel * @param snapshotId * @return "Model ID" to ModelSnapshot map */ protected abstract Map<Integer, SnapshotModelType> retrieveModelSnapshotsByParent(final ParentModelType parentModel); /** * * @param model * @return "Model ID" to Model map */ protected abstract Map<Integer, ModelType> retrieveModelsByParent(final ParentModelType parentModel); protected final <T> IQueryBuilder<T> query(final Class<T> modelClass) { return queryBL.createQueryBuilder(modelClass, getContext()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\AbstractSnapshotHandler.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ArchiveGetDataRequest other = (ArchiveGetDataRequest)obj; if (adArchiveId != other.adArchiveId) { return false; } if (sessionId != other.sessionId) { return false; } return true; } public int getAdArchiveId() { return adArchiveId; }
public void setAdArchiveId(final int adArchiveId) { this.adArchiveId = adArchiveId; } public int getSessionId() { return sessionId; } public void setSessionId(final int sessionId) { this.sessionId = sessionId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive.api\src\main\java\de\metas\document\archive\esb\api\ArchiveGetDataRequest.java
1
请完成以下Java代码
public void dynInit() throws Exception { } public abstract void configureMiniTable(IMiniTable miniTable); public abstract void saveSelection(IMiniTable miniTable); public void validate() { } public String generate() { return null; } public void executeQuery() { } public Trx getTrx() { return trx; } public void setTrx(Trx trx) { this.trx = trx; } public ProcessInfo getProcessInfo() { return pi; } public void setProcessInfo(ProcessInfo pi) { this.pi = pi; } public boolean isSelectionActive() { return m_selectionActive; } public void setSelectionActive(boolean active) { m_selectionActive = active; } public ArrayList<Integer> getSelection() { return selection; } public void setSelection(ArrayList<Integer> selection) { this.selection = selection; } public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; } public int getReportEngineType() { return reportEngineType; } public void setReportEngineType(int reportEngineType) { this.reportEngineType = reportEngineType; } public MPrintFormat getPrintFormat() { return this.printFormat; } public void setPrintFormat(MPrintFormat printFormat) { this.printFormat = printFormat; } public String getAskPrintMsg() { return askPrintMsg; } public void setAskPrintMsg(String askPrintMsg) { this.askPrintMsg = askPrintMsg; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\GenForm.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemConfigQRCodeJsonConverter { public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("EXT-SYS-CALL"); public static String toGlobalQRCodeJsonString(final ExternalSystemConfigQRCode qrCode) { return toGlobalQRCode(qrCode).getAsString(); } public static GlobalQRCode toGlobalQRCode(final ExternalSystemConfigQRCode qrCode) { return JsonConverterV1.toGlobalQRCode(qrCode); } public static ExternalSystemConfigQRCode fromGlobalQRCodeJsonString(final String qrCodeString) { return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString)); } public static ExternalSystemConfigQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode) { if (!GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType())) { throw new AdempiereException("Invalid QR Code") .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long }
final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION)) { return JsonConverterV1.fromGlobalQRCode(globalQRCode); } else { throw new AdempiereException("Invalid QR Code version: " + version); } } public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode) { return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\config\qrcode\ExternalSystemConfigQRCodeJsonConverter.java
2
请在Spring Boot框架中完成以下Java代码
public class CustomerOrder { public CustomerOrder(){} @Id //@GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; public void setId(Long id) { this.id = id; } public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } @OneToMany(mappedBy = "customerOrder" , cascade = CascadeType.ALL) private Set<Product> products; @Column private LocalDate orderDate; public CustomerOrder(Long id, Set<Product> products, LocalDate orderDate, Customer customer) { this.id = id; this.products = products; this.orderDate = orderDate; this.customer = customer; } @Override public String toString() { return "Consult{" + "id=" + id + ", products=" + products + ", orderDate=" + orderDate + ", customer=" + customer +
'}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomerOrder co = (CustomerOrder) o; return Objects.equals(id, co.id); } @Override public int hashCode() { return Objects.hash(id); } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="customer_id", nullable = false) private Customer customer; public Long getId() { return id; } public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\CustomerOrder.java
2
请完成以下Java代码
public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.pricing.attributebased.I_M_ProductPrice_Attribute getM_ProductPrice_Attribute() { return get_ValueAsPO(COLUMNNAME_M_ProductPrice_Attribute_ID, de.metas.pricing.attributebased.I_M_ProductPrice_Attribute.class); } @Override public void setM_ProductPrice_Attribute(de.metas.pricing.attributebased.I_M_ProductPrice_Attribute M_ProductPrice_Attribute) { set_ValueFromPO(COLUMNNAME_M_ProductPrice_Attribute_ID, de.metas.pricing.attributebased.I_M_ProductPrice_Attribute.class, M_ProductPrice_Attribute); } /** Set Attribute price. @param M_ProductPrice_Attribute_ID Attribute price */ @Override public void setM_ProductPrice_Attribute_ID (int M_ProductPrice_Attribute_ID) { if (M_ProductPrice_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_ID, Integer.valueOf(M_ProductPrice_Attribute_ID)); } /** Get Attribute price. @return Attribute price */ @Override public int getM_ProductPrice_Attribute_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribute price line. @param M_ProductPrice_Attribute_Line_ID Attribute price line */ @Override public void setM_ProductPrice_Attribute_Line_ID (int M_ProductPrice_Attribute_Line_ID) { if (M_ProductPrice_Attribute_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_Line_ID, Integer.valueOf(M_ProductPrice_Attribute_Line_ID)); } /** Get Attribute price line. @return Attribute price line */ @Override public int getM_ProductPrice_Attribute_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_Line_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute_Line.java
1
请完成以下Java代码
public void setPaymentRule (java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } /** Get Zahlungsweise. @return Wie die Rechnung bezahlt wird */ @Override public java.lang.String getPaymentRule () { return (java.lang.String)get_Value(COLUMNNAME_PaymentRule); } /** 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; } /** * Status AD_Reference_ID=541011 * Reference name: C_Payment_Reservation_Status */ public static final int STATUS_AD_Reference_ID=541011; /** WAITING_PAYER_APPROVAL = W */ public static final String STATUS_WAITING_PAYER_APPROVAL = "W";
/** APPROVED = A */ public static final String STATUS_APPROVED = "A"; /** VOIDED = V */ public static final String STATUS_VOIDED = "V"; /** COMPLETED = C */ public static final String STATUS_COMPLETED = "C"; /** Set Status. @param Status Status */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation.java
1
请完成以下Java代码
public void setLeistungsdatum (final @Nullable java.lang.String Leistungsdatum) { set_Value (COLUMNNAME_Leistungsdatum, Leistungsdatum); } @Override public java.lang.String getLeistungsdatum() { return get_ValueAsString(COLUMNNAME_Leistungsdatum); } @Override public void setSkonto (final @Nullable java.lang.String Skonto) { set_Value (COLUMNNAME_Skonto, Skonto); } @Override public java.lang.String getSkonto() { return get_ValueAsString(COLUMNNAME_Skonto); } @Override public void setUmsatz (final @Nullable java.lang.String Umsatz) { set_Value (COLUMNNAME_Umsatz, Umsatz); } @Override
public java.lang.String getUmsatz() { return get_ValueAsString(COLUMNNAME_Umsatz); } @Override public void setZI_Art (final @Nullable java.lang.String ZI_Art) { set_Value (COLUMNNAME_ZI_Art, ZI_Art); } @Override public java.lang.String getZI_Art() { return get_ValueAsString(COLUMNNAME_ZI_Art); } @Override public void setZI_Inhalt (final @Nullable java.lang.String ZI_Inhalt) { set_Value (COLUMNNAME_ZI_Inhalt, ZI_Inhalt); } @Override public java.lang.String getZI_Inhalt() { return get_ValueAsString(COLUMNNAME_ZI_Inhalt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExportLine.java
1
请完成以下Java代码
public CurrencyConversionType getById(@NonNull final CurrencyConversionTypeId id) { final CurrencyConversionType conversionType = typesById.get(id); if (conversionType == null) { throw new AdempiereException("@NotFound@ @C_ConversionType_ID@: " + id); } return conversionType; } public CurrencyConversionType getByMethod(@NonNull final ConversionTypeMethod method) { final CurrencyConversionType conversionType = typesByMethod.get(method); if (conversionType == null) { throw new AdempiereException("@NotFound@ @C_ConversionType_ID@: " + method); } return conversionType; } @NonNull
public CurrencyConversionType getDefaultConversionType( @NonNull final ClientId adClientId, @NonNull final OrgId adOrgId, @NonNull final Instant date) { final CurrencyConversionTypeRouting bestMatchingRouting = routings.stream() .filter(routing -> routing.isMatching(adClientId, adOrgId, date)) .min(CurrencyConversionTypeRouting.moreSpecificFirstComparator()) .orElseThrow(() -> new AdempiereException("@NotFound@ @C_ConversionType_ID@") .setParameter("adClientId", adClientId) .setParameter("adOrgId", adOrgId) .setParameter("date", date) .appendParametersToMessage()); return getById(bestMatchingRouting.getConversionTypeId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyConversionTypesMap.java
1
请完成以下Java代码
public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public Integer getVersion() { return version; } public Integer getVersionGt() { return versionGt; } public Integer getVersionGte() { return versionGte; } public Integer getVersionLt() { return versionLt; } public Integer getVersionLte() { return versionLte; } public boolean isLatest() { return latest; } public boolean isOnlyInbound() { return onlyInbound; } public boolean isOnlyOutbound() { return onlyOutbound; } public String getImplementation() { return implementation; } public Date getCreateTime() { return createTime; }
public Date getCreateTimeAfter() { return createTimeAfter; } public Date getCreateTimeBefore() { return createTimeBefore; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\ChannelDefinitionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public T samlRequest(String samlRequest) { this.samlRequest = samlRequest; return _this(); } /** * Sets the {@code authenticationRequestUri}, a URL that will receive the * AuthNRequest message * @param authenticationRequestUri the relay state value, unencoded. * @return this object */ public T authenticationRequestUri(String authenticationRequestUri) { this.authenticationRequestUri = authenticationRequestUri; return _this(); } /**
* This is the unique id used in the {@link #samlRequest} * @param id the SAML2 request id * @return the {@link AbstractSaml2AuthenticationRequest.Builder} for further * configurations * @since 5.8 */ public T id(String id) { Assert.notNull(id, "id cannot be null"); this.id = id; return _this(); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\AbstractSaml2AuthenticationRequest.java
2
请在Spring Boot框架中完成以下Java代码
static BeanMetadataElement parseUserDetailsClassOrUserMapperRef(Element elt, ParserContext parserContext) { String userDetailsClass = elt.getAttribute(ATT_USER_CLASS); String userMapperRef = elt.getAttribute(ATT_USER_CONTEXT_MAPPER_REF); if (StringUtils.hasText(userDetailsClass) && StringUtils.hasText(userMapperRef)) { parserContext.getReaderContext() .error("Attributes " + ATT_USER_CLASS + " and " + ATT_USER_CONTEXT_MAPPER_REF + " cannot be used together.", parserContext.extractSource(elt)); } if (StringUtils.hasText(userMapperRef)) { return new RuntimeBeanReference(userMapperRef); } RootBeanDefinition mapper = getMapper(userDetailsClass); mapper.setSource(parserContext.extractSource(elt)); return mapper; } private static RootBeanDefinition getMapper(String userDetailsClass) { if (OPT_PERSON.equals(userDetailsClass)) { return new RootBeanDefinition(PERSON_MAPPER_CLASS, null, null); } if (OPT_INETORGPERSON.equals(userDetailsClass)) { return new RootBeanDefinition(INET_ORG_PERSON_MAPPER_CLASS, null, null); } return new RootBeanDefinition(LDAP_USER_MAPPER_CLASS, null, null); } static RootBeanDefinition parseAuthoritiesPopulator(Element elt, ParserContext parserContext) { String groupSearchFilter = elt.getAttribute(ATT_GROUP_SEARCH_FILTER); String groupSearchBase = elt.getAttribute(ATT_GROUP_SEARCH_BASE); String groupRoleAttribute = elt.getAttribute(ATT_GROUP_ROLE_ATTRIBUTE); String rolePrefix = elt.getAttribute(ATT_ROLE_PREFIX); if (!StringUtils.hasText(groupSearchFilter)) { groupSearchFilter = DEF_GROUP_SEARCH_FILTER;
} if (!StringUtils.hasText(groupSearchBase)) { groupSearchBase = DEF_GROUP_SEARCH_BASE; } BeanDefinitionBuilder populator = BeanDefinitionBuilder.rootBeanDefinition(LDAP_AUTHORITIES_POPULATOR_CLASS); populator.getRawBeanDefinition().setSource(parserContext.extractSource(elt)); populator.addConstructorArgValue(parseServerReference(elt, parserContext)); populator.addConstructorArgValue(groupSearchBase); populator.addPropertyValue("groupSearchFilter", groupSearchFilter); populator.addPropertyValue("searchSubtree", Boolean.TRUE); if (StringUtils.hasText(rolePrefix)) { if ("none".equals(rolePrefix)) { rolePrefix = ""; } populator.addPropertyValue("rolePrefix", rolePrefix); } if (StringUtils.hasLength(groupRoleAttribute)) { populator.addPropertyValue("groupRoleAttribute", groupRoleAttribute); } return (RootBeanDefinition) populator.getBeanDefinition(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapUserServiceBeanDefinitionParser.java
2
请完成以下Java代码
public void setM_Product_DataEntry_ID (final int M_Product_DataEntry_ID) { if (M_Product_DataEntry_ID < 1) set_Value (COLUMNNAME_M_Product_DataEntry_ID, null); else set_Value (COLUMNNAME_M_Product_DataEntry_ID, M_Product_DataEntry_ID); } @Override public int getM_Product_DataEntry_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_DataEntry_ID); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); }
@Override public void setQty_Planned (final @Nullable BigDecimal Qty_Planned) { set_Value (COLUMNNAME_Qty_Planned, Qty_Planned); } @Override public BigDecimal getQty_Planned() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Planned); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty_Reported (final @Nullable BigDecimal Qty_Reported) { set_Value (COLUMNNAME_Qty_Reported, Qty_Reported); } @Override public BigDecimal getQty_Reported() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported); return bd != null ? bd : BigDecimal.ZERO; } /** * Type AD_Reference_ID=540263 * Reference name: C_Flatrate_DataEntry Type */ public static final int TYPE_AD_Reference_ID=540263; /** Invoicing_PeriodBased = IP */ public static final String TYPE_Invoicing_PeriodBased = "IP"; /** Correction_PeriodBased = CP */ public static final String TYPE_Correction_PeriodBased = "CP"; /** Procurement_PeriodBased = PC */ public static final String TYPE_Procurement_PeriodBased = "PC"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry.java
1
请完成以下Java代码
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代码
private Optional<GeographicalCoordinates> getAddressCoordinates(final DocumentFilter filter) { final GeoCoordinatesRequest request = createGeoCoordinatesRequest(filter).orElse(null); if (request == null) { return Optional.empty(); } final GeocodingService geocodingService = SpringContextHolder.instance.getBean(GeocodingService.class); return geocodingService.findBestCoordinates(request); } private static Optional<GeoCoordinatesRequest> createGeoCoordinatesRequest(@NonNull final DocumentFilter filter) { final String countryCode2 = extractCountryCode2(filter); if (countryCode2 == null) { return Optional.empty(); } final GeoCoordinatesRequest request = GeoCoordinatesRequest.builder() .countryCode2(countryCode2) .postal(filter.getParameterValueAsString(PARAM_Postal, "")) .address(filter.getParameterValueAsString(PARAM_Address1, ""))
.city(filter.getParameterValueAsString(PARAM_City, "")) .build(); return Optional.of(request); } private static String extractCountryCode2(@NonNull final DocumentFilter filter) { final CountryId countryId = filter.getParameterValueAsRepoIdOrNull(PARAM_CountryId, CountryId::ofRepoIdOrNull); if (countryId == null) { throw new FillMandatoryException(PARAM_CountryId); // return null; } return Services.get(ICountryDAO.class).retrieveCountryCode2ByCountryId(countryId); } private static int extractDistanceInKm(final DocumentFilter filter) { final int distanceInKm = filter.getParameterValueAsInt(PARAM_Distance, -1); return Math.max(distanceInKm, 0); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\geo_location\GeoLocationFilterConverter.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getDocumentation() { return documentationAttribute.getValue(this); } public void setDocumentation(String documentation) { documentationAttribute.setValue(this, documentation); } public double getResolution() {
return resolutionAttribute.getValue(this); } public void setResolution(double resolution) { resolutionAttribute.setValue(this, resolution); } public String getId() { return idAttribute.getValue(this); } public void setId(String id) { idAttribute.setValue(this, id); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\di\DiagramImpl.java
1
请完成以下Java代码
public static CandidateId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final CandidateId candidateId) { return candidateId != null ? candidateId.getRepoId() : -1; } public static boolean isNull(@Nullable final CandidateId id) { return id == null || id.isNull(); } private CandidateId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "MD_Candidate_ID"); } @Override @Deprecated public String toString() { if (isNull()) { return "NULL"; } else if (isUnspecified()) { return "UNSPECIFIED"; } else { return String.valueOf(repoId); } } @Override @JsonValue public int getRepoId() { if (isUnspecified()) { throw Check.mkEx("Illegal call of getRepoId() on the unspecified CandidateId instance"); } else if (isNull()) { return -1; } else { return repoId;
} } public boolean isNull() { return repoId == IdConstants.NULL_REPO_ID; } public boolean isUnspecified() { return repoId == IdConstants.UNSPECIFIED_REPO_ID; } public boolean isRegular() { return !isNull() && !isUnspecified(); } public static boolean isRegularNonNull(@Nullable final CandidateId candidateId) { return candidateId != null && candidateId.isRegular(); } public void assertRegular() { if (!isRegular()) { throw new AdempiereException("Expected " + this + " to be a regular ID"); } } public static boolean equals(@Nullable CandidateId id1, @Nullable CandidateId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidateId.java
1
请在Spring Boot框架中完成以下Java代码
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() { return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { customizeSpringfoxHandlerMappings(getHandlerMappings(bean)); } return bean; } private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) { List<T> filteredMappings = mappings.stream() .filter(mapping -> mapping.getPatternParser() == null) .collect(Collectors.toList()); mappings.clear(); mappings.addAll(filteredMappings); }
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) { Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings"); if (field != null) { field.setAccessible(true); try { return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to access handlerMappings field", e); } } return Collections.emptyList(); } }; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\webConfig\SwaggerConfig.java
2
请完成以下Java代码
protected List<IFacet<I_C_Invoice_Candidate>> collectFacets(final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder) { // FRESH-560: Add default filter final IQueryBuilder<I_C_Invoice_Candidate> queryBuilderWithDefaultFilters = Services.get(IInvoiceCandDAO.class).applyDefaultFilter(queryBuilder); final List<Map<String, Object>> bpartners = queryBuilderWithDefaultFilters .andCollect(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID, I_C_BPartner.class) .create() .listDistinct(I_C_BPartner.COLUMNNAME_C_BPartner_ID, I_C_BPartner.COLUMNNAME_Name, I_C_BPartner.COLUMNNAME_Value); final List<IFacet<I_C_Invoice_Candidate>> facets = new ArrayList<>(bpartners.size()); for (final Map<String, Object> row : bpartners) { final IFacet<I_C_Invoice_Candidate> facet = createFacet(row); facets.add(facet); } return facets; }
private IFacet<I_C_Invoice_Candidate> createFacet(final Map<String, Object> row) { final IFacetCategory facetCategoryBPartners = getFacetCategory(); final int bpartnerId = (int)row.get(I_C_BPartner.COLUMNNAME_C_BPartner_ID); final String bpartnerName = new StringBuilder() .append(row.get(I_C_BPartner.COLUMNNAME_Value)) .append(" - ") .append(row.get(I_C_BPartner.COLUMNNAME_Name)) .toString(); final Facet<I_C_Invoice_Candidate> facet = Facet.<I_C_Invoice_Candidate> builder() .setFacetCategory(facetCategoryBPartners) .setDisplayName(bpartnerName) .setFilter(TypedSqlQueryFilter.of(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID + "=" + bpartnerId)) .build(); return facet; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\facet\impl\C_Invoice_Candidate_BillBPartner_FacetCollector.java
1
请在Spring Boot框架中完成以下Java代码
public class X_M_ShipmentSchedule_AttributeConfig extends org.compiere.model.PO implements I_M_ShipmentSchedule_AttributeConfig, org.compiere.model.I_Persistent { private static final long serialVersionUID = 835521478L; /** Standard Constructor */ public X_M_ShipmentSchedule_AttributeConfig (final Properties ctx, final int M_ShipmentSchedule_AttributeConfig_ID, @Nullable final String trxName) { super (ctx, M_ShipmentSchedule_AttributeConfig_ID, trxName); } /** Load Constructor */ public X_M_ShipmentSchedule_AttributeConfig (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_Value (COLUMNNAME_M_Attribute_ID, null); else set_Value (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public de.metas.inoutcandidate.model.I_M_IolCandHandler getM_IolCandHandler() { return get_ValueAsPO(COLUMNNAME_M_IolCandHandler_ID, de.metas.inoutcandidate.model.I_M_IolCandHandler.class); } @Override public void setM_IolCandHandler(final de.metas.inoutcandidate.model.I_M_IolCandHandler M_IolCandHandler) { set_ValueFromPO(COLUMNNAME_M_IolCandHandler_ID, de.metas.inoutcandidate.model.I_M_IolCandHandler.class, M_IolCandHandler); } @Override public void setM_IolCandHandler_ID (final int M_IolCandHandler_ID) { if (M_IolCandHandler_ID < 1) set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, M_IolCandHandler_ID); } @Override public int getM_IolCandHandler_ID() { return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_ID); } @Override public void setM_ShipmentSchedule_AttributeConfig_ID (final int M_ShipmentSchedule_AttributeConfig_ID) { if (M_ShipmentSchedule_AttributeConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID, M_ShipmentSchedule_AttributeConfig_ID); } @Override public int getM_ShipmentSchedule_AttributeConfig_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID); } @Override public void setOnlyIfInReferencedASI (final boolean OnlyIfInReferencedASI) { set_Value (COLUMNNAME_OnlyIfInReferencedASI, OnlyIfInReferencedASI); } @Override public boolean isOnlyIfInReferencedASI() { return get_ValueAsBoolean(COLUMNNAME_OnlyIfInReferencedASI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_AttributeConfig.java
2
请完成以下Java代码
private void assertInnerUrlIsNotMalformed(String spec, String innerUrl) { if (innerUrl.startsWith("nested:")) { org.springframework.boot.loader.net.protocol.nested.Handler.assertUrlIsNotMalformed(innerUrl); return; } try { new URL(innerUrl); } catch (MalformedURLException ex) { throw new IllegalStateException("invalid url: %s (%s)".formatted(spec, ex)); } } @Override protected int hashCode(URL url) { String protocol = url.getProtocol(); int hash = (protocol != null) ? protocol.hashCode() : 0; String file = url.getFile(); int indexOfSeparator = file.indexOf(SEPARATOR); if (indexOfSeparator == -1) { return hash + file.hashCode(); } String fileWithoutEntry = file.substring(0, indexOfSeparator); try { hash += new URL(fileWithoutEntry).hashCode(); } catch (MalformedURLException ex) { hash += fileWithoutEntry.hashCode(); } String entry = file.substring(indexOfSeparator + 2); return hash + entry.hashCode(); } @Override protected boolean sameFile(URL url1, URL url2) { if (!url1.getProtocol().equals(PROTOCOL) || !url2.getProtocol().equals(PROTOCOL)) { return false; } String file1 = url1.getFile(); String file2 = url2.getFile(); int indexOfSeparator1 = file1.indexOf(SEPARATOR); int indexOfSeparator2 = file2.indexOf(SEPARATOR); if (indexOfSeparator1 == -1 || indexOfSeparator2 == -1) { return super.sameFile(url1, url2); } String entry1 = file1.substring(indexOfSeparator1 + 2);
String entry2 = file2.substring(indexOfSeparator2 + 2); if (!entry1.equals(entry2)) { return false; } try { URL innerUrl1 = new URL(file1.substring(0, indexOfSeparator1)); URL innerUrl2 = new URL(file2.substring(0, indexOfSeparator2)); if (!super.sameFile(innerUrl1, innerUrl2)) { return false; } } catch (MalformedURLException unused) { return super.sameFile(url1, url2); } return true; } static int indexOfSeparator(String spec) { return indexOfSeparator(spec, 0, spec.length()); } static int indexOfSeparator(String spec, int start, int limit) { for (int i = limit - 1; i >= start; i--) { if (spec.charAt(i) == '!' && (i + 1) < limit && spec.charAt(i + 1) == '/') { return i; } } return -1; } /** * Clear any internal caches. */ public static void clearCache() { JarUrlConnection.clearCache(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\Handler.java
1
请完成以下Java代码
abstract class DiscoveredOperationsFactory<O extends Operation> { private static final Map<OperationType, Class<? extends Annotation>> OPERATION_TYPES; static { Map<OperationType, Class<? extends Annotation>> operationTypes = new EnumMap<>(OperationType.class); operationTypes.put(OperationType.READ, ReadOperation.class); operationTypes.put(OperationType.WRITE, WriteOperation.class); operationTypes.put(OperationType.DELETE, DeleteOperation.class); OPERATION_TYPES = Collections.unmodifiableMap(operationTypes); } private final ParameterValueMapper parameterValueMapper; private final @Nullable Collection<OperationInvokerAdvisor> invokerAdvisors; DiscoveredOperationsFactory(ParameterValueMapper parameterValueMapper, @Nullable Collection<OperationInvokerAdvisor> invokerAdvisors) { this.parameterValueMapper = parameterValueMapper; this.invokerAdvisors = invokerAdvisors; } Collection<O> createOperations(EndpointId id, Object target) { return MethodIntrospector .selectMethods(target.getClass(), (MetadataLookup<O>) (method) -> createOperation(id, target, method)) .values(); } private @Nullable O createOperation(EndpointId endpointId, Object target, Method method) { return OPERATION_TYPES.entrySet() .stream() .map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue())) .filter(Objects::nonNull) .findFirst()
.orElse(null); } private @Nullable O createOperation(EndpointId endpointId, Object target, Method method, OperationType operationType, Class<? extends Annotation> annotationType) { MergedAnnotation<?> annotation = MergedAnnotations.from(method).get(annotationType); if (!annotation.isPresent()) { return null; } DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, operationType, annotation.asAnnotationAttributes()); OperationInvoker invoker = new ReflectiveOperationInvoker(target, operationMethod, this.parameterValueMapper); invoker = applyAdvisors(endpointId, operationMethod, invoker); return createOperation(endpointId, operationMethod, invoker); } private OperationInvoker applyAdvisors(EndpointId endpointId, OperationMethod operationMethod, OperationInvoker invoker) { if (this.invokerAdvisors != null) { for (OperationInvokerAdvisor advisor : this.invokerAdvisors) { invoker = advisor.apply(endpointId, operationMethod.getOperationType(), operationMethod.getParameters(), invoker); } } return invoker; } protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\annotation\DiscoveredOperationsFactory.java
1
请完成以下Java代码
private static class ProxyRenderer implements TableCellRenderer { public ProxyRenderer(TableCellRenderer renderer) { super(); this.delegate = renderer; } /** The renderer. */ private final TableCellRenderer delegate; @Override public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, final int col) { final Component comp = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); if (hasFocus && table.isCellEditable(row, col)) table.editCellAt(row, col); return comp; } } // ProxyRenderer /** * Create a new row */ public void newRow() { stopEditor(true); final FindAdvancedSearchTableModel model = getModel(); model.newRow();
final int rowIndex = model.getRowCount() - 1; getSelectionModel().setSelectionInterval(rowIndex, rowIndex); requestFocusInWindow(); } public void deleteCurrentRow() { stopEditor(false); final int rowIndex = getSelectedRow(); if (rowIndex >= 0) { final FindAdvancedSearchTableModel model = getModel(); model.removeRow(rowIndex); // Select next row if possible final int rowToSelect = Math.min(rowIndex, model.getRowCount() - 1); if (rowToSelect >= 0) { getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect); } } requestFocusInWindow(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindAdvancedSearchTable.java
1
请完成以下Java代码
public void setId(String id) { this.id = id; } public String getId() { return id; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public long getSequenceCounter() { return sequenceCounter; } public void setSequenceCounter(long sequenceCounter) { this.sequenceCounter = sequenceCounter; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime;
} // persistent object implementation /////////////// public Object getPersistentState() { // events are immutable return HistoryEvent.class; } // state inspection public boolean isEventOfType(HistoryEventType type) { return type.getEventName().equals(eventType); } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEvent.java
1
请完成以下Java代码
public boolean isGreaterThanOrEqualAlphabetic() { return greaterThanOrEqualAlphabetic; } public void setGreaterThanOrEqualAlphabetic(boolean greaterThanOrEqualAlphabetic) { this.greaterThanOrEqualAlphabetic = greaterThanOrEqualAlphabetic; } public boolean isAnd() { return and; } public void setAnd(boolean and) { this.and = and; } public boolean isAndAlphabetic() { return andAlphabetic; } public void setAndAlphabetic(boolean andAlphabetic) { this.andAlphabetic = andAlphabetic; } public boolean isOr() { return or; } public void setOr(boolean or) { this.or = or; } public boolean isOrAlphabetic() { return orAlphabetic; } public void setOrAlphabetic(boolean orAlphabetic) { this.orAlphabetic = orAlphabetic; } public boolean isNot() { return not; } public void setNot(boolean not) { this.not = not; } public boolean isNotAlphabetic() {
return notAlphabetic; } public void setNotAlphabetic(boolean notAlphabetic) { this.notAlphabetic = notAlphabetic; } @Override public String toString() { return "SpelRelational{" + "equal=" + equal + ", equalAlphabetic=" + equalAlphabetic + ", notEqual=" + notEqual + ", notEqualAlphabetic=" + notEqualAlphabetic + ", lessThan=" + lessThan + ", lessThanAlphabetic=" + lessThanAlphabetic + ", lessThanOrEqual=" + lessThanOrEqual + ", lessThanOrEqualAlphabetic=" + lessThanOrEqualAlphabetic + ", greaterThan=" + greaterThan + ", greaterThanAlphabetic=" + greaterThanAlphabetic + ", greaterThanOrEqual=" + greaterThanOrEqual + ", greaterThanOrEqualAlphabetic=" + greaterThanOrEqualAlphabetic + ", and=" + and + ", andAlphabetic=" + andAlphabetic + ", or=" + or + ", orAlphabetic=" + orAlphabetic + ", not=" + not + ", notAlphabetic=" + notAlphabetic + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRelational.java
1
请完成以下Java代码
public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } /** Set Nutzer 1. @param User1_ID User defined list element #1 */ @Override public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get Nutzer 1. @return User defined list element #1 */ @Override public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException {
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } /** Set Nutzer 2. @param User2_ID User defined list element #2 */ @Override public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get Nutzer 2. @return User defined list element #2 */ @Override public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Movement.java
1
请完成以下Java代码
public GraphQlArgumentBinder getArgumentBinder() { return this.argumentBinder; } @Override public boolean supportsParameter(MethodParameter parameter) { return (parameter.getParameterAnnotation(Argument.class) != null || parameter.getParameterType() == ArgumentValue.class); } @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception { String name = getArgumentName(parameter); ResolvableType targetType = ResolvableType.forMethodParameter(parameter); return doBind(environment, name, targetType); } /** * Perform the binding with the configured {@link #getArgumentBinder() binder}. * @param environment for access to the arguments * @param name the name of an argument, or {@code null} to use the full map * @param targetType the type of Object to create * @since 1.3.0 */ protected @Nullable Object doBind( DataFetchingEnvironment environment, String name, ResolvableType targetType) throws BindException { return this.argumentBinder.bind(environment, name, targetType); } static String getArgumentName(MethodParameter parameter) { Argument argument = parameter.getParameterAnnotation(Argument.class); if (argument != null) { if (StringUtils.hasText(argument.name())) { return argument.name();
} } else if (parameter.getParameterType() != ArgumentValue.class) { throw new IllegalStateException( "Expected either @Argument or a method parameter of type ArgumentValue"); } String parameterName = parameter.getParameterName(); if (parameterName != null) { return parameterName; } throw new IllegalArgumentException( "Name for argument of type [" + parameter.getNestedParameterType().getName() + "] not specified, and parameter name information not found in class file either."); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\ArgumentMethodArgumentResolver.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void addOperation(Operation operation) { operations.put(operation.getId(), operation);
} public Operation getOperation(String operationId) { return operations.get(operationId); } public Collection<Operation> getOperations() { return operations.values(); } public BpmnInterfaceImplementation getImplementation() { return implementation; } public void setImplementation(BpmnInterfaceImplementation implementation) { this.implementation = implementation; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\webservice\BpmnInterface.java
2
请完成以下Java代码
protected ViewLayout createViewLayout(final ViewLayoutKey key) { final ITranslatableString caption = getProcessCaption(WEBUI_ProductsProposal_ShowProductsToAddFromBasePriceList.class) .orElse(null); return ViewLayout.builder() .setWindowId(key.getWindowId()) .setCaption(caption) .allowViewCloseAction(ViewCloseAction.BACK) .setFilters(ProductsProposalViewFilters.getDescriptors().getAll()) // .addElementsFromViewRowClass(ProductsProposalRow.class, key.getViewDataType()) .removeElementByFieldName(ProductsProposalRow.FIELD_Qty) .setAllowOpeningRowDetails(false) // .build(); } @Override protected ProductsProposalRowsLoader createRowsLoaderFromRecord(final TableRecordReference recordRef) { throw new UnsupportedOperationException(); } public final ProductsProposalView createView(@NonNull final ProductsProposalView parentView) { final PriceListVersionId basePriceListVersionId = parentView.getBasePriceListVersionIdOrFail(); final ProductsProposalRowsData rowsData = ProductsProposalRowsLoader.builder() .bpartnerProductStatsService(bpartnerProductStatsService) .orderProductProposalsService(orderProductProposalsService) .lookupDataSourceFactory(lookupDataSourceFactory) // .priceListVersionId(basePriceListVersionId) .productIdsToExclude(parentView.getProductIds()) .bpartnerId(parentView.getBpartnerId().orElse(null)) .currencyId(parentView.getCurrencyId()) .soTrx(parentView.getSoTrx()) // .build().load(); logger.debug("loaded ProductsProposalRowsData with size={} for basePriceListVersionId={}", basePriceListVersionId, rowsData.size()); final ProductsProposalView view = ProductsProposalView.builder() .windowId(getWindowId())
.rowsData(rowsData) .processes(getRelatedProcessDescriptors()) .initialViewId(parentView.getInitialViewId()) .build(); put(view); return view; } @Override protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors() { return ImmutableList.of( createProcessDescriptor(WEBUI_ProductsProposal_AddProductFromBasePriceList.class)); } @Override public ProductsProposalView filterView( final IView view, final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo) { final ProductsProposalView productsProposalView = ProductsProposalView.cast(view); final ProductsProposalViewFilter filter = ProductsProposalViewFilters.extractPackageableViewFilterVO(filterViewRequest); productsProposalView.filter(filter); return productsProposalView; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\BasePLVProductsProposalViewFactory.java
1
请完成以下Java代码
public final class NullGridTabRowBuilder implements IGridTabRowBuilder { public static final NullGridTabRowBuilder instance = new NullGridTabRowBuilder(); private NullGridTabRowBuilder() { super(); } /** * Does nothing. */ @Override public void apply(Object model) { // nothing } /** * @return false */ @Override public boolean isCreateNewRecord() { return false; } @Override public void setSource(Object model)
{ // nothing } /** * @return always false */ @Override public boolean isValid() { return false; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\NullGridTabRowBuilder.java
1
请完成以下Java代码
public class DefaultProjectAssetGenerator implements ProjectAssetGenerator<Path> { private final ProjectDirectoryFactory projectDirectoryFactory; /** * Create a new instance with the {@link ProjectDirectoryFactory} to use. * @param projectDirectoryFactory the project directory factory to use */ public DefaultProjectAssetGenerator(ProjectDirectoryFactory projectDirectoryFactory) { this.projectDirectoryFactory = projectDirectoryFactory; } /** * Create a new instance without an explicit {@link ProjectDirectoryFactory}. A bean * of that type is expected to be available in the context. */ public DefaultProjectAssetGenerator() { this(null); } @Override public Path generate(ProjectGenerationContext context) throws IOException { ProjectDescription description = context.getBean(ProjectDescription.class); Path projectRoot = resolveProjectDirectoryFactory(context).createProjectDirectory(description); Path projectDirectory = initializerProjectDirectory(projectRoot, description); List<ProjectContributor> contributors = context.getBeanProvider(ProjectContributor.class) .orderedStream() .toList(); for (ProjectContributor contributor : contributors) { contributor.contribute(projectDirectory); } return projectRoot;
} private ProjectDirectoryFactory resolveProjectDirectoryFactory(ProjectGenerationContext context) { return (this.projectDirectoryFactory != null) ? this.projectDirectoryFactory : context.getBean(ProjectDirectoryFactory.class); } private Path initializerProjectDirectory(Path rootDir, ProjectDescription description) throws IOException { Path projectDirectory = resolveProjectDirectory(rootDir, description); Files.createDirectories(projectDirectory); return projectDirectory; } private Path resolveProjectDirectory(Path rootDir, ProjectDescription description) { if (description.getBaseDirectory() != null) { return rootDir.resolve(description.getBaseDirectory()); } return rootDir; } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\DefaultProjectAssetGenerator.java
1
请在Spring Boot框架中完成以下Java代码
class PropertiesHazelcastConnectionDetails implements HazelcastConnectionDetails { private final HazelcastProperties properties; private final ResourceLoader resourceLoader; PropertiesHazelcastConnectionDetails(HazelcastProperties properties, ResourceLoader resourceLoader) { this.properties = properties; this.resourceLoader = resourceLoader; } @Override public ClientConfig getClientConfig() { Resource configLocation = this.properties.resolveConfigLocation(); ClientConfig config = (configLocation != null) ? loadClientConfig(configLocation) : ClientConfig.load(); config.setClassLoader(this.resourceLoader.getClassLoader()); return config; }
private ClientConfig loadClientConfig(Resource configLocation) { try { URL configUrl = configLocation.getURL(); String configFileName = configUrl.getPath().toLowerCase(Locale.ROOT); return (!isYaml(configFileName)) ? new XmlClientConfigBuilder(configUrl).build() : new YamlClientConfigBuilder(configUrl).build(); } catch (IOException ex) { throw new UncheckedIOException("Failed to load Hazelcast config", ex); } } private boolean isYaml(String configFileName) { return configFileName.endsWith(".yaml") || configFileName.endsWith(".yml"); } }
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\autoconfigure\PropertiesHazelcastConnectionDetails.java
2
请在Spring Boot框架中完成以下Java代码
public class HttpSessionPublicKeyCredentialRequestOptionsRepository implements PublicKeyCredentialRequestOptionsRepository { static final String DEFAULT_ATTR_NAME = PublicKeyCredentialRequestOptionsRepository.class.getName() .concat(".ATTR_NAME"); private String attrName = DEFAULT_ATTR_NAME; @Override public void save(HttpServletRequest request, HttpServletResponse response, @Nullable PublicKeyCredentialRequestOptions options) { HttpSession session = request.getSession(); session.setAttribute(this.attrName, options); }
@Override public @Nullable PublicKeyCredentialRequestOptions load(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return null; } return (PublicKeyCredentialRequestOptions) session.getAttribute(this.attrName); } public void setAttrName(String attrName) { Assert.notNull(attrName, "attrName cannot be null"); this.attrName = attrName; } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\HttpSessionPublicKeyCredentialRequestOptionsRepository.java
2
请在Spring Boot框架中完成以下Java代码
public static class CircuitBreakerConfig { private @Nullable String id; private @Nullable String fallbackPath; private Set<String> statusCodes = new HashSet<>(); private boolean resumeWithoutError = false; public @Nullable String getId() { return id; } public CircuitBreakerConfig setId(String id) { this.id = id; return this; } public @Nullable String getFallbackPath() { return fallbackPath; } public CircuitBreakerConfig setFallbackUri(String fallbackUri) { Objects.requireNonNull(fallbackUri, "fallbackUri String may not be null"); setFallbackUri(URI.create(fallbackUri)); return this; } public CircuitBreakerConfig setFallbackUri(@Nullable URI fallbackUri) { if (fallbackUri != null) { Assert.isTrue(fallbackUri.getScheme().equalsIgnoreCase("forward"), () -> "Scheme must be forward, but is " + fallbackUri.getScheme()); fallbackPath = fallbackUri.getPath(); } else { fallbackPath = null; } return this; } public CircuitBreakerConfig setFallbackPath(String fallbackPath) { this.fallbackPath = fallbackPath; return this;
} public Set<String> getStatusCodes() { return statusCodes; } public CircuitBreakerConfig setStatusCodes(String... statusCodes) { return setStatusCodes(new LinkedHashSet<>(Arrays.asList(statusCodes))); } public CircuitBreakerConfig setStatusCodes(Set<String> statusCodes) { this.statusCodes = statusCodes; return this; } public boolean isResumeWithoutError() { return resumeWithoutError; } public CircuitBreakerConfig setResumeWithoutError(boolean resumeWithoutError) { this.resumeWithoutError = resumeWithoutError; return this; } } public static class CircuitBreakerStatusCodeException extends ResponseStatusException { public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) { super(statusCode); } } public static class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(CircuitBreakerFilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\CircuitBreakerFilterFunctions.java
2
请完成以下Java代码
public DeploymentQueryImpl processDefinitionKeyLike(String keyLike) { if (keyLike == null) { throw new ActivitiIllegalArgumentException("keyLike is null"); } this.processDefinitionKeyLike = keyLike; return this; } public DeploymentQueryImpl latest() { if (key == null) { throw new ActivitiIllegalArgumentException("latest can only be used together with a deployment key"); } this.latest = true; return this; } @Override public DeploymentQuery latestVersion() { this.latestVersion = true; return this; } // sorting //////////////////////////////////////////////////////// public DeploymentQuery orderByDeploymentId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_ID); } public DeploymentQuery orderByDeploymenTime() { return orderBy(DeploymentQueryProperty.DEPLOY_TIME); } public DeploymentQuery orderByDeploymentName() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_NAME); } public DeploymentQuery orderByTenantId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_TENANT_ID); } // results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getDeploymentEntityManager().findDeploymentCountByQueryCriteria(this); } @Override public List<Deployment> executeList(CommandContext commandContext, Page page) {
checkQueryOk(); return commandContext.getDeploymentEntityManager().findDeploymentsByQueryCriteria(this, page); } // getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public boolean isLatestVersion() { return latestVersion; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeploymentQueryImpl.java
1
请完成以下Java代码
public I_GL_Journal build() { InterfaceWrapperHelper.save(glJournal); for (final GL_JournalLine_Builder glJournalLineBuilder : glJournalLineBuilders) { glJournalLineBuilder.build(); } return glJournal; } public GL_JournalLine_Builder newLine() { final GL_JournalLine_Builder glJournalLineBuilder = new GL_JournalLine_Builder(this); glJournalLineBuilders.add(glJournalLineBuilder); return glJournalLineBuilder; } I_GL_Journal getGL_Journal() {
return glJournal; } public CurrencyConversionTypeId getConversionTypeDefaultId(@NonNull GLJournalRequest request) { return currencyDAO.getDefaultConversionTypeId( request.getClientId(), request.getOrgId(), request.getDateAcct()); } private Optional<GLCategoryId> getDefaultGLCategoryId(@NonNull final ClientId clientId) { return glCategoryRepository.getDefaultId(clientId, GLCategoryType.Manual); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\GL_Journal_Builder.java
1
请完成以下Java代码
public class DefaultUserAuthDetailsCache implements UserAuthDetailsCache { private final UserService userService; @Value("${cache.userAuthDetails.maxSize:1000}") private int cacheMaxSize; @Value("${cache.userAuthDetails.timeToLiveInMinutes:30}") private int cacheValueTtl; private Cache<UserId, UserAuthDetails> cache; @PostConstruct private void init() { cache = Caffeine.newBuilder() .maximumSize(cacheMaxSize) .expireAfterAccess(cacheValueTtl, TimeUnit.MINUTES) .build(); } @EventListener(ComponentLifecycleMsg.class) public void onComponentLifecycleEvent(ComponentLifecycleMsg event) { if (event.getEntityId() != null) { if (event.getEntityId().getEntityType() == EntityType.USER) { evict(new UserId(event.getEntityId().getId()));
} } } @Override public UserAuthDetails getUserAuthDetails(TenantId tenantId, UserId userId) { log.trace("Retrieving user with enabled credentials status for id {} for tenant {} from cache", userId, tenantId); return cache.get(userId, id -> userService.findUserAuthDetailsByUserId(tenantId, id)); } public void evict(UserId userId) { cache.invalidate(userId); log.trace("Evicted record for user {} from cache", userId); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\user\cache\DefaultUserAuthDetailsCache.java
1
请完成以下Java代码
public CmmnClassDelegate create(String className, List<FieldExtension> fieldExtensions) { return new CmmnClassDelegate(className, fieldExtensions); } @Override public CmmnClassDelegate createLifeCycleListener(String className, String sourceState, String targetState, List<FieldExtension> fieldExtensions) { CmmnClassDelegate cmmnClassDelegate = create(className, fieldExtensions); cmmnClassDelegate.setSourceState(sourceState); cmmnClassDelegate.setTargetState(targetState); return cmmnClassDelegate; } @Override public Object defaultInstantiateDelegate(Class<?> clazz, ServiceTask serviceTask, boolean allExpressions) { Object object = ReflectUtil.instantiate(clazz.getName()); if (serviceTask != null) { for (FieldExtension extension : serviceTask.getFieldExtensions()) {
Object value; if (StringUtils.isNotEmpty(extension.getExpression())) { value = expressionManager.createExpression(extension.getExpression()); } else if (allExpressions) { value = new FixedValue(extension.getStringValue()); } else { value = extension.getStringValue(); } ReflectUtil.invokeSetterOrField(object, extension.getFieldName(), value, false); } ReflectUtil.invokeSetterOrField(object, "serviceTask", serviceTask, false); } return object; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\DefaultCmmnClassDelegateFactory.java
1
请完成以下Java代码
public boolean isRetain() { return retain; } public Builder setRetain(boolean retain) { this.retain = retain; return this; } public MqttQoS getQos() { return qos; } public Builder setQos(MqttQoS qos) { if(qos == null){ throw new NullPointerException("qos"); } this.qos = qos; return this; } public MqttLastWill build(){ return new MqttLastWill(topic, message, retain, qos); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MqttLastWill that = (MqttLastWill) o; if (retain != that.retain) return false; if (!topic.equals(that.topic)) return false; if (!message.equals(that.message)) return false; return qos == that.qos; } @Override
public int hashCode() { int result = topic.hashCode(); result = 31 * result + message.hashCode(); result = 31 * result + (retain ? 1 : 0); result = 31 * result + qos.hashCode(); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MqttLastWill{"); sb.append("topic='").append(topic).append('\''); sb.append(", message='").append(message).append('\''); sb.append(", retain=").append(retain); sb.append(", qos=").append(qos.name()); sb.append('}'); return sb.toString(); } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttLastWill.java
1
请在Spring Boot框架中完成以下Java代码
public class PmsRolePermission extends PermissionBaseEntity { private static final long serialVersionUID = -9012707031072904356L; private Long roleId; // 角色ID private Long permissionId;// 权限ID /** * 角色ID * * @return */ public Long getRoleId() { return roleId; } /** * 角色ID * * @return */ public void setRoleId(Long roleId) { this.roleId = roleId; } /** * 权限ID * * @return */ public Long getPermissionId() { return permissionId; }
/** * 权限ID * * @return */ public void setPermissionId(Long permissionId) { this.permissionId = permissionId; } public PmsRolePermission() { super(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsRolePermission.java
2
请在Spring Boot框架中完成以下Java代码
public class AsyncBatchId implements RepoIdAware { public static final AsyncBatchId NONE_ASYNC_BATCH_ID = AsyncBatchId.ofRepoId(1); int repoId; @JsonCreator public static AsyncBatchId ofRepoId(final int repoId) { return new AsyncBatchId(repoId); } @Nullable public static AsyncBatchId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new AsyncBatchId(repoId) : null; } @NonNull public static AsyncBatchId ofRepoIdOrNone(final int repoId) { return repoId > 0 ? new AsyncBatchId(repoId) : NONE_ASYNC_BATCH_ID; } @NonNull public static AsyncBatchId ofRepoIdOr(final int repoId, @NonNull final Supplier<AsyncBatchId> supplier) { return repoId > 0 ? new AsyncBatchId(repoId) : supplier.get(); } public static int toRepoId(@Nullable final AsyncBatchId asyncBatchId) { return asyncBatchId != null ? asyncBatchId.getRepoId() : -1; }
@Nullable public static AsyncBatchId toAsyncBatchIdOrNull(@Nullable final AsyncBatchId asyncBatchId) { return asyncBatchId != null && !asyncBatchId.equals(NONE_ASYNC_BATCH_ID) ? asyncBatchId : null; } private AsyncBatchId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "asyncBatchId"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\AsyncBatchId.java
2
请完成以下Java代码
private void initAction(final boolean small) { this.action = AppsAction.builder() .setAction(ACTION_Name) .setSmallSize(small) .build(); action.setDelegate(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showPopup(); } }); } private CColumnControlButton getCColumnControlButton() { final GridController currentGridController = this.parent.getCurrentGridController(); if (currentGridController == null) { return null; } final VTable table = currentGridController.getVTable(); if (table == null)
{ return null; } final CColumnControlButton columnControlButton = table.getColumnControl(); return columnControlButton; } public void showPopup() { final CColumnControlButton columnControlButton = getCColumnControlButton(); if (columnControlButton == null) { return; } final AbstractButton button = action.getButton(); columnControlButton.togglePopup(button); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AGridColumnsToggle.java
1
请完成以下Java代码
public de.metas.dataentry.model.I_DataEntry_Field getDataEntry_Field() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DataEntry_Field_ID, de.metas.dataentry.model.I_DataEntry_Field.class); } @Override public void setDataEntry_Field(de.metas.dataentry.model.I_DataEntry_Field DataEntry_Field) { set_ValueFromPO(COLUMNNAME_DataEntry_Field_ID, de.metas.dataentry.model.I_DataEntry_Field.class, DataEntry_Field); } /** Set Dateneingabefeld. @param DataEntry_Field_ID Dateneingabefeld */ @Override public void setDataEntry_Field_ID (int DataEntry_Field_ID) { if (DataEntry_Field_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_Field_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_Field_ID, Integer.valueOf(DataEntry_Field_ID)); } /** Get Dateneingabefeld. @return Dateneingabefeld */ @Override public int getDataEntry_Field_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Field_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Eingabefeldwert. @param DataEntry_ListValue_ID Eingabefeldwert */ @Override public void setDataEntry_ListValue_ID (int DataEntry_ListValue_ID) { if (DataEntry_ListValue_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_ListValue_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_ListValue_ID, Integer.valueOf(DataEntry_ListValue_ID)); } /** Get Eingabefeldwert. @return Eingabefeldwert */ @Override public int getDataEntry_ListValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_ListValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); }
/** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_ListValue.java
1
请完成以下Java代码
public IMutableHUContext createMutableHUContext(final Properties ctx, @NonNull final String trxName) { final PlainContextAware contextProvider = PlainContextAware.newWithTrxName(ctx, trxName); return new MutableHUContext(contextProvider); } @Override public IMutableHUContext createMutableHUContext(final IContextAware contextProvider) { return new MutableHUContext(contextProvider); } @Override public final IHUContext deriveWithTrxName(final IHUContext huContext, final String trxNameNew) { // FIXME: handle the case of SaveOnCommit Storage and Attributes when changing transaction name // // Check: if transaction name was not changed, do nothing, return the old context final String contextTrxName = huContext.getTrxName();// // TODO tbp: here the context has wrong org. WHYYYYY final ITrxManager trxManager = Services.get(ITrxManager.class); if (trxManager.isSameTrxName(contextTrxName, trxNameNew)) {
return huContext; } final IMutableHUContext huContextNew = huContext.copyAsMutable(); huContextNew.setTrxName(trxNameNew); configureProcessingContext(huContextNew); return huContextNew; } @Override public String toString() { return "HUContextFactory []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUContextFactory.java
1
请完成以下Java代码
public head setProfile (String profile) { addAttribute ("profile", profile); return this; } /** * Sets the lang="" and xml:lang="" attributes * * @param lang * the lang="" and xml:lang="" attributes */ public Element setLang (String lang) { addAttribute ("lang", lang); addAttribute ("xml:lang", lang); return this; } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public head addElement (String hashcode, Element element) { addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public head addElement (String hashcode, String element) { addElementToRegistry (hashcode, element); return (this); } /**
* Adds an Element to the element. * * @param element * Adds an Element to the element. */ public head addElement (Element element) { addElementToRegistry (element); return (this); } /** * Adds an Element to the element. * * @param element * Adds an Element to the element. */ public head addElement (String element) { addElementToRegistry (element); return (this); } /** * Removes an Element from the element. * * @param hashcode * the name of the element to be removed. */ public head removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\head.java
1
请完成以下Java代码
public static void main(String[] args) throws IOException { Logger.getLogger("org").setLevel(Level.OFF); GraphLoader loader = new GraphLoader(); GraphFrame graph = loader.getGraphFrameUserRelationship(); GraphExperiments experiments = new GraphExperiments(); experiments.doGraphFrameOperations(graph); experiments.doGraphFrameAlgorithms(graph); } private void doGraphFrameOperations(GraphFrame graph) { graph.vertices().show(); graph.edges().show(); graph.vertices().filter("name = 'Martin'").show(); graph.filterEdges("type = 'Friend'")
.dropIsolatedVertices().vertices().show(); graph.degrees().show(); graph.inDegrees().show(); graph.outDegrees().show(); } private void doGraphFrameAlgorithms(GraphFrame graph) { graph.pageRank().maxIter(20).resetProbability(0.15).run().vertices().show(); graph.connectedComponents().run().show(); graph.triangleCount().run().show(); } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\graphframes\GraphExperiments.java
1
请完成以下Java代码
public static class Searcher extends BaseSearcher<Pinyin[]> { /** * 分词从何处开始,这是一个状态 */ int begin; DoubleArrayTrie<Pinyin[]> trie; protected Searcher(char[] c, DoubleArrayTrie<Pinyin[]> trie) { super(c); this.trie = trie; } protected Searcher(String text, DoubleArrayTrie<Pinyin[]> trie) { super(text); this.trie = trie; } @Override public Map.Entry<String, Pinyin[]> next() { // 保证首次调用找到一个词语 Map.Entry<String, Pinyin[]> result = null; while (begin < c.length) {
LinkedList<Map.Entry<String, Pinyin[]>> entryList = trie.commonPrefixSearchWithValue(c, begin); if (entryList.size() == 0) { ++begin; } else { result = entryList.getLast(); offset = begin; begin += result.getKey().length(); break; } } if (result == null) { return null; } return result; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\PinyinDictionary.java
1
请完成以下Java代码
private static List<Coordinate> parseCoordinates(JsonArray coordinatesJson) { List<Coordinate> result = new LinkedList<>(); for (JsonElement coords : coordinatesJson) { double x = coords.getAsJsonArray().get(0).getAsDouble(); double y = coords.getAsJsonArray().get(1).getAsDouble(); result.add(new Coordinate(x, y)); } if (result.size() >= 3) { result.add(result.get(0)); } return result; } private static boolean containsPrimitives(JsonArray array) {
for (JsonElement element : array) { return element.isJsonPrimitive(); } return false; } private static boolean containsArrayWithPrimitives(JsonArray array) { for (JsonElement element : array) { if (!containsPrimitives(element.getAsJsonArray())) { return false; } } return true; } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\geo\GeoUtil.java
1
请完成以下Java代码
public void setModel(final TableModel dataModel) { Check.assumeInstanceOfOrNull(dataModel, FindAdvancedSearchTableModel.class, "dataModel"); super.setModel(dataModel); } public void stopEditor(final boolean saveValue) { CTable.stopEditor(this, saveValue); } private static class ProxyRenderer implements TableCellRenderer { public ProxyRenderer(TableCellRenderer renderer) { super(); this.delegate = renderer; } /** The renderer. */ private final TableCellRenderer delegate; @Override public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, final int col) { final Component comp = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); if (hasFocus && table.isCellEditable(row, col)) table.editCellAt(row, col); return comp; } } // ProxyRenderer /** * Create a new row */ public void newRow() { stopEditor(true); final FindAdvancedSearchTableModel model = getModel(); model.newRow(); final int rowIndex = model.getRowCount() - 1;
getSelectionModel().setSelectionInterval(rowIndex, rowIndex); requestFocusInWindow(); } public void deleteCurrentRow() { stopEditor(false); final int rowIndex = getSelectedRow(); if (rowIndex >= 0) { final FindAdvancedSearchTableModel model = getModel(); model.removeRow(rowIndex); // Select next row if possible final int rowToSelect = Math.min(rowIndex, model.getRowCount() - 1); if (rowToSelect >= 0) { getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect); } } requestFocusInWindow(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindAdvancedSearchTable.java
1
请完成以下Java代码
protected String generateSeriesData() { byte[] newSeries = new byte[this.seriesLength]; this.random.nextBytes(newSeries); return new String(Base64.getEncoder().encode(newSeries)); } protected String generateTokenData() { byte[] newToken = new byte[this.tokenLength]; this.random.nextBytes(newToken); return new String(Base64.getEncoder().encode(newToken)); } private void addCookie(PersistentRememberMeToken token, HttpServletRequest request, HttpServletResponse response) { setCookie(new String[] { token.getSeries(), token.getTokenValue() }, getTokenValiditySeconds(), request, response); }
public void setSeriesLength(int seriesLength) { this.seriesLength = seriesLength; } public void setTokenLength(int tokenLength) { this.tokenLength = tokenLength; } @Override public void setTokenValiditySeconds(int tokenValiditySeconds) { Assert.isTrue(tokenValiditySeconds > 0, "tokenValiditySeconds must be positive for this implementation"); super.setTokenValiditySeconds(tokenValiditySeconds); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\PersistentTokenBasedRememberMeServices.java
1
请在Spring Boot框架中完成以下Java代码
public static class Servlet { /** * Session repository filter order. */ private int filterOrder = SessionRepositoryFilter.DEFAULT_ORDER; /** * Session repository filter dispatcher types. */ private Set<DispatcherType> filterDispatcherTypes = new HashSet<>( Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); public int getFilterOrder() { return this.filterOrder; }
public void setFilterOrder(int filterOrder) { this.filterOrder = filterOrder; } public Set<DispatcherType> getFilterDispatcherTypes() { return this.filterDispatcherTypes; } public void setFilterDispatcherTypes(Set<DispatcherType> filterDispatcherTypes) { this.filterDispatcherTypes = filterDispatcherTypes; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionProperties.java
2
请完成以下Java代码
public void setFeePercentageOfGrandTotal (final BigDecimal FeePercentageOfGrandTotal) { set_Value (COLUMNNAME_FeePercentageOfGrandTotal, FeePercentageOfGrandTotal); } @Override public BigDecimal getFeePercentageOfGrandTotal() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FeePercentageOfGrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setInvoiceProcessingServiceCompany_BPartnerAssignment_ID (final int InvoiceProcessingServiceCompany_BPartnerAssignment_ID) { if (InvoiceProcessingServiceCompany_BPartnerAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, InvoiceProcessingServiceCompany_BPartnerAssignment_ID); } @Override public int getInvoiceProcessingServiceCompany_BPartnerAssignment_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID); } @Override public org.compiere.model.I_InvoiceProcessingServiceCompany getInvoiceProcessingServiceCompany() { return get_ValueAsPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class); }
@Override public void setInvoiceProcessingServiceCompany(final org.compiere.model.I_InvoiceProcessingServiceCompany InvoiceProcessingServiceCompany) { set_ValueFromPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class, InvoiceProcessingServiceCompany); } @Override public void setInvoiceProcessingServiceCompany_ID (final int InvoiceProcessingServiceCompany_ID) { if (InvoiceProcessingServiceCompany_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, InvoiceProcessingServiceCompany_ID); } @Override public int getInvoiceProcessingServiceCompany_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany_BPartnerAssignment.java
1
请完成以下Java代码
public boolean hasChildElements() { return true; } @Override protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { Case caze = new Case(); caze.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); caze.setInitiatorVariableName(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INITIATOR_VARIABLE_NAME)); String candidateUsersString = CmmnXmlUtil.getAttributeValue(CmmnXmlConstants.ATTRIBUTE_CASE_CANDIDATE_USERS, xtr); if (StringUtils.isNotEmpty(candidateUsersString)) { List<String> candidateUsers = CmmnXmlUtil.parseDelimitedList(candidateUsersString); caze.setCandidateStarterUsers(candidateUsers); }
String candidateGroupsString = CmmnXmlUtil.getAttributeValue(CmmnXmlConstants.ATTRIBUTE_CASE_CANDIDATE_GROUPS, xtr); if (StringUtils.isNotEmpty(candidateGroupsString)) { List<String> candidateGroups = CmmnXmlUtil.parseDelimitedList(candidateGroupsString); caze.setCandidateStarterGroups(candidateGroups); } if ("true".equals(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_IS_ASYNCHRONOUS))) { caze.setAsync(true); } conversionHelper.getCmmnModel().addCase(caze); conversionHelper.setCurrentCase(caze); return caze; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CaseXmlConverter.java
1
请完成以下Java代码
public SqlComposedKey extractComposedKey(final DocumentId rowId) { return SqlDocumentQueryBuilder.extractComposedKey(rowId, keyFields); } public SqlAndParams getSqlValuesCommaSeparated(@NonNull final DocumentId rowId) { return extractComposedKey(rowId).getSqlValuesCommaSeparated(); } public List<Object> getSqlValuesList(@NonNull final DocumentId rowId) { return extractComposedKey(rowId).getSqlValuesList(); } @Nullable public DocumentId retrieveRowId(final ResultSet rs) { final String sqlColumnPrefix = null; final boolean useKeyColumnNames = true; return retrieveRowId(rs, sqlColumnPrefix, useKeyColumnNames); } @Nullable public DocumentId retrieveRowId(final ResultSet rs, @Nullable final String sqlColumnPrefix, final boolean useKeyColumnNames) { final List<Object> rowIdParts = keyFields .stream() .map(keyField -> retrieveRowIdPart(rs, buildKeyColumnNameEffective(keyField.getColumnName(), sqlColumnPrefix, useKeyColumnNames), keyField.getSqlValueClass())) .collect(Collectors.toList()); final boolean isNotNull = rowIdParts.stream().anyMatch(Objects::nonNull); if (!isNotNull) { return null; } return DocumentId.ofComposedKeyParts(rowIdParts); } private String buildKeyColumnNameEffective(final String keyColumnName, @Nullable final String sqlColumnPrefix, final boolean useKeyColumnName) { final String selectionColumnName = useKeyColumnName ? keyColumnName : getWebuiSelectionColumnNameForKeyColumnName(keyColumnName); if (sqlColumnPrefix != null && !sqlColumnPrefix.isEmpty()) { return sqlColumnPrefix + selectionColumnName; } else { return selectionColumnName; } } @Nullable private Object retrieveRowIdPart(final ResultSet rs, final String columnName, final Class<?> sqlValueClass) { try { if (Integer.class.equals(sqlValueClass) || int.class.equals(sqlValueClass))
{ final int rowIdPart = rs.getInt(columnName); if (rs.wasNull()) { return null; } return rowIdPart; } else if (String.class.equals(sqlValueClass)) { return rs.getString(columnName); } else { throw new AdempiereException("Unsupported type " + sqlValueClass + " for " + columnName); } } catch (final SQLException ex) { throw new DBException("Failed fetching " + columnName + " (" + sqlValueClass + ")", ex); } } @Value @Builder private static class KeyColumnNameInfo { @NonNull String keyColumnName; @NonNull String webuiSelectionColumnName; boolean isNullable; public String getEffectiveColumnName(@NonNull final MappingType mappingType) { if (mappingType == MappingType.SOURCE_TABLE) { return keyColumnName; } else if (mappingType == MappingType.WEBUI_SELECTION_TABLE) { return webuiSelectionColumnName; } else { // shall not happen throw new AdempiereException("Unknown mapping type: " + mappingType); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewKeyColumnNamesMap.java
1
请在Spring Boot框架中完成以下Java代码
private ClientRegistration createClientRegistration(ClientRegistration staticRegistration, ObjectNode body) { var clientId = body.get("client_id").asText(); var clientSecret = body.get("client_secret").asText(); log.info("creating ClientRegistration: registrationId={}, client_id={}", staticRegistration.getRegistrationId(),clientId); return ClientRegistration.withClientRegistration(staticRegistration) .clientId(body.get("client_id").asText()) .clientSecret(body.get("client_secret").asText()) .build(); } private String createRegistrationToken() { var body = new LinkedMultiValueMap<String,String>(); body.put( "grant_type", List.of("client_credentials")); body.put( "scope", registrationDetails.registrationScopes()); var headers = new HttpHeaders(); headers.setBasicAuth(registrationDetails.registrationUsername(), registrationDetails.registrationPassword()); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); var request = new RequestEntity<>( body, headers, HttpMethod.POST, registrationDetails.tokenEndpoint()); var result = registrationClient.exchange(request, ObjectNode.class); if ( !result.getStatusCode().is2xxSuccessful()) { throw new RuntimeException("Failed to create registration token: code=" + result.getStatusCode()); }
return result.getBody().get("access_token").asText(); } /** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ @Override public Iterator<ClientRegistration> iterator() { return registrations .values() .iterator(); } public void doRegistrations() { staticClients.forEach((key, value) -> findByRegistrationId(key)); } public record RegistrationDetails( URI registrationEndpoint, String registrationUsername, String registrationPassword, List<String> registrationScopes, List<String> grantTypes, List<String> redirectUris, URI tokenEndpoint ) { } // Type-safe RestTemplate public static class RegistrationRestTemplate extends RestTemplate { } }
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\java\com\baeldung\spring\security\dynreg\client\service\DynamicClientRegistrationRepository.java
2
请完成以下Java代码
public boolean equals(Object obj) { return this.delegate.equals(obj); } @Override public int hashCode() { return this.delegate.hashCode(); } @Override public boolean exists() { return this.delegate.exists(); } @Override public Spliterator<Resource> spliterator() { return this.delegate.spliterator(); } @Override public boolean isDirectory() { return this.delegate.isDirectory(); } @Override public boolean isReadable() { return this.delegate.isReadable(); } @Override public Instant lastModified() { return this.delegate.lastModified(); } @Override public long length() { return this.delegate.length(); } @Override public URI getURI() { return this.delegate.getURI(); } @Override public String getName() { return this.delegate.getName(); } @Override public String getFileName() { return this.delegate.getFileName(); } @Override public InputStream newInputStream() throws IOException { return this.delegate.newInputStream(); } @Override @SuppressWarnings({ "deprecation", "removal" }) public ReadableByteChannel newReadableByteChannel() throws IOException { return this.delegate.newReadableByteChannel(); } @Override public List<Resource> list() { return asLoaderHidingResources(this.delegate.list()); } private boolean nonLoaderResource(Resource resource) {
return !resource.getPath().startsWith(this.loaderBasePath); } private List<Resource> asLoaderHidingResources(Collection<Resource> resources) { return resources.stream().filter(this::nonLoaderResource).map(this::asLoaderHidingResource).toList(); } private Resource asLoaderHidingResource(Resource resource) { return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource); } @Override public @Nullable Resource resolve(String subUriPath) { if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) { return null; } Resource resolved = this.delegate.resolve(subUriPath); return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null; } @Override public boolean isAlias() { return this.delegate.isAlias(); } @Override public URI getRealURI() { return this.delegate.getRealURI(); } @Override public void copyTo(Path destination) throws IOException { this.delegate.copyTo(destination); } @Override public Collection<Resource> getAllResources() { return asLoaderHidingResources(this.delegate.getAllResources()); } @Override public String toString() { return this.delegate.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java
1
请完成以下Java代码
class WorkflowNodeTransitionModel { @NonNull private final WorkflowModel workflowModel; @NonNull private final WFNodeId fromNodeId; @NonNull private final WFNodeTransition transition; WorkflowNodeTransitionModel( @NonNull final WorkflowModel workflowModel, @NonNull final WFNodeId fromNodeId, @NonNull final WFNodeTransition transition) { this.workflowModel = workflowModel; this.fromNodeId = fromNodeId; this.transition = transition; } public @NonNull WFNodeTransitionId getId() {return transition.getId();} public @NonNull ClientId getClientId() {return transition.getClientId();}
public @NonNull WFNodeId getFromNodeId() { return fromNodeId; } public @NonNull WFNodeId getNextNodeId() {return transition.getNextNodeId();} public @NonNull WorkflowNodeModel getNextNode() { return workflowModel.getNodeById(transition.getNextNodeId()); } public String getDescription() {return transition.getDescription();} public int getSeqNo() {return transition.getSeqNo();} public WFNodeSplitType getFromSplitType() {return transition.getFromSplitType();} public boolean isUnconditional() {return transition.isUnconditional();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeTransitionModel.java
1
请完成以下Java代码
private static LoggingSystem get(ClassLoader classLoader, String loggingSystemClassName) { try { Class<?> systemClass = ClassUtils.forName(loggingSystemClassName, classLoader); Constructor<?> constructor = systemClass.getDeclaredConstructor(ClassLoader.class); constructor.setAccessible(true); return (LoggingSystem) constructor.newInstance(classLoader); } catch (Exception ex) { throw new IllegalStateException(ex); } } /** * {@link LoggingSystem} that does nothing. */ static class NoOpLoggingSystem extends LoggingSystem { @Override public void beforeInitialize() { }
@Override public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) { } @Override public List<LoggerConfiguration> getLoggerConfigurations() { return Collections.emptyList(); } @Override public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) { return null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggingSystem.java
1
请完成以下Java代码
public String getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public List<VariableDefinition> getInputs() { return inputs != null ? inputs : emptyList(); } public List<VariableDefinition> getOutputs() { return outputs != null ? outputs : emptyList(); } public void setId(String id) { this.id = id;
} public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } public void setInputs(List<VariableDefinition> inputs) { this.inputs = inputs; } public void setOutputs(List<VariableDefinition> outputs) { this.outputs = outputs; } }
repos\Activiti-develop\activiti-core-common\activiti-connector-model\src\main\java\org\activiti\core\common\model\connector\ActionDefinition.java
1
请完成以下Java代码
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
请完成以下Java代码
public void setVatRate(BigDecimal value) { this.vatRate = value; } /** * Gets the value of the validate property. * * @return * possible object is * {@link Boolean } * */ public boolean isValidate() { if (validate == null) { return false; } else { return validate; } } /** * Sets the value of the validate property. * * @param value * allowed object is * {@link Boolean } * */ public void setValidate(Boolean value) { this.validate = value; } /** * Gets the value of the obligation property. * * @return * possible object is * {@link Boolean } * */ public boolean isObligation() { if (obligation == null) { return true; } else { return obligation; } } /** * Sets the value of the obligation property. * * @param value * allowed object is * {@link Boolean } * */ public void setObligation(Boolean value) { this.obligation = value; } /** * Gets the value of the sectionCode property. * * @return * possible object is * {@link String } * */ public String getSectionCode() { return sectionCode; } /** * Sets the value of the sectionCode property. * * @param value * allowed object is * {@link String } *
*/ public void setSectionCode(String value) { this.sectionCode = value; } /** * Gets the value of the remark property. * * @return * possible object is * {@link String } * */ public String getRemark() { return remark; } /** * Sets the value of the remark property. * * @param value * allowed object is * {@link String } * */ public void setRemark(String value) { this.remark = value; } /** * Gets the value of the serviceAttributes property. * * @return * possible object is * {@link Long } * */ public long getServiceAttributes() { if (serviceAttributes == null) { return 0L; } else { return serviceAttributes; } } /** * Sets the value of the serviceAttributes property. * * @param value * allowed object is * {@link Long } * */ public void setServiceAttributes(Long value) { this.serviceAttributes = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordServiceType.java
1