instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private final void clearQueuedEvents() { queuedEvents.clear(); } private final List<Event> getQueuedEventsAndClear() { if (queuedEvents.isEmpty()) { return Collections.emptyList(); } final List<Event> copy = new ArrayList<>(queuedEvents); queuedEvents.clear(); return copy; } /** * Post all queued events. */ public final void flush() { final List<Event> queuedEventsList = getQueuedEventsAndClear(); logger.debug("flush - posting {} queued events to event bus; this={}", queuedEventsList.size(), this);
for (final Event event : queuedEventsList) { super.processEvent(event); } } @Override public String toString() { final Topic topic = getTopic(); return MoreObjects.toStringHelper(this) .omitNullValues() .add("topicName", topic.getName()) .add("type", topic.getType()) .add("destroyed", isDestroyed() ? Boolean.TRUE : null) .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\QueueableForwardingEventBus.java
1
请完成以下Java代码
public boolean lock() { return po.lock(); // lock } /** * UnLock it * @return true if unlocked (false only if unlock fails) */ public boolean unlock(String trxName) { return po.unlock(trxName); // unlock } /** * Set Trx * @param trxName transaction
*/ public void set_TrxName(String trxName) { po.set_TrxName(trxName); // setTrx } /** * Get Trx * @return transaction */ public String get_TrxName() { return po.get_TrxName(); // getTrx } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
1
请在Spring Boot框架中完成以下Java代码
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 Optional<I_C_UOM> getByX12DE355IfExists(@NonNull final X12DE355 x12de355) { return getUomIdByX12DE355IfExists(x12de355) .map(this::getById); } @Override public I_C_UOM getEachUOM() { return getByX12DE355(X12DE355.EACH); } @Override public TemporalUnit getTemporalUnitByUomId(@NonNull final UomId uomId) { final I_C_UOM uom = getById(uomId); return UOMUtil.toTemporalUnit(uom); } @Override public I_C_UOM getByTemporalUnit(@NonNull final TemporalUnit temporalUnit) { final UomId uomId = getUomIdByTemporalUnit(temporalUnit); return getById(uomId); } @Override public UomId getUomIdByTemporalUnit(@NonNull final TemporalUnit temporalUnit) { final X12DE355 x12de355 = X12DE355.ofTemporalUnit(temporalUnit); try { return getUomIdByX12DE355(x12de355); } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex) .setParameter("temporalUnit", temporalUnit) .setParameter("x12de355", x12de355) .setParameter("Suggestion", "Create an UOM for that X12DE355 code or activate it if already exists.") .appendParametersToMessage(); } } @Override public UOMPrecision getStandardPrecision(final UomId uomId) { if (uomId == null) { // NOTE: if there is no UOM specified, we assume UOM is Each => precision=0 return UOMPrecision.ZERO; } final I_C_UOM uom = getById(uomId); return UOMPrecision.ofInt(uom.getStdPrecision()); } @Override
public boolean isUOMForTUs(@NonNull final UomId uomId) { final I_C_UOM uom = getById(uomId); return isUOMForTUs(uom); } public static boolean isUOMForTUs(@NonNull final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355()); return X12DE355.COLI.equals(x12de355) || X12DE355.TU.equals(x12de355); } @Override public @NonNull UOMType getUOMTypeById(@NonNull final UomId uomId) { final I_C_UOM uom = getById(uomId); return UOMType.ofNullableCodeOrOther(uom.getUOMType()); } @Override public @NonNull Optional<I_C_UOM> getBySymbol(@NonNull final String uomSymbol) { return Optional.ofNullable(queryBL.createQueryBuilder(I_C_UOM.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_UOM.COLUMNNAME_UOMSymbol, uomSymbol) .create() .firstOnlyOrNull(I_C_UOM.class)); } @Override public ITranslatableString getUOMSymbolById(@NonNull final UomId uomId) { final I_C_UOM uom = getById(uomId); return InterfaceWrapperHelper.getModelTranslationMap(uom).getColumnTrl(I_C_UOM.COLUMNNAME_UOMSymbol, uom.getUOMSymbol()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMDAO.java
1
请完成以下Java代码
private ImmutableList<DocumentFilterDescriptor> getFilters() { if (filters == null || filters.isEmpty()) { return ImmutableList.of(); } else { return filters.stream() .sorted(Comparator.comparing(DocumentFilterDescriptor::getSortNo)) .collect(ImmutableList.toImmutableList()); } } public Builder setFilters(final Collection<DocumentFilterDescriptor> filters) { this.filters = filters; return this; } public Builder addFilter(@NonNull final DocumentFilterDescriptor filter) { if (filters == null) { filters = new ArrayList<>(); } filters.add(filter); return this; } private DocumentQueryOrderByList getDefaultOrderBys() { return defaultOrderBys != null ? defaultOrderBys : DocumentQueryOrderByList.EMPTY; } public Builder setDefaultOrderBys(final DocumentQueryOrderByList defaultOrderBys) { this.defaultOrderBys = defaultOrderBys; return this; } public Set<String> getFieldNames() { return elementBuilders .stream() .flatMap(element -> element.getFieldNames().stream()) .collect(GuavaCollectors.toImmutableSet()); } public Builder setIdFieldName(final String idFieldName) { this.idFieldName = idFieldName; return this; } private String getIdFieldName() { return idFieldName; } public Builder setHasAttributesSupport(final boolean hasAttributesSupport) { this.hasAttributesSupport = hasAttributesSupport; return this; } public Builder setIncludedViewLayout(final IncludedViewLayout includedViewLayout) { this.includedViewLayout = includedViewLayout; return this; } public Builder clearViewCloseActions() { allowedViewCloseActions = new LinkedHashSet<>(); return this; } public Builder allowViewCloseAction(@NonNull final ViewCloseAction viewCloseAction) { if (allowedViewCloseActions == null) { allowedViewCloseActions = new LinkedHashSet<>();
} allowedViewCloseActions.add(viewCloseAction); return this; } private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions() { return allowedViewCloseActions != null ? ImmutableSet.copyOf(allowedViewCloseActions) : DEFAULT_allowedViewCloseActions; } public Builder setHasTreeSupport(final boolean hasTreeSupport) { this.hasTreeSupport = hasTreeSupport; return this; } public Builder setTreeCollapsible(final boolean treeCollapsible) { this.treeCollapsible = treeCollapsible; return this; } public Builder setTreeExpandedDepth(final int treeExpandedDepth) { this.treeExpandedDepth = treeExpandedDepth; return this; } public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails) { this.allowOpeningRowDetails = allowOpeningRowDetails; return this; } public Builder setFocusOnFieldName(final String focusOnFieldName) { this.focusOnFieldName = focusOnFieldName; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java
1
请完成以下Java代码
public void setC_DocType_ID (final int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID); } @Override public int getC_DocType_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_ID); } @Override public void setDocumentCopies_Override (final int DocumentCopies_Override) { set_Value (COLUMNNAME_DocumentCopies_Override, DocumentCopies_Override); } @Override public int getDocumentCopies_Override() {
return get_ValueAsInt(COLUMNNAME_DocumentCopies_Override); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_PrintFormat.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentReservationId implements RepoIdAware { @JsonCreator public static PaymentReservationId ofRepoId(final int repoId) { return new PaymentReservationId(repoId); } public static PaymentReservationId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PaymentReservationId(repoId) : null; } public static int toRepoId(final PaymentReservationId id) { return id != null ? id.getRepoId() : -1; }
int repoId; private PaymentReservationId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Payment_Reservation_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationId.java
2
请完成以下Java代码
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerScope(ProcessScope.PROCESS_SCOPE_NAME, this); Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory, "BeanFactory was not a BeanDefinitionRegistry, so ProcessScope cannot be used."); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition definition = beanFactory.getBeanDefinition(beanName); // Replace this or any of its inner beans with scoped proxy if it has this scope boolean scoped = PROCESS_SCOPE_NAME.equals(definition.getScope()); Scopifier scopifier = new Scopifier(registry, PROCESS_SCOPE_NAME, proxyTargetClass, scoped); scopifier.visitBeanDefinition(definition); if (scoped) { Scopifier.createScopedProxy(beanName, definition, registry, proxyTargetClass); } } beanFactory.registerSingleton(ProcessScope.PROCESS_SCOPE_PROCESS_VARIABLES_SINGLETON, this.processVariablesMap); beanFactory.registerResolvableDependency(ProcessInstance.class, createSharedProcessInstance()); } public void destroy() throws Exception { logger.info(ProcessScope.class.getName() + "#destroy() called ..."); } public void afterPropertiesSet() throws Exception { Assert.notNull(this.processEngine, "the 'processEngine' must not be null!"); this.runtimeService = this.processEngine.getRuntimeService(); } private Object createDirtyCheckingProxy(final String name, final Object scopedObject) throws Throwable { ProxyFactory proxyFactoryBean = new ProxyFactory(scopedObject); proxyFactoryBean.setProxyTargetClass(this.proxyTargetClass); proxyFactoryBean.addAdvice(new MethodInterceptor() { public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object result = methodInvocation.proceed(); persistVariable(name, scopedObject); return result; } }); return proxyFactoryBean.getProxy(this.classLoader); } private void persistVariable(String variableName, Object scopedObject) { ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance(); ExecutionEntity executionEntity = (ExecutionEntity) processInstance; Assert.isTrue(scopedObject instanceof Serializable, "the scopedObject is not " + Serializable.class.getName() + "!"); executionEntity.setVariable(variableName, scopedObject); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\scope\ProcessScope.java
1
请在Spring Boot框架中完成以下Java代码
public int updateNewStatus(List<Long> ids, Integer newStatus) { PmsProduct record = new PmsProduct(); record.setNewStatus(newStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); return productMapper.updateByExampleSelective(record, example); } @Override public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) { PmsProduct record = new PmsProduct(); record.setDeleteStatus(deleteStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); return productMapper.updateByExampleSelective(record, example); } @Override public List<PmsProduct> list(String keyword) { PmsProductExample productExample = new PmsProductExample(); PmsProductExample.Criteria criteria = productExample.createCriteria(); criteria.andDeleteStatusEqualTo(0); if(!StrUtil.isEmpty(keyword)){ criteria.andNameLike("%" + keyword + "%"); productExample.or().andDeleteStatusEqualTo(0).andProductSnLike("%" + keyword + "%"); } return productMapper.selectByExample(productExample); }
/** * 建立和插入关系表操作 * * @param dao 可以操作的dao * @param dataList 要插入的数据 * @param productId 建立关系的id */ private void relateAndInsertList(Object dao, List dataList, Long productId) { try { if (CollectionUtils.isEmpty(dataList)) return; for (Object item : dataList) { Method setId = item.getClass().getMethod("setId", Long.class); setId.invoke(item, (Long) null); Method setProductId = item.getClass().getMethod("setProductId", Long.class); setProductId.invoke(item, productId); } Method insertList = dao.getClass().getMethod("insertList", List.class); insertList.invoke(dao, dataList); } catch (Exception e) { LOGGER.warn("创建商品出错:{}", e.getMessage()); throw new RuntimeException(e.getMessage()); } } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductServiceImpl.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; }
public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Transient public double getDiscounted() { return discounted; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", price=" + price + ", discounted=" + discounted + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCalculatePropertyFormula\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
public List<HistoricJobLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsByQueryCriteria(this, page); } // getter ////////////////////////////////// public boolean isTenantIdSet() { return isTenantIdSet; } public String getJobId() { return jobId; } public String getJobExceptionMessage() { return jobExceptionMessage; } public String getJobDefinitionId() { return jobDefinitionId; } public String getJobDefinitionType() { return jobDefinitionType; } public String getJobDefinitionConfiguration() { return jobDefinitionConfiguration; } public String[] getActivityIds() { return activityIds; } public String[] getFailedActivityIds() { return failedActivityIds; } public String[] getExecutionIds() { return executionIds; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() {
return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() { return state; } public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请完成以下Spring Boot application配置
spring: profiles: active: prod datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/dbgirl?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 usern
ame: root password: 123 jpa: hibernate: ddl-auto: create show-sql: true
repos\SpringBootLearning-master\firstspringboot-2h\src\main\resources\application.yml
2
请完成以下Java代码
public static String processStatements (String sqlStatements, boolean allowDML) { if (sqlStatements == null || sqlStatements.length() == 0) return ""; StringBuffer result = new StringBuffer(); // StringTokenizer st = new StringTokenizer(sqlStatements, ";", false); while (st.hasMoreTokens()) { result.append(processStatement(st.nextToken(), allowDML)); result.append(Env.NL); } // return result.toString(); } // processStatements /** * Process SQL Statements * @param sqlStatement one statement * @param allowDML allow DML statements * @return result */ public static String processStatement (String sqlStatement, boolean allowDML) { if (sqlStatement == null) return ""; StringBuffer sb = new StringBuffer(); char[] chars = sqlStatement.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isWhitespace(c)) sb.append(' '); else sb.append(c); } String sql = sb.toString().trim(); if (sql.length() == 0) return ""; // StringBuffer result = new StringBuffer("SQL> ") .append(sql) .append(Env.NL); if (!allowDML) { boolean error = false; String SQL = sql.toUpperCase(); for (int i = 0; i < DML_KEYWORDS.length; i++) { if (SQL.startsWith(DML_KEYWORDS[i] + " ") || SQL.indexOf(" " + DML_KEYWORDS[i] + " ") != -1 || SQL.indexOf("(" + DML_KEYWORDS[i] + " ") != -1) { result.append("===> ERROR: Not Allowed Keyword ") .append(DML_KEYWORDS[i]) .append(Env.NL); error = true; } } if (error) return result.toString(); } // !allowDML // Process Connection conn = DB.createConnection(true, Connection.TRANSACTION_READ_COMMITTED); Statement stmt = null; try { stmt = conn.createStatement();
boolean OK = stmt.execute(sql); int count = stmt.getUpdateCount(); if (count == -1) { result.append("---> ResultSet"); } else result.append("---> Result=").append(count); } catch (SQLException e) { log.error("process statement: " + sql + " - " + e.toString()); result.append("===> ").append(e.toString()); } // Clean up try { stmt.close(); } catch (SQLException e1) { log.error("processStatement - close statement", e1); } stmt = null; try { conn.close(); } catch (SQLException e2) { log.error("processStatement - close connection", e2); } conn = null; // result.append(Env.NL); return result.toString(); } // processStatement } // VSQLProcess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VSQLProcess.java
1
请完成以下Java代码
public final C_AllocationLine_Builder invoiceId(@Nullable final InvoiceId invoiceId) { return invoiceId(InvoiceId.toRepoId(invoiceId)); } public final C_AllocationLine_Builder invoiceId(final int invoiceId) { allocLine.setC_Invoice_ID(invoiceId); return this; } public final C_AllocationLine_Builder paymentId(@Nullable final PaymentId paymentId) { return paymentId(PaymentId.toRepoId(paymentId)); } public final C_AllocationLine_Builder paymentId(final int paymentId) { allocLine.setC_Payment_ID(paymentId); return this; } public final C_AllocationLine_Builder amount(final BigDecimal amt) { allocLine.setAmount(amt); return this; } public final C_AllocationLine_Builder discountAmt(final BigDecimal discountAmt) { allocLine.setDiscountAmt(discountAmt); return this; } public final C_AllocationLine_Builder writeOffAmt(final BigDecimal writeOffAmt) { allocLine.setWriteOffAmt(writeOffAmt); return this; } public final C_AllocationLine_Builder overUnderAmt(final BigDecimal overUnderAmt) { allocLine.setOverUnderAmt(overUnderAmt); return this; } public C_AllocationLine_Builder paymentWriteOffAmt(final BigDecimal paymentWriteOffAmt) { allocLine.setPaymentWriteOffAmt(paymentWriteOffAmt); return this; } public final C_AllocationLine_Builder skipIfAllAmountsAreZero() { this.skipIfAllAmountsAreZero = true; return this; } private boolean isSkipBecauseAllAmountsAreZero() { if (!skipIfAllAmountsAreZero) { return false; }
// NOTE: don't check the OverUnderAmt because that amount is not affecting allocation, // so an allocation is Zero with our without the over/under amount. return allocLine.getAmount().signum() == 0 && allocLine.getDiscountAmt().signum() == 0 && allocLine.getWriteOffAmt().signum() == 0 // && allocLine.getPaymentWriteOffAmt().signum() == 0; } public final C_AllocationHdr_Builder lineDone() { return parent; } /** * @param allocHdrSupplier allocation header supplier which will provide the allocation header created & saved, just in time, so call it ONLY if you are really gonna create an allocation line. * @return created {@link I_C_AllocationLine} or <code>null</code> if it was not needed. */ @Nullable final I_C_AllocationLine create(@NonNull final Supplier<I_C_AllocationHdr> allocHdrSupplier) { if (isSkipBecauseAllAmountsAreZero()) { return null; } // // Get the allocation header, created & saved. final I_C_AllocationHdr allocHdr = allocHdrSupplier.get(); Check.assumeNotNull(allocHdr, "Param 'allocHdr' not null"); Check.assume(allocHdr.getC_AllocationHdr_ID() > 0, "Param 'allocHdr' has C_AllocationHdr_ID>0"); allocLine.setC_AllocationHdr(allocHdr); allocLine.setAD_Org_ID(allocHdr.getAD_Org_ID()); allocationDAO.save(allocLine); return allocLine; } public final C_AllocationHdr_Builder getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\C_AllocationLine_Builder.java
1
请完成以下Java代码
protected void exceptionRejectedTakeBuffer(RingBuffer ringBuffer) { LOGGER.warn("Rejected take buffer. {}", ringBuffer); throw new RuntimeException("Rejected take buffer. " + ringBuffer); } /** * Initialize flags as CAN_PUT_FLAG */ private PaddedAtomicLong[] initFlags(int bufferSize) { PaddedAtomicLong[] flags = new PaddedAtomicLong[bufferSize]; for (int i = 0; i < bufferSize; i++) { flags[i] = new PaddedAtomicLong(CAN_PUT_FLAG); } return flags; } /** * Getters */ public long getTail() { return tail.get(); } public long getCursor() { return cursor.get(); } public int getBufferSize() { return bufferSize; }
/** * Setters */ public void setBufferPaddingExecutor(BufferPaddingExecutor bufferPaddingExecutor) { this.bufferPaddingExecutor = bufferPaddingExecutor; } public void setRejectedPutHandler(RejectedPutBufferHandler rejectedPutHandler) { this.rejectedPutHandler = rejectedPutHandler; } public void setRejectedTakeHandler(RejectedTakeBufferHandler rejectedTakeHandler) { this.rejectedTakeHandler = rejectedTakeHandler; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("RingBuffer [bufferSize=").append(bufferSize) .append(", tail=").append(tail) .append(", cursor=").append(cursor) .append(", paddingThreshold=").append(paddingThreshold).append("]"); return builder.toString(); } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\buffer\RingBuffer.java
1
请在Spring Boot框架中完成以下Java代码
public CmmnDeploymentBuilder disableSchemaValidation() { this.isCmmn20XsdValidationEnabled = false; return this; } @Override public CmmnDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } @Override public CmmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public CmmnDeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this;
} @Override public CmmnDeployment deploy() { return repositoryService.deploy(this); } public CmmnDeploymentEntity getDeployment() { return deployment; } public boolean isCmmnXsdValidationEnabled() { return isCmmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentBuilderImpl.java
2
请完成以下Java代码
public ResponseEntity updateProfile(@AuthenticationPrincipal User currentUser, @RequestHeader("Authorization") String token, @Valid @RequestBody UpdateUserParam updateUserParam, BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new InvalidRequestException(bindingResult); } checkUniquenessOfUsernameAndEmail(currentUser, updateUserParam, bindingResult); currentUser.update( updateUserParam.getEmail(), updateUserParam.getUsername(), updateUserParam.getPassword(), updateUserParam.getBio(), updateUserParam.getImage()); userRepository.save(currentUser); UserData userData = userQueryService.findById(currentUser.getId()).get(); return ResponseEntity.ok(userResponse( new UserWithToken(userData, token.split(" ")[1]) )); } private void checkUniquenessOfUsernameAndEmail(User currentUser, UpdateUserParam updateUserParam, BindingResult bindingResult) { if (!"".equals(updateUserParam.getUsername())) { Optional<User> byUsername = userRepository.findByUsername(updateUserParam.getUsername()); if (byUsername.isPresent() && !byUsername.get().equals(currentUser)) { bindingResult.rejectValue("username", "DUPLICATED", "username already exist"); } } if (!"".equals(updateUserParam.getEmail())) { Optional<User> byEmail = userRepository.findByEmail(updateUserParam.getEmail()); if (byEmail.isPresent() && !byEmail.get().equals(currentUser)) { bindingResult.rejectValue("email", "DUPLICATED", "email already exist"); } } if (bindingResult.hasErrors()) { throw new InvalidRequestException(bindingResult);
} } private Map<String, Object> userResponse(UserWithToken userWithToken) { return new HashMap<String, Object>() {{ put("user", userWithToken); }}; } } @Getter @JsonRootName("user") @NoArgsConstructor class UpdateUserParam { @Email(message = "should be an email") private String email = ""; private String password = ""; private String username = ""; private String bio = ""; private String image = ""; }
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\CurrentUserApi.java
1
请完成以下Java代码
public static <T extends AuthenticatorResponse> PublicKeyCredentialBuilder<T> builder() { return new PublicKeyCredentialBuilder<>(); } /** * The {@link PublicKeyCredentialBuilder} * * @param <R> the response type * @author Rob Winch * @since 6.4 */ public static final class PublicKeyCredentialBuilder<R extends AuthenticatorResponse> { @SuppressWarnings("NullAway.Init") private String id; private @Nullable PublicKeyCredentialType type; @SuppressWarnings("NullAway.Init") private Bytes rawId; @SuppressWarnings("NullAway.Init") private R response; private @Nullable AuthenticatorAttachment authenticatorAttachment; private @Nullable AuthenticationExtensionsClientOutputs clientExtensionResults; private PublicKeyCredentialBuilder() { } /** * Sets the {@link #getId()} property * @param id the id * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder id(String id) { this.id = id; return this; } /** * Sets the {@link #getType()} property. * @param type the type * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder type(PublicKeyCredentialType type) { this.type = type; return this; } /** * Sets the {@link #getRawId()} property. * @param rawId the raw id * @return the PublicKeyCredentialBuilder
*/ public PublicKeyCredentialBuilder rawId(Bytes rawId) { this.rawId = rawId; return this; } /** * Sets the {@link #getResponse()} property. * @param response the response * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder response(R response) { this.response = response; return this; } /** * Sets the {@link #getAuthenticatorAttachment()} property. * @param authenticatorAttachment the authenticator attachement * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder authenticatorAttachment(AuthenticatorAttachment authenticatorAttachment) { this.authenticatorAttachment = authenticatorAttachment; return this; } /** * Sets the {@link #getClientExtensionResults()} property. * @param clientExtensionResults the client extension results * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder clientExtensionResults( AuthenticationExtensionsClientOutputs clientExtensionResults) { this.clientExtensionResults = clientExtensionResults; return this; } /** * Creates a new {@link PublicKeyCredential} * @return a new {@link PublicKeyCredential} */ public PublicKeyCredential<R> build() { Assert.notNull(this.id, "id cannot be null"); Assert.notNull(this.rawId, "rawId cannot be null"); Assert.notNull(this.response, "response cannot be null"); return new PublicKeyCredential(this.id, this.type, this.rawId, this.response, this.authenticatorAttachment, this.clientExtensionResults); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredential.java
1
请在Spring Boot框架中完成以下Java代码
public class QrtzScheduler { Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ApplicationContext applicationContext; @PostConstruct public void init() { logger.info("Hello world from Quartz..."); } @Bean public SpringBeanJobFactory springBeanJobFactory() { AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory(); logger.debug("Configuring Job factory"); jobFactory.setApplicationContext(applicationContext); return jobFactory; } @Bean public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); scheduler.start(); return scheduler; } @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setJobFactory(springBeanJobFactory()); factory.setQuartzProperties(quartzProperties()); return factory;
} public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } @Bean public JobDetail jobDetail() { return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean public Trigger trigger(JobDetail job) { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } }
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\springquartz\basics\scheduler\QrtzScheduler.java
2
请完成以下Java代码
public UserId getUpdatedBy() {return UserId.ofRepoIdOrSystem(po.getUpdatedBy());} @Override @Nullable public DocStatus getDocStatus() { final int index = po.get_ColumnIndex("DocStatus"); return index >= 0 ? DocStatus.ofNullableCodeOrUnknown((String)po.get_Value(index)) : null; } @Override public boolean isProcessing() {return po.get_ValueAsBoolean("Processing");} @Override public boolean isProcessed() {return po.get_ValueAsBoolean("Processed");} @Override public boolean isActive() {return po.isActive();} @Override public PostingStatus getPostingStatus() {return PostingStatus.ofNullableCode(po.get_ValueAsString("Posted"));} @Override public boolean hasColumnName(final String columnName) {return po.getPOInfo().hasColumnName(columnName);} @Override public int getValueAsIntOrZero(final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Integer ii = (Integer)po.get_Value(index); if (ii != null) { return ii; } } return 0; } @Override @Nullable public <T extends RepoIdAware> T getValueAsIdOrNull(final String columnName, final IntFunction<T> idOrNullMapper) { final int index = po.get_ColumnIndex(columnName); if (index < 0) { return null; } final Object valueObj = po.get_Value(index); final Integer valueInt = NumberUtils.asInteger(valueObj, null); if (valueInt == null) { return null; }
return idOrNullMapper.apply(valueInt); } @Override @Nullable public LocalDateAndOrgId getValueAsLocalDateOrNull(@NonNull final String columnName, @NonNull final Function<OrgId, ZoneId> timeZoneMapper) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Timestamp ts = po.get_ValueAsTimestamp(index); if (ts != null) { final OrgId orgId = OrgId.ofRepoId(po.getAD_Org_ID()); return LocalDateAndOrgId.ofTimestamp(ts, orgId, timeZoneMapper); } } return null; } @Override @Nullable public Boolean getValueAsBooleanOrNull(@NonNull final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Object valueObj = po.get_Value(index); return DisplayType.toBoolean(valueObj, null); } return null; } @Override @Nullable public String getValueAsString(@NonNull final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Object valueObj = po.get_Value(index); return valueObj != null ? valueObj.toString() : null; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\POAcctDocModel.java
1
请在Spring Boot框架中完成以下Java代码
private void execute0() { job = job.withChangedRawMaterialsIssueStep( request.getActivityId(), request.getIssueScheduleId(), (step) -> { if (processed) { // shall not happen logger.warn("Ignoring request because was already processed: request={}, step={}", request, step); return step; } return issueToStep(step); }); if (!processed) { throw new AdempiereException("Failed fulfilling issue request") .setParameter("request", request) .setParameter("job", job); } save(); }
private RawMaterialsIssueStep issueToStep(final RawMaterialsIssueStep step) { step.assertNotIssued(); final PPOrderIssueSchedule issueSchedule = ppOrderIssueScheduleService.issue(request); this.processed = true; return step.withIssued(issueSchedule.getIssued()); } private void save() { newSaver().saveActivityStatuses(job); } @NonNull private ManufacturingJobLoaderAndSaver newSaver() {return new ManufacturingJobLoaderAndSaver(loadingAndSavingSupportServices);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue\IssueRawMaterialsCommand.java
2
请在Spring Boot框架中完成以下Java代码
public void close() throws IOException { } @Override public SSLEngine createClientSslEngine(String peerHost, int peerPort, String endpointIdentification) { SslBundle sslBundle = this.sslBundle; Assert.state(sslBundle != null, "'sslBundle' must not be null"); SSLEngine sslEngine = sslBundle.createSslContext().createSSLEngine(peerHost, peerPort); sslEngine.setUseClientMode(true); SSLParameters sslParams = sslEngine.getSSLParameters(); sslParams.setEndpointIdentificationAlgorithm(endpointIdentification); sslEngine.setSSLParameters(sslParams); return sslEngine; } @Override public SSLEngine createServerSslEngine(String peerHost, int peerPort) { SslBundle sslBundle = this.sslBundle; Assert.state(sslBundle != null, "'sslBundle' must not be null"); SSLEngine sslEngine = sslBundle.createSslContext().createSSLEngine(peerHost, peerPort); sslEngine.setUseClientMode(false); return sslEngine; } @Override public boolean shouldBeRebuilt(Map<String, Object> nextConfigs) { return !nextConfigs.equals(this.configs); } @Override public Set<String> reconfigurableConfigs() {
return Set.of(SSL_BUNDLE_CONFIG_NAME); } @Override public @Nullable KeyStore keystore() { SslBundle sslBundle = this.sslBundle; Assert.state(sslBundle != null, "'sslBundle' must not be null"); return sslBundle.getStores().getKeyStore(); } @Override public @Nullable KeyStore truststore() { SslBundle sslBundle = this.sslBundle; Assert.state(sslBundle != null, "'sslBundle' must not be null"); return sslBundle.getStores().getTrustStore(); } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\SslBundleSslEngineFactory.java
2
请在Spring Boot框架中完成以下Java代码
protected @NonNull Object configureAsLocalClientRegion(@NonNull Environment environment, @NonNull Object clientRegion) { return clientRegion instanceof ClientRegionFactoryBean ? configureAsLocalClientRegion(environment, (ClientRegionFactoryBean<?, ?>) clientRegion) : configureAsLocalClientRegion(environment, (CacheTypeAwareRegionFactoryBean<?, ?>) clientRegion); } protected @NonNull <K, V> CacheTypeAwareRegionFactoryBean<K, V> configureAsLocalClientRegion( @NonNull Environment environment, @NonNull CacheTypeAwareRegionFactoryBean<K, V> clientRegion) { ClientRegionShortcut shortcut = environment.getProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY, ClientRegionShortcut.class, LOCAL_CLIENT_REGION_SHORTCUT); clientRegion.setClientRegionShortcut(shortcut); clientRegion.setPoolName(GemfireUtils.DEFAULT_POOL_NAME); return clientRegion; } protected @NonNull <K, V> ClientRegionFactoryBean<K, V> configureAsLocalClientRegion( @NonNull Environment environment, @NonNull ClientRegionFactoryBean<K, V> clientRegion) { ClientRegionShortcut shortcut = environment.getProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY, ClientRegionShortcut.class, LOCAL_CLIENT_REGION_SHORTCUT); clientRegion.setPoolName(null); clientRegion.setShortcut(shortcut); return clientRegion; } public static final class AllClusterNotAvailableConditions extends AllNestedConditions { public AllClusterNotAvailableConditions() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @Conditional(ClusterNotAvailableCondition.class) static class IsClusterNotAvailableCondition { } @Conditional(NotCloudFoundryEnvironmentCondition.class) static class IsNotCloudFoundryEnvironmentCondition { }
@Conditional(NotKubernetesEnvironmentCondition.class) static class IsNotKubernetesEnvironmentCondition { } } public static final class ClusterNotAvailableCondition extends ClusterAwareConfiguration.ClusterAwareCondition { @Override public synchronized boolean matches(@NonNull ConditionContext conditionContext, @NonNull AnnotatedTypeMetadata typeMetadata) { return !super.matches(conditionContext, typeMetadata); } } public static final class NotCloudFoundryEnvironmentCondition implements Condition { @Override public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { return !CloudPlatform.CLOUD_FOUNDRY.isActive(context.getEnvironment()); } } public static final class NotKubernetesEnvironmentCondition implements Condition { @Override public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { return !CloudPlatform.KUBERNETES.isActive(context.getEnvironment()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterNotAvailableConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public final class HibernateMetricsAutoConfiguration implements SmartInitializingSingleton { private static final String ENTITY_MANAGER_FACTORY_SUFFIX = "entityManagerFactory"; private final Map<String, EntityManagerFactory> entityManagerFactories; private final MeterRegistry meterRegistry; HibernateMetricsAutoConfiguration(ConfigurableListableBeanFactory beanFactory, MeterRegistry meterRegistry) { this.entityManagerFactories = SimpleAutowireCandidateResolver.resolveAutowireCandidates(beanFactory, EntityManagerFactory.class); this.meterRegistry = meterRegistry; } @Override public void afterSingletonsInstantiated() { bindEntityManagerFactoriesToRegistry(this.entityManagerFactories, this.meterRegistry); } private void bindEntityManagerFactoriesToRegistry(Map<String, EntityManagerFactory> entityManagerFactories, MeterRegistry registry) { entityManagerFactories.forEach((name, factory) -> bindEntityManagerFactoryToRegistry(name, factory, registry)); } private void bindEntityManagerFactoryToRegistry(String beanName, EntityManagerFactory entityManagerFactory, MeterRegistry registry) {
String entityManagerFactoryName = getEntityManagerFactoryName(beanName); try { new HibernateMetrics(entityManagerFactory.unwrap(SessionFactory.class), entityManagerFactoryName, Collections.emptyList()) .bindTo(registry); } catch (PersistenceException ex) { // Continue } } /** * Get the name of an {@link EntityManagerFactory} based on its {@code beanName}. * @param beanName the name of the {@link EntityManagerFactory} bean * @return a name for the given entity manager factory */ private String getEntityManagerFactoryName(String beanName) { if (beanName.length() > ENTITY_MANAGER_FACTORY_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, ENTITY_MANAGER_FACTORY_SUFFIX)) { return beanName.substring(0, beanName.length() - ENTITY_MANAGER_FACTORY_SUFFIX.length()); } return beanName; } }
repos\spring-boot-4.0.1\module\spring-boot-hibernate\src\main\java\org\springframework\boot\hibernate\autoconfigure\metrics\HibernateMetricsAutoConfiguration.java
2
请完成以下Java代码
public String getAmount () { return (String)get_Value(COLUMNNAME_Amount); } /** Set Bank statement line. @param C_BankStatementLine_ID Line on a statement from this Bank */ public void setC_BankStatementLine_ID (int C_BankStatementLine_ID) { if (C_BankStatementLine_ID < 1) set_Value (COLUMNNAME_C_BankStatementLine_ID, null); else set_Value (COLUMNNAME_C_BankStatementLine_ID, Integer.valueOf(C_BankStatementLine_ID)); } /** Get Bank statement line. @return Line on a statement from this Bank */ public int getC_BankStatementLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_DirectDebit_ID. @param C_DirectDebit_ID C_DirectDebit_ID */ public void setC_DirectDebit_ID (int C_DirectDebit_ID) { if (C_DirectDebit_ID < 1) throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory."); set_ValueNoCheck (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID)); } /** Get C_DirectDebit_ID. @return C_DirectDebit_ID */ public int getC_DirectDebit_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Dtafile. @param Dtafile Copy of the *.dta stored as plain text */ public void setDtafile (String Dtafile) { set_Value (COLUMNNAME_Dtafile, Dtafile); } /** Get Dtafile.
@return Copy of the *.dta stored as plain text */ public String getDtafile () { return (String)get_Value(COLUMNNAME_Dtafile); } /** Set IsRemittance. @param IsRemittance IsRemittance */ public void setIsRemittance (boolean IsRemittance) { set_Value (COLUMNNAME_IsRemittance, Boolean.valueOf(IsRemittance)); } /** Get IsRemittance. @return IsRemittance */ public boolean isRemittance () { Object oo = get_Value(COLUMNNAME_IsRemittance); 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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebit.java
1
请完成以下Java代码
public IMigrationExecutorProvider getMigrationExecutorProvider() { return factory; } @Override public void setMigrationOperation(MigrationOperation operation) { Check.assumeNotNull(operation, "operation not null"); this.migrationOperation = operation; } @Override public boolean isApplyDML() { return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DML; } @Override public boolean isApplyDDL() { return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DDL; } @Override public boolean isSkipMissingColumns() { // TODO configuration to be implemented return true; } @Override
public boolean isSkipMissingTables() { // TODO configuration to be implemented return true; } @Override public void addPostponedExecutable(IPostponedExecutable executable) { Check.assumeNotNull(executable, "executable not null"); postponedExecutables.add(executable); } @Override public List<IPostponedExecutable> popPostponedExecutables() { final List<IPostponedExecutable> result = new ArrayList<IPostponedExecutable>(postponedExecutables); postponedExecutables.clear(); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutorContext.java
1
请完成以下Java代码
public void localVariableMultithreading() { boolean run = true; executor.execute(() -> { while (run) { // do operation } }); // commented because it doesn't compile, it's just an example of non-final local variables in lambdas // run = false; } public void instanceVariableMultithreading() { executor.execute(() -> { while (run) { // do operation } }); run = false; } /** * WARNING: always avoid this workaround!! */ public void workaroundSingleThread() { int[] holder = new int[] { 2 }; IntStream sums = IntStream .of(1, 2, 3) .map(val -> val + holder[0]);
holder[0] = 0; System.out.println(sums.sum()); } /** * WARNING: always avoid this workaround!! */ public void workaroundMultithreading() { int[] holder = new int[] { 2 }; Runnable runnable = () -> System.out.println(IntStream .of(1, 2, 3) .map(val -> val + holder[0]) .sum()); new Thread(runnable).start(); // simulating some processing try { Thread.sleep(new Random().nextInt(3) * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } holder[0] = 0; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\lambdas\LambdaVariables.java
1
请完成以下Java代码
public boolean isExecution() { return BooleanUtils.isTrue(execution); } public void setExecution(Boolean execution) { this.execution = execution; } public Boolean isTask() { return BooleanUtils.isTrue(task); } public void setTask(Boolean task) { this.task = task; } public Boolean isHistory() { return BooleanUtils.isTrue(history); } public void setHistory(Boolean history) { this.history = history; } public boolean isSkippable() { return BooleanUtils.isTrue(skippable);
} public void setSkippable(Boolean skippable) { this.skippable = skippable; } @Override public String toString() { return joinOn(this.getClass()) .add("execution=" + execution) .add("task=" + task) .add("history=" + history) .add("skippable=" + skippable) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\EventingProperty.java
1
请完成以下Java代码
private ILUTUProducerAllocationDestination createLUTUProducerDestination() { final ILUTUProducerAllocationDestination destination; { final IHUSplitDefinition splitDefinition = createSplitDefinition(luPIItem, tuPIItem, cuProductId, cuUOM, cuPerTU, tuPerLU, maxLUToAllocate); // // Create and configure destination destination = new LUTUProducerDestination(splitDefinition); if (splitOnNoPI) { destination.setMaxLUs(0); // don't create any LU destination.setMaxTUsForRemainingQty(splitDefinition.getTuPerLU().intValueExact()); // create just "qtyTU" TUs destination.setCreateTUsForRemainingQty(true); // create TUs for remaining (i.e. whole qty) } else { // Don't create TUs for remaining Qty (after all required LUs were created) - see 06049 destination.setCreateTUsForRemainingQty(false); } } return destination; } private IHUSplitDefinition createSplitDefinition( final I_M_HU_PI_Item luPIItem, final I_M_HU_PI_Item tuPIItem, final ProductId cuProductId,
final I_C_UOM cuUOM, final BigDecimal cuPerTU, final BigDecimal tuPerLU, final BigDecimal maxLUToAllocate) { return new HUSplitDefinition(luPIItem, tuPIItem, cuProductId, cuUOM, cuPerTU, tuPerLU, maxLUToAllocate); } /** * Create an allocation request for the cuQty of the builder * * @param huContext * @param referencedModel referenced model to be used in created request * @return created request */ private IAllocationRequest createSplitAllocationRequest(final IHUContext huContext) { final ZonedDateTime date = SystemTime.asZonedDateTime(); return AllocationUtils.createQtyRequest( huContext, cuProductId, // Product Quantity.of(getCUQty(), cuUOM), // Qty date, // Date cuTrxReferencedModel, // Referenced model, if any false // force allocation ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUSplitBuilder.java
1
请完成以下Java代码
public ProcessPreconditionsResolution toInternal() { // makes no sense to change the internal flag if accepted if (accepted) { return this; } if (internal) { return this; } return toBuilder().internal(true).build(); } public String computeCaption(@NonNull final ITranslatableString originalProcessCaption, @NonNull final String adLanguage) { final ITranslatableString caption = captionMapper != null ? captionMapper.computeCaption(originalProcessCaption) : originalProcessCaption; return caption.translate(adLanguage); } /** * Derive this resolution, overriding the caption. * * @param captionOverride caption override; null value will be considered as no override */ public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final String captionOverride) { return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride)); } public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final ITranslatableString captionOverride) { return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride)); } @Value private static class ProcessCaptionOverrideMapper implements ProcessCaptionMapper { @NonNull ITranslatableString captionOverride; public ProcessCaptionOverrideMapper(@NonNull final ITranslatableString captionOverride) { this.captionOverride = captionOverride; } public ProcessCaptionOverrideMapper(@NonNull final String captionOverride) { this.captionOverride = TranslatableStrings.anyLanguage(captionOverride); } @Override public ITranslatableString computeCaption(final ITranslatableString originalProcessCaption) { return captionOverride; }
} public ProcessPreconditionsResolution withCaptionMapper(@Nullable final ProcessCaptionMapper captionMapper) { return toBuilder().captionMapper(captionMapper).build(); } /** * Override default SortNo used with ordering related processes */ public ProcessPreconditionsResolution withSortNo(final int sortNo) { return !this.sortNo.isPresent() || this.sortNo.getAsInt() != sortNo ? toBuilder().sortNo(OptionalInt.of(sortNo)).build() : this; } public @NonNull OptionalInt getSortNo() {return this.sortNo;} public ProcessPreconditionsResolution and(final Supplier<ProcessPreconditionsResolution> resolutionSupplier) { if (isRejected()) { return this; } return resolutionSupplier.get(); } public void throwExceptionIfRejected() { if (isRejected()) { throw new AdempiereException(getRejectReason()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionsResolution.java
1
请完成以下Java代码
public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setPP_OrderCandidate_PP_Order_ID (final int PP_OrderCandidate_PP_Order_ID) { if (PP_OrderCandidate_PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_OrderCandidate_PP_Order_ID, null); else
set_ValueNoCheck (COLUMNNAME_PP_OrderCandidate_PP_Order_ID, PP_OrderCandidate_PP_Order_ID); } @Override public int getPP_OrderCandidate_PP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_OrderCandidate_PP_Order_ID); } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderCandidate_PP_Order.java
1
请完成以下Java代码
public void mousePressed(MouseEvent e) { grabFocus(); getModel().nextState(); } }); // Reset the keyboard action map ActionMap map = new ActionMapUIResource(); map.put("pressed", new AbstractAction() { /** * */ private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { grabFocus(); getModel().nextState(); } }); map.put("released", null); SwingUtilities.replaceUIActionMap(this, map); setState(state); } public QuadristateCheckbox(String text, State initial) { this(text, null, initial); } public QuadristateCheckbox(String text) { this(text, State.UNCHECKED); } public QuadristateCheckbox() { this(null); } @Override protected void init(String text, Icon icon) { // substitutes the underlying checkbox model: // if we had call setModel an exception would be raised // because setModel calls a getModel that return a // QuadristateButtonModel, but at this point we // have a JToggleButtonModel this.model = new QuadristateButtonModel(); super.setModel(this.model); // side effect: set listeners super.init(text, icon); } @Override public QuadristateButtonModel getModel() { return (QuadristateButtonModel) super.getModel(); } public void setModel(QuadristateButtonModel model) { super.setModel(model); } @Override
@Deprecated public void setModel(ButtonModel model) { // if (!(model instanceof TristateButtonModel)) // useless: Java always calls the most specific method super.setModel(model); } /** No one may add mouse listeners, not even Swing! */ @Override public void addMouseListener(MouseListener l) { } /** * Set the new state to either CHECKED, UNCHECKED or GREY_CHECKED. If * state == null, it is treated as GREY_CHECKED. */ public void setState(State state) { getModel().setState(state); } /** * Return the current state, which is determined by the selection status * of the model. */ public State getState() { return getModel().getState(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\QuadristateCheckbox.java
1
请完成以下Java代码
private SimpleCookie sessionIdCookie() { SimpleCookie cookie = new SimpleCookie(); cookie.setName("JSESSIONID"); cookie.setHttpOnly(true); cookie.setMaxAge(10800000); return cookie; } @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new LinkedHashMap(); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/*.html", "anon"); filterChainDefinitionMap.put("/*.ico", "anon"); filterChainDefinitionMap.put("/ajaxLogin", "anon"); filterChainDefinitionMap.put("/login/**", "anon"); // if (StringUtils.isNotBlank(this.anonUrls)) { // String[] anonUrlsList = StringUtils.splitByWholeSeparator(this.anonUrls, ","); // String[] var5 = anonUrlsList; // int var6 = anonUrlsList.length; // for (int var7 = 0; var7 < var6; ++var7) { // String s = var5[var7]; // filterChainDefinitionMap.put(s, "anon"); // } // } filterChainDefinitionMap.put("/sync/**", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/captcha/**", "anon"); filterChainDefinitionMap.put("/doc.html/**", "anon"); filterChainDefinitionMap.put("/swagger-resources/**", "anon");
filterChainDefinitionMap.put("/v2/**", "anon"); filterChainDefinitionMap.put("/webjars/**", "anon"); filterChainDefinitionMap.put("/swagger-resources/configuration/ui/**", "anon"); filterChainDefinitionMap.put("/swagger-resources/configuration/security/**", "anon"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setLoginUrl("/unauth"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
repos\spring-boot-quick-master\quick-framework\base-adapter\src\main\java\com\base\adapter\ShiroConfig.java
1
请完成以下Java代码
public void setIsSaveInHistoric (boolean IsSaveInHistoric) { set_Value (COLUMNNAME_IsSaveInHistoric, Boolean.valueOf(IsSaveInHistoric)); } /** Get Save In Historic. @return Save In Historic */ public boolean isSaveInHistoric () { Object oo = get_Value(COLUMNNAME_IsSaveInHistoric); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Deleted. @param LastDeleted Last Deleted */ public void setLastDeleted (int LastDeleted) { set_Value (COLUMNNAME_LastDeleted, Integer.valueOf(LastDeleted)); } /** Get Last Deleted. @return Last Deleted */ public int getLastDeleted () { Integer ii = (Integer)get_Value(COLUMNNAME_LastDeleted); if (ii == null) return 0; return ii.intValue(); } /** Set Last Run. @param LastRun Last Run */ public void setLastRun (Timestamp LastRun) { set_Value (COLUMNNAME_LastRun, LastRun); } /** Get Last Run. @return Last Run */ public Timestamp getLastRun () { return (Timestamp)get_Value(COLUMNNAME_LastRun); } /** 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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_HouseKeeping.java
1
请完成以下Java代码
public int getSource_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Source_Column_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Source Table. @param Source_Table_ID Source Table */ @Override public void setSource_Table_ID (int Source_Table_ID) { if (Source_Table_ID < 1) set_Value (COLUMNNAME_Source_Table_ID, null); else set_Value (COLUMNNAME_Source_Table_ID, Integer.valueOf(Source_Table_ID)); } /** Get Source Table. @return Source Table */ @Override public int getSource_Table_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_Source_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set SQL to get Target Record IDs by Source Record IDs. @param SQL_GetTargetRecordIdBySourceRecordId SQL to get Target Record IDs by Source Record IDs */ @Override public void setSQL_GetTargetRecordIdBySourceRecordId (java.lang.String SQL_GetTargetRecordIdBySourceRecordId) { set_Value (COLUMNNAME_SQL_GetTargetRecordIdBySourceRecordId, SQL_GetTargetRecordIdBySourceRecordId); } /** Get SQL to get Target Record IDs by Source Record IDs. @return SQL to get Target Record IDs by Source Record IDs */ @Override public java.lang.String getSQL_GetTargetRecordIdBySourceRecordId () { return (java.lang.String)get_Value(COLUMNNAME_SQL_GetTargetRecordIdBySourceRecordId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SQLColumn_SourceTableColumn.java
1
请完成以下Java代码
public class RuecknahmeangebotAnfordern { @XmlElement(namespace = "", required = true) protected String clientSoftwareKennung; @XmlElement(namespace = "", required = true) protected Ruecknahmeangebot ruecknahmeangebot; /** * Gets the value of the clientSoftwareKennung property. * * @return * possible object is * {@link String } * */ public String getClientSoftwareKennung() { return clientSoftwareKennung; } /** * Sets the value of the clientSoftwareKennung property. * * @param value * allowed object is * {@link String } * */ public void setClientSoftwareKennung(String value) { this.clientSoftwareKennung = value; } /** * Gets the value of the ruecknahmeangebot property. * * @return
* possible object is * {@link Ruecknahmeangebot } * */ public Ruecknahmeangebot getRuecknahmeangebot() { return ruecknahmeangebot; } /** * Sets the value of the ruecknahmeangebot property. * * @param value * allowed object is * {@link Ruecknahmeangebot } * */ public void setRuecknahmeangebot(Ruecknahmeangebot value) { this.ruecknahmeangebot = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\RuecknahmeangebotAnfordern.java
1
请完成以下Java代码
protected void prepare () { // prepare } /** * Process * @return info * @throws Exception */ protected String doIt () throws Exception { int year_ID = getRecord_ID(); MHRYear year = new MHRYear (getCtx(), getRecord_ID(), get_TrxName()); if (year.get_ID() <= 0 || year.get_ID() != year_ID) return "Year not exist"; else if(year.isProcessed())
return "No Created, The Period's exist"; log.info(year.toString()); // if (year.createPeriods()) { //arhipac: Cristina Ghita -- because of the limitation of UI, you can not enter more records on a tab which has //TabLevel>0 and there are just processed records, so we have not to set year processed //tracker: 2584313 https://sourceforge.net/tracker/index.php?func=detail&aid=2584313&group_id=176962&atid=934929 year.setProcessed(false); year.save(); return "@OK@ Create Periods"; } return Msg.translate(getCtx(), "PeriodNotValid"); } // doIt } // YearCreatePeriods
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\process\HRCreatePeriods.java
1
请完成以下Java代码
private static LocalDate toLocalDate(@NonNull final String yyMMdd) { if (yyMMdd.length() != 6) { throw new AdempiereException("Invalid expire date format: " + yyMMdd); } final String dd = yyMMdd.substring(4, 6); if (dd.endsWith("00")) // last day of month indicator { final String yyMM = yyMMdd.substring(0, 4); return YearMonth.parse(yyMM, FORMAT_yyMM).atEndOfMonth(); } else { return LocalDate.parse(yyMMdd, FORMAT_yyMMdd); } } private static String toYYMMDD(@NonNull final LocalDate localDate) { if (TimeUtil.isLastDayOfMonth(localDate)) { return FORMAT_yyMM.format(localDate) + "00"; } else
{ return FORMAT_yyMMdd.format(localDate); } } @JsonValue public String toJson() { return toYYMMDDString(); } public String toYYMMDDString() { return yyMMdd; } public LocalDate toLocalDate() { return localDate; } public Timestamp toTimestamp() { return TimeUtil.asTimestamp(toLocalDate()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\client\schema\JsonExpirationDate.java
1
请完成以下Java代码
public void setAssortmentType (final String AssortmentType) { set_Value (COLUMNNAME_AssortmentType, AssortmentType); } @Override public String getAssortmentType() { return get_ValueAsString(COLUMNNAME_AssortmentType); } @Override public void setM_Product_AlbertaArticle_ID (final int M_Product_AlbertaArticle_ID) { if (M_Product_AlbertaArticle_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaArticle_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaArticle_ID, M_Product_AlbertaArticle_ID); } @Override public int getM_Product_AlbertaArticle_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaArticle_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setMedicalAidPositionNumber (final @Nullable String MedicalAidPositionNumber) { set_Value (COLUMNNAME_MedicalAidPositionNumber, MedicalAidPositionNumber); } @Override public String getMedicalAidPositionNumber() { return get_ValueAsString(COLUMNNAME_MedicalAidPositionNumber); } /** * PurchaseRating AD_Reference_ID=541279 * Reference name: PurchaseRating */ public static final int PURCHASERATING_AD_Reference_ID=541279; /** A = A */ public static final String PURCHASERATING_A = "A"; /** B = B */ public static final String PURCHASERATING_B = "B"; /** C = C */ public static final String PURCHASERATING_C = "C"; /** D = D */ public static final String PURCHASERATING_D = "D"; /** E = E */
public static final String PURCHASERATING_E = "E"; /** F = F */ public static final String PURCHASERATING_F = "F"; /** G = G */ public static final String PURCHASERATING_G = "G"; @Override public void setPurchaseRating (final @Nullable String PurchaseRating) { set_Value (COLUMNNAME_PurchaseRating, PurchaseRating); } @Override public String getPurchaseRating() { return get_ValueAsString(COLUMNNAME_PurchaseRating); } @Override public void setSize (final @Nullable String Size) { set_Value (COLUMNNAME_Size, Size); } @Override public String getSize() { return get_ValueAsString(COLUMNNAME_Size); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaArticle.java
1
请完成以下Java代码
public static final <IT, RT> ITrxItemChunkProcessor<IT, RT> wrapIfNeeded(@NonNull final ITrxItemProcessor<IT, RT> processor) { if (processor instanceof ITrxItemChunkProcessor) { final ITrxItemChunkProcessor<IT, RT> chunkProcessor = (ITrxItemChunkProcessor<IT, RT>)processor; return chunkProcessor; } else { return new TrxItemProcessor2TrxItemChunkProcessorWrapper<>(processor); } } private final ITrxItemProcessor<IT, RT> processor; private TrxItemProcessor2TrxItemChunkProcessorWrapper(@NonNull final ITrxItemProcessor<IT, RT> processor) { this.processor = processor; } @Override public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx) { processor.setTrxItemProcessorCtx(processorCtx); } @Override public void process(final IT item) throws Exception { processor.process(item); } @Override public RT getResult()
{ return processor.getResult(); } /** * @return always return <code>false</code>. Each item is a separated chunk */ @Override public boolean isSameChunk(final IT item) { return false; } @Override public void newChunk(final IT item) { // nothing } @Override public void completeChunk() { // nothing } @Override public void cancelChunk() { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessor2TrxItemChunkProcessorWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public UserValuePreferences build() { if (isEmpty()) { return UserValuePreferences.EMPTY; } return new UserValuePreferences(this); } public boolean isEmpty() { return name2value.isEmpty(); } public UserValuePreferencesBuilder add(final I_AD_Preference adPreference) { final Optional<AdWindowId> currentWindowId = extractAdWindowId(adPreference); if (isEmpty()) { adWindowIdOptional = currentWindowId; } else if (!adWindowIdOptional.equals(currentWindowId)) { throw new IllegalArgumentException("Preference " + adPreference + "'s AD_Window_ID=" + currentWindowId + " is not matching builder's AD_Window_ID=" + adWindowIdOptional); } final String attributeName = adPreference.getAttribute(); final String attributeValue = adPreference.getValue(); name2value.put(attributeName, UserValuePreference.of(adWindowIdOptional, attributeName, attributeValue)); return this;
} public UserValuePreferencesBuilder addAll(final UserValuePreferencesBuilder fromBuilder) { if (fromBuilder == null || fromBuilder.isEmpty()) { return this; } if (!isEmpty() && !adWindowIdOptional.equals(fromBuilder.adWindowIdOptional)) { throw new IllegalArgumentException("Builder " + fromBuilder + "'s AD_Window_ID=" + fromBuilder.adWindowIdOptional + " is not matching builder's AD_Window_ID=" + adWindowIdOptional); } name2value.putAll(fromBuilder.name2value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ValuePreferenceBL.java
2
请完成以下Spring Boot application配置
logging.level.org.springframework.data=INFO logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG logging.level.example.springdata.
jdbc.mybatis=TRACE mybatis.config-location=mybatis-config.xml
repos\spring-data-examples-main\jdbc\mybatis\src\main\resources\application.properties
2
请完成以下Java代码
private List<AttributeSetInstanceId> createAllASIs(@NonNull final List<ImmutableAttributeSet> attributeSets) { final ImmutableList.Builder<AttributeSetInstanceId> result = ImmutableList.builder(); for (final ImmutableAttributeSet attributeSet : attributeSets) { final I_M_AttributeSetInstance asiRecord = attributeSetInstanceBL.createASIFromAttributeSet(attributeSet); result.add(AttributeSetInstanceId.ofRepoId(asiRecord.getM_AttributeSetInstance_ID())); } return result.build(); } private static ImmutableSet<FlatrateDataEntryDetailKey> extractExistingDetailKeys(final FlatrateDataEntry entry) { return entry .getDetails() .stream() .map(detail -> new FlatrateDataEntryDetailKey( detail.getBPartnerDepartment().getId(), createAttributesKey(detail.getAsiId())) ) .collect(ImmutableSet.toImmutableSet()); } private static AttributesKey createAttributesKey(@NonNull final AttributeSetInstanceId asiId) { return AttributesKeys .createAttributesKeyFromASIAllAttributes(asiId) .orElse(AttributesKey.NONE); } private List<BPartnerDepartment> retrieveBPartnerDepartments(@NonNull final BPartnerId bPartnerId) { final List<BPartnerDepartment> departments = bPartnerDepartmentRepo.getByBPartnerId(bPartnerId); if (departments.isEmpty()) {
return ImmutableList.of(BPartnerDepartment.none(bPartnerId)); } return departments; } @Value static class FlatrateDataEntryDetailKey { @NonNull BPartnerDepartmentId bPartnerDepartmentId; @NonNull AttributesKey attributesKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\FlatrateDataEntryService.java
1
请完成以下Java代码
public String resolveKey(ServerWebExchange exchange, List<String> varyOnHeaders) { return cacheKeyGenerator.generateKey(exchange.getRequest(), varyOnHeaders); } Mono<Void> processFromCache(ServerWebExchange exchange, String metadataKey, CachedResponse cachedResponse) { final ServerHttpResponse response = exchange.getResponse(); afterCacheExchangeMutators.forEach(processor -> processor.accept(exchange, cachedResponse)); saveMetadataInCache(metadataKey, new CachedResponseMetadata(cachedResponse.headers().getVary())); return response .writeWith(Flux.fromIterable(cachedResponse.body()).map(data -> response.bufferFactory().wrap(data))); } private @Nullable CachedResponseMetadata retrieveMetadata(String metadataKey) { CachedResponseMetadata metadata; try { metadata = cache.get(metadataKey, CachedResponseMetadata.class); } catch (RuntimeException anyException) { LOGGER.error("Error reading from cache. Metadata Data will not come from cache.", anyException); metadata = null; } return metadata; } boolean isResponseCacheable(ServerHttpResponse response) { return isStatusCodeToCache(response) && isCacheControlAllowed(response) && !isVaryWildcard(response); } boolean isNoCacheRequestWithoutUpdate(ServerHttpRequest request) { return LocalResponseCacheUtils.isNoCacheRequest(request) && ignoreNoCacheUpdate; } private boolean isStatusCodeToCache(ServerHttpResponse response) { return statusesToCache.contains(response.getStatusCode()); } boolean isRequestCacheable(ServerHttpRequest request) { return HttpMethod.GET.equals(request.getMethod()) && !hasRequestBody(request) && isCacheControlAllowed(request); } private boolean isVaryWildcard(ServerHttpResponse response) {
HttpHeaders headers = response.getHeaders(); List<String> varyValues = headers.getOrEmpty(HttpHeaders.VARY); return varyValues.stream().anyMatch(VARY_WILDCARD::equals); } private boolean isCacheControlAllowed(HttpMessage request) { HttpHeaders headers = request.getHeaders(); List<String> cacheControlHeader = headers.getOrEmpty(HttpHeaders.CACHE_CONTROL); return cacheControlHeader.stream().noneMatch(forbiddenCacheControlValues::contains); } private static boolean hasRequestBody(ServerHttpRequest request) { return request.getHeaders().getContentLength() > 0; } private void saveInCache(String cacheKey, CachedResponse cachedResponse) { try { cache.put(cacheKey, cachedResponse); } catch (RuntimeException anyException) { LOGGER.error("Error writing into cache. Data will not be cached", anyException); } } private void saveMetadataInCache(String metadataKey, CachedResponseMetadata metadata) { try { cache.put(metadataKey, metadata); } catch (RuntimeException anyException) { LOGGER.error("Error writing into cache. Data will not be cached", anyException); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheManager.java
1
请完成以下Java代码
public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (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 Einzelpreis. @param PriceActual Effektiver Preis */ @Override public void setPriceActual (java.math.BigDecimal PriceActual) { set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ @Override public java.math.BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); 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_BPartner_Product_Stats_Invoice_Online_V.java
1
请在Spring Boot框架中完成以下Java代码
public ProcessApplicationDeploymentBuilderImpl name(String name) { return (ProcessApplicationDeploymentBuilderImpl) super.name(name); } @Override public ProcessApplicationDeploymentBuilderImpl tenantId(String tenantId) { return (ProcessApplicationDeploymentBuilderImpl) super.tenantId(tenantId); } @Override public ProcessApplicationDeploymentBuilderImpl nameFromDeployment(String deploymentId) { return (ProcessApplicationDeploymentBuilderImpl) super.nameFromDeployment(deploymentId); } @Override public ProcessApplicationDeploymentBuilderImpl source(String source) { return (ProcessApplicationDeploymentBuilderImpl) super.source(source); } @Override public ProcessApplicationDeploymentBuilderImpl enableDuplicateFiltering() { return (ProcessApplicationDeploymentBuilderImpl) super.enableDuplicateFiltering(); } @Override public ProcessApplicationDeploymentBuilderImpl enableDuplicateFiltering(boolean deployChangedOnly) { return (ProcessApplicationDeploymentBuilderImpl) super.enableDuplicateFiltering(deployChangedOnly); } @Override public ProcessApplicationDeploymentBuilderImpl addDeploymentResources(String deploymentId) { return (ProcessApplicationDeploymentBuilderImpl) super.addDeploymentResources(deploymentId); } @Override 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
请完成以下Java代码
private void createAndLinkElementsForTabs() { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final IADElementDAO adElementsRepo = Services.get(IADElementDAO.class); for (final AdTabId tabId : adWindowDAO.retrieveTabIdsWithMissingADElements()) { final I_AD_Tab tab = adWindowDAO.getTabByIdInTrx(tabId); final AdElementId elementId = adElementsRepo.createNewElement(CreateADElementRequest.builder() .name(tab.getName()) .printName(tab.getName()) .description(tab.getDescription()) .help(tab.getHelp()) .tabCommitWarning(tab.getCommitWarning()) .build()); updateElementTranslationsFromTab(elementId, tabId); DYNATTR_AD_Tab_UpdateTranslations.setValue(tab, false); tab.setAD_Element_ID(elementId.getRepoId()); save(tab); } } private void createAndLinkElementsForWindows() { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final IADElementDAO adElementsRepo = Services.get(IADElementDAO.class); final Set<AdWindowId> windowIdsWithMissingADElements = adWindowDAO.retrieveWindowIdsWithMissingADElements(); for (final AdWindowId windowId : windowIdsWithMissingADElements) { final I_AD_Window window = adWindowDAO.getWindowByIdInTrx(windowId); final AdElementId elementId = adElementsRepo.createNewElement(CreateADElementRequest.builder() .name(window.getName()) .printName(window.getName()) .description(window.getDescription())
.help(window.getHelp()) .build()); updateElementTranslationsFromWindow(elementId, windowId); DYNATTR_AD_Window_UpdateTranslations.setValue(window, false); window.setAD_Element_ID(elementId.getRepoId()); save(window); } } private void createAndLinkElementsForMenus() { final IADMenuDAO adMenuDAO = Services.get(IADMenuDAO.class); final IADElementDAO adElementsRepo = Services.get(IADElementDAO.class); final Set<AdMenuId> menuIdsWithMissingADElements = adMenuDAO.retrieveMenuIdsWithMissingADElements(); for (final AdMenuId menuId : menuIdsWithMissingADElements) { final I_AD_Menu menu = adMenuDAO.getById(menuId); final AdElementId elementId = adElementsRepo.createNewElement(CreateADElementRequest.builder() .name(menu.getName()) .printName(menu.getName()) .description(menu.getDescription()) .webuiNameBrowse(menu.getWEBUI_NameBrowse()) .webuiNameNew(menu.getWEBUI_NameNew()) .webuiNameNewBreadcrumb(menu.getWEBUI_NameNewBreadcrumb()).build()); updateElementTranslationsFromMenu(elementId, menuId); DYNATTR_AD_Menu_UpdateTranslations.setValue(menu, false); menu.setAD_Element_ID(elementId.getRepoId()); save(menu); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\translation\api\impl\ElementTranslationBL.java
1
请在Spring Boot框架中完成以下Java代码
public class PaginationService { private static final transient Logger logger = LogManager.getLogger(PaginationService.class); private final PageDescriptorRepository pageDescriptorRepository; public PaginationService(@NonNull final PageDescriptorRepository pageDescriptorRepository) { this.pageDescriptorRepository = pageDescriptorRepository; } public <T, ET extends T> QueryResultPage<ET> loadFirstPage( @NonNull final Class<ET> clazz, @NonNull final TypedSqlQuery<T> query, final int pageSize) { final UUISelection uuidSelection = QuerySelectionHelper.createUUIDSelection(query); final PageDescriptor firstPageDescriptor = PageDescriptor.createNew( uuidSelection.getUuid(), pageSize, uuidSelection.getSize(), uuidSelection.getTime()); pageDescriptorRepository.save(firstPageDescriptor); return loadPage( clazz, firstPageDescriptor); } public <ET> QueryResultPage<ET> loadPage( @NonNull final Class<ET> clazz, @NonNull final String pageIdentifier) { final PageDescriptor currentPageDescriptor = pageDescriptorRepository.getBy(pageIdentifier); if (currentPageDescriptor == null) { throw new UnknownPageIdentifierException(pageIdentifier); } return loadPage(clazz, currentPageDescriptor); } private <ET> QueryResultPage<ET> loadPage( @NonNull final Class<ET> clazz, @NonNull final PageDescriptor currentPageDescriptor) { final TypedSqlQuery<ET> query = QuerySelectionHelper.createUUIDSelectionQuery( PlainContextAware.newWithThreadInheritedTrx(), clazz, currentPageDescriptor.getPageIdentifier().getSelectionUid()); final int currentPageSize = currentPageDescriptor.getPageSize(); final List<ET> items = query .addWhereClause(
true /* joinByAnd */, QuerySelectionHelper.SELECTION_LINE_ALIAS + " > " + currentPageDescriptor.getOffset()) .setLimit(currentPageSize) .list(clazz); final int actualPageSize = items.size(); logger.debug("Loaded next page: bufferSize={}, offset={} -> {} records", currentPageSize, currentPageDescriptor.getOffset(), actualPageSize); // True when buffer contains as much data as was required. If this flag is false then it's a good indicator that we are on last page. final boolean pageFullyLoaded = actualPageSize >= currentPageSize; final PageDescriptor nextPageDescriptor; if (pageFullyLoaded) { nextPageDescriptor = currentPageDescriptor.createNext(); pageDescriptorRepository.save(nextPageDescriptor); } else { nextPageDescriptor = null; } return new QueryResultPage<ET>( currentPageDescriptor, nextPageDescriptor, currentPageDescriptor.getTotalSize(), currentPageDescriptor.getSelectionTime(), ImmutableList.copyOf(items)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\PaginationService.java
2
请完成以下Java代码
private static JSONIncludedTabInfo createIncludedTabInfo(final DocumentChanges.IncludedDetailInfo includedDetailInfo) { final JSONIncludedTabInfo tabInfo = JSONIncludedTabInfo.newInstance(includedDetailInfo.getDetailId()); if (includedDetailInfo.isStale()) { tabInfo.markAllRowsStaled(); } final LogicExpressionResult allowCreateNew = includedDetailInfo.getAllowNew(); if (allowCreateNew != null) { tabInfo.setAllowCreateNew(allowCreateNew.booleanValue(), allowCreateNew.getName()); } final LogicExpressionResult allowDelete = includedDetailInfo.getAllowDelete(); if (allowDelete != null) { tabInfo.setAllowDelete(allowDelete.booleanValue(), allowDelete.getName()); } return tabInfo; } @JsonProperty("validStatus") @JsonInclude(JsonInclude.Include.NON_EMPTY) @Getter private JSONDocumentValidStatus validStatus; @JsonProperty("saveStatus") @JsonInclude(JsonInclude.Include.NON_EMPTY) private JSONDocumentSaveStatus saveStatus; /** * {@link JSONIncludedTabInfo}s indexed by tabId */ @JsonProperty("includedTabsInfo") @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonSerialize(using = JsonMapAsValuesListSerializer.class) // serialize as Map (see #288) private Map<String, JSONIncludedTabInfo> includedTabsInfo; @JsonProperty("standardActions") @JsonInclude(JsonInclude.Include.NON_EMPTY) private Set<DocumentStandardAction> standardActions; @JsonProperty("websocketEndpoint") @JsonInclude(JsonInclude.Include.NON_EMPTY) private final String websocketEndpoint; @JsonProperty("hasComments") @JsonInclude(JsonInclude.Include.NON_EMPTY) @Nullable private Boolean hasComments; private JSONDocument(final DocumentPath documentPath) { super(documentPath); setUnboxPasswordFields(); this.websocketEndpoint = buildWebsocketEndpointOrNull(getWindowId(), getId()); } @Nullable private static String buildWebsocketEndpointOrNull(final WindowId windowId, final DocumentId documentId) { if (windowId != null && documentId != null) { return WebsocketTopicNames.buildDocumentTopicName(windowId, documentId) .getAsString();
} else { return null; } } private void setValidStatus(final JSONDocumentValidStatus validStatus) { this.validStatus = validStatus; } private void setSaveStatus(final JSONDocumentSaveStatus saveStatus) { this.saveStatus = saveStatus; } public void addIncludedTabInfo(final JSONIncludedTabInfo tabInfo) { if (includedTabsInfo == null) { includedTabsInfo = new HashMap<>(); } includedTabsInfo.put(tabInfo.getTabId().toJson(), tabInfo); } @JsonIgnore public Collection<JSONIncludedTabInfo> getIncludedTabsInfos() { if (includedTabsInfo == null || includedTabsInfo.isEmpty()) { return ImmutableSet.of(); } return includedTabsInfo.values(); } private void setStandardActions(final Set<DocumentStandardAction> standardActions) { this.standardActions = standardActions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocument.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> retrieveNamesForPrefix( @NonNull final String prefix, @NonNull final ClientAndOrgId clientAndOrgId) { return getMap().getNamesForPrefix(prefix, clientAndOrgId); } private SysConfigMap getMap() { return cache.getOrLoad(0, this::retrieveMap); } private SysConfigMap retrieveMap() { final Stopwatch stopwatch = Stopwatch.createStarted(); final ImmutableListMultimap<String, SysConfigEntryValue> entryValuesByName = retrieveSysConfigEntryValues(); final ImmutableMap<String, SysConfigEntry> entiresByName = entryValuesByName.asMap() .entrySet() .stream() .map(e -> SysConfigEntry.builder() .name(e.getKey()) .entryValues(e.getValue()) .build()) .collect(ImmutableMap.toImmutableMap( SysConfigEntry::getName, entry -> entry )); final SysConfigMap result = new SysConfigMap(entiresByName); logger.info("Retrieved {} in {}", result, stopwatch.stop()); return result; } protected ImmutableListMultimap<String, SysConfigEntryValue> retrieveSysConfigEntryValues() { final String sql = "SELECT Name, Value, AD_Client_ID, AD_Org_ID FROM AD_SysConfig" + " WHERE IsActive='Y'" + " ORDER BY Name, AD_Client_ID, AD_Org_ID"; PreparedStatement pstmt = null; ResultSet rs = null; try { final ImmutableListMultimap.Builder<String, SysConfigEntryValue> resultBuilder = ImmutableListMultimap.builder();
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); while (rs.next()) { final String name = rs.getString("Name"); final String value = rs.getString("Value"); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg( ClientId.ofRepoId(rs.getInt("AD_Client_ID")), OrgId.ofRepoId(rs.getInt("AD_Org_ID"))); final SysConfigEntryValue entryValue = SysConfigEntryValue.of(value, clientAndOrgId); resultBuilder.put(name, entryValue); } return resultBuilder.build(); } catch (final SQLException ex) { throw new DBException(ex, sql); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigDAO.java
2
请完成以下Java代码
public boolean isI_IsImported () { Object oo = get_Value(COLUMNNAME_I_IsImported); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_M_InOutLineConfirm getM_InOutLineConfirm() throws RuntimeException { return (I_M_InOutLineConfirm)MTable.get(getCtx(), I_M_InOutLineConfirm.Table_Name) .getPO(getM_InOutLineConfirm_ID(), get_TrxName()); } /** Set Ship/Receipt Confirmation Line. @param M_InOutLineConfirm_ID Material Shipment or Receipt Confirmation Line */ public void setM_InOutLineConfirm_ID (int M_InOutLineConfirm_ID) { if (M_InOutLineConfirm_ID < 1) set_Value (COLUMNNAME_M_InOutLineConfirm_ID, null); else set_Value (COLUMNNAME_M_InOutLineConfirm_ID, Integer.valueOf(M_InOutLineConfirm_ID)); } /** Get Ship/Receipt Confirmation Line. @return Material Shipment or Receipt Confirmation Line */ public int getM_InOutLineConfirm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLineConfirm_ID); if (ii == null) return 0; return ii.intValue(); } /** 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; } /** Set Scrapped Quantity. @param ScrappedQty The Quantity scrapped due to QA issues */ public void setScrappedQty (BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Scrapped Quantity. @return The Quantity scrapped due to QA issues */ public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_InOutLineConfirm.java
1
请完成以下Java代码
public class PlainMRPDAO extends MRPDAO { private final Map<ArrayKey, BigDecimal> qtysOnHandsMap = new HashMap<>(); @Override public final BigDecimal getQtyOnHand(final Properties ctx, final int M_Warehouse_ID, final int M_Product_ID, final String trxName) { final ArrayKey key = Util.mkKey(M_Warehouse_ID, M_Product_ID); final BigDecimal qtyOnHand = qtysOnHandsMap.get(key); if (qtyOnHand == null) { return BigDecimal.ZERO; } return qtyOnHand; } public final BigDecimal getQtyOnHand(final I_M_Warehouse warehouse, final I_M_Product product) { final ArrayKey key = mkKey(warehouse, product); final BigDecimal qtyOnHand = qtysOnHandsMap.get(key);
if (qtyOnHand == null) { return BigDecimal.ZERO; } return qtyOnHand; } public final void setQtyOnHand(final I_M_Warehouse warehouse, final I_M_Product product, final BigDecimal qtyOnHand) { final ArrayKey key = mkKey(warehouse, product); qtysOnHandsMap.put(key, qtyOnHand); } private ArrayKey mkKey(final I_M_Warehouse warehouse, final I_M_Product product) { final int warehouseId = warehouse.getM_Warehouse_ID(); final int productId = product.getM_Product_ID(); return Util.mkKey(warehouseId, productId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\PlainMRPDAO.java
1
请完成以下Java代码
public boolean learn(String segmentedSentence) { return learn(segmentedSentence.split("\\s+")); } /** * 在线学习 * * @param words 分好词的句子 * @return 是否学习成功(失败的原因是参数错误) */ public boolean learn(String... words) { // for (int i = 0; i < words.length; i++) // 防止传入带词性的词语 // { // int index = words[i].indexOf('/'); // if (index > 0) // { // words[i] = words[i].substring(0, index); // } // }
return learn(new CWSInstance(words, model.featureMap)); } @Override protected Instance createInstance(Sentence sentence, FeatureMap featureMap) { return CWSInstance.create(sentence, featureMap); } @Override public double[] evaluate(String corpora) throws IOException { // 这里用CWS的F1 double[] prf = Utility.prf(Utility.evaluateCWS(corpora, this)); return prf; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronSegmenter.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } public String getTenantId() { return tenantId; } public String getHostname() { return hostname; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getBatchId() { return batchId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog; } public boolean isDeletionLog() { return deletionLog; } public static HistoricJobLogDto fromHistoricJobLog(HistoricJobLog historicJobLog) { HistoricJobLogDto result = new HistoricJobLogDto(); result.id = historicJobLog.getId(); result.timestamp = historicJobLog.getTimestamp(); result.removalTime = historicJobLog.getRemovalTime(); result.jobId = historicJobLog.getJobId(); result.jobDueDate = historicJobLog.getJobDueDate(); result.jobRetries = historicJobLog.getJobRetries(); result.jobPriority = historicJobLog.getJobPriority(); result.jobExceptionMessage = historicJobLog.getJobExceptionMessage(); result.jobDefinitionId = historicJobLog.getJobDefinitionId();
result.jobDefinitionType = historicJobLog.getJobDefinitionType(); result.jobDefinitionConfiguration = historicJobLog.getJobDefinitionConfiguration(); result.activityId = historicJobLog.getActivityId(); result.failedActivityId = historicJobLog.getFailedActivityId(); result.executionId = historicJobLog.getExecutionId(); result.processInstanceId = historicJobLog.getProcessInstanceId(); result.processDefinitionId = historicJobLog.getProcessDefinitionId(); result.processDefinitionKey = historicJobLog.getProcessDefinitionKey(); result.deploymentId = historicJobLog.getDeploymentId(); result.tenantId = historicJobLog.getTenantId(); result.hostname = historicJobLog.getHostname(); result.rootProcessInstanceId = historicJobLog.getRootProcessInstanceId(); result.batchId = historicJobLog.getBatchId(); result.creationLog = historicJobLog.isCreationLog(); result.failureLog = historicJobLog.isFailureLog(); result.successLog = historicJobLog.isSuccessLog(); result.deletionLog = historicJobLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricJobLogDto.java
1
请在Spring Boot框架中完成以下Java代码
public List<BusinessEntityType> getAdditionalBusinessPartner() { if (additionalBusinessPartner == null) { additionalBusinessPartner = new ArrayList<BusinessEntityType>(); } return this.additionalBusinessPartner; } /** * Other references if no dedicated field is available.Gets the value of the additionalReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<ReferenceType>(); } return this.additionalReference; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\SLSRPTListLineExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
public Tracing tracing(@Value("${spring.application.name}") String serviceName) { return Tracing.newBuilder() .localServiceName(serviceName) // .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() // .addScopeDecorator(MDCScopeDecorator.create()) // puts trace IDs into logs // .build() // ) .spanReporter(spanReporter()).build(); } /** * Allows someone to add tags to a span if a trace is in progress */ @Bean public SpanCustomizer spanCustomizer(Tracing tracing) { return CurrentSpanCustomizer.create(tracing); } // ==================== HTTP 相关 ==================== /** * Decides how to name and tag spans. By default they are named the same as the http method */ @Bean public HttpTracing httpTracing(Tracing tracing) { return HttpTracing.create(tracing); } /** * Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { return TracingFilter.create(httpTracing); } // ==================== SpringMVC 相关 ====================
// @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) // ==================== HttpClient 相关 ==================== @Bean public RestTemplateCustomizer useTracedHttpClient(HttpTracing httpTracing) { // 创建 CloseableHttpClient 对象,内置 HttpTracing 进行 HTTP 链路追踪。 final CloseableHttpClient httpClient = TracingHttpClientBuilder.create(httpTracing).build(); // 创建 RestTemplateCustomizer 对象 return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-demo\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public final class ModelTypeInstanceContext { private final ModelInstanceImpl model; private final DomElement domElement; private final ModelElementTypeImpl modelType; public ModelTypeInstanceContext(DomElement domElement, ModelInstanceImpl model, ModelElementTypeImpl modelType) { this.domElement = domElement; this.model = model; this.modelType = modelType; } /** * @return the dom element */ public DomElement getDomElement() { return domElement; }
/** * @return the model */ public ModelInstanceImpl getModel() { return model; } /** * @return the modelType */ public ModelElementTypeImpl getModelType() { return modelType; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\ModelTypeInstanceContext.java
1
请完成以下Java代码
public void setValues(SubProcess otherElement) { super.setValues(otherElement); /* * This is required because data objects in Designer have no DI info and are added as properties, not flow elements * * Determine the differences between the 2 elements' data object */ for (ValuedDataObject thisObject : getDataObjects()) { boolean exists = false; for (ValuedDataObject otherObject : otherElement.getDataObjects()) { if (thisObject.getId().equals(otherObject.getId())) { exists = true; } } if (!exists) { // missing object removeFlowElement(thisObject.getId()); } } dataObjects = new ArrayList<ValuedDataObject>(); if (otherElement.getDataObjects() != null && !otherElement.getDataObjects().isEmpty()) { for (ValuedDataObject dataObject : otherElement.getDataObjects()) { ValuedDataObject clone = dataObject.clone(); dataObjects.add(clone); // add it to the list of FlowElements // if it is already there, remove it first so order is same as // data object list removeFlowElement(clone.getId()); addFlowElement(clone);
} } flowElementList.clear(); for (FlowElement flowElement : otherElement.getFlowElements()) { addFlowElement(flowElement); } artifactList.clear(); for (Artifact artifact : otherElement.getArtifacts()) { addArtifact(artifact); } } public List<ValuedDataObject> getDataObjects() { return dataObjects; } public void setDataObjects(List<ValuedDataObject> dataObjects) { this.dataObjects = dataObjects; } @Override public void accept(ReferenceOverrider referenceOverrider) { getFlowElements().forEach(flowElement -> flowElement.accept(referenceOverrider)); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SubProcess.java
1
请完成以下Java代码
protected <C> C readValue(String value, JavaType type) { try { return objectMapper.readValue(value, type); } catch (JsonParseException e) { throw LOG.unableToReadValue(value, e); } catch (JsonMappingException e) { throw LOG.unableToReadValue(value, e); } catch (IOException e) { throw LOG.unableToReadValue(value, e); } } public JavaType constructJavaTypeFromCanonicalString(String canonicalString) { try { return TypeFactory.defaultInstance().constructFromCanonical(canonicalString); } catch (IllegalArgumentException e) { throw LOG.unableToConstructJavaType(canonicalString, e); }
} public String getCanonicalTypeName(Object value) { ensureNotNull("value", value); for (TypeDetector typeDetector : typeDetectors) { if (typeDetector.canHandle(value)) { return typeDetector.detectType(value); } } throw LOG.unableToDetectCanonicalType(value); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\JacksonJsonDataFormat.java
1
请在Spring Boot框架中完成以下Java代码
public CurrentChargesResponse fetch(CurrentChargesRequest request) { List<String> subscriptions = request.getSubscriptionIds(); if (subscriptions == null || subscriptions.isEmpty()) { System.out.println("Fetching ALL charges for customer: " + request.getCustomerId()); subscriptions = mockSubscriptions(); } else { System.out.println(format("Fetching charges for customer: %s and subscriptions: %s", request.getCustomerId(), subscriptions)); } CurrentChargesResponse charges = mockCharges(request.getCustomerId(), subscriptions, request.isItemized()); System.out.println("Fetched charges..."); return charges; } private CurrentChargesResponse mockCharges(String customerId, List<String> subscriptions, boolean itemized) { List<LineItem> lineItems = mockLineItems(subscriptions); BigDecimal amountDue = lineItems .stream() .map(li -> li.getAmount()) .reduce(new BigDecimal("0"), BigDecimal::add); return CurrentChargesResponse .builder() .customerId(customerId) .lineItems(itemized ? lineItems : emptyList()) .amountDue(amountDue) .build(); }
private List<LineItem> mockLineItems(List<String> subscriptions) { return subscriptions .stream() .map(subscription -> LineItem.builder() .subscriptionId(subscription) .quantity(current().nextInt(20)) .amount(new BigDecimal(current().nextDouble(1_000))) .build()) .collect(toList()); } private List<String> mockSubscriptions() { String[] subscriptions = new String[5]; fill(subscriptions, UUID.randomUUID().toString()); return asList(subscriptions); } }
repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\service\DefaultFetchCurrentChargesService.java
2
请在Spring Boot框架中完成以下Java代码
public Sender sender() { return OkHttpSender.create("http://127.0.0.1:9411/api/v2/spans"); } /** * Configuration for how to buffer spans into messages for Zipkin */ @Bean public AsyncReporter<Span> spanReporter() { return AsyncReporter.create(sender()); } /** * Controls aspects of tracing such as the service name that shows up in the UI */ @Bean public Tracing tracing(@Value("${spring.application.name}") String serviceName) { return Tracing.newBuilder() .localServiceName(serviceName) // .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() // .addScopeDecorator(MDCScopeDecorator.create()) // puts trace IDs into logs // .build() // ) .spanReporter(spanReporter()).build(); } /** * Allows someone to add tags to a span if a trace is in progress */ @Bean public SpanCustomizer spanCustomizer(Tracing tracing) { return CurrentSpanCustomizer.create(tracing); } // ==================== HTTP 相关 ==================== /** * Decides how to name and tag spans. By default they are named the same as the http method */ @Bean public HttpTracing httpTracing(Tracing tracing) { return HttpTracing.create(tracing); } /**
* Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { return TracingFilter.create(httpTracing); } // ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) // ==================== HttpClient 相关 ==================== @Bean public RestTemplateCustomizer useTracedHttpClient(HttpTracing httpTracing) { // 创建 CloseableHttpClient 对象,内置 HttpTracing 进行 HTTP 链路追踪。 final CloseableHttpClient httpClient = TracingHttpClientBuilder.create(httpTracing).build(); // 创建 RestTemplateCustomizer 对象 return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-demo\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public Date getGlueUpdatetime() { return glueUpdatetime; } public void setGlueUpdatetime(Date glueUpdatetime) { this.glueUpdatetime = glueUpdatetime; } public String getChildJobId() { return childJobId; } public void setChildJobId(String childJobId) { this.childJobId = childJobId; } public int getTriggerStatus() { return triggerStatus; } public void setTriggerStatus(int triggerStatus) { this.triggerStatus = triggerStatus; }
public long getTriggerLastTime() { return triggerLastTime; } public void setTriggerLastTime(long triggerLastTime) { this.triggerLastTime = triggerLastTime; } public long getTriggerNextTime() { return triggerNextTime; } public void setTriggerNextTime(long triggerNextTime) { this.triggerNextTime = triggerNextTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java
1
请完成以下Java代码
public List<Import> getImports() { return imports; } public void setImports(List<Import> imports) { this.imports = imports; } public List<Interface> getInterfaces() { return interfaces; } public void setInterfaces(List<Interface> interfaces) { this.interfaces = interfaces; } public List<Artifact> getGlobalArtifacts() { return globalArtifacts; } public void setGlobalArtifacts(List<Artifact> globalArtifacts) { this.globalArtifacts = globalArtifacts; } public void addNamespace(String prefix, String uri) { namespaceMap.put(prefix, uri); } public boolean containsNamespacePrefix(String prefix) { return namespaceMap.containsKey(prefix); } public String getNamespace(String prefix) { return namespaceMap.get(prefix); } public Map<String, String> getNamespaces() { return namespaceMap; } public String getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; } public String getSourceSystemId() { return sourceSystemId; } public void setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; }
public List<String> getUserTaskFormTypes() { return userTaskFormTypes; } public void setUserTaskFormTypes(List<String> userTaskFormTypes) { this.userTaskFormTypes = userTaskFormTypes; } public List<String> getStartEventFormTypes() { return startEventFormTypes; } public void setStartEventFormTypes(List<String> startEventFormTypes) { this.startEventFormTypes = startEventFormTypes; } @JsonIgnore public Object getEventSupport() { return eventSupport; } public void setEventSupport(Object eventSupport) { this.eventSupport = eventSupport; } public String getStartFormKey(String processId) { FlowElement initialFlowElement = getProcessById(processId).getInitialFlowElement(); if (initialFlowElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) initialFlowElement; return startEvent.getFormKey(); } return null; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BpmnModel.java
1
请完成以下Java代码
public void setTwnNm(String value) { this.twnNm = value; } /** * Gets the value of the ctrySubDvsn property. * * @return * possible object is * {@link String } * */ public String getCtrySubDvsn() { return ctrySubDvsn; } /** * Sets the value of the ctrySubDvsn property. * * @param value * allowed object is * {@link String } * */ public void setCtrySubDvsn(String value) { this.ctrySubDvsn = value; } /** * Gets the value of the ctry property. * * @return * possible object is * {@link String } * */ public String getCtry() { return ctry; } /** * Sets the value of the ctry property. * * @param value * allowed object is
* {@link String } * */ public void setCtry(String value) { this.ctry = value; } /** * Gets the value of the adrLine property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the adrLine property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdrLine().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAdrLine() { if (adrLine == null) { adrLine = new ArrayList<String>(); } return this.adrLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PostalAddress6.java
1
请完成以下Java代码
public class AuthenticationResult { protected boolean isAuthenticated; protected String authenticatedUser; protected List<String> groups; protected List<String> tenants; public AuthenticationResult(String authenticatedUser, boolean isAuthenticated) { this.authenticatedUser = authenticatedUser; this.isAuthenticated = isAuthenticated; } public String getAuthenticatedUser() { return authenticatedUser; } public void setAuthenticatedUser(String authenticatedUser) { this.authenticatedUser = authenticatedUser; } public boolean isAuthenticated() { return isAuthenticated; } public void setAuthenticated(boolean isAuthenticated) { this.isAuthenticated = isAuthenticated; } public List<String> getGroups() { return groups; } public void setGroups(List<String> groups) { this.groups = groups;
} public List<String> getTenants() { return tenants; } public void setTenants(List<String> tenants) { this.tenants = tenants; } public static AuthenticationResult successful(String userId) { return new AuthenticationResult(userId, true); } public static AuthenticationResult unsuccessful() { return new AuthenticationResult(null, false); } public static AuthenticationResult unsuccessful(String userId) { return new AuthenticationResult(userId, false); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\security\auth\AuthenticationResult.java
1
请在Spring Boot框架中完成以下Java代码
public JwtSettings reloadJwtSettings() { log.trace("Executing reloadJwtSettings"); var settings = getJwtSettings(true); jwtTokenFactory.ifPresent(JwtTokenFactory::reload); return settings; } @Override public JwtSettings getJwtSettings() { log.trace("Executing getJwtSettings"); return getJwtSettings(false); } public JwtSettings getJwtSettings(boolean forceReload) { if (this.jwtSettings == null || forceReload) { synchronized (this) { if (this.jwtSettings == null || forceReload) { jwtSettings = getJwtSettingsFromDb(); } } } return this.jwtSettings; } private JwtSettings getJwtSettingsFromDb() { AdminSettings adminJwtSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, ADMIN_SETTINGS_JWT_KEY);
return adminJwtSettings != null ? mapAdminToJwtSettings(adminJwtSettings) : null; } private JwtSettings mapAdminToJwtSettings(AdminSettings adminSettings) { Objects.requireNonNull(adminSettings, "adminSettings for JWT is null"); return JacksonUtil.treeToValue(adminSettings.getJsonValue(), JwtSettings.class); } private AdminSettings mapJwtToAdminSettings(JwtSettings jwtSettings) { Objects.requireNonNull(jwtSettings, "jwtSettings is null"); AdminSettings adminJwtSettings = new AdminSettings(); adminJwtSettings.setTenantId(TenantId.SYS_TENANT_ID); adminJwtSettings.setKey(ADMIN_SETTINGS_JWT_KEY); adminJwtSettings.setJsonValue(JacksonUtil.valueToTree(jwtSettings)); return adminJwtSettings; } public static boolean isSigningKeyDefault(JwtSettings settings) { return TOKEN_SIGNING_KEY_DEFAULT.equals(settings.getTokenSigningKey()); } public static boolean validateKeyLength(String key) { return Base64.getDecoder().decode(key).length * Byte.SIZE >= KEY_LENGTH; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\settings\DefaultJwtSettingsService.java
2
请完成以下Java代码
public static String get36UUID() { return UUID.randomUUID().toString(); } /** * 验证一个字符串是否完全由纯数字组成的字符串,当字符串为空时也返回false. * * @author WuShuicheng . * @param str * 要判断的字符串 . * @return true or false . */ public static boolean isNumeric(String str) { if (StringUtils.isBlank(str)) { return false; } else { return str.matches("\\d*"); } } /** * 计算采用utf-8编码方式时字符串所占字节数 * * @param content * @return */ public static int getByteSize(String content) { int size = 0; if (null != content) { try { // 汉字采用utf-8编码时占3个字节 size = content.getBytes("utf-8").length; } catch (UnsupportedEncodingException e) { LOG.error(e); } } return size; } /** * 函数功能说明 : 截取字符串拼接in查询参数. 修改者名字: 修改日期: 修改内容: * * @参数: @param ids * @参数: @return * @return String * @throws
*/ public static List<String> getInParam(String param) { boolean flag = param.contains(","); List<String> list = new ArrayList<String>(); if (flag) { list = Arrays.asList(param.split(",")); } else { list.add(param); } return list; } /** * 判断对象是否为空 * * @param obj * @return */ public static boolean isNotNull(Object obj) { if (obj != null && obj.toString() != null && !"".equals(obj.toString().trim())) { return true; } else { return false; } } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\StringUtil.java
1
请完成以下Java代码
public void setResourceId(String resourceId) { this.resourceId = resourceId; } /** * @return the name of the violated permission if there * is only one {@link MissingAuthorizationDto}, {@code null} otherwise * * @deprecated Use {@link #getMissingAuthorizations()} to get the name of the violated permission * of the {@link MissingAuthorizationDto}(s). This method will be removed in future version. */ @Deprecated public String getPermissionName() { return permissionName; } /** * @deprecated Use {@link #setMissingAuthorizations(List)}} to set the * the {@link MissingAuthorizationDto}(s). This method will be removed in future version. */
@Deprecated public void setPermissionName(String permissionName) { this.permissionName = permissionName; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } /** * @return Disjunctive list of {@link MissingAuthorizationDto} from * which a user needs to have at least one for the authorization to pass */ public List<MissingAuthorizationDto> getMissingAuthorizations() { return missingAuthorizations; } public void setMissingAuthorizations(List<MissingAuthorizationDto> info) { this.missingAuthorizations = info; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AuthorizationExceptionDto.java
1
请完成以下Java代码
public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Merkmale. @return Merkmals Ausprägungen zum Produkt */ @Override public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Datum. @param ValueDate Datum */ @Override public void setValueDate (java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); }
/** Get Datum. @return Datum */ @Override public java.sql.Timestamp getValueDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValueDate); } /** Set Zahlwert. @param ValueNumber Numeric Value */ @Override public void setValueNumber (java.math.BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } /** Get Zahlwert. @return Numeric Value */ @Override public java.math.BigDecimal getValueNumber () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeInstance.java
1
请完成以下Java代码
public class LogFileWebEndpoint { private static final Log logger = LogFactory.getLog(LogFileWebEndpoint.class); private final @Nullable LogFile logFile; private final @Nullable File externalFile; public LogFileWebEndpoint(@Nullable LogFile logFile, @Nullable File externalFile) { this.logFile = logFile; this.externalFile = externalFile; } @ReadOperation(produces = "text/plain; charset=UTF-8") public @Nullable Resource logFile() { Resource logFileResource = getLogFileResource(); if (logFileResource == null || !logFileResource.isReadable()) { return null; }
return logFileResource; } private @Nullable Resource getLogFileResource() { if (this.externalFile != null) { return new FileSystemResource(this.externalFile); } if (this.logFile == null) { logger.debug("Missing 'logging.file.name' or 'logging.file.path' properties"); return null; } return new FileSystemResource(this.logFile.toString()); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\logging\LogFileWebEndpoint.java
1
请完成以下Java代码
public void build() { markAsBuilt(); if (parameterName2valueMap.isEmpty()) { return; } final I_C_Queue_WorkPackage workpackage = getC_Queue_WorkPackage(); for (final Map.Entry<String, Object> parameterName2value : parameterName2valueMap.entrySet()) { final String parameterName = parameterName2value.getKey(); final Object parameterValue = parameterName2value.getValue(); final I_C_Queue_WorkPackage_Param workpackageParam = WorkPackageParamsUtil.createWorkPackageParamRecord(workpackage, parameterName); workpackageParamDAO.setParameterValue(workpackageParam, parameterValue); InterfaceWrapperHelper.save(workpackageParam); } } private void assertNotBuilt() { Check.assume(!built.get(), "not already built"); } private void markAsBuilt() { final boolean wasAlreadyBuilt = built.getAndSet(true); Check.assume(!wasAlreadyBuilt, "not already built"); } @Override public IWorkPackageBuilder end() { return _parentBuilder; } /* package */void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage workpackage) { assertNotBuilt(); _workpackage = workpackage; } private I_C_Queue_WorkPackage getC_Queue_WorkPackage() { Check.assumeNotNull(_workpackage, "workpackage not null"); return _workpackage; } @Override public IWorkPackageParamsBuilder setParameter(final String parameterName, final Object parameterValue) { assertNotBuilt(); Check.assumeNotEmpty(parameterName, "parameterName not empty"); parameterName2valueMap.put(parameterName, parameterValue);
return this; } @Override public IWorkPackageParamsBuilder setParameters(final Map<String, ?> parameters) { assertNotBuilt(); if (parameters == null || parameters.isEmpty()) { return this; } for (final Map.Entry<String, ?> param : parameters.entrySet()) { final String parameterName = param.getKey(); Check.assumeNotEmpty(parameterName, "parameterName not empty"); final Object parameterValue = param.getValue(); parameterName2valueMap.put(parameterName, parameterValue); } return this; } @Override public IWorkPackageParamsBuilder setParameters(@Nullable final IParams parameters) { assertNotBuilt(); if (parameters == null) { return this; } final Collection<String> parameterNames = parameters.getParameterNames(); if(parameterNames.isEmpty()) { return this; } for (final String parameterName : parameterNames) { Check.assumeNotEmpty(parameterName, "parameterName not empty"); final Object parameterValue = parameters.getParameterAsObject(parameterName); parameterName2valueMap.put(parameterName, parameterValue); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageParamsBuilder.java
1
请完成以下Java代码
public class MigrationExecutionDto { protected MigrationPlanDto migrationPlan; protected List<String> processInstanceIds; protected ProcessInstanceQueryDto processInstanceQuery; protected boolean skipIoMappings; protected boolean skipCustomListeners; public MigrationPlanDto getMigrationPlan() { return migrationPlan; } public void setMigrationPlan(MigrationPlanDto migrationPlan) { this.migrationPlan = migrationPlan; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; }
public boolean isSkipIoMappings() { return skipIoMappings; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationExecutionDto.java
1
请完成以下Java代码
public ParamsBuilder value(@NonNull final String parameterName, final boolean valueBoolean) { return valueObj(parameterName, valueBoolean); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final BigDecimal valueBD) { return valueObj(parameterName, valueBD); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final ZonedDateTime valueZDT) { return valueObj(parameterName, valueZDT); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final LocalDate valueLD) { return valueObj(parameterName, valueLD); } public ParamsBuilder valueObj(@NonNull final String parameterName, @Nullable final Object value) { parameterNames.add(parameterName); if (value != null)
{ values.put(parameterName, value); } else { values.remove(parameterName); } return this; } public ParamsBuilder valueObj(@NonNull final Object value) { return valueObj(toParameterName(value.getClass()), value); } public ParamsBuilder putAll(@NonNull final IParams params) { for (String parameterName : params.getParameterNames()) { valueObj(parameterName, params.getParameterAsObject(parameterName)); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\Params.java
1
请完成以下Java代码
private ICNetAmtToInvoiceChecker getICNetAmtToInvoiceChecker(final IWorkPackageBuilder group) { final ICNetAmtToInvoiceChecker netAmtToInvoiceChecker = group2netAmtToInvoiceChecker.get(group); Check.assumeNotNull(netAmtToInvoiceChecker, "netAmtToInvoiceChecker not null for {}", group); return netAmtToInvoiceChecker; } /** * Close group: i.e. make workpackage as ready for processing. */ @Override protected void closeGroup(@NonNull final IWorkPackageBuilder group) { // // Create workpackage parameters (08610) final ICNetAmtToInvoiceChecker netAmtToInvoiceChecker = getICNetAmtToInvoiceChecker(group); final IWorkPackageParamsBuilder parameters = group.parameters(); if (invoicingParams != null) { parameters.setParameters(invoicingParams.asMap()); } parameters.setParameter(IInvoicingParams.PARA_Check_NetAmtToInvoice, netAmtToInvoiceChecker.getValue()); if (_asyncBatchId != null) { group.setAsyncBatchId(_asyncBatchId); } // // Mark the workpackage as ready for processing (when trxName will be commited) group.buildAndEnqueue(); } public InvoiceCandidate2WorkpackageAggregator setAD_PInstance_Creator_ID(@NonNull final PInstanceId adPInstanceId) { this.pInstanceId = adPInstanceId; return this; } public InvoiceCandidate2WorkpackageAggregator setAsyncBatchId(final AsyncBatchId asyncBatchId) { _asyncBatchId = asyncBatchId;
return this; } public InvoiceCandidate2WorkpackageAggregator setPriority(final IWorkpackagePrioStrategy priority) { workpackagePriority = priority; return this; } public InvoiceCandidate2WorkpackageAggregator setInvoicingParams(@NonNull final IInvoicingParams invoicingParams) { this.invoicingParams = invoicingParams; return this; } /** * Gets unprocessed workpackages queue size */ public final int getQueueSize() { return getWorkPackageQueue().size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidate2WorkpackageAggregator.java
1
请完成以下Java代码
public Criteria andRoleIdIn(List<Long> values) { addCriterion("role_id in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotIn(List<Long> values) { addCriterion("role_id not in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdBetween(Long value1, Long value2) { addCriterion("role_id between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotBetween(Long value1, Long value2) { addCriterion("role_id not between", value1, value2, "roleId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue;
} public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminRoleRelationExample.java
1
请完成以下Java代码
public void setUserType(String userType) { this.userType = userType; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) {
this.age = age; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 5-7 课: 综合实战客户管理系统(一)\user-manage\src\main\java\com\neo\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getUserName() { return this.userName; } public void setUserName(@Nullable String userName) { this.userName = userName; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public @Nullable String getPipeline() { return this.pipeline; } public void setPipeline(@Nullable String pipeline) { this.pipeline = pipeline; } public @Nullable String getApiKeyCredentials() {
return this.apiKeyCredentials; } public void setApiKeyCredentials(@Nullable String apiKeyCredentials) { this.apiKeyCredentials = apiKeyCredentials; } public boolean isEnableSource() { return this.enableSource; } public void setEnableSource(boolean enableSource) { this.enableSource = enableSource; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticProperties.java
2
请完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getRegTime() { return regTime; }
public void setRegTime(Date regTime) { this.regTime = regTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\entity\UserEntity.java
1
请完成以下Java代码
public MetricsCollectionTask getMetricsCollectionTask() { return metricsCollectionTask; } public void setMetricsCollectionTask(MetricsCollectionTask metricsCollectionTask) { this.metricsCollectionTask = metricsCollectionTask; } public void setReporterId(String reporterId) { this.reporterId = reporterId; if (metricsCollectionTask != null) { metricsCollectionTask.setReporter(reporterId); } } protected class ReportDbMetricsValueCmd implements Command<Void> {
protected String name; protected long value; public ReportDbMetricsValueCmd(String name, long value) { this.name = name; this.value = value; } @Override public Void execute(CommandContext commandContext) { commandContext.getMeterLogManager().insert(new MeterLogEntity(name, reporterId, value, ClockUtil.getCurrentTime())); return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\reporter\DbMetricsReporter.java
1
请完成以下Java代码
public class Fresh_QtyOnHand_Line { @Init public void registerCallout() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void onBeforeSave(final I_Fresh_QtyOnHand_Line line) { // Make sure that we always keep DateDoc in sync with the document header final I_Fresh_QtyOnHand header = line.getFresh_QtyOnHand(); line.setDateDoc(header.getDateDoc()); // NOTE: ASIKey will be set automatically by Fresh_QtyOnHand_Line_OnUpdate_Trigger } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void fireStouckEstimatedEvent(final I_Fresh_QtyOnHand_Line line) { }
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_Fresh_QtyOnHand_Line.COLUMNNAME_M_Warehouse_ID, }) @CalloutMethod(columnNames = I_Fresh_QtyOnHand_Line.COLUMNNAME_M_Warehouse_ID) public void fireWarehouseChanges(@NonNull final I_Fresh_QtyOnHand_Line line) { final ProductPlanningService productPlanningService = SpringContextHolder.instance.getBean(ProductPlanningService.class); final ResourceId plantId = productPlanningService.getPlantOfWarehouse(WarehouseId.ofRepoId(line.getM_Warehouse_ID())) .orElseThrow(() -> new AdempiereException(AdMessageKey.of("Fresh_QtyOnHand_Line.MissingWarehousePlant")) .markAsUserValidationError()); line.setPP_Plant_ID(plantId.getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\freshQtyOnHand\model\validator\Fresh_QtyOnHand_Line.java
1
请完成以下Java代码
public CaseInstanceMigrationBuilder withCaseInstanceVariables(Map<String, Object> variables) { this.caseInstanceMigrationDocumentDocumentBuilder.addCaseInstanceVariables(variables); return this; } @Override public CaseInstanceMigrationDocument getCaseInstanceMigrationDocument() { return this.caseInstanceMigrationDocumentDocumentBuilder.build(); } @Override public void migrate(String caseInstanceId) { getCmmnMigrationService().migrateCaseInstance(caseInstanceId, getCaseInstanceMigrationDocument()); } @Override public CaseInstanceMigrationValidationResult validateMigration(String caseInstanceId) { return getCmmnMigrationService().validateMigrationForCaseInstance(caseInstanceId, getCaseInstanceMigrationDocument()); } @Override public void migrateCaseInstances(String caseDefinitionId) { getCmmnMigrationService().migrateCaseInstancesOfCaseDefinition(caseDefinitionId, getCaseInstanceMigrationDocument()); } @Override public Batch batchMigrateCaseInstances(String caseDefinitionId) { return getCmmnMigrationService().batchMigrateCaseInstancesOfCaseDefinition(caseDefinitionId, getCaseInstanceMigrationDocument()); } @Override public CaseInstanceMigrationValidationResult validateMigrationOfCaseInstances(String caseDefinitionId) { return getCmmnMigrationService().validateMigrationForCaseInstancesOfCaseDefinition(caseDefinitionId, getCaseInstanceMigrationDocument()); } @Override public void migrateCaseInstances(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId) { getCmmnMigrationService().migrateCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, getCaseInstanceMigrationDocument()); }
@Override public Batch batchMigrateCaseInstances(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId) { return getCmmnMigrationService().batchMigrateCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, getCaseInstanceMigrationDocument()); } @Override public CaseInstanceMigrationValidationResult validateMigrationOfCaseInstances(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId) { return getCmmnMigrationService().validateMigrationForCaseInstancesOfCaseDefinition(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, getCaseInstanceMigrationDocument()); } protected CmmnMigrationService getCmmnMigrationService() { if (cmmnMigrationService == null) { throw new FlowableException("CaseMigrationService cannot be null, Obtain your builder instance from the CaseMigrationService to access this feature"); } return cmmnMigrationService; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getInternalId() { return internalId; } /** * Sets the value of the internalId property. * * @param value * allowed object is * {@link String } * */ public void setInternalId(String value) { this.internalId = value; } /** * Gets the value of the internalSubId property. * * @return * possible object is * {@link String } * */
public String getInternalSubId() { return internalSubId; } /** * Sets the value of the internalSubId property. * * @param value * allowed object is * {@link String } * */ public void setInternalSubId(String value) { this.internalSubId = 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\SenderType.java
2
请在Spring Boot框架中完成以下Java代码
public class FormServiceImpl extends CommonEngineServiceImpl<ProcessEngineConfigurationImpl> implements FormService { @Override public Object getRenderedStartForm(String processDefinitionId) { return commandExecutor.execute(new GetRenderedStartFormCmd(processDefinitionId, null)); } @Override public Object getRenderedStartForm(String processDefinitionId, String engineName) { return commandExecutor.execute(new GetRenderedStartFormCmd(processDefinitionId, engineName)); } @Override public Object getRenderedTaskForm(String taskId) { return commandExecutor.execute(new GetRenderedTaskFormCmd(taskId, null)); } @Override public Object getRenderedTaskForm(String taskId, String engineName) { return commandExecutor.execute(new GetRenderedTaskFormCmd(taskId, engineName)); } @Override public StartFormData getStartFormData(String processDefinitionId) { return commandExecutor.execute(new GetStartFormCmd(processDefinitionId)); } @Override public TaskFormData getTaskFormData(String taskId) { return commandExecutor.execute(new GetTaskFormCmd(taskId)); } @Override public ProcessInstance submitStartFormData(String processDefinitionId, Map<String, String> properties) { return commandExecutor.execute(new SubmitStartFormCmd(processDefinitionId, null, properties)); }
@Override public ProcessInstance submitStartFormData(String processDefinitionId, String businessKey, Map<String, String> properties) { return commandExecutor.execute(new SubmitStartFormCmd(processDefinitionId, businessKey, properties)); } @Override public void submitTaskFormData(String taskId, Map<String, String> properties) { commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, true)); } @Override public String getStartFormKey(String processDefinitionId) { return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId)); } @Override public String getTaskFormKey(String processDefinitionId, String taskDefinitionKey) { return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId, taskDefinitionKey)); } @Override public void saveFormData(String taskId, Map<String, String> properties) { commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, false)); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\FormServiceImpl.java
2
请完成以下Java代码
public void setAuthorizedClientProvider(ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider) { Assert.notNull(authorizedClientProvider, "authorizedClientProvider cannot be null"); this.authorizedClientProvider = authorizedClientProvider; } /** * Sets the {@code Function} used for mapping attribute(s) from the * {@link OAuth2AuthorizeRequest} to a {@code Map} of attributes to be associated to * the {@link OAuth2AuthorizationContext#getAttributes() authorization context}. * @param contextAttributesMapper the {@code Function} used for supplying the * {@code Map} of attributes to the {@link OAuth2AuthorizationContext#getAttributes() * authorization context} */ public void setContextAttributesMapper( Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper) { Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null"); this.contextAttributesMapper = contextAttributesMapper; } /** * Sets the handler that handles successful authorizations. * * The default saves {@link OAuth2AuthorizedClient}s in the * {@link ReactiveOAuth2AuthorizedClientService}. * @param authorizationSuccessHandler the handler that handles successful * authorizations. * @since 5.3 */ public void setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler) { Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null"); this.authorizationSuccessHandler = authorizationSuccessHandler; } /** * Sets the handler that handles authorization failures. * * <p> * A {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} is used * by default.
* </p> * @param authorizationFailureHandler the handler that handles authorization failures. * @since 5.3 * @see RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler */ public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) { Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null"); this.authorizationFailureHandler = authorizationFailureHandler; } /** * The default implementation of the {@link #setContextAttributesMapper(Function) * contextAttributesMapper}. */ public static class DefaultContextAttributesMapper implements Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> { private final AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper mapper = new AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper(); @Override public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest) { return Mono.fromCallable(() -> this.mapper.apply(authorizeRequest)); } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.java
1
请完成以下Java代码
private ListenableFuture<TbMsg> getDetails(TbContext ctx, TbMsg msg, ObjectNode messageData) { ListenableFuture<? extends ContactBased<I>> contactBasedFuture = getContactBasedFuture(ctx, msg); return Futures.transformAsync(contactBasedFuture, contactBased -> { if (contactBased == null) { return Futures.immediateFuture(msg); } var msgMetaData = msg.getMetaData().copy(); fetchEntityDetailsToMsg(contactBased, messageData, msgMetaData); return Futures.immediateFuture(transformMessage(msg, messageData, msgMetaData)); }, MoreExecutors.directExecutor()); } private void fetchEntityDetailsToMsg(ContactBased<I> contactBased, ObjectNode messageData, TbMsgMetaData msgMetaData) { String value = null; for (var entityDetail : config.getDetailsList()) { switch (entityDetail) { case ID: value = contactBased.getId().getId().toString(); break; case TITLE: value = contactBased.getName(); break; case ADDRESS: value = contactBased.getAddress(); break; case ADDRESS2: value = contactBased.getAddress2(); break; case CITY: value = contactBased.getCity(); break; case COUNTRY: value = contactBased.getCountry(); break; case STATE: value = contactBased.getState(); break; case EMAIL: value = contactBased.getEmail(); break; case PHONE: value = contactBased.getPhone(); break; case ZIP: value = contactBased.getZip(); break;
case ADDITIONAL_INFO: if (contactBased.getAdditionalInfo().hasNonNull("description")) { value = contactBased.getAdditionalInfo().get("description").asText(); } break; } if (value == null) { continue; } setDetail(entityDetail.getRuleEngineName(), value, messageData, msgMetaData); } } private void setDetail(String property, String value, ObjectNode messageData, TbMsgMetaData msgMetaData) { String fieldName = getPrefix() + property; if (TbMsgSource.METADATA.equals(fetchTo)) { msgMetaData.putValue(fieldName, value); } else if (TbMsgSource.DATA.equals(fetchTo)) { messageData.put(fieldName, value); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractGetEntityDetailsNode.java
1
请完成以下Java代码
public DmnTransformFactory getTransformFactory() { return transformFactory; } public List<DmnTransformListener> getTransformListeners() { return transformListeners; } public void setTransformListeners(List<DmnTransformListener> transformListeners) { this.transformListeners = transformListeners; } public DmnTransformer transformListeners(List<DmnTransformListener> transformListeners) { setTransformListeners(transformListeners); return this; } public DmnElementTransformHandlerRegistry getElementTransformHandlerRegistry() { return elementTransformHandlerRegistry; } public void setElementTransformHandlerRegistry(DmnElementTransformHandlerRegistry elementTransformHandlerRegistry) { this.elementTransformHandlerRegistry = elementTransformHandlerRegistry; } public DmnTransformer elementTransformHandlerRegistry(DmnElementTransformHandlerRegistry elementTransformHandlerRegistry) { setElementTransformHandlerRegistry(elementTransformHandlerRegistry); return this; } public DmnDataTypeTransformerRegistry getDataTypeTransformerRegistry() { return dataTypeTransformerRegistry; }
public void setDataTypeTransformerRegistry(DmnDataTypeTransformerRegistry dataTypeTransformerRegistry) { this.dataTypeTransformerRegistry = dataTypeTransformerRegistry; } public DmnTransformer dataTypeTransformerRegistry(DmnDataTypeTransformerRegistry dataTypeTransformerRegistry) { setDataTypeTransformerRegistry(dataTypeTransformerRegistry); return this; } public DmnHitPolicyHandlerRegistry getHitPolicyHandlerRegistry() { return hitPolicyHandlerRegistry; } public void setHitPolicyHandlerRegistry(DmnHitPolicyHandlerRegistry hitPolicyHandlerRegistry) { this.hitPolicyHandlerRegistry = hitPolicyHandlerRegistry; } public DmnTransformer hitPolicyHandlerRegistry(DmnHitPolicyHandlerRegistry hitPolicyHandlerRegistry) { setHitPolicyHandlerRegistry(hitPolicyHandlerRegistry); return this; } public DmnTransform createTransform() { return transformFactory.createTransform(this); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DefaultDmnTransformer.java
1
请完成以下Java代码
public java.math.BigDecimal getInvoicedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InvoicedQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zeilennetto. @param LineNetAmt Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public void setLineNetAmt (java.math.BigDecimal LineNetAmt) { set_Value (COLUMNNAME_LineNetAmt, LineNetAmt); } /** Get Zeilennetto. @return Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public java.math.BigDecimal getLineNetAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineNetAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Position. @param LineNo Zeile Nr. */ @Override public void setLineNo (int LineNo) { set_Value (COLUMNNAME_LineNo, Integer.valueOf(LineNo)); } /** Get Position. @return Zeile Nr. */ @Override public int getLineNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LineNo); if (ii == null) return 0; return ii.intValue(); }
@Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customs_Invoice_Line.java
1
请完成以下Java代码
public ReentrantLock getLock() { return lock; } boolean isLocked() { return lock.isLocked(); } boolean hasQueuedThreads() { return lock.hasQueuedThreads(); } int getCounter() { return counter; }
public static void main(String[] args) { final int threadCount = 2; final ExecutorService service = Executors.newFixedThreadPool(threadCount); final SharedObjectWithLock object = new SharedObjectWithLock(); service.execute(object::perform); service.execute(object::performTryLock); service.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SharedObjectWithLock.java
1
请完成以下Java代码
public @Nullable PrivateKey getPrivateKey(@Nullable String password) { return PemPrivateKeyParser.parse(this.text, password); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return Objects.equals(this.text, ((PemContent) obj).text); } @Override public int hashCode() { return Objects.hash(this.text); } @Override public String toString() { return this.text; } /** * Load {@link PemContent} from the given content (either the PEM content itself or a * reference to the resource to load). * @param content the content to load * @param resourceLoader the resource loader used to load content * @return a new {@link PemContent} instance or {@code null} * @throws IOException on IO error */ static @Nullable PemContent load(@Nullable String content, ResourceLoader resourceLoader) throws IOException { if (!StringUtils.hasLength(content)) { return null; } if (isPresentInText(content)) { return new PemContent(content); } try (InputStream in = resourceLoader.getResource(content).getInputStream()) { return load(in); } catch (IOException | UncheckedIOException ex) { throw new IOException("Error reading certificate or key from file '%s'".formatted(content), ex); } } /** * Load {@link PemContent} from the given {@link Path}.
* @param path a path to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(Path path) throws IOException { Assert.notNull(path, "'path' must not be null"); try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { return load(in); } } /** * Load {@link PemContent} from the given {@link InputStream}. * @param in an input stream to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(InputStream in) throws IOException { return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8)); } /** * Return a new {@link PemContent} instance containing the given text. * @param text the text containing PEM encoded content * @return a new {@link PemContent} instance */ @Contract("!null -> !null") public static @Nullable PemContent of(@Nullable String text) { return (text != null) ? new PemContent(text) : null; } /** * Return if PEM content is present in the given text. * @param text the text to check * @return if the text includes PEM encoded content. */ public static boolean isPresentInText(@Nullable String text) { return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemContent.java
1
请完成以下Java代码
public class CharStackWithArray { private char[] elements; private int size; public CharStackWithArray() { size = 0; elements = new char[4]; } public int size() { return size; } public char peek() { if (size == 0) { throw new EmptyStackException(); } return elements[size - 1]; } public char pop() { if (size == 0) {
throw new EmptyStackException(); } return elements[--size]; } public void push(char item) { ensureCapacity(size + 1); elements[size] = item; size++; } private void ensureCapacity(int newSize) { char newBiggerArray[]; if (elements.length < newSize) { newBiggerArray = new char[elements.length * 2]; System.arraycopy(elements, 0, newBiggerArray, 0, size); elements = newBiggerArray; } } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\charstack\CharStackWithArray.java
1
请在Spring Boot框架中完成以下Java代码
public String getMessageFunction() { return messageFunction; } /** * Sets the value of the messageFunction property. * * @param value * allowed object is * {@link String } * */ public void setMessageFunction(String value) { this.messageFunction = value; } /** * Reference to the consignment. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference; } /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */
public void setConsignmentReference(String value) { this.consignmentReference = value; } /** * Free text information.Gets the value of the freeText property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the freeText property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFreeText().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FreeTextType } * * */ public List<FreeTextType> getFreeText() { if (freeText == null) { freeText = new ArrayList<FreeTextType>(); } return this.freeText; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDRSPExtensionType.java
2
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name);
} /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Category. @param R_Category_ID Request Category */ public void setR_Category_ID (int R_Category_ID) { if (R_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_R_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Category_ID, Integer.valueOf(R_Category_ID)); } /** Get Category. @return Request Category */ public int getR_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Category_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_R_Category.java
1
请完成以下Spring Boot application配置
server.port=8888 spring.cloud.config.server.git.uri= spring.cloud.bus.enabled=true spring.security.user.name=root spring.security.user.password=s3cr3t spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest encrypt.key-store.location=classpath:/config
-server.jks encrypt.key-store.password=my-s70r3-s3cr3t encrypt.key-store.alias=config-server-key encrypt.key-store.secret=my-k34-s3cr3t
repos\tutorials-master\spring-cloud-modules\spring-cloud-bus\spring-cloud-bus-server\src\main\resources\application.properties
2
请完成以下Java代码
public String determineCompatibilityRangeRequirement() { return this.range.toString(); } public static Mapping create(String range, String version) { return new Mapping(range, version); } public static Mapping create(String range, String version, String... repositories) { return new Mapping(range, version, repositories); } public String getCompatibilityRange() { return this.compatibilityRange; } public void setCompatibilityRange(String compatibilityRange) { this.compatibilityRange = compatibilityRange; } public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public List<String> getRepositories() { return this.repositories; } public List<String> getAdditionalBoms() {
return this.additionalBoms; } public VersionRange getRange() { return this.range; } public void setRepositories(List<String> repositories) { this.repositories = repositories; } public void setAdditionalBoms(List<String> additionalBoms) { this.additionalBoms = additionalBoms; } public void setRange(VersionRange range) { this.range = range; } @Override public String toString() { return "Mapping [" + ((this.compatibilityRange != null) ? "compatibilityRange=" + this.compatibilityRange + ", " : "") + ((this.groupId != null) ? "groupId=" + this.groupId + ", " : "") + ((this.artifactId != null) ? "artifactId=" + this.artifactId + ", " : "") + ((this.version != null) ? "version=" + this.version + ", " : "") + ((this.repositories != null) ? "repositories=" + this.repositories + ", " : "") + ((this.additionalBoms != null) ? "additionalBoms=" + this.additionalBoms + ", " : "") + ((this.range != null) ? "range=" + this.range : "") + "]"; } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\BillOfMaterials.java
1
请在Spring Boot框架中完成以下Java代码
final void addMapping(int index, UrlMapping urlMapping) { this.urlMappings.add(index, urlMapping); } /** * Creates the mapping of {@link RequestMatcher} to {@link Collection} of * {@link ConfigAttribute} instances * @return the mapping of {@link RequestMatcher} to {@link Collection} of * {@link ConfigAttribute} instances. Cannot be null. */ final LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> createRequestMap() { Assert.state(this.unmappedMatchers == null, () -> "An incomplete mapping was found for " + this.unmappedMatchers + ". Try completing it with something like requestUrls().<something>.hasRole('USER')"); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); for (UrlMapping mapping : getUrlMappings()) { RequestMatcher matcher = mapping.getRequestMatcher(); Collection<ConfigAttribute> configAttrs = mapping.getConfigAttrs(); requestMap.put(matcher, configAttrs); } return requestMap; } /** * A mapping of {@link RequestMatcher} to {@link Collection} of * {@link ConfigAttribute} instances */ static final class UrlMapping { private final RequestMatcher requestMatcher; private final Collection<ConfigAttribute> configAttrs;
UrlMapping(RequestMatcher requestMatcher, Collection<ConfigAttribute> configAttrs) { this.requestMatcher = requestMatcher; this.configAttrs = configAttrs; } RequestMatcher getRequestMatcher() { return this.requestMatcher; } Collection<ConfigAttribute> getConfigAttrs() { return this.configAttrs; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractConfigAttributeRequestMatcherRegistry.java
2
请完成以下Java代码
public class MicroBatcher { Queue<String> tasksQueue = new ConcurrentLinkedQueue<>(); Thread batchThread; int executionThreshold; int timeoutThreshold; boolean working = false; MicroBatcher(int executionThreshold, int timeoutThreshold, Consumer<List<String>> executionLogic) { batchThread = new Thread(batchHandling(executionLogic)); batchThread.setDaemon(true); batchThread.start(); this.executionThreshold = executionThreshold; this.timeoutThreshold = timeoutThreshold; } void submit(String task) { tasksQueue.add(task); } Runnable batchHandling(Consumer<List<String>> executionLogic) { return () -> { while (!batchThread.isInterrupted()) { long startTime = System.currentTimeMillis(); while (tasksQueue.size() < executionThreshold && (System.currentTimeMillis() - startTime) < timeoutThreshold) { try { Thread.sleep(100); } catch (InterruptedException e) { return; // exit the external loop } }
List<String> tasks = new ArrayList<>(executionThreshold); while (tasksQueue.size() > 0 && tasks.size() < executionThreshold) { tasks.add(tasksQueue.poll()); } working = true; executionLogic.accept(tasks); working = false; } }; } boolean finished() { return tasksQueue.isEmpty() && !working; } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\smartbatching\MicroBatcher.java
1
请完成以下Java代码
public class DocumentLineType1Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; }
/** * Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\DocumentLineType1Choice.java
1
请完成以下Java代码
public byte[] serialize(Object value, ValueFields valueFields) { if (value == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = createObjectOutputStream(baos); oos.writeObject(value); } catch (Exception e) { throw new ActivitiException( "Couldn't serialize value '" + value + "' in variable '" + valueFields.getName() + "'", e ); } finally { IoUtil.closeSilently(oos); } return baos.toByteArray(); } public Object deserialize(byte[] bytes, ValueFields valueFields) { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); try { ObjectInputStream ois = createObjectInputStream(bais); Object deserializedObject = ois.readObject(); return deserializedObject;
} catch (Exception e) { throw new ActivitiException("Couldn't deserialize object in variable '" + valueFields.getName() + "'", e); } finally { IoUtil.closeSilently(bais); } } public boolean isAbleToStore(Object value) { // TODO don't we need null support here? return value instanceof Serializable; } protected ObjectInputStream createObjectInputStream(InputStream is) throws IOException { return new ObjectInputStream(is) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { return ReflectUtil.loadClass(desc.getName()); } }; } protected ObjectOutputStream createObjectOutputStream(OutputStream os) throws IOException { return new ObjectOutputStream(os); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\SerializableType.java
1
请完成以下Java代码
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 Produktschlüssel.
@param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_DiscountSchema.java
1
请完成以下Java代码
public class EDIExport extends JavaProcess { private int recordId = -1; // Services private final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class); @Override protected void prepare() { recordId = getRecord_ID(); } @Override protected String doIt() { final IExport<? extends I_EDI_Document> export = ediDocumentBL.createExport( getCtx(), getClientID(), getTable_ID(), recordId, get_TrxName()); final List<Exception> feedback = export.doExport(); if (feedback == null || feedback.isEmpty()) { return MSG_OK; } final String errorTitle = buildAndTrlTitle(export.getTableIdentifier(), export.getDocument()); final String errorMessage = ediDocumentBL.buildFeedback(feedback);
final I_EDI_Document document = export.getDocument(); document.setEDIErrorMsg(errorMessage); saveRecord(document); throw new AdempiereException(errorTitle + "\n" + errorMessage).markAsUserValidationError(); } private String buildAndTrlTitle(final String tableNameIdentifier, final I_EDI_Document document) { final StringBuilder titleBuilder = new StringBuilder(); titleBuilder.append("@").append(tableNameIdentifier).append("@ ").append(document.getDocumentNo()); final String tableNameIdentifierTrl = Services.get(IMsgBL.class).parseTranslation(getCtx(), titleBuilder.toString()); return tableNameIdentifierTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDIExport.java
1