instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper("memoizing-last-call") .addValue(delegate) .toString(); } @Override public R apply(final T input) { final K key = keyFunction.apply(input); lock.readLock().lock(); boolean readLockAcquired = true; boolean writeLockAcquired = false; try { if (Objects.equals(lastKey, key)) { return lastValue; } // Upgrade to write lock lock.readLock().unlock(); // must release read lock before acquiring write lock readLockAcquired = false; lock.writeLock().lock(); writeLockAcquired = true; try { lastValue = delegate.apply(input); lastKey = key; return lastValue; } finally { // Downgrade to read lock lock.readLock().lock(); // acquire read lock before releasing write lock readLockAcquired = true; lock.writeLock().unlock(); // unlock write, still hold read writeLockAcquired = false; } } finally { if (writeLockAcquired) { lock.writeLock().unlock(); } if (readLockAcquired) { lock.readLock().unlock(); } } } @Override public R peek(final T input)
{ final ReadLock readLock = lock.readLock(); readLock.lock(); try { return lastValue; } finally { readLock.unlock(); } } @Override public void forget() { final WriteLock writeLock = lock.writeLock(); writeLock.lock(); try { lastKey = null; lastValue = null; } finally { writeLock.unlock(); } } } private static final class SimpleMemoizingFunction<T, R> extends MemoizingFunctionWithKeyExtractor<T, R, T> { private SimpleMemoizingFunction(final Function<T, R> delegate) { super(delegate, input -> input); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Functions.java
1
请完成以下Java代码
public class JpaAlarmCommentDao extends JpaPartitionedAbstractDao<AlarmCommentEntity, AlarmComment> implements AlarmCommentDao, TenantEntityDao<AlarmComment> { private final SqlPartitioningRepository partitioningRepository; @Value("${sql.alarm_comments.partition_size:168}") private int partitionSizeInHours; @Autowired private AlarmCommentRepository alarmCommentRepository; @Override public PageData<AlarmCommentInfo> findAlarmComments(TenantId tenantId, AlarmId id, PageLink pageLink) { log.trace("Try to find alarm comments by alarm id using [{}]", id); return DaoUtil.toPageData( alarmCommentRepository.findAllByAlarmId(id.getId(), DaoUtil.toPageable(pageLink))); } @Override public AlarmComment findAlarmCommentById(TenantId tenantId, UUID key) { log.trace("Try to find alarm comment by id using [{}]", key); return DaoUtil.getData(alarmCommentRepository.findById(key)); } @Override public ListenableFuture<AlarmComment> findAlarmCommentByIdAsync(TenantId tenantId, UUID key) { log.trace("Try to find alarm comment by id using [{}]", key); return findByIdAsync(tenantId, key); } @Override public void createPartition(AlarmCommentEntity entity) { partitioningRepository.createPartitionIfNotExists(ALARM_COMMENT_TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
} @Override public PageData<AlarmComment> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(alarmCommentRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } @Override protected Class<AlarmCommentEntity> getEntityClass() { return AlarmCommentEntity.class; } @Override protected JpaRepository<AlarmCommentEntity, UUID> getRepository() { return alarmCommentRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\alarm\JpaAlarmCommentDao.java
1
请完成以下Java代码
public <T> T findInCache(Class<T> entityClass, String id) { CachedEntity cachedObject = null; Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache == null) { classCache = findClassCacheByCheckingSubclasses(entityClass); } if (classCache != null) { cachedObject = classCache.get(id); } if (cachedObject != null) { return (T) cachedObject.getEntity(); } return null; } protected Map<String, CachedEntity> findClassCacheByCheckingSubclasses(Class<?> entityClass) { for (Class<?> clazz : cachedObjects.keySet()) { if (entityClass.isAssignableFrom(clazz)) { return cachedObjects.get(clazz); } } return null; } @Override public void cacheRemove(Class<?> entityClass, String entityId) { Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache == null) { return; } classCache.remove(entityId); } @Override public <T> Collection<CachedEntity> findInCacheAsCachedObjects(Class<T> entityClass) { Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache != null) { return classCache.values(); } return null; } @Override @SuppressWarnings("unchecked") public <T> List<T> findInCache(Class<T> entityClass) { Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) { classCache = findClassCacheByCheckingSubclasses(entityClass); } if (classCache != null) { List<T> entities = new ArrayList<T>(classCache.size()); for (CachedEntity cachedObject : classCache.values()) { entities.add((T) cachedObject.getEntity()); } return entities; } return emptyList(); } public Map<Class<?>, Map<String, CachedEntity>> getAllCachedEntities() { return cachedObjects; } @Override public void close() {} @Override public void flush() {} }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\cache\EntityCacheImpl.java
1
请完成以下Java代码
public String[] getActiveContextsInfo() { final List<Properties> activeContextsCopy = new ArrayList<>(activeContexts); final int count = activeContextsCopy.size(); final List<String> activeContextsInfo = new ArrayList<>(count); int index = 1; for (final Properties ctx : activeContextsCopy) { if (ctx == null) { continue; } final String ctxInfo = index + "/" + count + ". " + toInfoString(ctx); activeContextsInfo.add(ctxInfo); index++; } return activeContextsInfo.toArray(new String[activeContextsInfo.size()]); } private String toInfoString(final Properties ctx) { final String threadName = (String)ctx.get(CTXNAME_ThreadName); final String threadId = (String)ctx.get(CTXNAME_ThreadId); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx);
final int adUserId = Env.getAD_User_ID(ctx); final int adRoleId = Env.getAD_Role_ID(ctx); final int adSessionId = Env.getAD_Session_ID(ctx); return "Thread=" + threadName + "(" + threadId + ")" // + "\n" + ", Client/Org=" + adClientId + "/" + adOrgId + ", User/Role=" + adUserId + "/" + adRoleId + ", SessionId=" + adSessionId // + "\n" + ", id=" + System.identityHashCode(ctx) + ", " + ctx.getClass() // + "\n" + ", " + ctx.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\TraceContextProviderListener.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) {
set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UOM_Conversion.java
1
请完成以下Java代码
public static class CheckTableRecordReferenceInterceptor extends AbstractModelInterceptor { public static CheckTableRecordReferenceInterceptor INSTANCE = new CheckTableRecordReferenceInterceptor(); private CheckTableRecordReferenceInterceptor() { } @Override protected void onInit(final IModelValidationEngine engine, final I_AD_Client client) { // nothing to do } @Override public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception { final boolean afterNewOrChange = changeType.isNewOrChange() && changeType.isAfter(); if (!afterNewOrChange) { // Note that currently we are not interested in splitting a partition if the only linking record gets deleted. return; // Nothing to do. } final ImmutableSet<String> columnNames = ImmutableSet.of(ITableRecordReference.COLUMNNAME_AD_Table_ID, ITableRecordReference.COLUMNNAME_Record_ID); if (!InterfaceWrapperHelper.isValueChanged(model, columnNames)) { return; } final IPartitionerService partitionerService = Services.get(IPartitionerService.class); final IDLMService dlmService = Services.get(IDLMService.class); final PartitionConfig config = dlmService.loadDefaultPartitionConfig(); final ITableRecordReference recordReference = TableRecordReference.ofReferencedOrNull(model); final Optional<PartitionerConfigLine> referencedLine = config.getLine(recordReference.getTableName()); if (!referencedLine.isPresent()) { return; // the table we are referencing is not part of DLM; nothing to do } final String modelTableName = InterfaceWrapperHelper.getModelTableName(model); final TableRecordIdDescriptor descriptor = TableRecordIdDescriptor.of(modelTableName, ITableRecordReference.COLUMNNAME_Record_ID, recordReference.getTableName());
final PartitionConfig augmentedConfig = partitionerService.augmentPartitionerConfig(config, Collections.singletonList(descriptor)); if (!augmentedConfig.isChanged()) { return; // we are done } // now that the augmented config is stored, further changes will be handeled by AddToPartitionInterceptor. dlmService.storePartitionConfig(augmentedConfig); // however, for the current 'model', we need to enqueue it ourselves final CreatePartitionAsyncRequest request = PartitionRequestFactory.asyncBuilder() .setConfig(config) .setRecordToAttach(TableRecordReference.ofOrNull(model)) .build(); final PInstanceId pinstanceId = null; DLMPartitionerWorkpackageProcessor.schedule(request, pinstanceId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\PartitionerInterceptor.java
1
请完成以下Java代码
public void onError(Throwable e) { System.out.println("error"); } @Override public void onCompleted() { System.out.println("Subscriber1 completed"); } }; } static Observer<Integer> getSecondObserver() { return new Observer<Integer>() { @Override public void onNext(Integer value) { subscriber2 += value; System.out.println("Subscriber2: " + value); }
@Override public void onError(Throwable e) { System.out.println("error"); } @Override public void onCompleted() { System.out.println("Subscriber2 completed"); } }; } public static void main(String[] args) throws InterruptedException { System.out.println(subjectMethod()); } }
repos\tutorials-master\rxjava-modules\rxjava-core\src\main\java\com\baeldung\rxjava\SubjectImpl.java
1
请完成以下Java代码
private static void finishJob(XxlJobLog xxlJobLog){ // 1、handle success, to trigger child job String triggerChildMsg = null; if (XxlJobContext.HANDLE_CODE_SUCCESS == xxlJobLog.getHandleCode()) { XxlJobInfo xxlJobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(xxlJobLog.getJobId()); if (xxlJobInfo!=null && xxlJobInfo.getChildJobId()!=null && xxlJobInfo.getChildJobId().trim().length()>0) { triggerChildMsg = "<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_child_run") +"<<<<<<<<<<< </span><br>"; String[] childJobIds = xxlJobInfo.getChildJobId().split(","); for (int i = 0; i < childJobIds.length; i++) { int childJobId = (childJobIds[i]!=null && childJobIds[i].trim().length()>0 && isNumeric(childJobIds[i]))?Integer.valueOf(childJobIds[i]):-1; if (childJobId > 0) { JobTriggerPoolHelper.trigger(childJobId, TriggerTypeEnum.PARENT, -1, null, null, null); ReturnT<String> triggerChildResult = ReturnT.SUCCESS; // add msg triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg1"), (i+1), childJobIds.length, childJobIds[i], (triggerChildResult.getCode()==ReturnT.SUCCESS_CODE?I18nUtil.getString("system_success"):I18nUtil.getString("system_fail")), triggerChildResult.getMsg()); } else { triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg2"), (i+1), childJobIds.length, childJobIds[i]); } }
} } if (triggerChildMsg != null) { xxlJobLog.setHandleMsg( xxlJobLog.getHandleMsg() + triggerChildMsg ); } // 2、fix_delay trigger next // on the way } private static boolean isNumeric(String str){ try { int result = Integer.valueOf(str); return true; } catch (NumberFormatException e) { return false; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\complete\XxlJobCompleter.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableList<IssueEntity> listIssues() { return root.listAllNodesBelow() .stream() .map(Node::getValue) .collect(ImmutableList.toImmutableList()); } public boolean hasNodeForId(@NonNull final IssueId issueId) { return listIssues().stream().map(IssueEntity::getIssueId).anyMatch(issueId::equals); } public ImmutableList<IssueEntity> getUpStreamForId(@NonNull final IssueId issueId) { final Optional<IssueEntity> issue = getIssueForId(issueId); if (!issue.isPresent()) { return ImmutableList.of(); } return this.root.getNode(issue.get()) .map(Node::getUpStream) .orElse(new ArrayList<>())
.stream() .map(Node::getValue) .collect(ImmutableList.toImmutableList()); } private Optional<IssueEntity> getIssueForId(@NonNull final IssueId issueId) { return listIssues() .stream() .filter(issueEntity -> issueId.equalsNullSafe(issueEntity.getIssueId())) .findFirst(); } private IssueHierarchy(final Node<IssueEntity> root) { this.root = root; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\hierarchy\IssueHierarchy.java
2
请完成以下Java代码
public void notify(DmnDecisionTableEvaluationEvent evaluationEvent) { // collector is registered as decision evaluation listener } public void notify(DmnDecisionEvaluationEvent evaluationEvent) { long executedDecisionInstances = evaluationEvent.getExecutedDecisionInstances(); long executedDecisionElements = evaluationEvent.getExecutedDecisionElements(); this.executedDecisionInstances.getAndAdd(executedDecisionInstances); this.executedDecisionElements.getAndAdd(executedDecisionElements); } @Override public long getExecutedDecisionInstances() { return executedDecisionInstances.get(); } @Override
public long getExecutedDecisionElements() { return executedDecisionElements.get(); } @Override public long clearExecutedDecisionInstances() { return executedDecisionInstances.getAndSet(0); } @Override public long clearExecutedDecisionElements() { return executedDecisionElements.getAndSet(0); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\metrics\DefaultEngineMetricCollector.java
1
请在Spring Boot框架中完成以下Java代码
protected SecurityUser authenticateByPublicId(String publicId, String authContextName, UserPrincipal userPrincipal) { TenantId systemId = TenantId.SYS_TENANT_ID; CustomerId customerId; try { customerId = new CustomerId(UUID.fromString(publicId)); } catch (Exception e) { throw new BadCredentialsException(authContextName + " is not valid"); } Customer publicCustomer = customerService.findCustomerById(systemId, customerId); if (publicCustomer == null) { throw new UsernameNotFoundException("Public entity not found"); } if (!publicCustomer.isPublic()) { throw new BadCredentialsException(authContextName + " is not valid"); } User user = new User(new UserId(EntityId.NULL_UUID)); user.setTenantId(publicCustomer.getTenantId()); user.setCustomerId(publicCustomer.getId()); user.setEmail(publicId); user.setAuthority(Authority.CUSTOMER_USER); user.setFirstName("Public"); user.setLastName("Public");
UserPrincipal principal = userPrincipal == null ? new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, publicId) : userPrincipal; return new SecurityUser(user, true, principal); } protected SecurityUser authenticateByUserId(TenantId tenantId, UserId userId) { UserAuthDetails userAuthDetails = userAuthDetailsCache.getUserAuthDetails(tenantId, userId); if (userAuthDetails == null) { throw new UsernameNotFoundException("User with credentials not found"); } if (!userAuthDetails.credentialsEnabled()) { throw new DisabledException("User is not active"); } User user = userAuthDetails.user(); if (user.getAuthority() == null) { throw new InsufficientAuthenticationException("User has no authority assigned"); } UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); return new SecurityUser(user, true, userPrincipal); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\AbstractAuthenticationProvider.java
2
请在Spring Boot框架中完成以下Java代码
public class Config { /** * 是否是索引分词(合理地最小分割),indexMode代表全切分词语的最小长度(包含) */ public int indexMode = 0; /** * 是否识别中国人名 */ public boolean nameRecognize = true; /** * 是否识别音译人名 */ public boolean translatedNameRecognize = true; /** * 是否识别日本人名 */ public boolean japaneseNameRecognize = false; /** * 是否识别地名 */ public boolean placeRecognize = false; /** * 是否识别机构 */ public boolean organizationRecognize = false; /** * 是否加载用户词典 */ public boolean useCustomDictionary = true; /** * 用户词典高优先级 */ public boolean forceCustomDictionary = false; /** * 词性标注 */ public boolean speechTagging = false; /** * 命名实体识别是否至少有一项被激活 */ public boolean ner = true; /** * 是否计算偏移量 */ public boolean offset = false; /**
* 是否识别数字和量词 */ public boolean numberQuantifierRecognize = false; /** * 并行分词的线程数 */ public int threadNumber = 1; /** * 更新命名实体识别总开关 */ public void updateNerConfig() { ner = nameRecognize || translatedNameRecognize || japaneseNameRecognize || placeRecognize || organizationRecognize; } /** * 是否是索引模式 * * @return */ public boolean isIndexMode() { return indexMode > 0; } /** * 是否执行字符正规化(繁体->简体,全角->半角,大写->小写),切换配置后必须删CustomDictionary.txt.bin缓存 */ public boolean normalization = HanLP.Config.Normalization; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Config.java
2
请完成以下Java代码
static class FullTextSearchRowFilter extends RowFilter<TableModel, Integer> { public static FullTextSearchRowFilter ofText(final String text) { if (Check.isEmpty(text, true)) { return null; } else { return new FullTextSearchRowFilter(text); } } private final String textUC; private FullTextSearchRowFilter(final String text) { super(); textUC = text.toUpperCase(); } @Override public boolean include(final javax.swing.RowFilter.Entry<? extends TableModel, ? extends Integer> entry) { for (int i = entry.getValueCount() - 1; i >= 0; i--) { String entryValue = entry.getStringValue(i);
if (entryValue == null || entryValue.isEmpty()) { continue; } entryValue = entryValue.toUpperCase(); if (entryValue.indexOf(textUC) >= 0) { return true; } } return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\plaf\UIDefaultsEditorDialog.java
1
请完成以下Java代码
public void setM_ChangeNotice_ID (int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID)); } /** Get Change Notice. @return Bill of Materials (Engineering) Change Notice (Version) */ public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeNotice.java
1
请完成以下Java代码
public void setDateEnd(XMLGregorianCalendar value) { this.dateEnd = value; } /** * Gets the value of the canton property. * * @return * possible object is * {@link String } * */ public String getCanton() { return canton; } /** * Sets the value of the canton property. * * @param value * allowed object is * {@link String } * */ public void setCanton(String value) { this.canton = value; } /** * Gets the value of the reason property. * * @return * possible object is * {@link String } * */ public String getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link String } * */ public void setReason(String value) { this.reason = value; } /** * Gets the value of the apid property. * * @return * possible object is * {@link String } * */ public String getApid() { return apid; } /** * Sets the value of the apid property. *
* @param value * allowed object is * {@link String } * */ public void setApid(String value) { this.apid = value; } /** * Gets the value of the acid property. * * @return * possible object is * {@link String } * */ public String getAcid() { return acid; } /** * Sets the value of the acid property. * * @param value * allowed object is * {@link String } * */ public void setAcid(String value) { this.acid = 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\TreatmentType.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = (Map<String, Object>) super.getPersistentState(); persistentState.put("lockOwner", lockOwner); persistentState.put("lockExpirationTime", lockExpirationTime); return persistentState; } // getters and setters //////////////////////////////////////////////////////// public void setExecution(ExecutionEntity execution) { super.setExecution(execution); execution.getJobs().add(this); } public String getLockOwner() { return lockOwner; }
public void setLockOwner(String claimedBy) { this.lockOwner = claimedBy; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date claimedUntil) { this.lockExpirationTime = claimedUntil; } @Override public String toString() { return "JobEntity [id=" + id + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getDefaultBillingAddressId() { return Optional.ofNullable(customer) .map(JsonCustomer::getDefaultBillingAddressId) .orElse(null); } @Nullable public String getGroupId() { return Optional.ofNullable(customer) .map(JsonCustomer::getGroupId) .orElse(null); } @NonNull public ExternalIdentifier getExternalIdentifier(@Nullable final String metasfreshIdJsonPath, @Nullable final String shopwareIdJsonPath) { final String id = getCustomField(metasfreshIdJsonPath); if (Check.isNotBlank(id)) { return ExternalIdentifier.builder() .identifier(id) .rawValue(id) .build(); } return getShopwareId(shopwareIdJsonPath); } @NonNull public ExternalIdentifier getShopwareId(@Nullable final String shopwareIdJsonPath) { final String id = getCustomField(shopwareIdJsonPath); if (Check.isNotBlank(id)) { return ExternalIdentifier.builder() .identifier(ExternalIdentifierFormat.formatExternalId(id)) .rawValue(id) .build(); } final String customerId = getShopwareId(); return ExternalIdentifier.builder() .identifier(ExternalIdentifierFormat.formatExternalId(customerId)) .rawValue(customerId) .build();
} @Nullable @VisibleForTesting public String getCustomField(@Nullable final String customPath) { return Optional.ofNullable(customPath) .filter(Check::isNotBlank) .map(customerNode::at) .map(JsonNode::asText) .filter(Check::isNotBlank) .orElse(null); } @NonNull public Instant getUpdatedAt() { final JsonCustomerBasicInfo basicInfo = getCustomerBasicInfo(); return CoalesceUtil.coalesceNotNull(basicInfo.getUpdatedAt(), basicInfo.getCreatedAt()) .toInstant(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\order\Customer.java
2
请在Spring Boot框架中完成以下Java代码
public class PaymentReservationCapture { @NonNull PaymentReservationId reservationId; @NonNull @NonFinal PaymentReservationCaptureStatus status; @NonNull Money amount; @NonNull OrgId orgId; @NonNull
OrderId salesOrderId; @NonNull InvoiceId salesInvoiceId; @NonNull PaymentId paymentId; @Nullable @NonFinal @Setter(AccessLevel.PACKAGE) PaymentReservationCaptureId id; public void setStatusAsCompleted() { status = PaymentReservationCaptureStatus.COMPLETED; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationCapture.java
2
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractRepository<T, ID extends Serializable> { protected DynamoDBMapper mapper; protected Class<T> entityClass; protected AbstractRepository() { ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); // This entityClass refers to the actual entity class in the subclass declaration. // For instance, ProductInfoDAO extends AbstractDAO<ProductInfo, String> // In this case entityClass = ProductInfo, and ID is String type // which refers to the ProductInfo's partition key string value this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0]; } public void save(T t) { mapper.save(t); } public T findOne(ID id) {
return mapper.load(entityClass, id); } /** * <strong>WARNING:</strong> It is not recommended to perform full table scan * targeting the real production environment. * * @return All items */ public List<T> findAll() { DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); return mapper.scan(entityClass, scanExpression); } public void setMapper(DynamoDBMapper dynamoDBMapper) { this.mapper = dynamoDBMapper; } }
repos\tutorials-master\aws-modules\aws-dynamodb\src\main\java\com\baeldung\dynamodb\repository\AbstractRepository.java
2
请完成以下Java代码
public Optional<HierarchyNode> getParent(final HierarchyNode child) { return Optional.ofNullable(child2Parent.get(child)); } public ImmutableList<HierarchyNode> getChildren(@NonNull final HierarchyNode parent) { return parent2Children.get(parent); } public static class HierarchyBuilder { private final ImmutableListMultimap.Builder<HierarchyNode, HierarchyNode> parent2Children = ImmutableListMultimap.builder(); private final HashMap<Beneficiary, HierarchyNode> beneficiary2Node = new HashMap<>(); public HierarchyBuilder addChildren(final HierarchyNode parent, final Collection<HierarchyNode> children) { beneficiary2Node.put(parent.getBeneficiary(), parent); children.forEach(child -> beneficiary2Node.put(child.getBeneficiary(), child)); parent2Children.putAll(parent, children); return this; } public Hierarchy build() { return new Hierarchy( ImmutableMap.copyOf(beneficiary2Node), parent2Children.build()); } } /** * @return the given {@code beneficiary}'s node, followed by its parent, grandparent and so on. */ public Iterable<HierarchyNode> getUpStream(@NonNull final Beneficiary beneficiary) { final HierarchyNode node = beneficiary2Node.get(beneficiary); if (node == null) { throw new AdempiereException("Beneficiary with C_BPartner_ID=" + beneficiary.getBPartnerId().getRepoId() + " is not part of this hierarchy") .appendParametersToMessage() .setParameter("this", this); } return () -> new ParentNodeIterator(child2Parent, node); } public static class ParentNodeIterator implements Iterator<HierarchyNode> { private final ImmutableMap<HierarchyNode, HierarchyNode> child2Parent; private HierarchyNode next; private HierarchyNode previous; private ParentNodeIterator( @NonNull final ImmutableMap<HierarchyNode, HierarchyNode> childAndParent,
@NonNull final HierarchyNode first) { this.child2Parent = childAndParent; this.next = first; } @Override public boolean hasNext() { return next != null; } @Override public HierarchyNode next() { final HierarchyNode result = next; if (result == null) { throw new NoSuchElementException("Previous HierarchyNode=" + previous + " had no parent"); } previous = next; next = child2Parent.get(next); return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\hierarchy\Hierarchy.java
1
请完成以下Java代码
public class PPRouting { @NonNull PPRoutingId id; @Default boolean valid = true; @NonNull @Default Range<Instant> validDates = Range.all(); @NonNull String code; @NonNull WFDurationUnit durationUnit; @NonNull Duration duration; @NonNull @Default BigDecimal qtyPerBatch = BigDecimal.ONE; /** The Yield is the percentage of a lot that is expected to be of acceptable quality may fall below 100 percent */ @NonNull @Default Percent yield = Percent.ONE_HUNDRED; @Nullable UserId userInChargeId; @NonNull PPRoutingActivityId firstActivityId; @NonNull @Default ImmutableList<PPRoutingActivity> activities = ImmutableList.of(); @NonNull @Default ImmutableList<PPRoutingProduct> products = ImmutableList.of(); public boolean isValidAtDate(@NonNull final Instant dateTime) {
return isValid() && validDates.contains(dateTime); } public PPRoutingActivity getActivityById(@NonNull final PPRoutingActivityId activityId) { return activities.stream() .filter(activity -> activityId.equals(activity.getId())) .findFirst() .orElseThrow(() -> new AdempiereException("No activity by " + activityId + " found in " + this)); } public PPRoutingActivity getFirstActivity() { return getActivityById(getFirstActivityId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPRouting.java
1
请完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public IdmEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (idmEngineConfiguration.getBeans() == null) { idmEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.idmEngine = idmEngineConfiguration.buildIdmEngine(); return this.idmEngine; } protected void configureExternallyManagedTransactions() { if (idmEngineConfiguration instanceof SpringIdmEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringIdmEngineConfiguration engineConfiguration = (SpringIdmEngineConfiguration) idmEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { idmEngineConfiguration.setTransactionsExternallyManaged(true); } } } @Override
public Class<IdmEngine> getObjectType() { return IdmEngine.class; } @Override public boolean isSingleton() { return true; } public IdmEngineConfiguration getIdmEngineConfiguration() { return idmEngineConfiguration; } public void setIdmEngineConfiguration(IdmEngineConfiguration idmEngineConfiguration) { this.idmEngineConfiguration = idmEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-idm-spring\src\main\java\org\flowable\idm\spring\IdmEngineFactoryBean.java
1
请完成以下Java代码
public void setQtyShipped (final @Nullable BigDecimal QtyShipped) { set_Value (COLUMNNAME_QtyShipped, QtyShipped); } @Override public BigDecimal getQtyShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalPrice (final BigDecimal TotalPrice) { set_Value (COLUMNNAME_TotalPrice, TotalPrice); } @Override public BigDecimal getTotalPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalPrice);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalWeightInKg (final BigDecimal TotalWeightInKg) { set_Value (COLUMNNAME_TotalWeightInKg, TotalWeightInKg); } @Override public BigDecimal getTotalWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalWeightInKg); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Item.java
1
请完成以下Java代码
private void directlyExportToAllMatchingConfigs(@NonNull final I_M_HU_Trace huTrace) { final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum); for (final ExternalSystemParentConfig config : configs) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(config.getChildConfig()); if (!shouldExportToExternalSystem(grsConfig, HUTraceType.ofCode(huTrace.getHUTraceType()))) { continue; } final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParent(HuId.ofRepoId(huTrace.getM_HU_ID())); final TableRecordReference topLevelHURecordRef = TableRecordReference.of(topLevelHU); exportToExternalSystem(grsConfig.getId(), topLevelHURecordRef, null); } } private boolean shouldExportDirectly(@NonNull final I_M_HU_Trace huTrace) { final HUTraceType huTraceType = HUTraceType.ofCode(huTrace.getHUTraceType()); final boolean purchasedOrProduced = huTraceType.equals(MATERIAL_RECEIPT) || huTraceType.equals(PRODUCTION_RECEIPT); final boolean docCompleted = DocStatus.ofCodeOptional(huTrace.getDocStatus()) .map(DocStatus::isCompleted) .orElse(false); return purchasedOrProduced && docCompleted; } private boolean shouldExportIfAlreadyExportedOnce(@NonNull final HUTraceType huTraceType) {
return huTraceType.equals(TRANSFORM_LOAD) || huTraceType.equals(TRANSFORM_PARENT); } private boolean shouldExportToExternalSystem(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig, @NonNull final HUTraceType huTraceType) { switch (huTraceType) { case MATERIAL_RECEIPT: return grsSignumConfig.isSyncHUsOnMaterialReceipt(); case PRODUCTION_RECEIPT: return grsSignumConfig.isSyncHUsOnProductionReceipt(); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportHUToGRSService.java
1
请完成以下Java代码
public InventoryLineHU withAddingQtyCount(@NonNull final Quantity qtyCountToAdd) { return withQtyCount(getQtyCount().add(qtyCountToAdd)); } public InventoryLineHU withZeroQtyCount() { return withQtyCount(getQtyCount().toZero()); } public InventoryLineHU withQtyCount(@NonNull final Quantity newQtyCount) { assertPhysicalInventory(); return toBuilder().qtyCount(newQtyCount).build(); } public static ImmutableSet<HuId> extractHuIds(@NonNull final Collection<InventoryLineHU> lineHUs) { return extractHuIds(lineHUs.stream()); } static ImmutableSet<HuId> extractHuIds(@NonNull final Stream<InventoryLineHU> lineHUs) { return lineHUs .map(InventoryLineHU::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter) { return toBuilder() .qtyCount(qtyConverter.apply(getQtyCount())) .qtyBook(qtyConverter.apply(getQtyBook())) .build(); } public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request) { return toBuilder().updatingFrom(request).build(); } public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request)
{ return builder().updatingFrom(request).build(); } // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder { InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请完成以下Java代码
protected void produceHistoricExternalTaskCreatedEvent() { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricExternalTaskLogManager().fireExternalTaskCreatedEvent(this); } protected void produceHistoricExternalTaskFailedEvent() { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricExternalTaskLogManager().fireExternalTaskFailedEvent(this); } protected void produceHistoricExternalTaskSuccessfulEvent() { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricExternalTaskLogManager().fireExternalTaskSuccessfulEvent(this); } protected void produceHistoricExternalTaskDeletedEvent() { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricExternalTaskLogManager().fireExternalTaskDeletedEvent(this); } public void extendLock(long newLockExpirationTime) { ensureActive(); long newTime = ClockUtil.getCurrentTime().getTime() + newLockExpirationTime; this.lockExpirationTime = new Date(newTime); } @Override public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); if (executionId != null) { referenceIdAndClass.put(executionId, ExecutionEntity.class); } if (errorDetailsByteArrayId != null) { referenceIdAndClass.put(errorDetailsByteArrayId, ByteArrayEntity.class); } return referenceIdAndClass; } public String getLastFailureLogId() { return lastFailureLogId; } public void setLastFailureLogId(String lastFailureLogId) { this.lastFailureLogId = lastFailureLogId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExternalTaskEntity.java
1
请完成以下Java代码
protected void prepare() { for (final ProcessInfoParameter para : getParameters()) { final String name = para.getParameterName(); if (para.getParameter() == null) { ; } else if (name.equals("PP_Product_BOM_ID")) { fromProductBOMId = para.getParameterAsInt(); } else { log.error("prepare - Unknown Parameter: " + name); } } toProductBOMId = getRecord_ID(); } // prepare @Override protected String doIt() { log.info("From PP_Product_BOM_ID=" + fromProductBOMId + " to " + toProductBOMId); if (toProductBOMId == 0) { throw new AdempiereException("Target PP_Product_BOM_ID == 0"); } if (fromProductBOMId == 0) { throw new AdempiereException("Source PP_Product_BOM_ID == 0");
} if (toProductBOMId == fromProductBOMId) { return MSG_OK; } final I_PP_Product_BOM fromBom = productBOMsRepo.getById(fromProductBOMId); final I_PP_Product_BOM toBOM = productBOMsRepo.getById(toProductBOMId); if (!productBOMsRepo.retrieveLines(toBOM).isEmpty()) { throw new AdempiereException("@Error@ Existing BOM Line(s)"); } for (final I_PP_Product_BOMLine fromBOMLine : productBOMsRepo.retrieveLines(fromBom)) { final I_PP_Product_BOMLine toBOMLine = InterfaceWrapperHelper.copy() .setFrom(fromBOMLine) .copyToNew(I_PP_Product_BOMLine.class); toBOMLine.setPP_Product_BOM_ID(toBOM.getPP_Product_BOM_ID()); InterfaceWrapperHelper.saveRecord(toBOMLine); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CopyFromBOM.java
1
请在Spring Boot框架中完成以下Java代码
public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); CustomerId customerId = publicCustomer.getId(); try { Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); logEntityActionService.logEntityAction(tenantId, edgeId, savedEdge, customerId, actionType, user, edgeId.toString(), customerId.toString(), publicCustomer.getName()); return savedEdge; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.EDGE), actionType, user, e, edgeId.toString()); throw e; } }
@Override public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception { TenantId tenantId = edge.getTenantId(); EdgeId edgeId = edge.getId(); try { Edge updatedEdge = edgeService.setEdgeRootRuleChain(tenantId, edge, ruleChainId); logEntityActionService.logEntityAction(tenantId, edgeId, edge, null, ActionType.UPDATED, user); return updatedEdge; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.EDGE), ActionType.UPDATED, user, e, edgeId.toString()); throw e; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\edge\DefaultTbEdgeService.java
2
请完成以下Java代码
public HistoricCaseInstanceQuery orderByCaseDefinitionId() { return orderBy(HistoricCaseInstanceQueryProperty.PROCESS_DEFINITION_ID); } public HistoricCaseInstanceQuery orderByCaseInstanceId() { return orderBy(HistoricCaseInstanceQueryProperty.PROCESS_INSTANCE_ID_); } public HistoricCaseInstanceQuery orderByTenantId() { return orderBy(HistoricCaseInstanceQueryProperty.TENANT_ID); } public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getHistoricCaseInstanceManager() .findHistoricCaseInstanceCountByQueryCriteria(this); } public List<HistoricCaseInstance> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getHistoricCaseInstanceManager() .findHistoricCaseInstancesByQueryCriteria(this, page); } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(createdAfter, createdBefore) || CompareUtil.areNotInAscendingOrder(closedAfter, closedBefore) || CompareUtil.elementIsNotContainedInList(caseInstanceId, caseInstanceIds) || CompareUtil.elementIsContainedInList(caseDefinitionKey, caseKeyNotIn); } public String getBusinessKey() { return businessKey; } public String getBusinessKeyLike() { return businessKeyLike; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionIdLike() { return caseDefinitionKey + ":%:%"; } public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseDefinitionNameLike() { return caseDefinitionNameLike;
} public String getCaseInstanceId() { return caseInstanceId; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public String getStartedBy() { return createdBy; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public void setSuperCaseInstanceId(String superCaseInstanceId) { this.superCaseInstanceId = superCaseInstanceId; } public List<String> getCaseKeyNotIn() { return caseKeyNotIn; } public Date getCreatedAfter() { return createdAfter; } public Date getCreatedBefore() { return createdBefore; } public Date getClosedAfter() { return closedAfter; } public Date getClosedBefore() { return closedBefore; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java
1
请完成以下Java代码
public class Hero { @Id private String id; private String name; private String city; private ComicUniversum universum; public Hero(String name, String city, ComicUniversum universum) { this.name = name; this.city = city; this.universum = universum; } public Hero() { } public String getName() { return name; } public String getCity() { return city; } public void setName(String name) { this.name = name; } public void setCity(String city) { this.city = city; } public ComicUniversum getUniversum() { return universum; } public void setUniversum(ComicUniversum universum) { this.universum = universum; } @Override public boolean equals(Object o) {
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Hero hero = (Hero) o; return Objects.equals(name, hero.name) && Objects.equals(city, hero.city) && universum == hero.universum; } @Override public int hashCode() { return Objects.hash(name, city, universum); } @Override public String toString() { return "Hero{" + "name='" + name + '\'' + ", city='" + city + '\'' + ", universum=" + universum.getDisplayName() + '}'; } }
repos\spring-boot-demo-master (1)\src\main\java\com\github\sparsick\springbootexample\hero\universum\Hero.java
1
请完成以下Java代码
private static String extractApproveUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder) { return extractUrlOrNull(apiOrder, "approve"); } private static String extractUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder, @NonNull final String rel) { for (final LinkDescription link : apiOrder.links()) { if (rel.contentEquals(link.rel())) { return link.href(); } } return null; } private static String toJson(final com.paypal.orders.Order apiOrder) { if (apiOrder == null) { return ""; } try { // IMPORTANT: we shall use paypal's JSON serializer, else we won't get any result return new com.braintreepayments.http.serializer.Json().serialize(apiOrder); } catch (final Exception ex) { logger.warn("Failed converting {} to JSON. Returning toString()", apiOrder, ex); return apiOrder.toString(); }
} public PayPalOrder markRemoteDeleted(@NonNull final PayPalOrderId id) { final I_PayPal_Order existingRecord = getRecordById(id); final PayPalOrder order = toPayPalOrder(existingRecord) .toBuilder() .status(PayPalOrderStatus.REMOTE_DELETED) .build(); updateRecord(existingRecord, order); saveRecord(existingRecord); return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderRepository.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Preis. @param Price Price */ @Override public void setPrice (java.math.BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } /** Get Preis. @return Price */ @Override public java.math.BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () {
Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Ranking. @param Ranking Relative Rank Number */ @Override public void setRanking (int Ranking) { set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking)); } /** Get Ranking. @return Relative Rank Number */ @Override public int getRanking () { Integer ii = (Integer)get_Value(COLUMNNAME_Ranking); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Enforce Client Security. @param EnforceClientSecurity Send alerts to recipient only if the client security rules of the role allows */ public void setEnforceClientSecurity (boolean EnforceClientSecurity) { set_Value (COLUMNNAME_EnforceClientSecurity, Boolean.valueOf(EnforceClientSecurity)); } /** Get Enforce Client Security. @return Send alerts to recipient only if the client security rules of the role allows */ public boolean isEnforceClientSecurity () { Object oo = get_Value(COLUMNNAME_EnforceClientSecurity); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Enforce Role Security. @param EnforceRoleSecurity Send alerts to recipient only if the data security rules of the role allows */ public void setEnforceRoleSecurity (boolean EnforceRoleSecurity) { set_Value (COLUMNNAME_EnforceRoleSecurity, Boolean.valueOf(EnforceRoleSecurity)); } /** Get Enforce Role Security. @return Send alerts to recipient only if the data security rules of the role allows */ public boolean isEnforceRoleSecurity () { Object oo = get_Value(COLUMNNAME_EnforceRoleSecurity); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Valid. @param IsValid Element is valid */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
} /** Get Valid. @return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Alert.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentTermQuery { OrgId orgId; ExternalId externalId; String value; BPartnerId bPartnerId; /** * Ignored, unless bPartnerId is given. */ SOTrx soTrx; boolean fallBackToDefault; @Builder(toBuilder = true) private PaymentTermQuery( @Nullable final OrgId orgId, @Nullable final ExternalId externalId, @Nullable final String value, @Nullable final BPartnerId bPartnerId, @Nullable final SOTrx soTrx, @Nullable final Boolean fallBackToDefault) { if (bPartnerId == null && externalId == null && value == null) { throw new AdempiereException("Either bPartnerId, externalId or value needs to be not-null"); } this.orgId = orgId; this.externalId = externalId; this.value = value; this.bPartnerId = bPartnerId;
this.soTrx = CoalesceUtil.coalesceNotNull(soTrx, SOTrx.SALES); this.fallBackToDefault = CoalesceUtil.coalesceNotNull(fallBackToDefault, false); } /** * Convenience method. If there is no payment term for the given bpartner and soTrx, it tries to fall back to the default term. */ public static PaymentTermQuery forPartner(@NonNull final BPartnerId bPartnerId, @NonNull final SOTrx soTrx) { return PaymentTermQuery.builder() .bPartnerId(bPartnerId) .soTrx(soTrx) .fallBackToDefault(true) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\PaymentTermQuery.java
2
请在Spring Boot框架中完成以下Java代码
public ProcessApplicationDeploymentBuilderImpl addDeploymentResourceById(String deploymentId, String resourceId) { return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourceById(deploymentId, resourceId); } @Override public ProcessApplicationDeploymentBuilderImpl addDeploymentResourcesById(String deploymentId, List<String> resourceIds) { return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourcesById(deploymentId, resourceIds); } @Override public ProcessApplicationDeploymentBuilderImpl addDeploymentResourceByName(String deploymentId, String resourceName) { return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourceByName(deploymentId, resourceName); } @Override public ProcessApplicationDeploymentBuilderImpl addDeploymentResourcesByName(String deploymentId, List<String> resourceNames) { return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResourcesByName(deploymentId, resourceNames);
} // getters / setters /////////////////////////////////////////////// public boolean isResumePreviousVersions() { return isResumePreviousVersions; } public ProcessApplicationReference getProcessApplicationReference() { return processApplicationReference; } public String getResumePreviousVersionsBy() { return resumePreviousVersionsBy; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\ProcessApplicationDeploymentBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public ImmutableList<Issue> fetchIssues(@NonNull final RetrieveIssuesRequest retrieveIssuesRequest) { final ImmutableList<Issue> issueList; final List<String> pathVariables = Arrays.asList( REPOS.getValue(), retrieveIssuesRequest.getRepositoryOwner(), retrieveIssuesRequest.getRepositoryId(), ISSUES.getValue()); final LinkedMultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(); queryParams.add(STATE.getValue(), ResourceState.ALL.getValue()); queryParams.add(PAGE.getValue(), String.valueOf(retrieveIssuesRequest.getPageIndex())); queryParams.add(PER_PAGE.getValue(), String.valueOf(retrieveIssuesRequest.getPageSize())); if (retrieveIssuesRequest.getDateFrom() != null) { final String since = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(retrieveIssuesRequest.getDateFrom().atStartOfDay(ZoneOffset.UTC)); queryParams.add(SINCE.getValue(), since); } final GetRequest getRequest = GetRequest.builder() .baseURL(GITHUB_BASE_URI) .pathVariables(pathVariables) .queryParameters(queryParams) .oAuthToken(retrieveIssuesRequest.getOAuthToken()) .build(); issueList = ImmutableList.copyOf(restService.performGet(getRequest, Issue[].class).getBody());
return issueList.stream() .filter(issue -> !issue.isPullRequest()) .collect(ImmutableList.toImmutableList()); } public Issue fetchIssueById(@NonNull final FetchIssueByIdRequest fetchIssueByIdRequest) { final List<String> pathVariables = Arrays.asList( REPOS.getValue(), fetchIssueByIdRequest.getRepositoryOwner(), fetchIssueByIdRequest.getRepositoryId(), ISSUES.getValue(), fetchIssueByIdRequest.getIssueNumber()); final GetRequest getRequest = GetRequest.builder() .baseURL(GITHUB_BASE_URI) .pathVariables(pathVariables) .oAuthToken(fetchIssueByIdRequest.getOAuthToken()) .build(); return restService.performGet(getRequest, Issue.class).getBody(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.github\src\main\java\de\metas\issue\tracking\github\api\v3\service\GithubClient.java
2
请完成以下Java代码
public class GameAnnotatedByJsonSerializeDeserialize { private Long id; private String name; @JsonSerialize(using = NumericBooleanSerializer.class) @JsonDeserialize(using = NumericBooleanDeserializer.class) private Boolean paused; @JsonSerialize(using = NumericBooleanSerializer.class) @JsonDeserialize(using = NumericBooleanDeserializer.class) private Boolean over; public GameAnnotatedByJsonSerializeDeserialize() { } public GameAnnotatedByJsonSerializeDeserialize(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; }
public Boolean isPaused() { return paused; } public void setPaused(Boolean paused) { this.paused = paused; } public Boolean isOver() { return over; } public void setOver(Boolean over) { this.over = over; } }
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\booleanAsInt\GameAnnotatedByJsonSerializeDeserialize.java
1
请完成以下Java代码
public class FillRuleUtil { /** * @param ruleCode ruleCode * @return */ @SuppressWarnings("unchecked") public static Object executeRule(String ruleCode, JSONObject formData) { if (!StringUtils.isEmpty(ruleCode)) { try { // 获取 Service ServiceImpl impl = (ServiceImpl) SpringContextUtils.getBean("sysFillRuleServiceImpl"); // 根据 ruleCode 查询出实体 QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("rule_code", ruleCode); JSONObject entity = JSON.parseObject(JSON.toJSONString(impl.getOne(queryWrapper))); if (entity == null) { log.warn("填值规则:" + ruleCode + " 不存在"); return null; } // 获取必要的参数 String ruleClass = entity.getString("ruleClass"); JSONObject params = entity.getJSONObject("ruleParams"); if (params == null) { params = new JSONObject(); } HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); // 解析 params 中的变量 // 优先级:queryString > 系统变量 > 默认值 for (String key : params.keySet()) { // 1. 判断 queryString 中是否有该参数,如果有就优先取值 //noinspection ConstantValue if (request != null) {
String parameter = request.getParameter(key); if (oConvertUtils.isNotEmpty(parameter)) { params.put(key, parameter); continue; } } String value = params.getString(key); // 2. 用于替换 系统变量的值 #{sys_user_code} if (value != null && value.contains(SymbolConstant.SYS_VAR_PREFIX)) { value = QueryGenerator.getSqlRuleValue(value); params.put(key, value); } } if (formData == null) { formData = new JSONObject(); } // 通过反射执行配置的类里的方法 IFillRuleHandler ruleHandler = (IFillRuleHandler) Class.forName(ruleClass).newInstance(); return ruleHandler.execute(params, formData); } catch (Exception e) { e.printStackTrace(); } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\FillRuleUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class HUMovementGenerateRequest { @Nullable LocatorId fromLocatorId; @NonNull LocatorId toLocatorId; @Singular("huIdToMove") @NonNull ImmutableSet<HuId> huIdsToMove; @NonNull Instant movementDate; @Nullable ClientAndOrgId clientAndOrgId; @Nullable DDOrderAndLineId ddOrderLineId; @Nullable String poReference; @Nullable String description; @Nullable UserId salesRepId; // // Shipper BPartner @Nullable BPartnerLocationId bpartnerAndLocationId; @Nullable BPartnerContactId bpartnerContactId;
// // Shipper @Nullable ShipperId shipperId; @Nullable FreightCostRule freightCostRule; @Nullable BigDecimal freightAmt; // // Delivery Rules & Priority @Nullable DeliveryRule deliveryRule; @Nullable DeliveryViaRule deliveryViaRule; @Nullable String priorityRule; // // Others @Nullable Dimension dimensionFields; }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\generate\HUMovementGenerateRequest.java
2
请完成以下Java代码
private int retrieveFirstFlatrateConditionsIdForCompensationGroup(final GroupId groupId) { final Integer flatrateConditionsId = groupChangesHandler.retrieveGroupOrderLinesQuery(groupId) .addNotNull(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID) .orderBy(I_C_OrderLine.COLUMNNAME_Line) .orderBy(I_C_OrderLine.COLUMNNAME_C_OrderLine_ID) .create() .first(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID, Integer.class); return flatrateConditionsId != null && flatrateConditionsId > 0 ? flatrateConditionsId : -1; } private void setFlatrateConditionsIdToCompensationGroup(final int flatrateConditionsId, final GroupId groupId, final GroupTemplateId groupTemplateId, final int excludeOrderLineId) { groupChangesHandler.retrieveGroupOrderLinesQuery(groupId) .addNotEqualsFilter(I_C_OrderLine.COLUMN_C_OrderLine_ID, excludeOrderLineId) .addNotEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID, flatrateConditionsId > 0 ? flatrateConditionsId : null) .create() .list(I_C_OrderLine.class) .stream() .filter(ol -> !groupChangesHandler.isProductExcludedFromFlatrateConditions(groupTemplateId, ProductId.ofRepoId(ol.getM_Product_ID()))) .forEach(otherOrderLine -> { otherOrderLine.setC_Flatrate_Conditions_ID(flatrateConditionsId); DYNATTR_SkipUpdatingGroupFlatrateConditions.setValue(otherOrderLine, Boolean.TRUE); save(otherOrderLine); }); } /** * Set QtyOrderedInPriceUOM, just to make sure is up2date. */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = { de.metas.interfaces.I_C_OrderLine.COLUMNNAME_QtyEntered, de.metas.interfaces.I_C_OrderLine.COLUMNNAME_Price_UOM_ID, de.metas.interfaces.I_C_OrderLine.COLUMNNAME_C_UOM_ID, de.metas.interfaces.I_C_OrderLine.COLUMNNAME_M_Product_ID }) public void setQtyEnteredInPriceUOM(final I_C_OrderLine orderLine) { if (subscriptionBL.isSubscription(orderLine)) { final org.compiere.model.I_C_Order order = orderLine.getC_Order(); final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx()); if (soTrx.isPurchase()) { return; // leave this job to the adempiere standard callouts } subscriptionBL.updateQtysAndPrices(orderLine, soTrx, true); } else { if(!orderLine.isManualQtyInPriceUOM()) { final BigDecimal qtyEnteredInPriceUOM = orderLineBL.convertQtyEnteredToPriceUOM(orderLine).toBigDecimal(); orderLine.setQtyEnteredInPriceUOM(qtyEnteredInPriceUOM); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_OrderLine.java
1
请在Spring Boot框架中完成以下Java代码
public Attachment uploadDate(String uploadDate) { this.uploadDate = uploadDate; return this; } /** * Der Zeitstempel des Hochladens * @return uploadDate **/ @Schema(example = "2020-11-18T10:33:08.995Z", description = "Der Zeitstempel des Hochladens") public String getUploadDate() { return uploadDate; } public void setUploadDate(String uploadDate) { this.uploadDate = uploadDate; } public Attachment metadata(AttachmentMetadata metadata) { this.metadata = metadata; return this; } /** * Get metadata * @return metadata **/ @Schema(description = "") public AttachmentMetadata getMetadata() { return metadata; } public void setMetadata(AttachmentMetadata metadata) { this.metadata = metadata; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Attachment attachment = (Attachment) o; return Objects.equals(this._id, attachment._id) && Objects.equals(this.filename, attachment.filename) && Objects.equals(this.contentType, attachment.contentType) && Objects.equals(this.uploadDate, attachment.uploadDate) && Objects.equals(this.metadata, attachment.metadata); }
@Override public int hashCode() { return Objects.hash(_id, filename, contentType, uploadDate, metadata); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Attachment {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" filename: ").append(toIndentedString(filename)).append("\n"); sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); sb.append(" uploadDate: ").append(toIndentedString(uploadDate)).append("\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Attachment.java
2
请完成以下Java代码
public class InfoProductRelated implements IInfoProductDetail { private final Logger log = LogManager.getLogger(getClass()); private IMiniTable relatedTbl = null; private String m_sqlRelated; public InfoProductRelated() { initUI(); init(); } private void initUI() { MiniTable table = new MiniTable(); table.setRowSelectionAllowed(false); relatedTbl = table; } private void init() { ColumnInfo[] s_layoutRelated = new ColumnInfo[] { new ColumnInfo(Msg.translate(Env.getCtx(), "Warehouse"), "orgname", String.class), new ColumnInfo( Msg.translate(Env.getCtx(), "Value"), "(Select Value from M_Product p where p.M_Product_ID=M_PRODUCT_SUBSTITUTERELATED_V.Substitute_ID)", String.class), new ColumnInfo(Msg.translate(Env.getCtx(), "Name"), "Name", String.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyAvailable"), "QtyAvailable", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyOnHand"), "QtyOnHand", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyReserved"), "QtyReserved", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "PriceStd"), "PriceStd", Double.class) }; String s_sqlFrom = "M_PRODUCT_SUBSTITUTERELATED_V"; String s_sqlWhere = "M_Product_ID = ? AND M_PriceList_Version_ID = ? and RowType = 'R'"; m_sqlRelated = relatedTbl.prepareTable(s_layoutRelated, s_sqlFrom, s_sqlWhere, false, "M_PRODUCT_SUBSTITUTERELATED_V"); relatedTbl.setMultiSelection(false); // relatedTbl.addMouseListener(this); // relatedTbl.getSelectionModel().addListSelectionListener(this); relatedTbl.autoSize(); } private void refresh(int M_Product_ID, int M_PriceList_Version_ID) { String sql = m_sqlRelated; log.trace(sql); PreparedStatement pstmt = null; ResultSet rs = null;
try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, M_Product_ID); pstmt.setInt(2, M_PriceList_Version_ID); rs = pstmt.executeQuery(); relatedTbl.loadTable(rs); rs.close(); } catch (Exception e) { log.warn(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } public java.awt.Component getComponent() { return (java.awt.Component)relatedTbl; } @Override public void refresh(int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID) { refresh( M_Product_ID, M_PriceList_Version_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductRelated.java
1
请完成以下Java代码
public void setJobType (final @Nullable java.lang.String JobType) { set_Value (COLUMNNAME_JobType, JobType); } @Override public java.lang.String getJobType() { return get_ValueAsString(COLUMNNAME_JobType); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CRM_Occupation.java
1
请完成以下Java代码
public final Reader getCharacterStream(final int parameterIndex) throws SQLException { return getCCallableStatementImpl().getCharacterStream(parameterIndex); } @Override public final Reader getCharacterStream(final String parameterName) throws SQLException { return getCCallableStatementImpl().getCharacterStream(parameterName); } @Override public final void setBlob(final String parameterName, final Blob x) throws SQLException { getCCallableStatementImpl().setBlob(parameterName, x); } @Override public final void setClob(final String parameterName, final Clob x) throws SQLException { getCCallableStatementImpl().setClob(parameterName, x); } @Override public final void setAsciiStream(final String parameterName, final InputStream x, final long length) throws SQLException { getCCallableStatementImpl().setAsciiStream(parameterName, x, length); } @Override public final void setBinaryStream(final String parameterName, final InputStream x, final long length) throws SQLException { getCCallableStatementImpl().setBinaryStream(parameterName, x, length); } @Override public final void setCharacterStream(final String parameterName, final Reader reader, final long length) throws SQLException { getCCallableStatementImpl().setCharacterStream(parameterName, reader, length); } @Override public final void setAsciiStream(final String parameterName, final InputStream x) throws SQLException { getCCallableStatementImpl().setAsciiStream(parameterName, x); }
@Override public final void setBinaryStream(final String parameterName, final InputStream x) throws SQLException { getCCallableStatementImpl().setBinaryStream(parameterName, x); } @Override public final void setCharacterStream(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setCharacterStream(parameterName, reader); } @Override public final void setNCharacterStream(final String parameterName, final Reader value) throws SQLException { getCCallableStatementImpl().setNCharacterStream(parameterName, value); } @Override public final void setClob(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setClob(parameterName, reader); } @Override public final void setBlob(final String parameterName, final InputStream inputStream) throws SQLException { getCCallableStatementImpl().setBlob(parameterName, inputStream); } @Override public final void setNClob(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setNClob(parameterName, reader); } @Override public <T> T getObject(int parameterIndex, Class<T> type) throws SQLException { return getCCallableStatementImpl().getObject(parameterIndex, type); } @Override public <T> T getObject(String parameterName, Class<T> type) throws SQLException { return getCCallableStatementImpl().getObject(parameterName, type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CCallableStatementProxy.java
1
请完成以下Java代码
public boolean isEligibleForReview() { if (size() == 0) { return false; } final boolean allApproved = streamByIds(DocumentIdsSelection.ALL).allMatch(ProductsToPickRow::isApproved); if (allApproved) { return false; } return streamByIds(DocumentIdsSelection.ALL) .allMatch(ProductsToPickRow::isEligibleForReview); } public void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate)
{ rowsData.updateViewRowFromPickingCandidate(rowId, pickingCandidate); } public boolean isApproved() { if (size() == 0) { return false; } return streamByIds(DocumentIdsSelection.ALL) .allMatch(ProductsToPickRow::isApproved); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\ProductsToPickView.java
1
请完成以下Java代码
public class RetrieveEmailFolder { public List<String> connectToMailServer(String imapHost, String email, String password) throws Exception { Properties properties = getMailProperties(imapHost); Session session = Session.getDefaultInstance(properties); Store store = session.getStore(); store.connect(email, password); List<String> availableFolders = retrieveAvailableFoldersUsingStore(store); store.close(); return availableFolders; } Properties getMailProperties(String imapHost) { Properties properties = new Properties(); properties.put("mail.store.protocol", "imap"); properties.put("mail.imap.host", imapHost); properties.put("mail.imap.port", "993"); properties.put("mail.imap.ssl.enable", "true"); return properties; } List<String> retrieveAvailableFoldersUsingStore(Store store) throws MessagingException {
List<String> folderList = new ArrayList<>(); Folder defaultFolder = store.getDefaultFolder(); listFolders(defaultFolder, folderList); return folderList; } void listFolders(Folder folder, List<String> folderList) throws MessagingException { Folder[] subfolders = folder.list(); if (subfolders.length == 0) { folderList.add(folder.getFullName()); } else { for (Folder subfolder : subfolders) { listFolders(subfolder, folderList); } } } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\retrievemailfolder\RetrieveEmailFolder.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Node_ID. @param Node_ID Node_ID */ @Override public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_Value (COLUMNNAME_Node_ID, null); else set_Value (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ @Override public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_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_AD_TreeBar.java
1
请完成以下Java代码
public DocumentId getId() {return rowId;} @Override public boolean isProcessed() {return false;} @Nullable @Override public DocumentPath getDocumentPath() {return null;} @Override public Set<String> getFieldNames() {return values.getFieldNames();} @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() {return values.get(this);} public OIRow withSelected(final boolean selected) { return this.selected != selected ? toBuilder().selected(selected).build() : this; } public OIRow withUserInputCleared() { return this.selected ? toBuilder().selected(false).build() : this; } @Nullable public OIRowUserInputPart getUserInputPart() { if (selected)
{ return OIRowUserInputPart.builder() .rowId(rowId) .factAcctId(factAcctId) .selected(selected) .build(); } else { return null; } } public OIRow withUserInput(@Nullable final OIRowUserInputPart userInput) { final boolean selectedNew = userInput != null && userInput.isSelected(); return this.selected != selectedNew ? toBuilder().selected(selectedNew).build() : this; } public Amount getOpenAmountEffective() {return openAmount;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIRow.java
1
请完成以下Java代码
protected final <ID extends RepoIdAware> void postDependingDocuments( final String tableName, final Collection<ID> documentIds) { if (documentIds == null || documentIds.isEmpty()) { return; // nothing to do } // task 08643: the list of documentModels might originate from a bag (i.e. InArrayFilter does not filter at all when given an empty set of values). // so we assume that if there are >=200 items, it's that bug and there are not really that many documentModels. // Note: we fixed the issue in the method's current callers (Doc_InOut and Doc_Invoice). if (documentIds.size() >= 200) { final PostingException ex = newPostingException() .setDocument(this) .setDetailMessage("There are too many depending document models to post. This might be a problem in filtering (legacy-bug in InArrayFilter)."); log.warn("Got to many depending documents to post. Skip posting depending documents.", ex); return;
} final ClientId clientId = getClientId(); documentIds.stream() .map(documentId -> DocumentPostRequest.builder() .record(TableRecordReference.of(tableName, documentId)) .clientId(clientId) .build()) .collect(DocumentPostMultiRequest.collect()) .ifPresent(services::scheduleReposting); } @Nullable public String getPOReference() {return StringUtils.trimBlankToNull(getValueAsString(I_Fact_Acct.COLUMNNAME_POReference));} } // Doc
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc.java
1
请完成以下Java代码
public Collection<Object> values() { List<Object> values = new ArrayList<Object>(); for (TypedValue typedValue : outputValues.values()) { values.add(typedValue.getValue()); } return values; } @Override public String toString() { return outputValues.toString(); } @Override public boolean containsValue(Object value) { return values().contains(value); } @Override public Object get(Object key) { TypedValue typedValue = outputValues.get(key); if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void clear() { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Set<Entry<String, Object>> entrySet() { Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) { DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue()); entrySet.add(entry); } return entrySet;
} protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> { protected final String key; protected final TypedValue typedValue; public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) { this.key = key; this.typedValue = typedValue; } @Override public String getKey() { return key; } @Override public Object getValue() { if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object setValue(Object value) { throw new UnsupportedOperationException("decision output entry is immutable"); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java
1
请完成以下Java代码
public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false;
} @Override public boolean isEnabled() { return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(username, user.username); } @Override public int hashCode() { return Objects.hash(username); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\mongoauth\domain\User.java
1
请完成以下Java代码
protected String doIt() throws Exception { final IQueryFilter<I_C_Invoice_Candidate> selectedICsFilter = getProcessInfo().getQueryFilterOrElseFalse(); logger.debug("selectedICsFilter={}", selectedICsFilter); Loggables.withLogger(logger, Level.DEBUG).addLog("Processing sales order InvoiceCandidates"); final Iterator<InvoiceCandidateId> salesOrderIcIds = createInvoiceCandidateIdIterator(selectedICsFilter); final Result result = processInvoiceCandidates(salesOrderIcIds); Loggables.withLogger(logger, Level.DEBUG).addLog("Processed {} InvoiceCandidates; anyException={}", result.getCounter(), result.isAnyException()); return MSG_OK; } private Iterator<InvoiceCandidateId> createInvoiceCandidateIdIterator(@NonNull final IQueryFilter<I_C_Invoice_Candidate> selectedICsFilter) { final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = queryBL .createQueryBuilder(I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .filter(selectedICsFilter); final Iterator<InvoiceCandidateId> icIds = queryBuilder .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterateIds(InvoiceCandidateId::ofRepoId); return icIds; } private Result processInvoiceCandidates(@NonNull final Iterator<InvoiceCandidateId> invoiceCandidateIds) { int counter = 0; boolean anyException = false; while (invoiceCandidateIds.hasNext()) { final InvoiceCandidateId invoiceCandidateId = invoiceCandidateIds.next(); try (final MDCCloseable ignore = TableRecordMDC.putTableRecordReference(I_C_Invoice_Candidate.Table_Name, invoiceCandidateId)) { trxManager.runInNewTrx(() -> {
logger.debug("Processing invoiceCandidate"); final I_C_Invoice_Candidate invoiceCandidateRecord = invoiceCandDAO.getById(invoiceCandidateId); invoiceCandidateFacadeService.syncICToCommissionInstance(invoiceCandidateRecord, false/* candidateDeleted */); }); counter++; } catch (final RuntimeException e) { anyException = true; final AdIssueId adIssueId = errorManager.createIssue(e); Loggables.withLogger(logger, Level.DEBUG) .addLog("C_Invoice_Candidate_ID={}: Caught {} and created AD_Issue_ID={}; exception-message={}", invoiceCandidateId.getRepoId(), e.getClass(), adIssueId.getRepoId(), e.getLocalizedMessage()); } } return new Result(counter, anyException); } @Value private static class Result { int counter; boolean anyException; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\process\C_Invoice_Candidate_CreateOrUpdateCommissionInstance.java
1
请完成以下Java代码
public List<I_M_Package> retrievePackages(final I_M_HU hu, final String trxName) { final Properties ctx = InterfaceWrapperHelper.getCtx(hu); return queryBL.createQueryBuilder(I_M_Package_HU.class, ctx, trxName) .addEqualsFilter(I_M_Package_HU.COLUMN_M_HU_ID, hu.getM_HU_ID()) .addOnlyActiveRecordsFilter() .andCollect(I_M_Package_HU.COLUMN_M_Package_ID) .addOnlyActiveRecordsFilter() .create() .list(I_M_Package.class); } @Override public List<I_M_Package> retrievePackagesForShipment(final I_M_InOut shipment) { Check.assumeNotNull(shipment, "shipment not null"); return queryBL.createQueryBuilder(I_M_Package.class, shipment) .addEqualsFilter(org.compiere.model.I_M_Package.COLUMNNAME_M_InOut_ID, shipment.getM_InOut_ID()) .create() .list(I_M_Package.class); } @Override public Collection<PackageId> retainPackageIdsWithHUs(final Collection<PackageId> packageIds) { if (Check.isEmpty(packageIds)) { return Collections.emptyList();
} return queryBL.createQueryBuilder(I_M_Package_HU.class) .addInArrayFilter(I_M_Package_HU.COLUMNNAME_M_Package_ID, packageIds) .create() .listDistinct(I_M_Package_HU.COLUMNNAME_M_Package_ID, PackageId.class); } @Override public I_M_Package retrievePackage(final I_M_HU hu) { final List<I_M_Package> mpackages = retrievePackages(hu, ITrx.TRXNAME_ThreadInherited); if (mpackages.isEmpty()) { return null; } else if (mpackages.size() > 1) { Check.errorIf(true, HUException.class, "More than one package was found for HU." + "\n@M_HU_ID@: {}" + "\n@M_Package_ID@: {}", hu, mpackages); return mpackages.get(0); // in case the system is configured to just log } else { return mpackages.get(0); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPackageDAO.java
1
请完成以下Java代码
public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTextColor() { return textColor; } public void setTextColor(String textColor) { this.textColor = textColor; } public String getBgColor() { return bgColor; } public void setBgColor(String bgColor) { this.bgColor = bgColor; }
public String getTextSize() { return textSize; } public void setTextSize(String textSize) { this.textSize = textSize; } public String getTextWeight() { return textWeight; } public void setTextWeight(String textWeight) { this.textWeight = textWeight; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\excel\MyCell.java
1
请完成以下Java代码
public int getS_ExternalReference_ID() { return get_ValueAsInt(COLUMNNAME_S_ExternalReference_ID); } /** * Type AD_Reference_ID=541127 * Reference name: ExternalReferenceType */ public static final int TYPE_AD_Reference_ID=541127; /** UserID = UserID */ public static final String TYPE_UserID = "UserID"; /** IssueID = IssueID */ public static final String TYPE_IssueID = "IssueID"; /** Time booking ID = TimeBookingID */ public static final String TYPE_TimeBookingID = "TimeBookingID"; /** MilestoneId = MilestonId */ public static final String TYPE_MilestoneId = "MilestonId"; /** Bpartner = BPartner */ public static final String TYPE_Bpartner = "BPartner"; /** BPartnerLocation = BPartnerLocation */ public static final String TYPE_BPartnerLocation = "BPartnerLocation"; /** Product = Product */ public static final String TYPE_Product = "Product"; /** ProductCategory = ProductCategory */ public static final String TYPE_ProductCategory = "ProductCategory"; /** PriceList = PriceList */ public static final String TYPE_PriceList = "PriceList"; /** PriceListVersion = PriceListVersion */ public static final String TYPE_PriceListVersion = "PriceListVersion"; /** ProductPrice = ProductPrice */ public static final String TYPE_ProductPrice = "ProductPrice"; /** BPartnerValue = BPartnerValue */ public static final String TYPE_BPartnerValue = "BPartnerValue"; /** Shipper = Shipper */ public static final String TYPE_Shipper = "Shipper"; /** Warehouse = Warehouse */ public static final String TYPE_Warehouse = "Warehouse"; @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); } @Override public void setVersion (final @Nullable java.lang.String Version) { set_Value (COLUMNNAME_Version, Version); } @Override public java.lang.String getVersion() { return get_ValueAsString(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java-gen\de\metas\externalreference\model\X_S_ExternalReference.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } final ResourceAsPermission other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(this.name, other.name) .isEqual(); } @Override public Resource getResource()
{ return this; } @Override public boolean hasAccess(final Access access) { // TODO: return accesses.contains(access); throw new UnsupportedOperationException("Not implemented"); } @Override public Permission mergeWith(Permission accessFrom) { checkCompatibleAndCast(accessFrom); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ResourceAsPermission.java
1
请完成以下Java代码
public InfoBuilder setWhereClause(final String whereClause) { _whereClause = whereClause; return this; } public String getWhereClause() { return _whereClause; } public InfoBuilder setAttributes(final Map<String, Object> attributes) { _attributes = attributes; return this; } private Map<String, Object> getAttributes() { return _attributes; } public InfoBuilder setInfoWindow(final I_AD_InfoWindow infoWindow) { _infoWindowDef = infoWindow; if (infoWindow != null) { final String tableName = Services.get(IADInfoWindowBL.class).getTableName(infoWindow); setTableName(tableName); } return this; } private I_AD_InfoWindow getInfoWindow() { if (_infoWindowDef != null) { return _infoWindowDef; } final String tableName = getTableName(); final I_AD_InfoWindow infoWindowFound = Services.get(IADInfoWindowDAO.class).retrieveInfoWindowByTableName(getCtx(), tableName); if (infoWindowFound != null && infoWindowFound.isActive()) { return infoWindowFound; } return null; } /** * @param iconName icon name (without size and without file extension). */ public InfoBuilder setIconName(final String iconName)
{ if (Check.isEmpty(iconName, true)) { return setIcon(null); } else { final Image icon = Images.getImage2(iconName + "16"); return setIcon(icon); } } public InfoBuilder setIcon(final Image icon) { this._iconImage = icon; return this; } private Image getIconImage() { return _iconImage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoBuilder.java
1
请完成以下Java代码
public class DBRes_ja extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][]{ { "CConnectionDialog", "\u30a2\u30c7\u30f3\u30d4\u30a8\u30fc\u30ec\u306e\u63a5\u7d9a" }, { "Name", "\u540d\u524d" }, { "AppsHost", "\u30a2\u30d7\u30ea\u30b1\u30fc\u30b7\u30e7\u30f3\u30fb\u30b5\u30fc\u30d0" }, { "AppsPort", "\u30a2\u30d7\u30ea\u30b1\u30fc\u30b7\u30e7\u30f3\u30fb\u30dd\u30fc\u30c8" }, { "TestApps", "\u30a2\u30d7\u30ea\u30b1\u30fc\u30b7\u30e7\u30f3\u30fb\u30b5\u30fc\u30d0\u306e\u30c6\u30b9\u30c8" }, { "DBHost", "\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9\u30fb\u30b5\u30fc\u30d0" }, { "DBPort", "\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9\u30fb\u30dd\u30fc\u30c8" }, { "DBName", "\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9\u306e\u540d\u524d" }, { "DBUidPwd", "\u30e6\u30fc\u30b6 / \u30d1\u30b9\u30ef\u30fc\u30c9" }, { "ViaFirewall", "\u30d5\u30a1\u30a4\u30a2\u30a6\u30a9\u30fc\u30eb" }, { "FWHost", "\u30d5\u30a1\u30a4\u30a2\u30a6\u30a9\u30fc\u30eb\u30fb\u30b5\u30fc\u30d0" }, { "FWPort", "\u30d5\u30a1\u30a4\u30a2\u30a6\u30a9\u30fc\u30eb\u30fb\u30dd\u30fc\u30c8" }, { "TestConnection", "\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9\u30fb\u30b5\u30fc\u30d0\u306e\u30c6\u30b9\u30c8" }, { "Type", "\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9" }, { "BequeathConnection", "\u7d99\u627f\u63a5\u7d9a" }, { "Overwrite", "\u30aa\u30fc\u30d0\u30fc\u30e9\u30a4\u30c9" }, { "ConnectionProfile", "Connection" }, { "LAN", "LAN" },
{ "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "\u63a5\u7d9a\u30a8\u30e9\u30fc" }, { "ServerNotActive", "\u30b5\u30fc\u30d0\u30fc\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_ja.java
1
请完成以下Java代码
public void setExternalSystemValue (final java.lang.String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public java.lang.String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setIsAutoSendCustomers (final boolean IsAutoSendCustomers) { set_Value (COLUMNNAME_IsAutoSendCustomers, IsAutoSendCustomers); } @Override public boolean isAutoSendCustomers() { return get_ValueAsBoolean(COLUMNNAME_IsAutoSendCustomers); } @Override public void setIsAutoSendVendors (final boolean IsAutoSendVendors) { set_Value (COLUMNNAME_IsAutoSendVendors, IsAutoSendVendors); } @Override public boolean isAutoSendVendors() { return get_ValueAsBoolean(COLUMNNAME_IsAutoSendVendors); } @Override public void setIsCreateBPartnerFolders (final boolean IsCreateBPartnerFolders) { set_Value (COLUMNNAME_IsCreateBPartnerFolders, IsCreateBPartnerFolders); } @Override public boolean isCreateBPartnerFolders() { return get_ValueAsBoolean(COLUMNNAME_IsCreateBPartnerFolders); } @Override public void setIsSyncBPartnersToRestEndpoint (final boolean IsSyncBPartnersToRestEndpoint) { set_Value (COLUMNNAME_IsSyncBPartnersToRestEndpoint, IsSyncBPartnersToRestEndpoint); } @Override public boolean isSyncBPartnersToRestEndpoint() { return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRestEndpoint); } @Override
public void setIsSyncHUsOnMaterialReceipt (final boolean IsSyncHUsOnMaterialReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnMaterialReceipt, IsSyncHUsOnMaterialReceipt); } @Override public boolean isSyncHUsOnMaterialReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnMaterialReceipt); } @Override public void setIsSyncHUsOnProductionReceipt (final boolean IsSyncHUsOnProductionReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnProductionReceipt, IsSyncHUsOnProductionReceipt); } @Override public boolean isSyncHUsOnProductionReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnProductionReceipt); } /** * TenantId AD_Reference_ID=276 * Reference name: AD_Org (all) */ public static final int TENANTID_AD_Reference_ID=276; @Override public void setTenantId (final java.lang.String TenantId) { set_Value (COLUMNNAME_TenantId, TenantId); } @Override public java.lang.String getTenantId() { return get_ValueAsString(COLUMNNAME_TenantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_GRSSignum.java
1
请完成以下Spring Boot application配置
server.port=8085 spring.main.allow-bean-definition-overriding=true logging.level.com.baeldung.cloud.openfeign.client=INFO feign.hystrix.enabled=true feign.client.config.paymentMethodClient.readTimeout: 200 feign.client.config.paymentMethodClient.connectTime
out: 100 feign.client.config.reportClient.readTimeout: 200 feign.client.config.reportClient.connectTimeout: 100
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign-2\src\main\resources\application.properties
2
请完成以下Java代码
private ProductId getProductId(@NonNull final String productSearchKey) { final I_M_Product product = getProductNotNull(productSearchKey); return ProductId.ofRepoId(product.getM_Product_ID()); } @NonNull private I_C_UOM getStockingUOM(@NonNull final String productSearchKey) { final I_M_Product product = getProductNotNull(productSearchKey); return uomDAO.getById(UomId.ofRepoId(product.getC_UOM_ID())); } @NonNull private I_M_Product getProductNotNull(@NonNull final String productSearchKey) { final I_M_Product product = searchKey2Product.computeIfAbsent(productSearchKey, this::loadProduct); if (product == null) { throw new AdempiereException("No product could be found for the target search key!") .appendParametersToMessage() .setParameter("ProductSearchKey", productSearchKey); }
return product; } private I_M_Product loadProduct(@NonNull final String productSearchKey) { return productRepo.retrieveProductByValue(productSearchKey); } private OrgId retrieveOrgId(@NonNull final String orgCode) { final OrgQuery query = OrgQuery.builder() .orgValue(orgCode) .failIfNotExists(true) .build(); return orgDAO.retrieveOrgIdBy(query).orElseThrow(() -> new AdempiereException("No AD_Org was found for the given search key!") .appendParametersToMessage() .setParameter("OrgSearchKey", orgCode)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\CustomerReturnRestService.java
1
请完成以下Java代码
public void save(RedisIndexedSessionRepository.RedisSession session) { long expirationInMillis = getExpirationTime(session).toEpochMilli(); this.redisOps.opsForZSet().add(this.expirationsKey, session.getId(), expirationInMillis); } /** * Remove the session id from the sorted set. * @param sessionId the session id */ @Override public void remove(String sessionId) { this.redisOps.opsForZSet().remove(this.expirationsKey, sessionId); } /** * Retrieves the sessions that are expected to be expired and invoke * {@link #touch(String)} on each of the session keys, resolved via * {@link #getSessionKey(String)}. */ @Override public void cleanupExpiredSessions() { Set<Object> sessionIds = this.redisOps.opsForZSet() .reverseRangeByScore(this.expirationsKey, 0, this.clock.millis(), 0, this.cleanupCount); if (CollectionUtils.isEmpty(sessionIds)) { return; } for (Object sessionId : sessionIds) { String sessionKey = getSessionKey((String) sessionId); touch(sessionKey); } } private Instant getExpirationTime(RedisIndexedSessionRepository.RedisSession session) { return session.getLastAccessedTime().plus(session.getMaxInactiveInterval()); } /** * Checks if the session exists. By trying to access the session we only trigger a * deletion if the TTL is expired. This is done to handle * <a href="https://github.com/spring-projects/spring-session/issues/93">gh-93</a> * @param sessionKey the key */ private void touch(String sessionKey) { this.redisOps.hasKey(sessionKey); }
private String getSessionKey(String sessionId) { return this.namespace + ":sessions:" + sessionId; } /** * Set the namespace for the keys. * @param namespace the namespace */ public void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be null or empty"); this.namespace = namespace; this.expirationsKey = this.namespace + ":sessions:expirations"; } /** * Configure the clock used when retrieving expired sessions for clean-up. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } /** * Configures how many sessions will be queried at a time to be cleaned up. Defaults * to 100. * @param cleanupCount how many sessions to be queried, must be bigger than 0. */ public void setCleanupCount(int cleanupCount) { Assert.state(cleanupCount > 0, "cleanupCount must be greater than 0"); this.cleanupCount = cleanupCount; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetRedisSessionExpirationStore.java
1
请完成以下Java代码
public class UserDto1 { private long id; private String username; // constructors public UserDto1() { super(); } public UserDto1(long id, String username) { super(); this.id = id; this.username = username; } // getters and setters public long getId() { return id; } public void setId(long id) {
this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "UserDto [id=" + id + ", username=" + username + "]"; } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\relational\UserDto1.java
1
请在Spring Boot框架中完成以下Java代码
public void setTRANPORTTERMSDESC(String value) { this.tranporttermsdesc = value; } /** * Gets the value of the locationqual property. * * @return * possible object is * {@link String } * */ public String getLOCATIONQUAL() { return locationqual; } /** * Sets the value of the locationqual property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONQUAL(String value) { this.locationqual = value; } /** * Gets the value of the locationcode property. * * @return * possible object is * {@link String } * */ public String getLOCATIONCODE() { return locationcode; } /** * Sets the value of the locationcode property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONCODE(String value) { this.locationcode = value; }
/** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the locationdate property. * * @return * possible object is * {@link String } * */ public String getLOCATIONDATE() { return locationdate; } /** * Sets the value of the locationdate property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONDATE(String value) { this.locationdate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HTRSC1.java
2
请完成以下Java代码
class M_CostType { private final IAcctSchemaDAO acctSchemaDAO; public M_CostType(@NonNull final IAcctSchemaDAO acctSchemaDAO) { this.acctSchemaDAO = acctSchemaDAO; } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void beforeSave(final I_M_CostType costType) { costType.setAD_Org_ID(OrgId.ANY.getRepoId()); }
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_M_CostType costType) { final CostTypeId costTypeId = CostTypeId.ofRepoId(costType.getM_CostType_ID()); final ClientId clientId = ClientId.ofRepoId(costType.getAD_Client_ID()); for (final AcctSchema as : acctSchemaDAO.getAllByClient(clientId)) { if (CostTypeId.equals(as.getCosting().getCostTypeId(), costTypeId)) { throw new AdempiereException("Cannot delete cost type `" + costType.getName() + "` because accounting schema `" + as.getName() + "` it's still using it"); } } } // beforeDelete }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\interceptors\M_CostType.java
1
请完成以下Java代码
public boolean isExpired() { return this.reason == Reason.EXPIRED; } /** * True if no {@link FactorGrantedAuthority#getAuthority()} on the * {@link org.springframework.security.core.Authentication} matched * {@link RequiredFactor#getAuthority()}. * @return true if missing, else false. */ public boolean isMissing() { return this.reason == Reason.MISSING; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } RequiredFactorError that = (RequiredFactorError) o; return Objects.equals(this.requiredFactor, that.requiredFactor) && this.reason == that.reason; } @Override public int hashCode() { return Objects.hash(this.requiredFactor, this.reason); } @Override public String toString() { return "RequiredFactorError{" + "requiredFactor=" + this.requiredFactor + ", reason=" + this.reason + '}'; } public static RequiredFactorError createMissing(RequiredFactor requiredFactor) { return new RequiredFactorError(requiredFactor, Reason.MISSING); } public static RequiredFactorError createExpired(RequiredFactor requiredFactor) { return new RequiredFactorError(requiredFactor, Reason.EXPIRED);
} /** * The reason that the error occurred. * * @author Rob Winch * @since 7.0 */ private enum Reason { /** * The authority was missing. * @see #isMissing() */ MISSING, /** * The authority was considered expired. * @see #isExpired() */ EXPIRED } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\RequiredFactorError.java
1
请完成以下Java代码
public Balance computeDiffToBalance() { final Money diff = toMoney(); if (isReversal()) { return diff.signum() < 0 ? ofCredit(diff) : ofDebit(diff.negate()); } else { return diff.signum() < 0 ? ofDebit(diff.negate()) : ofCredit(diff); } } public Balance invert() { return new Balance(this.credit, this.debit); } // // // // // @ToString private static class BalanceBuilder { private Money debit; private Money credit; public void add(@NonNull Balance balance) { add(balance.getDebit(), balance.getCredit()); } public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder) { add(balanceBuilder.debit, balanceBuilder.credit); return this; }
public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd) { if (debitToAdd != null) { this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd; } if (creditToAdd != null) { this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd; } } public Optional<Balance> build() { return debit != null || credit != null ? Optional.of(new Balance(debit, credit)) : Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java
1
请在Spring Boot框架中完成以下Java代码
protected String doIt() { final HUEditorRow row = getSingleSelectedRow(); final HUsToReturnViewContext viewContext = getHUsToReturnViewContext(); final HuId huId = row.getHuId(); final InOutId customerReturnsId = viewContext.getCustomerReturnsId(); if (isValidHuForInOut(customerReturnsId, huId)) { repairCustomerReturnsService.prepareCloneHUAndCreateCustomerReturnLine() .customerReturnId(customerReturnsId) .productId(row.getProductId()) .qtyReturned(row.getQtyCUAsQuantity()) .cloneFromHuId(huId) .build();
} getResult().setCloseWebuiModalView(true); getView().removeHUIdsAndInvalidate(ImmutableList.of(huId)); return MSG_OK; } private boolean isValidHuForInOut(final InOutId inOutId, final HuId huId) { return repairCustomerReturnsService.isValidHuForInOut(inOutId, huId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\HUsToReturn_SelectHU.java
2
请在Spring Boot框架中完成以下Java代码
public static class Event { String id; EventType type; EventStatus status; /** * e.g. 2024-10-05T12:48:34.312Z */ String timestamp; BigDecimal amount; @JsonProperty("fee_amount") BigDecimal fee_amount; // other fields: // "deducted_amount": 0.0, // "deducted_fee_amount": 0.0, // "transaction_id": "1a434bf8-bd5c-44a6-8576-37bc9aedc912", // "installment_number": 1, // "payout_reference": "SUMUP PID", @JsonIgnore public boolean isRefunded() { return EventType.equals(type, EventType.REFUND) && EventStatus.equals(status, EventStatus.REFUNDED); } @JsonIgnore
public BigDecimal getAmountPlusFee() { BigDecimal result = BigDecimal.ZERO; if (amount != null) { result = result.add(amount); } if (amount != null) { result = result.add(fee_amount); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\json\JsonGetTransactionResponse.java
2
请在Spring Boot框架中完成以下Java代码
private LocatorId getDropToLocatorId() { if (dropToQRCode == null) { return null; } LocatorId dropToLocatorId = this._dropToLocatorId; if (dropToLocatorId == null) { dropToLocatorId = this._dropToLocatorId = warehouseService.resolveLocator(dropToQRCode).getLocatorId(); } return dropToLocatorId; } private ImmutableList<DistributionJob> updateJobsFromSchedules(final List<DistributionJob> jobs, final ImmutableList<DDOrderMoveSchedule> schedules) { final ImmutableMap<DistributionJobStepId, DDOrderMoveSchedule> schedulesByStepId = Maps.uniqueIndex(schedules, schedule -> DistributionJobStepId.ofScheduleId(schedule.getId())); return jobs.stream() .map(job -> updateJob(job, schedulesByStepId)) .collect(ImmutableList.toImmutableList()); } private DistributionJob updateJob(final DistributionJob job, final ImmutableMap<DistributionJobStepId, DDOrderMoveSchedule> schedulesByStepId) { return job.withChangedSteps(step -> { final DDOrderMoveSchedule schedule = schedulesByStepId.get(step.getId()); return schedule != null ? DistributionJobLoader.toDistributionJobStep(schedule, loadingSupportServices) : step; }); }
private List<DistributionJob> tryCompleteJobsIfFullyMoved(@NonNull final List<DistributionJob> jobs) { return jobs.stream() .map(this::completeJobIfFullyMoved) .collect(ImmutableList.toImmutableList()); } private DistributionJob completeJobIfFullyMoved(@NonNull final DistributionJob job) { if (!job.isFullyMoved()) { return job; } return distributionJobService.complete(job); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\commands\drop_to\DistributionJobDropToCommand.java
2
请完成以下Java代码
void start() { this.handler.initializeHandler(); this.webServer.start(); this.applicationContext .publishEvent(new ReactiveWebServerInitializedEvent(this.webServer, this.applicationContext)); } void shutDownGracefully(GracefulShutdownCallback callback) { this.webServer.shutDownGracefully(callback); } void stop() { this.webServer.stop(); } WebServer getWebServer() { return this.webServer; } HttpHandler getHandler() { return this.handler; } /** * A delayed {@link HttpHandler} that doesn't initialize things too early. */ static final class DelayedInitializationHttpHandler implements HttpHandler { private final Supplier<HttpHandler> handlerSupplier; private final boolean lazyInit; private volatile HttpHandler delegate = this::handleUninitialized; private DelayedInitializationHttpHandler(Supplier<HttpHandler> handlerSupplier, boolean lazyInit) { this.handlerSupplier = handlerSupplier; this.lazyInit = lazyInit; }
private Mono<Void> handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) { throw new IllegalStateException("The HttpHandler has not yet been initialized"); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.handle(request, response); } void initializeHandler() { this.delegate = this.lazyInit ? new LazyHttpHandler(this.handlerSupplier) : this.handlerSupplier.get(); } HttpHandler getHandler() { return this.delegate; } } /** * {@link HttpHandler} that initializes its delegate on first request. */ private static final class LazyHttpHandler implements HttpHandler { private final Mono<HttpHandler> delegate; private LazyHttpHandler(Supplier<HttpHandler> handlerSupplier) { this.delegate = Mono.fromSupplier(handlerSupplier); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.flatMap((handler) -> handler.handle(request, response)); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerManager.java
1
请在Spring Boot框架中完成以下Java代码
public String getDATEQUAL() { return datequal; } /** * Sets the value of the datequal property. * * @param value * allowed object is * {@link String } * */ public void setDATEQUAL(String value) { this.datequal = value; } /** * Gets the value of the datefrom property. * * @return * possible object is * {@link String } * */ public String getDATEFROM() { return datefrom; } /** * Sets the value of the datefrom property. * * @param value * allowed object is * {@link String } * */ public void setDATEFROM(String value) { this.datefrom = value; } /** * Gets the value of the dateto property. * * @return * possible object is * {@link String } * */ public String getDATETO() { return dateto; } /** * Sets the value of the dateto property. * * @param value * allowed object is * {@link String } * */ public void setDATETO(String value) {
this.dateto = value; } /** * Gets the value of the days property. * * @return * possible object is * {@link String } * */ public String getDAYS() { return days; } /** * Sets the value of the days property. * * @param value * allowed object is * {@link String } * */ public void setDAYS(String value) { this.days = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DDATE1.java
2
请完成以下Java代码
public Integer getId() { return id; } public UserDO setId(Integer id) { this.id = id; return this; } public String getUsername() { return username; } public UserDO setUsername(String username) { this.username = username; return this; } public String getPassword() { return password; } public UserDO setPassword(String password) { this.password = password; return this; } public Date getCreateTime() { return createTime; } public UserDO setCreateTime(Date createTime) { this.createTime = createTime;
return this; } public Integer getDeleted() { return deleted; } public UserDO setDeleted(Integer deleted) { this.deleted = deleted; return this; } @Override public String toString() { return "UserDO{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", createTime=" + createTime + ", deleted=" + deleted + '}'; } }
repos\SpringBoot-Labs-master\lab-21\lab-21-cache-redis\src\main\java\cn\iocoder\springboot\lab21\cache\dataobject\UserDO.java
1
请完成以下Java代码
private CommissionPoints computeCustomerBasedCPointsPerUnit( @NonNull final CommissionPoints commissionPointsBase, @NonNull final Quantity totalQtyInvolved, @NonNull final Integer pointsPrecision) { final BigDecimal customerPricePerQty = commissionPointsBase.toBigDecimal() .divide(totalQtyInvolved.toBigDecimal(), pointsPrecision, RoundingMode.HALF_UP); return CommissionPoints.of(customerPricePerQty); } @NonNull private CommissionPoints computeSalesRepBasedCPointsPerUnit( @NonNull final CommissionTriggerData commissionTriggerData, @NonNull final CommissionShare share) { final ComputeSalesRepPriceRequest request = ComputeSalesRepPriceRequest.builder() .salesRepId(share.getBeneficiary().getBPartnerId()) .soTrx(SOTrx.SALES)
.productId(commissionTriggerData.getProductId()) .qty(commissionTriggerData.getTotalQtyInvolved()) .customerCurrencyId(commissionTriggerData.getDocumentCurrencyId()) .commissionDate(commissionTriggerData.getTriggerDocumentDate()) .build(); final ProductPrice salesRepNetUnitPrice = customerTradeMarginService.calculateSalesRepNetUnitPrice(request) .orElseThrow(() -> new AdempiereException("No price found for SalesRepPricingResultRequest: " + request)); Check.assume(salesRepNetUnitPrice.getCurrencyId().equals(commissionTriggerData.getDocumentCurrencyId()), "salesRepNetUnitPrice.currencyId={} is in the commissionTriggerDocument.DocumentCurrencyId; commissionTriggerDocument={}", CurrencyId.toRepoId(salesRepNetUnitPrice.getCurrencyId()), commissionTriggerData); Check.assume(salesRepNetUnitPrice.getUomId().equals(commissionTriggerData.getTotalQtyInvolved().getUomId()), "salesRepNetUnitPrice.uomId={} is in the commissionTriggerDocument.totalQtyInvolved.uomId; commissionTriggerDocument={}", UomId.toRepoId(salesRepNetUnitPrice.getUomId()), commissionTriggerData); return CommissionPoints.of(salesRepNetUnitPrice.toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\margin\MarginAlgorithm.java
1
请完成以下Java代码
public class LoopDiagonally { public String loopDiagonally(String[][] twoDArray) { int length = twoDArray.length; int diagonalLines = (length + length) - 1; int itemsInDiagonal = 0; int midPoint = (diagonalLines / 2) + 1; StringBuilder output = new StringBuilder(); for (int i = 1; i <= diagonalLines; i++) { StringBuilder items = new StringBuilder(); int rowIndex; int columnIndex; if (i <= midPoint) { itemsInDiagonal++; for (int j = 0; j < itemsInDiagonal; j++) { rowIndex = (i - j) - 1;
columnIndex = j; items.append(twoDArray[rowIndex][columnIndex]); } } else { itemsInDiagonal--; for (int j = 0; j < itemsInDiagonal; j++) { rowIndex = (length - 1) - j; columnIndex = (i - length) + j; items.append(twoDArray[rowIndex][columnIndex]); } } if (i != diagonalLines) { output.append(items).append(" "); } else { output.append(items); } } return output.toString(); } }
repos\tutorials-master\core-java-modules\core-java-arrays-multidimensional\src\main\java\com\baeldung\array\looping\LoopDiagonally.java
1
请在Spring Boot框架中完成以下Java代码
public class EventDescriptor { @NonNull String eventId; @NonNull ClientAndOrgId clientAndOrgId; @NonNull UserId userId; @Nullable String traceId; public static EventDescriptor ofClientAndOrg(final int adClientId, final int adOrgId) { return ofClientOrgAndTraceId(ClientAndOrgId.ofClientAndOrg(adClientId, adOrgId), null); } public static EventDescriptor ofClientAndOrg(@NonNull final ClientId adClientId, @NonNull final OrgId adOrgId) { return ofClientOrgAndTraceId(ClientAndOrgId.ofClientAndOrg(adClientId, adOrgId), null); } public static EventDescriptor ofClientAndOrg(@NonNull final ClientAndOrgId clientAndOrgId) { return ofClientOrgAndTraceId(clientAndOrgId, null); } public static EventDescriptor ofClientOrgAndUserId(@NonNull final ClientAndOrgId clientAndOrgId, @NonNull final UserId userId) { return ofClientOrgUserIdAndTraceId(clientAndOrgId, userId, null); } public static EventDescriptor ofClientOrgAndTraceId(@NonNull final ClientAndOrgId clientAndOrgId, @Nullable final String traceId) { return ofClientOrgUserIdAndTraceId( clientAndOrgId, Env.getLoggedUserIdIfExists().orElse(UserId.SYSTEM), traceId); } public static EventDescriptor ofClientOrgUserIdAndTraceId( @NonNull final ClientAndOrgId clientAndOrgId, @NonNull final UserId userId, @Nullable final String traceId) { return builder() .eventId(newEventId()) .clientAndOrgId(clientAndOrgId) .userId(userId) .traceId(traceId) .build(); } private static String newEventId() { return UUID.randomUUID().toString(); } public ClientId getClientId()
{ return getClientAndOrgId().getClientId(); } public OrgId getOrgId() { return getClientAndOrgId().getOrgId(); } @NonNull public EventDescriptor withNewEventId() { return toBuilder() .eventId(newEventId()) .build(); } @NonNull public EventDescriptor withClientAndOrg(@NonNull final ClientAndOrgId clientAndOrgId) { return toBuilder() .clientAndOrgId(clientAndOrgId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\EventDescriptor.java
2
请完成以下Java代码
public HUPPOrderIssueProducer targetOrderBOMLine(@NonNull final PPOrderBOMLineId targetOrderBOMLineId) { final I_PP_Order_BOMLine targetOrderBOMLine = ppOrderBOMsRepo.getOrderBOMLineById(targetOrderBOMLineId); return targetOrderBOMLine(targetOrderBOMLine); } public HUPPOrderIssueProducer fixedQtyToIssue(@Nullable final Quantity fixedQtyToIssue) { this.fixedQtyToIssue = fixedQtyToIssue; return this; } public HUPPOrderIssueProducer considerIssueMethodForQtyToIssueCalculation(final boolean considerIssueMethodForQtyToIssueCalculation) { this.considerIssueMethodForQtyToIssueCalculation = considerIssueMethodForQtyToIssueCalculation; return this; } public HUPPOrderIssueProducer processCandidates(@NonNull final ProcessIssueCandidatesPolicy processCandidatesPolicy) { this.processCandidatesPolicy = processCandidatesPolicy; return this; } private boolean isProcessCandidates() { final ProcessIssueCandidatesPolicy processCandidatesPolicy = this.processCandidatesPolicy; if (ProcessIssueCandidatesPolicy.NEVER.equals(processCandidatesPolicy)) { return false; } else if (ProcessIssueCandidatesPolicy.ALWAYS.equals(processCandidatesPolicy)) { return true; } else if (ProcessIssueCandidatesPolicy.IF_ORDER_PLANNING_STATUS_IS_COMPLETE.equals(processCandidatesPolicy)) { final I_PP_Order ppOrder = getPpOrder();
final PPOrderPlanningStatus orderPlanningStatus = PPOrderPlanningStatus.ofCode(ppOrder.getPlanningStatus()); return PPOrderPlanningStatus.COMPLETE.equals(orderPlanningStatus); } else { throw new AdempiereException("Unknown processCandidatesPolicy: " + processCandidatesPolicy); } } public HUPPOrderIssueProducer changeHUStatusToIssued(final boolean changeHUStatusToIssued) { this.changeHUStatusToIssued = changeHUStatusToIssued; return this; } public HUPPOrderIssueProducer generatedBy(final IssueCandidateGeneratedBy generatedBy) { this.generatedBy = generatedBy; return this; } public HUPPOrderIssueProducer failIfIssueOnlyForReceived(final boolean fail) { this.failIfIssueOnlyForReceived = fail; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueProducer.java
1
请完成以下Java代码
private WeightingSpecifications getWeightSpecificationsAndUpdateIfNotSet(final I_PP_Order_Weighting_Run weightingRun) { final WeightingSpecificationsId currentWeightingSpecificationsId = WeightingSpecificationsId.ofRepoIdOrNull(weightingRun.getPP_Weighting_Spec_ID()); if (currentWeightingSpecificationsId != null) { return weightingSpecificationsRepository.getById(currentWeightingSpecificationsId); } else { final WeightingSpecificationsId weightingSpecificationsId = weightingSpecificationsRepository.getDefaultId(); weightingRun.setPP_Weighting_Spec_ID(weightingSpecificationsId.getRepoId()); return updateFromCurrentWeightSpecifications(weightingRun) .orElseThrow(() -> new AdempiereException("No weight specifications found")); // shall not happen } } private Optional<WeightingSpecifications> updateFromCurrentWeightSpecifications(final I_PP_Order_Weighting_Run weightingRun) { final WeightingSpecificationsId weightingSpecificationsId = WeightingSpecificationsId.ofRepoIdOrNull(weightingRun.getPP_Weighting_Spec_ID()); if (weightingSpecificationsId == null) { return Optional.empty();
} else { final WeightingSpecifications weightingSpecifications = weightingSpecificationsRepository.getById(weightingSpecificationsId); weightingRun.setC_UOM_ID(weightingSpecifications.getUomId().getRepoId()); weightingRun.setTolerance_Perc(weightingSpecifications.getTolerance().toBigDecimal()); weightingRun.setWeightChecksRequired(weightingSpecifications.getWeightChecksRequired()); updateFromPPOrderIfSet(weightingRun, false); return Optional.of(weightingSpecifications); } } @CalloutMethod(columnNames = I_PP_Order_Weighting_Run.COLUMNNAME_PP_Weighting_Spec_ID) public void onPP_Weighting_Spec_ID(final I_PP_Order_Weighting_Run weightingRun) { updateFromCurrentWeightSpecifications(weightingRun); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\callout\PP_Order_Weighting_Run.java
1
请完成以下Java代码
protected ObjectNode createOrGetBpmnNode(ObjectNode infoNode) { if (!infoNode.has(BPMN_NODE)) { infoNode.putObject(BPMN_NODE); } return (ObjectNode) infoNode.get(BPMN_NODE); } protected ObjectNode getBpmnNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(BPMN_NODE); } protected void setLocalizationProperty( String language, String id, String propertyName, String propertyValue, ObjectNode infoNode ) { ObjectNode localizationNode = createOrGetLocalizationNode(infoNode); if (!localizationNode.has(language)) { localizationNode.putObject(language); }
ObjectNode languageNode = (ObjectNode) localizationNode.get(language); if (!languageNode.has(id)) { languageNode.putObject(id); } ((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue); } protected ObjectNode createOrGetLocalizationNode(ObjectNode infoNode) { if (!infoNode.has(LOCALIZATION_NODE)) { infoNode.putObject(LOCALIZATION_NODE); } return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } protected ObjectNode getLocalizationNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DynamicBpmnServiceImpl.java
1
请完成以下Java代码
public @NonNull String getHandledTableName() { return I_M_InOut.Table_Name; } @Override public StandardDocumentReportType getStandardDocumentReportType() { return StandardDocumentReportType.SHIPMENT; } @Override public @NonNull DocumentReportInfo getDocumentReportInfo( @NonNull final TableRecordReference recordRef, @Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse) { final InOutId inoutId = recordRef.getIdAssumingTableName(I_M_InOut.Table_Name, InOutId::ofRepoId); final I_M_InOut inout = inoutBL.getById(inoutId); final BPartnerId bpartnerId = BPartnerId.ofRepoId(inout.getC_BPartner_ID()); final I_C_BPartner bpartner = util.getBPartnerById(bpartnerId); final DocTypeId docTypeId = extractDocTypeId(inout); final I_C_DocType docType = util.getDocTypeById(docTypeId); final ClientId clientId = ClientId.ofRepoId(inout.getAD_Client_ID()); final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers( () -> adPrintFormatToUseId, () -> util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null), () -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()), () -> util.getDefaultPrintFormats(clientId).getShipmentPrintFormatId()); if (printFormatId == null) { throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@"); } final Language language = util.getBPartnerLanguage(bpartner).orElse(null); final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder() .adTableId(recordRef.getAdTableId()) .bpartnerId(bpartnerId) .bPartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, inout.getC_BPartner_Location_ID())) .docTypeId(docTypeId) .onlyCopiesGreaterZero(true) .build();
return DocumentReportInfo.builder() .recordRef(TableRecordReference.of(I_M_InOut.Table_Name, inoutId)) .reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId)) .copies(util.getDocumentCopies(docType, bpPrintFormatQuery)) .documentNo(inout.getDocumentNo()) .bpartnerId(bpartnerId) .docTypeId(docTypeId) .language(language) .poReference(inout.getPOReference()) .build(); } private DocTypeId extractDocTypeId(@NonNull final I_M_InOut inout) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(inout.getC_DocType_ID()); if (docTypeId != null) { return docTypeId; } else { throw new AdempiereException("No document type set"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\InOutDocumentReportAdvisor.java
1
请完成以下Java代码
private static final class AttributeListValueMap { public static AttributeListValueMap ofList(final List<AttributeListValue> list) { if (list.isEmpty()) { return EMPTY; } return new AttributeListValueMap(list); } private static final AttributeListValueMap EMPTY = new AttributeListValueMap(); private final ImmutableMap<String, AttributeListValue> map; private AttributeListValueMap() { map = ImmutableMap.of(); } private AttributeListValueMap(@NonNull final List<AttributeListValue> list) { map = Maps.uniqueIndex(list, AttributeListValue::getValue); } public List<AttributeListValue> toList() { return ImmutableList.copyOf(map.values()); }
@Nullable public AttributeListValue getByIdOrNull(@NonNull final AttributeValueId id) { return map.values() .stream() .filter(av -> AttributeValueId.equals(av.getId(), id)) .findFirst() .orElse(null); } public AttributeListValue getByValueOrNull(final String value) { return map.get(value); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDAO.java
1
请完成以下Java代码
public List<MetricIntervalValue> interval() { callback = new MetricsQueryIntervalCmd(this); return (List<MetricIntervalValue>) commandExecutor.execute(this); } @Override public List<MetricIntervalValue> interval(long interval) { this.interval = interval; return interval(); } public long sum() { callback = new MetricsQuerySumCmd(this); return (Long) commandExecutor.execute(this); } @Override public Object execute(CommandContext commandContext) { if (callback != null) { return callback.execute(commandContext); } throw new ProcessEngineException("Query can't be executed. Use either sum or interval to query the metrics."); } @Override public MetricsQuery offset(int offset) { setFirstResult(offset); return this; } @Override public MetricsQuery limit(int maxResults) { setMaxResults(maxResults); return this; } @Override public MetricsQuery aggregateByReporter() { aggregateByReporter = true; return this; } @Override public void setMaxResults(int maxResults) { if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) { throw new ProcessEngineException("Metrics interval query row limit can't be set larger than " + DEFAULT_LIMIT_SELECT_INTERVAL + '.'); } this.maxResults = maxResults; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public Long getStartDateMilliseconds() { return startDateMilliseconds; } public Long getEndDateMilliseconds() { return endDateMilliseconds; } public String getName() { return name; } public String getReporter() { return reporter; } public Long getInterval() { if (interval == null) { return DEFAULT_SELECT_INTERVAL; }
return interval; } @Override public int getMaxResults() { if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) { return DEFAULT_LIMIT_SELECT_INTERVAL; } return super.getMaxResults(); } protected class MetricsQueryIntervalCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectInterval(metricsQuery); } } protected class MetricsQuerySumCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectSum(metricsQuery); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java
1
请完成以下Java代码
public class GetRenderedTaskFormCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected String formEngineName; public GetRenderedTaskFormCmd(String taskId, String formEngineName) { this.taskId = taskId; this.formEngineName = formEngineName; } public Object execute(CommandContext commandContext) { TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull("Task '" + taskId + "' not found", "task", task); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadTaskVariable(task);
} ensureNotNull("Task form definition for '" + taskId + "' not found", "task.getTaskDefinition()", task.getTaskDefinition()); TaskFormHandler taskFormHandler = task.getTaskDefinition().getTaskFormHandler(); if (taskFormHandler == null) { return null; } FormEngine formEngine = Context .getProcessEngineConfiguration() .getFormEngines() .get(formEngineName); ensureNotNull("No formEngine '" + formEngineName + "' defined process engine configuration", "formEngine", formEngine); TaskFormData taskForm = taskFormHandler.createTaskForm(task); return formEngine.renderTaskForm(taskForm); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetRenderedTaskFormCmd.java
1
请完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public List<Role> getAuthorities() { return authorities; } public void setAuthorities(List<Role> authorities) { this.authorities = authorities; } /** * 用户账号是否过期 */ @Override public boolean isAccountNonExpired() {
return true; } /** * 用户账号是否被锁定 */ @Override public boolean isAccountNonLocked() { return true; } /** * 用户密码是否过期 */ @Override public boolean isCredentialsNonExpired() { return true; } /** * 用户是否可用 */ @Override public boolean isEnabled() { return true; } }
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\entity\User.java
1
请在Spring Boot框架中完成以下Java代码
static class PropagationWithBaggage { private final TracingProperties tracingProperties; PropagationWithBaggage(TracingProperties tracingProperties) { this.tracingProperties = tracingProperties; } @Bean @ConditionalOnEnabledTracingExport TextMapPropagator textMapPropagatorWithBaggage(OtelCurrentTraceContext otelCurrentTraceContext) { List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields(); List<String> tagFields = this.tracingProperties.getBaggage().getTagFields(); BaggageTextMapPropagator baggagePropagator = new BaggageTextMapPropagator(remoteFields, new OtelBaggageManager(otelCurrentTraceContext, remoteFields, tagFields)); return CompositeTextMapPropagator.create(this.tracingProperties.getPropagation(), baggagePropagator); } @Bean @ConditionalOnMissingBean @ConditionalOnBooleanProperty(name = "management.tracing.baggage.correlation.enabled", matchIfMissing = true) Slf4JBaggageEventListener otelSlf4JBaggageEventListener() {
return new Slf4JBaggageEventListener(this.tracingProperties.getBaggage().getCorrelation().getFields()); } } /** * Propagates neither traces nor baggage. */ @Configuration(proxyBeanMethods = false) static class NoPropagation { @Bean @ConditionalOnMissingBean TextMapPropagator noopTextMapPropagator() { return TextMapPropagator.noop(); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryPropagationConfigurations.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String[] getAllExclude() { List<String> allExclude = new ArrayList<>(); if (StringUtils.hasText(this.exclude)) { allExclude.addAll(StringUtils.commaDelimitedListToSet(this.exclude)); } if (StringUtils.hasText(this.additionalExclude)) { allExclude.addAll(StringUtils.commaDelimitedListToSet(this.additionalExclude)); } return StringUtils.toStringArray(allExclude); } public String getExclude() { return this.exclude; } public void setExclude(String exclude) { this.exclude = exclude; } public @Nullable String getAdditionalExclude() { return this.additionalExclude; } public void setAdditionalExclude(@Nullable String additionalExclude) { this.additionalExclude = additionalExclude; } public Duration getPollInterval() { return this.pollInterval; } public void setPollInterval(Duration pollInterval) { this.pollInterval = pollInterval; } public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } public @Nullable String getTriggerFile() { return this.triggerFile; } public void setTriggerFile(@Nullable String triggerFile) { this.triggerFile = triggerFile; } public List<File> getAdditionalPaths() { return this.additionalPaths; } public void setAdditionalPaths(List<File> additionalPaths) { this.additionalPaths = additionalPaths; }
public boolean isLogConditionEvaluationDelta() { return this.logConditionEvaluationDelta; } public void setLogConditionEvaluationDelta(boolean logConditionEvaluationDelta) { this.logConditionEvaluationDelta = logConditionEvaluationDelta; } } /** * LiveReload properties. */ public static class Livereload { /** * Whether to enable a livereload.com-compatible server. */ private boolean enabled; /** * Server port. */ private int port = 35729; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
2
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList("languageServiceEndpoint", "defaultLanguage"); } @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { return client.get() .uri(config.getLanguageServiceEndpoint()) .exchange() .flatMap(response -> { return (response.statusCode() .is2xxSuccessful()) ? response.bodyToMono(String.class) : Mono.just(config.getDefaultLanguage()); }) .map(LanguageRange::parse) .map(range -> { exchange.getRequest() .mutate() .headers(h -> h.setAcceptLanguage(range)); String allOutgoingRequestLanguages = exchange.getRequest() .getHeaders() .getAcceptLanguage() .stream() .map(r -> r.getRange()) .collect(Collectors.joining(",")); logger.info("Chain Request output - Request contains Accept-Language header: " + allOutgoingRequestLanguages); return exchange; }) .flatMap(chain::filter); }; } public static class Config { private String languageServiceEndpoint; private String defaultLanguage; public Config() { }
public String getLanguageServiceEndpoint() { return languageServiceEndpoint; } public void setLanguageServiceEndpoint(String languageServiceEndpoint) { this.languageServiceEndpoint = languageServiceEndpoint; } public String getDefaultLanguage() { return defaultLanguage; } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ChainRequestGatewayFilterFactory.java
1
请完成以下Java代码
public Map<DocumentId, PaymentToReconcileRow> getDocumentId2TopLevelRows() { return rowsHolder.getDocumentId2TopLevelRows(); } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(TableRecordReferenceSet recordRefs) { return recordRefs.streamIds(I_C_Payment.Table_Name, PaymentId::ofRepoId) .map(PaymentToReconcileRow::convertPaymentIdToDocumentId) .filter(rowsHolder.isRelevantForRefreshingByDocumentId()) .collect(DocumentIdsSelection.toDocumentIdsSelection()); } @Override
public void invalidateAll() { invalidate(DocumentIdsSelection.ALL); } @Override public void invalidate(final DocumentIdsSelection rowIds) { final ImmutableSet<PaymentId> paymentIds = rowsHolder .getRecordIdsToRefresh(rowIds, PaymentToReconcileRow::convertDocumentIdToPaymentId); final List<PaymentToReconcileRow> newRows = repository.getPaymentToReconcileRowsByIds(paymentIds); rowsHolder.compute(rows -> rows.replacingRows(rowIds, newRows)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentToReconcileRows.java
1
请完成以下Java代码
private static boolean isEmptyPOFieldValue(final Object value) { if (value == null) { return true; } else if (value instanceof String) { return ((String)value).isEmpty(); } else { return false; } } private IQueryBuilder<Object> toQueryBuilder(final SqlDocumentEntityDataBindingDescriptor dataBinding, final DocumentId documentId) { final String tableName = dataBinding.getTableName(); final List<SqlDocumentFieldDataBindingDescriptor> keyFields = dataBinding.getKeyFields(); final int keyFieldsCount = keyFields.size(); if (keyFieldsCount == 0) { throw new AdempiereException("No primary key defined for " + tableName); } final List<Object> keyParts = documentId.toComposedKeyParts(); if (keyFieldsCount != keyParts.size()) { throw new AdempiereException("Invalid documentId '" + documentId + "'. It shall have " + keyFieldsCount + " parts but it has " + keyParts.size()); } final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(tableName, PlainContextAware.newWithThreadInheritedTrx()); for (int i = 0; i < keyFieldsCount; i++) { final SqlDocumentFieldDataBindingDescriptor keyField = keyFields.get(i); final String keyColumnName = keyField.getColumnName(); final Object keyValue = convertToPOValue(keyParts.get(i), keyColumnName, keyField.getWidgetType(), keyField.getSqlValueClass()); queryBuilder.addEqualsFilter(keyColumnName, keyValue); } return queryBuilder; } private static TableRecordReference extractRootRecordReference(final Document includedDocument) { if (includedDocument.isRootDocument()) { return null; } final Document rootDocument = includedDocument.getRootDocument(); final String rootTableName = rootDocument.getEntityDescriptor().getTableNameOrNull(); if (rootTableName == null) { return null; } final int rootRecordId = rootDocument.getDocumentId().toIntOr(-1); if (rootRecordId < 0) { return null;
} return TableRecordReference.of(rootTableName, rootRecordId); } private static DocumentId extractDocumentId(final PO po, SqlDocumentEntityDataBindingDescriptor dataBinding) { if (dataBinding.isSingleKey()) { return DocumentId.of(InterfaceWrapperHelper.getId(po)); } else { final List<SqlDocumentFieldDataBindingDescriptor> keyFields = dataBinding.getKeyFields(); if (keyFields.isEmpty()) { throw new AdempiereException("No primary key defined for " + dataBinding.getTableName()); } final List<Object> keyParts = keyFields.stream() .map(keyField -> po.get_Value(keyField.getColumnName())) .collect(ImmutableList.toImmutableList()); return DocumentId.ofComposedKeyParts(keyParts); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\save\DefaultSaveHandler.java
1
请完成以下Java代码
public class M_Attribute extends CalloutEngine { public String onSetADJavaClass(final Properties ctx, final int WindowNo, final GridTab mTab, final GridField mField, final Object value, final Object oldValue) { final I_M_Attribute attribute = InterfaceWrapperHelper.create(mTab, I_M_Attribute.class); final IAttributeValueGenerator handler = Services.get(IAttributesBL.class).getAttributeValueGeneratorOrNull(attribute); // // Set M_Attribute.AttributeValueType from handler if (handler != null) { final String attributeValueType = attribute.getAttributeValueType(); if (X_M_Attribute.ATTRIBUTEVALUETYPE_List.equals(attributeValueType)) { // NOTE: handler it's allowed to have only String or Number value types (because it's items can be only of those values) // but we are dealing with a list, so don't change it
} else { // Update Attribute's value type from generator final String valueType = handler.getAttributeValueType(); if(valueType != null) { attribute.setAttributeValueType(valueType); } } } return NO_ERROR; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\callout\M_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2022-02-18T14:17:41.660Z[GMT]")public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). * * @param array The array * @param value The value to search * @return true if the array contains the value */ public static boolean containsIgnoreCase(String[] array, String value) { for (String str : array) { if (value == null && str == null) return true; if (value != null && value.equalsIgnoreCase(str)) return true; } return false; } /** * Join an array of strings with the given separator. * <p> * Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency. * </p> * * @param array The array of strings * @param separator The separator * @return the resulting string */ public static String join(String[] array, String separator) { int len = array.length; if (len == 0) return ""; StringBuilder out = new StringBuilder(); out.append(array[0]); for (int i = 1; i < len; i++) { out.append(separator).append(array[i]); } return out.toString(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\StringUtil.java
2
请完成以下Java代码
public class AttachmentEntity implements Attachment, PersistentObject, HasRevision, Serializable { private static final long serialVersionUID = 1L; protected String id; protected int revision; protected String name; protected String description; protected String type; protected String taskId; protected String processInstanceId; protected String url; protected String contentId; protected ByteArrayEntity content; protected String userId; protected Date time; public AttachmentEntity() { } @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("name", name); persistentState.put("description", description); return persistentState; } @Override public int getRevisionNext() { return revision + 1; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public String getType() { return type; }
public void setType(String type) { this.type = type; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public ByteArrayEntity getContent() { return content; } public void setContent(ByteArrayEntity content) { this.content = content; } public void setUserId(String userId) { this.userId = userId; } @Override public String getUserId() { return userId; } @Override public Date getTime() { return time; } @Override public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntity.java
1
请完成以下Java代码
public List<I_C_Period> retrievePeriods( final Properties ctx, final I_C_Year year, final String trxName) { return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName) .setParameters(year.getC_Year_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Period.COLUMNNAME_StartDate) .list(I_C_Period.class); } @Override protected List<I_C_Period> retrievePeriods( final Properties ctx, final int calendarId, final Timestamp begin, final Timestamp end, final String trxName) { Check.assume(begin != null, "Param 'begin' is not null"); Check.assume(end != null, "Param 'end' is not null"); final String wc = I_C_Period.COLUMNNAME_C_Year_ID + " IN (" + " select " + I_C_Year.COLUMNNAME_C_Year_ID + " from " + I_C_Year.Table_Name + " where " + I_C_Year.COLUMNNAME_C_Calendar_ID + "=?" + ") AND " + I_C_Period.COLUMNNAME_EndDate + ">=? AND " + I_C_Period.COLUMNNAME_StartDate + "<=?"; return new Query(ctx, I_C_Period.Table_Name, wc, trxName) .setParameters(calendarId, begin, end) .setOnlyActiveRecords(true) .setClient_ID() // .setApplyAccessFilter(true) isn't required here and case cause problems when running from ad_scheduler .setOrderBy(I_C_Period.COLUMNNAME_StartDate) .list(I_C_Period.class); } @Override public List<I_C_Year> retrieveYearsOfCalendar(final I_C_Calendar calendar) { final Properties ctx = InterfaceWrapperHelper.getCtx(calendar); final String trxName = InterfaceWrapperHelper.getTrxName(calendar); final String whereClause = I_C_Year.COLUMNNAME_C_Calendar_ID + "=?"; return new Query(ctx, I_C_Year.Table_Name, whereClause, trxName) .setParameters(calendar.getC_Calendar_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Year.COLUMNNAME_C_Year_ID)
.list(I_C_Year.class); } @Override public I_C_Period retrieveFirstPeriodOfTheYear(final I_C_Year year) { final Properties ctx = InterfaceWrapperHelper.getCtx(year); final String trxName = InterfaceWrapperHelper.getTrxName(year); return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName) .setParameters(year.getC_Year_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Period.COLUMNNAME_StartDate) .first(I_C_Period.class); } @Override public I_C_Period retrieveLastPeriodOfTheYear(final I_C_Year year) { final Properties ctx = InterfaceWrapperHelper.getCtx(year); final String trxName = InterfaceWrapperHelper.getTrxName(year); return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName) .setParameters(year.getC_Year_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Period.COLUMNNAME_StartDate + " DESC ") .first(I_C_Period.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\CalendarDAO.java
1
请在Spring Boot框架中完成以下Java代码
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 boolean rollback() { throw new UnsupportedOperationException(); } @Override public boolean rollback(final boolean throwException) throws SQLException { throw new UnsupportedOperationException(); } @Override public boolean rollback(final ITrxSavepoint savepoint) throws DBException { throw new UnsupportedOperationException(); } @Override public ITrxSavepoint createTrxSavepoint(final String name) throws DBException { throw new UnsupportedOperationException(); } @Override public void releaseSavepoint(final ITrxSavepoint savepoint) { throw new UnsupportedOperationException(); } @Override public ITrxListenerManager getTrxListenerManager() { throw new UnsupportedOperationException(); } @Override public ITrxManager getTrxManager() { throw new UnsupportedOperationException(); } @Override public <T> T setProperty(final String name, final Object value)
{ throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name, final Supplier<T> valueInitializer) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer) { throw new UnsupportedOperationException(); } @Override public <T> T setAndGetProperty(final String name, final Function<T, T> valueRemappingFunction) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\NullTrxPlaceholder.java
1
请在Spring Boot框架中完成以下Java代码
public JAXBElement<Integer> createSignatureCheck(Integer value) { return new JAXBElement<Integer>(_SignatureCheck_QNAME, Integer.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Integer }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Integer }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/messaging/header", name = "SignatureManifestCheck") public JAXBElement<Integer> createSignatureManifestCheck(Integer value) { return new JAXBElement<Integer>(_SignatureManifestCheck_QNAME, Integer.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SignatureVerificationResultType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link SignatureVerificationResultType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/messaging/header", name = "SignatureVerificationResult") public JAXBElement<SignatureVerificationResultType> createSignatureVerificationResult(SignatureVerificationResultType value) { return new JAXBElement<SignatureVerificationResultType>(_SignatureVerificationResult_QNAME, SignatureVerificationResultType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SignatureVerificationType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link SignatureVerificationType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/messaging/header", name = "SignatureVerification")
public JAXBElement<SignatureVerificationType> createSignatureVerification(SignatureVerificationType value) { return new JAXBElement<SignatureVerificationType>(_SignatureVerification_QNAME, SignatureVerificationType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link String }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/messaging/header", name = "SignatureVerificationOmittedErrorCode") public JAXBElement<String> createSignatureVerificationOmittedErrorCode(String value) { return new JAXBElement<String>(_SignatureVerificationOmittedErrorCode_QNAME, String.class, null, value); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\ObjectFactory.java
2
请完成以下Java代码
public void setR_IssueStatus_ID (int R_IssueStatus_ID) { if (R_IssueStatus_ID < 1) set_Value (COLUMNNAME_R_IssueStatus_ID, null); else set_Value (COLUMNNAME_R_IssueStatus_ID, Integer.valueOf(R_IssueStatus_ID)); } /** Get Issue Status. @return Status of an Issue */ public int getR_IssueStatus_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueStatus_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_Request getR_Request() throws RuntimeException { return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name) .getPO(getR_Request_ID(), get_TrxName()); } /** Set Request. @param R_Request_ID Request from a Business Partner or Prospect */ public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Request. @return Request from a Business Partner or Prospect */ public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Source Class. @param SourceClassName Source Class Name */
public void setSourceClassName (String SourceClassName) { set_Value (COLUMNNAME_SourceClassName, SourceClassName); } /** Get Source Class. @return Source Class Name */ public String getSourceClassName () { return (String)get_Value(COLUMNNAME_SourceClassName); } /** Set Source Method. @param SourceMethodName Source Method Name */ public void setSourceMethodName (String SourceMethodName) { set_Value (COLUMNNAME_SourceMethodName, SourceMethodName); } /** Get Source Method. @return Source Method Name */ public String getSourceMethodName () { return (String)get_Value(COLUMNNAME_SourceMethodName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueKnown.java
1
请在Spring Boot框架中完成以下Java代码
public static class Sequences { @NonNull SimpleSequence packSeqNoSequence; @NonNull SimpleSequence packItemLineSequence; } /** * All that's needed to create with a pack-request that includes a pack-item-request or just a single pack-item-request. */ @Value @RequiredArgsConstructor public static class RequestParameters { @NonNull HU topLevelHU; @NonNull BPartnerId bPartnerId; @NonNull StockQtyAndUOMQty quantity; @NonNull ProductId productId; @NonNull
I_EDI_DesadvLine desadvLineRecord; @NonNull I_M_InOutLine inOutLineRecord; @NonNull DesadvLineWithDraftedPackItems desadvLineWithPacks; @NonNull InvoicableQtyBasedOn invoicableQtyBasedOn; @Nullable BigDecimal uomToStockRatio; @NonNull SimpleSequence packSeqNoSequence; @NonNull SimpleSequence packItemLineSequence; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPackService.java
2
请完成以下Java代码
public Builder addColumn(final List<DocumentLayoutElementDescriptor.Builder> elementsBuilders) { if (elementsBuilders == null || elementsBuilders.isEmpty()) { return this; } final DocumentLayoutElementGroupDescriptor.Builder elementsGroupBuilder = DocumentLayoutElementGroupDescriptor.builder(); elementsBuilders.stream() .map(elementBuilder -> DocumentLayoutElementLineDescriptor.builder().addElement(elementBuilder)) .forEach(elementLineBuilder -> elementsGroupBuilder.addElementLine(elementLineBuilder)); final DocumentLayoutColumnDescriptor.Builder column = DocumentLayoutColumnDescriptor.builder().addElementGroup(elementsGroupBuilder); addColumn(column); return this; } public Builder setInvalid(final String invalidReason) { Check.assumeNotEmpty(invalidReason, "invalidReason is not empty"); this.invalidReason = invalidReason; logger.trace("Layout section was marked as invalid: {}", this); return this; } public Builder setClosableMode(@NonNull final ClosableMode closableMode) { this.closableMode = closableMode; return this; } public Builder setCaptionMode(@NonNull final CaptionMode captionMode) { this.captionMode = captionMode; return this;
} public boolean isValid() { return invalidReason == null; } public boolean isInvalid() { return invalidReason != null; } public boolean isNotEmpty() { return streamElementBuilders().findAny().isPresent(); } private Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return columnsBuilders.stream().flatMap(DocumentLayoutColumnDescriptor.Builder::streamElementBuilders); } public Builder setExcludeSpecialFields() { streamElementBuilders().forEach(elementBuilder -> elementBuilder.setExcludeSpecialFields()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSectionDescriptor.java
1
请完成以下Java代码
private static ProductsProposalRow reduceUserRequest(final ProductsProposalRow row, final UserChange request) { final ProductsProposalRowBuilder newRowBuilder = row.toBuilder(); if (request.getQty() != null) { newRowBuilder.qty(request.getQty().orElse(null)); } if (request.getPrice() != null) { if (!row.isPriceEditable()) { throw new AdempiereException("Price is not editable") .setParameter("row", row); } final BigDecimal newUserEnteredPriceValue = request.getPrice().orElse(BigDecimal.ZERO); final ProductProposalPrice newPrice = row.getPrice().withUserEnteredPriceValue(newUserEnteredPriceValue); newRowBuilder.price(newPrice); } if (request.getDescription() != null) {
newRowBuilder.description(request.getDescription().orElse(null)); } return newRowBuilder.build(); } private static ProductsProposalRow reduceRowUpdate(final ProductsProposalRow row, final RowUpdate request) { return row.toBuilder() .price(request.getPrice()) .lastShipmentDays(request.getLastShipmentDays()) .copiedFromProductPriceId(request.getCopiedFromProductPriceId()) .build(); } private static ProductsProposalRow reduceRowSaved(final ProductsProposalRow row, final RowSaved request) { return row.toBuilder() .productPriceId(request.getProductPriceId()) .price(request.getPrice()) .copiedFromProductPriceId(null) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowReducers.java
1