instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
class Order implements AutoCloseable { private final Cleaner cleaner; private Cleaner.Cleanable cleanable; public Order(Cleaner cleaner) { this.cleaner = cleaner; } public void register(Product product, int id) { this.cleanable = cleaner.register(product, new CleaningAction(id)); } public void close() { cleanable.clean(); System.out.println("Cleanable closed"); }
static class CleaningAction implements Runnable { private final int id; public CleaningAction(int id) { this.id = id; } @Override public void run() { System.out.printf("Object with id %s is garbage collected. %n", id); } } }
repos\tutorials-master\core-java-modules\core-java-9\src\main\java\com\baeldung\java9\finalizers\Order.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue private Long id; private String lastName; private String department; public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }
repos\tutorials-master\persistence-modules\hibernate-queries-2\src\main\java\com\baeldung\hibernate\listentity\entity\Employee.java
2
请完成以下Java代码
public static CostDetailCreateResultsList ofList(@NonNull final List<CostDetailCreateResult> list) { if (list.isEmpty()) { return EMPTY; } return new CostDetailCreateResultsList(list); } public static CostDetailCreateResultsList ofNullable(@Nullable final CostDetailCreateResult result) { return result != null ? of(result) : EMPTY; } public static CostDetailCreateResultsList of(@NonNull final CostDetailCreateResult result) {return ofList(ImmutableList.of(result));} public static Collector<CostDetailCreateResult, ?, CostDetailCreateResultsList> collect() {return GuavaCollectors.collectUsingListAccumulator(CostDetailCreateResultsList::ofList);} public Stream<CostDetailCreateResult> stream() {return list.stream();} public CostDetailCreateResult getSingleResult() {return CollectionUtils.singleElement(list);} public Optional<CostAmountAndQty> getAmtAndQtyToPost(@NonNull final CostAmountType type, @NonNull AcctSchema as) { return list.stream() .filter(result -> isAccountable(result, as)) .map(result -> result.getAmtAndQty(type)) .reduce(CostAmountAndQty::add); } public CostAmount getMainAmountToPost(@NonNull final AcctSchema as) { return getAmtAndQtyToPost(CostAmountType.MAIN, as) .map(CostAmountAndQty::getAmt) .orElseThrow(() -> new NoSuchElementException("No value present")); } public CostAmountDetailed getTotalAmountToPost(@NonNull final AcctSchema as) { return toAggregatedCostAmount().getTotalAmountToPost(as); }
public AggregatedCostAmount toAggregatedCostAmount() { final CostSegment costSegment = CollectionUtils.extractSingleElement(list, CostDetailCreateResult::getCostSegment); final Map<CostElement, CostAmountDetailed> amountsByCostElement = list.stream() .collect(Collectors.toMap( CostDetailCreateResult::getCostElement, // keyMapper CostDetailCreateResult::getAmt, // valueMapper CostAmountDetailed::add)); // mergeFunction return AggregatedCostAmount.builder() .costSegment(costSegment) .amounts(amountsByCostElement) .build(); } private static boolean isAccountable(@NonNull CostDetailCreateResult result, @NonNull final AcctSchema as) { return result.getCostElement().isAccountable(as.getCosting()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateResultsList.java
1
请完成以下Java代码
public final class QtyRejectedReasonCode { public static final ReferenceId REFERENCE_ID = ReferenceId.ofRepoId(X_M_Picking_Candidate.REJECTREASON_AD_Reference_ID); public static QtyRejectedReasonCode ofCode(@NonNull final String code) { return interner.intern(new QtyRejectedReasonCode(code)); } public static Optional<QtyRejectedReasonCode> ofNullableCode(@Nullable final String code) { return StringUtils.trimBlankToOptional(code).map(QtyRejectedReasonCode::ofCode); } private static final Interner<QtyRejectedReasonCode> interner = Interners.newStrongInterner(); @Getter private final String code; private QtyRejectedReasonCode(@NonNull final String code)
{ Check.assumeNotEmpty(code, "code not empty"); this.code = code; } @Override @Deprecated public String toString() { return getCode(); } @JsonValue public String toJson() { return getCode(); } @Nullable public static String toCode(@Nullable QtyRejectedReasonCode reasonCode) {return reasonCode != null ? reasonCode.getCode() : null;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\QtyRejectedReasonCode.java
1
请完成以下Java代码
public final ResultSet getGeneratedKeys() throws SQLException { return delegate.getGeneratedKeys(); } @Override public final int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException { return trace(sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); } @Override public final int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException { return trace(sql, () -> delegate.executeUpdate(sql, columnIndexes)); } @Override public final int executeUpdate(final String sql, final String[] columnNames) throws SQLException { return trace(sql, () -> delegate.executeUpdate(sql, columnNames)); } @Override public final boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException { return trace(sql, () -> delegate.execute(sql, autoGeneratedKeys)); } @Override public final boolean execute(final String sql, final int[] columnIndexes) throws SQLException { return trace(sql, () -> delegate.execute(sql, columnIndexes)); } @Override public final boolean execute(final String sql, final String[] columnNames) throws SQLException { return trace(sql, () -> delegate.execute(sql, columnNames)); } @Override
public final int getResultSetHoldability() throws SQLException { return delegate.getResultSetHoldability(); } @Override public final boolean isClosed() throws SQLException { return delegate.isClosed(); } @Override public final void setPoolable(final boolean poolable) throws SQLException { delegate.setPoolable(poolable); } @Override public final boolean isPoolable() throws SQLException { return delegate.isPoolable(); } @Override public final void closeOnCompletion() throws SQLException { delegate.closeOnCompletion(); } @Override public final boolean isCloseOnCompletion() throws SQLException { return delegate.isCloseOnCompletion(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingStatement.java
1
请在Spring Boot框架中完成以下Java代码
public void closed(CommandContext commandContext) { execute(commandContext); } public void execute(CommandContext commandContext) { asyncExecutor.executeAsyncJob(job); } @Override public void closing(CommandContext commandContext) { } @Override public void afterSessionsFlush(CommandContext commandContext) { }
@Override public void closeFailure(CommandContext commandContext) { } @Override public Integer order() { return 10; } @Override public boolean multipleAllowed() { return true; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobAddedNotification.java
2
请完成以下Java代码
protected String doIt() throws Exception { if ( posKeyLayoutId == 0 ) throw new FillMandatoryException("C_POSKeyLayout_ID"); int count = 0; String where = ""; Object [] params = new Object[] {}; if ( productCategoryId > 0 ) { where = "M_Product_Category_ID = ? "; params = new Object[] {productCategoryId}; } Query query = new Query(getCtx(), MProduct.Table_Name, where, get_TrxName()) .setParameters(params) .setOnlyActiveRecords(true) .setOrderBy("Value"); List<MProduct> products = query.list(MProduct.class); for (MProduct product : products )
{ final I_C_POSKey key = InterfaceWrapperHelper.newInstance(I_C_POSKey.class, this); key.setName(product.getName()); key.setM_Product_ID(product.getM_Product_ID()); key.setC_POSKeyLayout_ID(posKeyLayoutId); key.setSeqNo(count*10); key.setQty(Env.ONE); InterfaceWrapperHelper.save(key); count++; } return "@Created@ " + count; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\PosKeyGenerate.java
1
请完成以下Java代码
public ProcessCaptionMapper getProcessCaptionMapperForNetAmountsFromQuery(final IQuery<I_C_Invoice_Candidate> query) { final List<Amount> netAmountsToInvoiceList = computeNetAmountsToInvoiceForQuery(query); if (netAmountsToInvoiceList.isEmpty()) { return null; } final ITranslatableString netAmountsToInvoiceString = joinAmountsToTranslatableString(netAmountsToInvoiceList); return originalProcessCaption -> TranslatableStrings.builder() .append(originalProcessCaption) .append(" (").append(netAmountsToInvoiceString).append(")") .build(); } private ImmutableList<Amount> computeNetAmountsToInvoiceForQuery(@NonNull final IQuery<I_C_Invoice_Candidate> query) { return query .sumMoney(I_C_Invoice_Candidate.COLUMNNAME_NetAmtToInvoice, I_C_Invoice_Candidate.COLUMNNAME_C_Currency_ID) .stream() .filter(amt -> amt != null && amt.signum() != 0) .map(moneyService::toAmount) .collect(ImmutableList.toImmutableList()); } private static ITranslatableString joinAmountsToTranslatableString(final List<Amount> amounts) {
Check.assumeNotEmpty(amounts, "amounts is not empty"); final TranslatableStringBuilder builder = TranslatableStrings.builder(); for (final Amount amt : amounts) { if (!builder.isEmpty()) { builder.append(" "); } builder.append(amt); } return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_Candidate_ProcessCaptionMapperHelper.java
1
请完成以下Spring Boot application配置
remoteservice.command.group.key=RemoteServiceGroup remoteservice.command.key=RemoteServiceKey remoteservice.command.execution.timeout=10000 remoteservice.command.threadpool.coresize=5 remoteservice.command.threadpool.maxsize=10 remot
eservice.command.task.queue.size=5 remoteservice.command.sleepwindow=5000 remoteservice.timeout=15000
repos\tutorials-master\hystrix\src\main\resources\application.properties
2
请完成以下Java代码
public CanonicalizationMethodType getCanonicalizationMethod() { return canonicalizationMethod; } /** * Sets the value of the canonicalizationMethod property. * * @param value * allowed object is * {@link CanonicalizationMethodType } * */ public void setCanonicalizationMethod(CanonicalizationMethodType value) { this.canonicalizationMethod = value; } /** * Gets the value of the signatureMethod property. * * @return * possible object is * {@link SignatureMethodType } * */ public SignatureMethodType getSignatureMethod() { return signatureMethod; } /** * Sets the value of the signatureMethod property. * * @param value * allowed object is * {@link SignatureMethodType } * */ public void setSignatureMethod(SignatureMethodType value) { this.signatureMethod = value; } /** * Gets the value of the reference 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 reference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType2 }
* * */ public List<ReferenceType2> getReference() { if (reference == null) { reference = new ArrayList<ReferenceType2>(); } return this.reference; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\SignedInfoType.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeptIds(String tenantId, String deptNames) { return deptService.getDeptIds(tenantId, deptNames); } @Override public List<String> getDeptNames(String deptIds) { return deptService.getDeptNames(deptIds); } @Override public String getPostIds(String tenantId, String postNames) { return postService.getPostIds(tenantId, postNames); } @Override public List<String> getPostNames(String postIds) { return postService.getPostNames(postIds); } @Override @GetMapping(API_PREFIX + "/getRole") public Role getRole(Long id) { return roleService.getById(id); } @Override public String getRoleIds(String tenantId, String roleNames) { return roleService.getRoleIds(tenantId, roleNames); } @Override
@GetMapping(API_PREFIX + "/getRoleName") public String getRoleName(Long id) { return roleService.getById(id).getRoleName(); } @Override public List<String> getRoleNames(String roleIds) { return roleService.getRoleNames(roleIds); } @Override @GetMapping(API_PREFIX + "/getRoleAlias") public String getRoleAlias(Long id) { return roleService.getById(id).getRoleAlias(); } @Override @GetMapping(API_PREFIX + "/tenant") public R<Tenant> getTenant(Long id) { return R.data(tenantService.getById(id)); } @Override @GetMapping(API_PREFIX + "/tenant-id") public R<Tenant> getTenant(String tenantId) { return R.data(tenantService.getByTenantId(tenantId)); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\feign\SysClient.java
2
请完成以下Java代码
public void setExecutionListeners(List<ActivitiListener> executionListeners) { this.executionListeners = executionListeners; } @JsonIgnore public FlowElementsContainer getParentContainer() { return parentContainer; } @JsonIgnore public SubProcess getSubProcess() { SubProcess subProcess = null; if (parentContainer instanceof SubProcess) { subProcess = (SubProcess) parentContainer; } return subProcess; } public void setParentContainer(FlowElementsContainer parentContainer) { this.parentContainer = parentContainer;
} public abstract FlowElement clone(); public void setValues(FlowElement otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setDocumentation(otherElement.getDocumentation()); executionListeners = new ArrayList<ActivitiListener>(); if (otherElement.getExecutionListeners() != null && !otherElement.getExecutionListeners().isEmpty()) { for (ActivitiListener listener : otherElement.getExecutionListeners()) { executionListeners.add(listener.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FlowElement.java
1
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public AuthenticationManager getObject() throws Exception { this.delegate.setAuthenticationEventPublisher(this.authenticationEventPublisher); this.delegate.setEraseCredentialsAfterAuthentication(this.eraseCredentialsAfterAuthentication); if (!this.observationRegistry.isNoop()) { return new ObservationAuthenticationManager(this.observationRegistry, this.delegate); } return this.delegate; } @Override public Class<?> getObjectType() { return AuthenticationManager.class; } public void setEraseCredentialsAfterAuthentication(boolean eraseCredentialsAfterAuthentication) { this.eraseCredentialsAfterAuthentication = eraseCredentialsAfterAuthentication; } public void setAuthenticationEventPublisher(AuthenticationEventPublisher authenticationEventPublisher) { this.authenticationEventPublisher = authenticationEventPublisher; } public void setObservationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } } static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> { @Override public ObservationRegistry getObject() throws Exception { return ObservationRegistry.NOOP; } @Override public Class<?> getObjectType() { return ObservationRegistry.class;
} } public static final class FilterChainDecoratorFactory implements FactoryBean<FilterChainProxy.FilterChainDecorator> { private ObservationRegistry observationRegistry = ObservationRegistry.NOOP; @Override public FilterChainProxy.FilterChainDecorator getObject() throws Exception { if (this.observationRegistry.isNoop()) { return new FilterChainProxy.VirtualFilterChainDecorator(); } return new ObservationFilterChainDecorator(this.observationRegistry); } @Override public Class<?> getObjectType() { return FilterChainProxy.FilterChainDecorator.class; } public void setObservationRegistry(ObservationRegistry registry) { this.observationRegistry = registry; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpSecurityBeanDefinitionParser.java
2
请完成以下Java代码
public UpdateProcessInstancesSuspensionStateBuilder byProcessInstanceQuery(ProcessInstanceQuery processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; return this; } @Override public UpdateProcessInstancesSuspensionStateBuilder byHistoricProcessInstanceQuery(HistoricProcessInstanceQuery historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; return this; } @Override public void suspend() { commandExecutor.execute(new UpdateProcessInstancesSuspendStateCmd(commandExecutor, this, true)); } @Override public void activate() { commandExecutor.execute(new UpdateProcessInstancesSuspendStateCmd(commandExecutor, this, false)); } @Override public Batch suspendAsync() {
return commandExecutor.execute(new UpdateProcessInstancesSuspendStateBatchCmd(commandExecutor, this, true)); } @Override public Batch activateAsync() { return commandExecutor.execute(new UpdateProcessInstancesSuspendStateBatchCmd(commandExecutor, this, false)); } public List<String> getProcessInstanceIds() { return processInstanceIds; } public ProcessInstanceQuery getProcessInstanceQuery() { return processInstanceQuery; } public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UpdateProcessInstancesSuspensionStateBuilderImpl.java
1
请完成以下Java代码
protected Map<URL, ProcessesXml> parseProcessesXmlFiles(final AbstractProcessApplication processApplication) { String[] deploymentDescriptors = getDeploymentDescriptorLocations(processApplication); List<URL> processesXmlUrls = getProcessesXmlUrls(deploymentDescriptors, processApplication); Map<URL, ProcessesXml> parsedFiles = new HashMap<URL, ProcessesXml>(); // perform parsing for (URL url : processesXmlUrls) { LOG.foundProcessesXmlFile(url.toString()); if(isEmptyFile(url)) { parsedFiles.put(url, ProcessesXml.EMPTY_PROCESSES_XML); LOG.emptyProcessesXml(); } else { parsedFiles.put(url, parseProcessesXml(url)); } } if(parsedFiles.isEmpty()) { LOG.noProcessesXmlForPa(processApplication.getName()); } return parsedFiles; } protected List<URL> getProcessesXmlUrls(String[] deploymentDescriptors, AbstractProcessApplication processApplication) { ClassLoader processApplicationClassloader = processApplication.getProcessApplicationClassloader(); List<URL> result = new ArrayList<URL>(); // load all deployment descriptor files using the classloader of the process application for (String deploymentDescriptor : deploymentDescriptors) { Enumeration<URL> processesXmlFileLocations = null; try { processesXmlFileLocations = processApplicationClassloader.getResources(deploymentDescriptor); } catch (IOException e) { throw LOG.exceptionWhileReadingProcessesXml(deploymentDescriptor, e); } while (processesXmlFileLocations.hasMoreElements()) { result.add(processesXmlFileLocations.nextElement()); } } return result; } protected String[] getDeploymentDescriptorLocations(AbstractProcessApplication processApplication) {
ProcessApplication annotation = processApplication.getClass().getAnnotation(ProcessApplication.class); if(annotation == null) { return new String[] {ProcessApplication.DEFAULT_META_INF_PROCESSES_XML}; } else { return annotation.deploymentDescriptors(); } } protected boolean isEmptyFile(URL url) { InputStream inputStream = null; try { inputStream = url.openStream(); return inputStream.available() == 0; } catch (IOException e) { throw LOG.exceptionWhileReadingProcessesXml(url.toString(), e); } finally { IoUtil.closeSilently(inputStream); } } protected ProcessesXml parseProcessesXml(URL url) { final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser(); ProcessesXml processesXml = processesXmlParser.createParse() .sourceUrl(url) .execute() .getProcessesXml(); return processesXml; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\ParseProcessesXmlStep.java
1
请完成以下Java代码
public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectHistoricActivityInstanceByNativeQuery", parameterMap); } @Override public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectHistoricActivityInstanceCountByNativeQuery", parameterMap); } @Override public void deleteHistoricActivityInstances(HistoricActivityInstanceQueryImpl historicActivityInstanceQuery) { setSafeInValueLists(historicActivityInstanceQuery); getDbSqlSession().delete("bulkDeleteHistoricActivityInstances", historicActivityInstanceQuery, HistoricActivityInstanceEntityImpl.class); } @Override public void bulkDeleteHistoricActivityInstancesByProcessInstanceIds(Collection<String> historicProcessInstanceIds) { getDbSqlSession().delete("bulkDeleteHistoricActivityInstancesForProcessInstanceIds", createSafeInValuesList(historicProcessInstanceIds), HistoricActivityInstanceEntityImpl.class);
} @Override public void deleteHistoricActivityInstancesForNonExistingProcessInstances() { getDbSqlSession().delete("bulkDeleteHistoricActivityInstancesForNonExistingProcessInstances", null, HistoricActivityInstanceEntityImpl.class); } protected void setSafeInValueLists(HistoricActivityInstanceQueryImpl activityInstanceQuery) { if (activityInstanceQuery.getProcessInstanceIds() != null) { activityInstanceQuery.setSafeProcessInstanceIds(createSafeInValuesList(activityInstanceQuery.getProcessInstanceIds())); } if (activityInstanceQuery.getCalledProcessInstanceIds() != null) { activityInstanceQuery.setSafeCalledProcessInstanceIds(createSafeInValuesList(activityInstanceQuery.getCalledProcessInstanceIds())); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisHistoricActivityInstanceDataManager.java
1
请完成以下Java代码
public OrgId getOrgId() {return getClientAndOrgId().getOrgId();} public DDOrderCandidate withForwardPPOrderId(@Nullable final PPOrderId newPPOrderId) { final PPOrderRef forwardPPOrderRefNew = PPOrderRef.withPPOrderId(forwardPPOrderRef, newPPOrderId); if (Objects.equals(this.forwardPPOrderRef, forwardPPOrderRefNew)) { return this; } return toBuilder().forwardPPOrderRef(forwardPPOrderRefNew).build(); } public Quantity getQtyToProcess() {return getQtyEntered().subtract(getQtyProcessed());} public void setQtyProcessed(final @NonNull Quantity qtyProcessed) { Quantity.assertSameUOM(this.qtyEntered, qtyProcessed); this.qtyProcessed = qtyProcessed;
updateProcessed(); } @Nullable public OrderId getSalesOrderId() { return salesOrderLineId != null ? salesOrderLineId.getOrderId() : null; } private void updateProcessed() { this.processed = getQtyToProcess().signum() == 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public class SimulatedCandidateService { @NonNull private final CandidateRepositoryWriteService candidateService; @NonNull private final List<SimulatedCleanUpService> simulatedCleanUpServiceList; public SimulatedCandidateService( final @NonNull CandidateRepositoryWriteService candidateService, final @NonNull List<SimulatedCleanUpService> simulatedCleanUpServiceList) { this.candidateService = candidateService; this.simulatedCleanUpServiceList = simulatedCleanUpServiceList; } @NonNull public Set<CandidateId> deleteAllSimulatedCandidates() { cleanUpSimulatedRelatedRecords(); final DeleteCandidatesQuery deleteCandidatesQuery = DeleteCandidatesQuery.builder() .status(X_MD_Candidate.MD_CANDIDATE_STATUS_Simulated) .isActive(false) .build();
return candidateService.deleteCandidatesAndDetailsByQuery(deleteCandidatesQuery); } public void deactivateAllSimulatedCandidates() { candidateService.deactivateSimulatedCandidates(); } private void cleanUpSimulatedRelatedRecords() { for (final SimulatedCleanUpService cleanUpService : simulatedCleanUpServiceList) { try { cleanUpService.cleanUpSimulated(); } catch (final Exception e) { Loggables.get().addLog("{0} failed to cleanup, see error: {1}", cleanUpService.getClass().getName(), e); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\SimulatedCandidateService.java
2
请完成以下Java代码
public void setComponentsCostPrice( @NonNull final CostAmount costPrice, @NonNull final CostElementId costElementId) { pricesByElementId.computeIfAbsent(costElementId, k -> BOMCostElementPrice.zero(costElementId, costPrice.getCurrencyId(), uomId)) .setComponentsCostPrice(costPrice); } public void clearComponentsCostPrice(@NonNull final CostElementId costElementId) { final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId); if (elementCostPrice != null) { elementCostPrice.clearComponentsCostPrice(); }
} ImmutableList<BOMCostElementPrice> getElementPrices() { return ImmutableList.copyOf(pricesByElementId.values()); } <T extends RepoIdAware> Stream<T> streamIds(@NonNull final Class<T> idType) { return getElementPrices() .stream() .map(elementCostPrice -> elementCostPrice.getId(idType)) .filter(Objects::nonNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMCostPrice.java
1
请完成以下Java代码
public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); }
/** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form_Access.java
1
请完成以下Java代码
public void setRemoteAddr (final @Nullable java.lang.String RemoteAddr) { set_Value (COLUMNNAME_RemoteAddr, RemoteAddr); } @Override public java.lang.String getRemoteAddr() { return get_ValueAsString(COLUMNNAME_RemoteAddr); } @Override public void setRemoteHost (final @Nullable java.lang.String RemoteHost) { set_Value (COLUMNNAME_RemoteHost, RemoteHost); } @Override public java.lang.String getRemoteHost() { return get_ValueAsString(COLUMNNAME_RemoteHost); } @Override public void setRequestURI (final @Nullable java.lang.String RequestURI) { set_Value (COLUMNNAME_RequestURI, RequestURI); } @Override public java.lang.String getRequestURI() { return get_ValueAsString(COLUMNNAME_RequestURI); } /** * Status AD_Reference_ID=541316 * Reference name: StatusList */ public static final int STATUS_AD_Reference_ID=541316; /** Empfangen = Empfangen */ public static final String STATUS_Empfangen = "Empfangen"; /** Verarbeitet = Verarbeitet */ public static final String STATUS_Verarbeitet = "Verarbeitet"; /** Fehler = Fehler */ public static final String STATUS_Fehler = "Fehler"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus()
{ return get_ValueAsString(COLUMNNAME_Status); } @Override public void setTime (final java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } @Override public void setUI_Trace_ExternalId (final @Nullable java.lang.String UI_Trace_ExternalId) { set_Value (COLUMNNAME_UI_Trace_ExternalId, UI_Trace_ExternalId); } @Override public java.lang.String getUI_Trace_ExternalId() { return get_ValueAsString(COLUMNNAME_UI_Trace_ExternalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit.java
1
请完成以下Java代码
public String getMeta_Content () { return (String)get_Value(COLUMNNAME_Meta_Content); } /** Set Meta Copyright. @param Meta_Copyright Contains Copyright information for the content */ public void setMeta_Copyright (String Meta_Copyright) { set_Value (COLUMNNAME_Meta_Copyright, Meta_Copyright); } /** Get Meta Copyright. @return Contains Copyright information for the content */ public String getMeta_Copyright () { return (String)get_Value(COLUMNNAME_Meta_Copyright); } /** Set Meta Publisher. @param Meta_Publisher Meta Publisher defines the publisher of the content */ public void setMeta_Publisher (String Meta_Publisher) { set_Value (COLUMNNAME_Meta_Publisher, Meta_Publisher); } /** Get Meta Publisher. @return Meta Publisher defines the publisher of the content */ public String getMeta_Publisher () { return (String)get_Value(COLUMNNAME_Meta_Publisher); } /** Set Meta RobotsTag. @param Meta_RobotsTag RobotsTag defines how search robots should handle this content */
public void setMeta_RobotsTag (String Meta_RobotsTag) { set_Value (COLUMNNAME_Meta_RobotsTag, Meta_RobotsTag); } /** Get Meta RobotsTag. @return RobotsTag defines how search robots should handle this content */ public String getMeta_RobotsTag () { return (String)get_Value(COLUMNNAME_Meta_RobotsTag); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java
1
请完成以下Java代码
public class ReturnedMessage { private final Message message; private final int replyCode; private final String replyText; private final String exchange; private final String routingKey; public ReturnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { this.message = message; this.replyCode = replyCode; this.replyText = replyText; this.exchange = exchange; this.routingKey = routingKey; } /** * Get the message. * @return the message. */ public Message getMessage() { return this.message; } /** * Get the reply code. * @return the reply code. */ public int getReplyCode() { return this.replyCode; } /**
* Get the reply text. * @return the reply text. */ public String getReplyText() { return this.replyText; } /** * Get the exchange. * @return the exchange name. */ public String getExchange() { return this.exchange; } /** * Get the routing key. * @return the routing key. */ public String getRoutingKey() { return this.routingKey; } @Override public String toString() { return "ReturnedMessage [message=" + this.message + ", replyCode=" + this.replyCode + ", replyText=" + this.replyText + ", exchange=" + this.exchange + ", routingKey=" + this.routingKey + "]"; } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\ReturnedMessage.java
1
请完成以下Java代码
public void deleteDeploymentAndRelatedData(String deploymentId, boolean cascade) { AppDefinitionEntityManager appDefinitionEntityManager = getAppDefinitionEntityManager(); List<AppDefinition> appDefinitions = appDefinitionEntityManager.createAppDefinitionQuery().deploymentId(deploymentId).list(); for (AppDefinition appDefinition : appDefinitions) { if (cascade) { appDefinitionEntityManager.deleteAppDefinitionAndRelatedData(appDefinition.getId()); } else { appDefinitionEntityManager.delete(appDefinition.getId()); } } getAppResourceEntityManager().deleteResourcesByDeploymentId(deploymentId); delete(findById(deploymentId)); } @Override public AppDeploymentEntity findLatestDeploymentByName(String deploymentName) { return dataManager.findLatestDeploymentByName(deploymentName); } @Override public List<String> getDeploymentResourceNames(String deploymentId) { return dataManager.getDeploymentResourceNames(deploymentId); } @Override
public AppDeploymentQuery createDeploymentQuery() { return new AppDeploymentQueryImpl(engineConfiguration.getCommandExecutor()); } @Override public List<AppDeployment> findDeploymentsByQueryCriteria(AppDeploymentQuery deploymentQuery) { return dataManager.findDeploymentsByQueryCriteria((AppDeploymentQueryImpl) deploymentQuery); } @Override public long findDeploymentCountByQueryCriteria(AppDeploymentQuery deploymentQuery) { return dataManager.findDeploymentCountByQueryCriteria((AppDeploymentQueryImpl) deploymentQuery); } protected AppResourceEntityManager getAppResourceEntityManager() { return engineConfiguration.getAppResourceEntityManager(); } protected AppDefinitionEntityManager getAppDefinitionEntityManager() { return engineConfiguration.getAppDefinitionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityManagerImpl.java
1
请完成以下Java代码
public void attachURL( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentId, @RequestBody @NonNull final JSONAttachURLRequest request) { userSession.assertLoggedIn(); getDocumentAttachments(windowIdStr, documentId) .addURLEntry(request.getName(), request.getUri()); } @GetMapping public List<JSONAttachment> getAttachments( @PathVariable("windowId") final String windowIdStr // , @PathVariable("documentId") final String documentId // ) { userSession.assertLoggedIn(); final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), documentId); if (documentPath.isComposedKey()) { // document with composed keys does not support attachments return ImmutableList.of(); } final boolean allowDelete = isAllowDeletingAttachments(); final List<JSONAttachment> attachments = getDocumentAttachments(documentPath) .toJson(); attachments.forEach(attachment -> attachment.setAllowDelete(allowDelete)); return attachments; } private boolean isAllowDeletingAttachments() { return userSession .getUserRolePermissions() .hasPermission(IUserRolePermissions.PERMISSION_IsAttachmentDeletionAllowed); } @GetMapping("/{id}") public ResponseEntity<StreamingResponseBody> getAttachmentById( @PathVariable("windowId") final String windowIdStr // , @PathVariable("documentId") final String documentId // , @PathVariable("id") final String entryIdStr) { userSession.assertLoggedIn(); final DocumentId entryId = DocumentId.of(entryIdStr.toUpperCase()); final IDocumentAttachmentEntry entry = getDocumentAttachments(windowIdStr, documentId) .getEntry(entryId); return toResponseBody(entry); } @NonNull private static ResponseEntity<StreamingResponseBody> toResponseBody(@NonNull final IDocumentAttachmentEntry entry) { final AttachmentEntryType type = entry.getType(); switch (type)
{ case Data: return DocumentAttachmentRestControllerHelper.extractResponseEntryFromData(entry); case URL: return DocumentAttachmentRestControllerHelper.extractResponseEntryFromURL(entry); case LocalFileURL: return DocumentAttachmentRestControllerHelper.extractResponseEntryFromLocalFileURL(entry); default: throw new AdempiereException("Invalid attachment entry") .setParameter("reason", "invalid type") .setParameter("type", type) .setParameter("entry", entry); } } @DeleteMapping("/{id}") public void deleteAttachmentById( @PathVariable("windowId") final String windowIdStr // , @PathVariable("documentId") final String documentId // , @PathVariable("id") final String entryIdStr // ) { userSession.assertLoggedIn(); if (!isAllowDeletingAttachments()) { throw new AdempiereException("Delete not allowed"); } final DocumentId entryId = DocumentId.of(entryIdStr); getDocumentAttachments(windowIdStr, documentId) .deleteEntry(entryId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentsRestController.java
1
请完成以下Java代码
public @NonNull String getSourceTableName() { return I_C_Order_Line_Alloc.Table_Name; } @Override public List<String> getSourceColumnNames() { return Collections.emptyList(); } /** * Updates the ASI of the <code>C_Order_Line_Alloc</code>'s <code>C_OrderLine</code> with the BPartner's ADR attribute, <b>if</b> that order line is a purchase order line. */ @Override public void modelChanged(Object model) { final I_C_Order_Line_Alloc alloc = InterfaceWrapperHelper.create(model, I_C_Order_Line_Alloc.class); final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(alloc.getC_OrderLine(), I_C_OrderLine.class); // final boolean forceApply = isEDIInput(alloc); // task 08692: We needed to copy the attribute even if it's a SO transaction, if this OL_Cand is about EDI, however...
final boolean forceApply = false; // task 08803 ...as of now, EDI-order lines shall have the same attribute values that manually created order lines have. new BPartnerAwareAttributeUpdater() .setBPartnerAwareFactory(OrderLineBPartnerAware.factory) .setBPartnerAwareAttributeService(Services.get(IADRAttributeBL.class)) .setSourceModel(orderLine) .setForceApplyForSOTrx(forceApply) .updateASI(); } @SuppressWarnings("unused") private boolean isEDIInput(final I_C_Order_Line_Alloc alloc) { // Services final IEDIOLCandBL ediOLCandBL = Services.get(IEDIOLCandBL.class); final I_C_OLCand olCand = alloc.getC_OLCand(); return ediOLCandBL.isEDIInput(olCand); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\listeners\adr\OrderLineAllocADRModelAttributeSetInstanceListener.java
1
请完成以下Java代码
public class WidgetTypeStandardNumberPrecision { public static final WidgetTypeStandardNumberPrecision DEFAULT = builder() .amountPrecision(OptionalInt.of(2)) .costPricePrecision(OptionalInt.of(2)) .build(); @NonNull private final OptionalInt amountPrecision; @NonNull private final OptionalInt costPricePrecision; @NonNull private final OptionalInt quantityPrecision; private static final OptionalInt ZERO = OptionalInt.of(0); @Builder private WidgetTypeStandardNumberPrecision( final @Nullable OptionalInt amountPrecision, final @Nullable OptionalInt costPricePrecision, final @Nullable OptionalInt quantityPrecision) { this.amountPrecision = CoalesceUtil.coalesceNotNull(amountPrecision, OptionalInt::empty); this.costPricePrecision = CoalesceUtil.coalesceNotNull(costPricePrecision, OptionalInt::empty); this.quantityPrecision = CoalesceUtil.coalesceNotNull(quantityPrecision, OptionalInt::empty); } public OptionalInt getMinPrecision(@NonNull DocumentFieldWidgetType widgetType) { switch (widgetType) { case Integer: return ZERO; case CostPrice: return costPricePrecision; case Amount: return amountPrecision; case Quantity: return quantityPrecision; default: return OptionalInt.empty(); } }
public WidgetTypeStandardNumberPrecision fallbackTo(@NonNull WidgetTypeStandardNumberPrecision other) { return builder() .amountPrecision(firstPresent(this.amountPrecision, other.amountPrecision)) .costPricePrecision(firstPresent(this.costPricePrecision, other.costPricePrecision)) .quantityPrecision(firstPresent(this.quantityPrecision, other.quantityPrecision)) .build(); } private static OptionalInt firstPresent(final OptionalInt optionalInt1, final OptionalInt optionalInt2) { if (optionalInt1 != null && optionalInt1.isPresent()) { return optionalInt1; } else if (optionalInt2 != null && optionalInt2.isPresent()) { return optionalInt2; } else { return OptionalInt.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\WidgetTypeStandardNumberPrecision.java
1
请完成以下Java代码
protected final void closeAllViewsAndShowInitialView() { closeAllViewsExcludingInitialView(); afterCloseOpenView(getInitialViewId()); } private final void closeAllViewsExcludingInitialView() { IView currentView = getView(); while (currentView != null && currentView.getParentViewId() != null) { try { viewsRepo.closeView(currentView.getViewId(), ViewCloseAction.CANCEL); } catch (Exception ex) { logger.warn("Failed closing view {}. Ignored", currentView, ex);
} final ViewId viewId = currentView.getParentViewId(); currentView = viewsRepo.getViewIfExists(viewId); } } protected final void afterCloseOpenView(final ViewId viewId) { getResult().setWebuiViewToOpen(WebuiViewToOpen.builder() .viewId(viewId.toJson()) .target(ViewOpenTarget.ModalOverlay) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\process\ProductsProposalViewBasedProcess.java
1
请完成以下Java代码
private String getAuthenticationType(AuthorizationObservationContext<?> context) { if (context.getAuthentication() == null) { return "n/a"; } return context.getAuthentication().getClass().getSimpleName(); } private String getObjectType(AuthorizationObservationContext<?> context) { if (context.getObject() == null) { return "unknown"; } if (context.getObject() instanceof MethodInvocation) { return "method"; } String className = context.getObject().getClass().getSimpleName(); if (className.contains("Method")) { return "method"; } if (className.contains("Request")) { return "request"; } if (className.contains("Message")) { return "message"; } if (className.contains("Exchange")) { return "exchange"; } return className; } private String getAuthorizationDecision(AuthorizationObservationContext<?> context) {
if (context.getAuthorizationResult() == null) { return "unknown"; } return String.valueOf(context.getAuthorizationResult().isGranted()); } private String getAuthorities(AuthorizationObservationContext<?> context) { if (context.getAuthentication() == null) { return "n/a"; } return String.valueOf(context.getAuthentication().getAuthorities()); } private String getDecisionDetails(AuthorizationObservationContext<?> context) { if (context.getAuthorizationResult() == null) { return "unknown"; } AuthorizationResult decision = context.getAuthorizationResult(); return String.valueOf(decision); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationObservationConvention.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<SecurPharmConfig> getDefaultConfig() { return getDefaultConfigId().map(this::getById); } private Optional<SecurPharmConfigId> getDefaultConfigId() { return defaultConfigIdCache.getOrLoad(0, this::retrieveDefaultConfigId); } private Optional<SecurPharmConfigId> retrieveDefaultConfigId() { final IQueryBL queryBL = Services.get(IQueryBL.class); final SecurPharmConfigId configId = queryBL .createQueryBuilder(I_M_Securpharm_Config.class) .addOnlyActiveRecordsFilter() .create() .firstIdOnly(SecurPharmConfigId::ofRepoIdOrNull); return Optional.ofNullable(configId); } @Override
public SecurPharmConfig getById(@NonNull final SecurPharmConfigId configId) { return configsCache.getOrLoad(configId, this::retrieveById); } private SecurPharmConfig retrieveById(@NonNull final SecurPharmConfigId configId) { final I_M_Securpharm_Config record = loadOutOfTrx(configId, I_M_Securpharm_Config.class); return ofRecord(record); } private static SecurPharmConfig ofRecord(@NonNull final I_M_Securpharm_Config config) { return SecurPharmConfig.builder() .id(SecurPharmConfigId.ofRepoId(config.getM_Securpharm_Config_ID())) .certificatePath(config.getCertificatePath()) .applicationUUID(config.getApplicationUUID()) .authBaseUrl(config.getAuthPharmaRestApiBaseURL()) .pharmaAPIBaseUrl(config.getPharmaRestApiBaseURL()) .keystorePassword(config.getTanPassword()) .supportUserId(UserId.ofRepoId(config.getSupport_User_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\config\DatabaseBackedSecurPharmConfigRespository.java
2
请完成以下Java代码
protected void prepare() { final IRangeAwareParams params = getParameterAsIParams(); warehouseFromId = getWarehouseId(params, "M_Warehouse_ID"); warehouseToId = getWarehouseId(params, "M_Warehouse_Dest_ID"); // make sure user selected different warehouses if (WarehouseId.equals(warehouseFromId, warehouseToId)) { throw new AdempiereException("@M_Warehouse_ID@ = @M_Warehouse_Dest_ID@"); } } private WarehouseId getWarehouseId(final IRangeAwareParams params, final String warehouseParameterName) { final WarehouseId warehouseId = WarehouseId.ofRepoIdOrNull(params.getParameterAsInt(warehouseParameterName, -1)); if (warehouseId == null) { throw new FillMandatoryException(warehouseParameterName); } return warehouseId; } @Override @RunOutOfTrx protected String doIt() { final LocatorId locatorToId = warehouseBL.getOrCreateDefaultLocatorId(warehouseToId); final OrgId orgId = warehouseBL.getWarehouseOrgId(warehouseToId); final BPartnerLocationId orgBPLocationId = bpartnerOrgBL.retrieveOrgBPLocationId(orgId); HUs2DDOrderProducer.newProducer(ddOrderMoveScheduleService) .setLocatorToId(locatorToId) .setBpartnerLocationId(orgBPLocationId) .setHUs(retrieveHUs()) .setWarehouseFromId(warehouseFromId) .process(); return MSG_OK;
} private Iterator<HUToDistribute> retrieveHUs() { return handlingUnitsDAO.createHUQueryBuilder() .setContext(getCtx(), ITrx.TRXNAME_ThreadInherited) .setOnlyTopLevelHUs() .addOnlyInWarehouseId(warehouseFromId) .addOnlyWithAttribute(IHUMaterialTrackingBL.ATTRIBUTENAME_IsQualityInspection, IHUMaterialTrackingBL.ATTRIBUTEVALUE_IsQualityInspection_Yes) .addHUStatusToInclude(X_M_HU.HUSTATUS_Active) .addFilter(ddOrderMoveScheduleService.getHUsNotAlreadyScheduledToMoveFilter()) // .createQuery() .stream(I_M_HU.class) .map(HUToDistribute::ofHU) .iterator(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\process\DD_Order_GenerateForQualityInspectionFlaggedHUs.java
1
请在Spring Boot框架中完成以下Java代码
public void restoreBook() { bookRepository.restoreById(1L); } @Transactional public void restoreAuthor() { authorRepository.restoreById(1L); bookRepository.restoreByAuthorId(1L); } public void displayAllExceptDeletedAuthors() { List<Author> authors = authorRepository.findAll(); System.out.println("\nAll authors except deleted:"); authors.forEach(a -> System.out.println("Author name: " + a.getName())); System.out.println(); } public void displayAllIncludeDeletedAuthors() { List<Author> authors = authorRepository.findAllIncludingDeleted(); System.out.println("\nAll authors including deleted:"); authors.forEach(a -> System.out.println("Author name: " + a.getName())); System.out.println(); } public void displayAllOnlyDeletedAuthors() { List<Author> authors = authorRepository.findAllOnlyDeleted(); System.out.println("\nAll deleted authors:"); authors.forEach(a -> System.out.println("Author name: " + a.getName())); System.out.println(); } public void displayAllExceptDeletedBooks() {
List<Book> books = bookRepository.findAll(); System.out.println("\nAll books except deleted:"); books.forEach(b -> System.out.println("Book title: " + b.getTitle())); System.out.println(); } public void displayAllIncludeDeletedBooks() { List<Book> books = bookRepository.findAllIncludingDeleted(); System.out.println("\nAll books including deleted:"); books.forEach(b -> System.out.println("Book title: " + b.getTitle())); System.out.println(); } public void displayAllOnlyDeletedBooks() { List<Book> books = bookRepository.findAllOnlyDeleted(); System.out.println("\nAll deleted books:"); books.forEach(b -> System.out.println("Book title: " + b.getTitle())); System.out.println(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSoftDeletes\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public boolean isAlreadyPacked(@NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final HuPackingInstructionsId packingInstructionsId) { return isSingleProductWithQtyEqualsTo(productId, qty) && HuPackingInstructionsId.equals(packingInstructionsId, getPackingInstructionsId()); } public boolean isSingleProductWithQtyEqualsTo(@NonNull final ProductId productId, @NonNull final Quantity qty) { return getStorage().isSingleProductWithQtyEqualsTo(productId, qty); } @NonNull public HuPackingInstructionsId getPackingInstructionsId() { HuPackingInstructionsId packingInstructionsId = this._packingInstructionsId; if (packingInstructionsId == null) { packingInstructionsId = this._packingInstructionsId = handlingUnitsBL.getPackingInstructionsId(hu); } return packingInstructionsId; } } // // // ------------------------------------ // // private static class PickFromHUsList { private final ArrayList<PickFromHU> list = new ArrayList<>(); PickFromHUsList() {} public void add(@NonNull final PickFromHU pickFromHU) {list.add(pickFromHU);} public List<I_M_HU> toHUsList() {return list.stream().map(PickFromHU::toM_HU).collect(ImmutableList.toImmutableList());} public PickFromHU getSingleHU() {return CollectionUtils.singleElement(list);} public boolean isSingleHUAlreadyPacked( final boolean checkIfAlreadyPacked, @NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final HuPackingInstructionsId packingInstructionsId) { if (list.size() != 1) { return false; } final PickFromHU hu = list.get(0); // NOTE we check isGeneratedFromInventory because we want to avoid splitting an HU that we just generated it, even if checkIfAlreadyPacked=false if (checkIfAlreadyPacked || hu.isGeneratedFromInventory()) { return hu.isAlreadyPacked(productId, qty, packingInstructionsId);
} else { return false; } } } // // // ------------------------------------ // // @Value(staticConstructor = "of") @EqualsAndHashCode(doNotUseGetters = true) private static class HuPackingInstructionsIdAndCaptionAndCapacity { @NonNull HuPackingInstructionsId huPackingInstructionsId; @NonNull String caption; @Nullable Capacity capacity; @Nullable public Capacity getCapacityOrNull() {return capacity;} @SuppressWarnings("unused") @NonNull public Optional<Capacity> getCapacity() {return Optional.ofNullable(capacity);} public TUPickingTarget toTUPickingTarget() { return TUPickingTarget.ofPackingInstructions(huPackingInstructionsId, caption); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackToHUsProducer.java
1
请完成以下Java代码
public ShipmentScheduleSegmentBuilder productId(final int productId) { productIds.add(productId); return this; } public ShipmentScheduleSegmentBuilder bpartnerId(final int bpartnerId) { bpartnerIds.add(bpartnerId); return this; } public ShipmentScheduleSegmentBuilder locatorId(final int locatorId) { locatorIds.add(locatorId); return this; } public ShipmentScheduleSegmentBuilder locator(final I_M_Locator locator) { if (locator == null) { return this; } locatorIds.add(locator.getM_Locator_ID()); return this; } public ShipmentScheduleSegmentBuilder warehouseId(@NonNull final WarehouseId warehouseId) { final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); final List<LocatorId> locatorIds = warehouseDAO.getLocatorIds(warehouseId); for (final LocatorId locatorId : locatorIds) { locatorId(locatorId.getRepoId()); } return this; }
public ShipmentScheduleSegmentBuilder warehouseIdIfNotNull(final @Nullable WarehouseId warehouseId) { if (warehouseId == null) { return this; } return warehouseId(warehouseId); } public ShipmentScheduleSegmentBuilder attributeSetInstanceId(final int M_AttributeSetInstance_ID) { final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(M_AttributeSetInstance_ID); return attributeSetInstanceId(asiId); } private ShipmentScheduleSegmentBuilder attributeSetInstanceId(@NonNull final AttributeSetInstanceId asiId) { final ShipmentScheduleAttributeSegment attributeSegment = ShipmentScheduleAttributeSegment.ofAttributeSetInstanceId(asiId); attributeSegments.add(attributeSegment); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\segments\ShipmentScheduleSegmentBuilder.java
1
请完成以下Java代码
public List<Map.Entry<Integer, Float>> nearest(String query) { return queryNearest(query, 10); } /** * 查询最相似的前n个文档 * * @param query 查询语句(或者说一个文档的内容) * @return */ public List<Map.Entry<Integer, Float>> nearest(String query, int n) { return queryNearest(query, n); } /** * 将一个文档转为向量 * * @param content 文档 * @return 向量 */ public Vector query(String content) { if (content == null || content.length() == 0) return null; List<Term> termList = segment.seg(content); if (filter) { CoreStopWordDictionary.apply(termList); } Vector result = new Vector(dimension()); int n = 0; for (Term term : termList) { Vector vector = wordVectorModel.vector(term.word); if (vector == null) { continue; } ++n; result.addToSelf(vector); } if (n == 0) { return null; } result.normalize(); return result; } @Override public int dimension() { return wordVectorModel.dimension(); } /** * 文档相似度计算 * * @param what * @param with * @return */ public float similarity(String what, String with)
{ Vector A = query(what); if (A == null) return -1f; Vector B = query(with); if (B == null) return -1f; return A.cosineForUnitVector(B); } public Segment getSegment() { return segment; } public void setSegment(Segment segment) { this.segment = segment; } /** * 是否激活了停用词过滤器 * * @return */ public boolean isFilterEnabled() { return filter; } /** * 激活/关闭停用词过滤器 * * @param filter */ public void enableFilter(boolean filter) { this.filter = filter; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\DocVectorModel.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getName() { if (name == null) { name = new ArrayList<String>(); } return this.name; } /** * Gets the value of the department property. * * @return * possible object is * {@link String } * */ public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the street property. * * @return * possible object is * {@link String } * */ public String getStreet() { return street; } /** * Sets the value of the street property. * * @param value * allowed object is * {@link String } * */ public void setStreet(String value) { this.street = value; } /** * Gets the value of the zip property. * * @return * possible object is * {@link String } * */ public String getZIP() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link String } * */ public void setZIP(String value) { this.zip = value; } /** * Gets the value of the town property. * * @return * possible object is * {@link String } *
*/ public String getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is * {@link String } * */ public void setTown(String value) { this.town = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link String } * */ public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */ public void setCountry(String value) { this.country = value; } /** * Details about the contact person at the delivery point. * * @return * possible object is * {@link ContactType } * */ public ContactType getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link ContactType } * */ public void setContact(ContactType value) { this.contact = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DeliveryPointDetails.java
2
请在Spring Boot框架中完成以下Java代码
public class TenantAwareAcquireTimerJobsRunnable extends AcquireTimerJobsRunnable { protected TenantInfoHolder tenantInfoHolder; protected String tenantId; public TenantAwareAcquireTimerJobsRunnable(AsyncExecutor asyncExecutor, TenantInfoHolder tenantInfoHolder, String tenantId, int moveExecutorPoolSize) { this(asyncExecutor, tenantInfoHolder, tenantId, null, AcquireJobsRunnableConfiguration.DEFAULT, moveExecutorPoolSize); } public TenantAwareAcquireTimerJobsRunnable(AsyncExecutor asyncExecutor, TenantInfoHolder tenantInfoHolder, String tenantId, AcquireTimerLifecycleListener lifecycleListener, AcquireJobsRunnableConfiguration configuration, int moveExecutorPoolSize) { super(asyncExecutor, asyncExecutor.getJobServiceConfiguration().getJobManager(), lifecycleListener, configuration, moveExecutorPoolSize); this.tenantInfoHolder = tenantInfoHolder; this.tenantId = tenantId; } protected ExecutorPerTenantAsyncExecutor getTenantAwareAsyncExecutor() { return (ExecutorPerTenantAsyncExecutor) asyncExecutor;
} @Override public synchronized void run() { tenantInfoHolder.setCurrentTenantId(tenantId); super.run(); tenantInfoHolder.clearCurrentTenantId(); } @Override protected void executeMoveTimerJobsToExecutableJobs(List<TimerJobEntity> timerJobs) { try { tenantInfoHolder.setCurrentTenantId(tenantId); super.executeMoveTimerJobsToExecutableJobs(timerJobs); } finally { tenantInfoHolder.clearCurrentTenantId(); } } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\multitenant\TenantAwareAcquireTimerJobsRunnable.java
2
请在Spring Boot框架中完成以下Java代码
public void saveData(RpUserPayInfo rpUserPayInfo) { rpUserPayInfoDao.insert(rpUserPayInfo); } @Override public void updateData(RpUserPayInfo rpUserPayInfo) { rpUserPayInfoDao.update(rpUserPayInfo); } @Override public RpUserPayInfo getDataById(String id) { return rpUserPayInfoDao.getById(id); } @Override
public PageBean listPage(PageParam pageParam, RpUserPayInfo rpUserPayInfo) { Map<String, Object> paramMap = new HashMap<String, Object>(); return rpUserPayInfoDao.listPage(pageParam, paramMap); } /** * 通过商户编号获取商户支付配置信息 * * @param userNO * @return */ @Override public RpUserPayInfo getByUserNo(String userNo, String payWayCode) { return rpUserPayInfoDao.getByUserNo(userNo, payWayCode); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpUserPayInfoServiceImpl.java
2
请完成以下Java代码
public class ChildrenImpl extends CmmnElementImpl implements Children { protected static ChildElementCollection<CaseFileItem> caseFileItemCollection; public ChildrenImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Collection<CaseFileItem> getCaseFileItems() { return caseFileItemCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Children.class, CMMN_ELEMENT_CHILDREN) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<Children>() { public Children newInstance(ModelTypeInstanceContext instanceContext) { return new ChildrenImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); caseFileItemCollection = sequenceBuilder.elementCollection(CaseFileItem.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ChildrenImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Column(unique = true) private String email; private boolean activated; public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\detachentity\domain\User.java
2
请完成以下Java代码
public abstract class SpringCamelBehavior extends CamelBehavior { private static final long serialVersionUID = 1L; protected final Object contextLock = new Object(); @Override protected CamelContext getCamelContext(DelegateExecution execution, boolean isV5Execution) { // Get the appropriate String representation of the CamelContext object // from ActivityExecution (if available). String camelContextValue = getStringFromField(camelContext, execution); if (StringUtils.isEmpty(camelContextValue)) { if (camelContextObj != null) { // No processing required. No custom CamelContext & the default is already set. return camelContextObj; } // Use a lock to resolve the default camel context. synchronized (contextLock) { // Check again, in case another thread set the member variable in the meantime. if (camelContextObj != null) { return camelContextObj; } camelContextObj = resolveCamelContext(camelContextValue, isV5Execution); } return camelContextObj; } else { return resolveCamelContext(camelContextValue, isV5Execution); } } protected CamelContext resolveCamelContext(String camelContextValue, boolean isV5Execution) { ProcessEngineConfiguration engineConfiguration = org.flowable.engine.impl.context.Context.getProcessEngineConfiguration(); if (isV5Execution) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); return (CamelContext) compatibilityHandler.getCamelContextObject(camelContextValue); } else {
// Convert it to a SpringProcessEngineConfiguration. If this doesn't work, throw a RuntimeException. try { SpringProcessEngineConfiguration springConfiguration = (SpringProcessEngineConfiguration) engineConfiguration; if (StringUtils.isEmpty(camelContextValue)) { camelContextValue = springConfiguration.getDefaultCamelContext(); } // Get the CamelContext object and set the super's member variable. Object ctx = springConfiguration.getApplicationContext().getBean(camelContextValue); if (!(ctx instanceof SpringCamelContext)) { throw new FlowableException("Could not find CamelContext named " + camelContextValue + "."); } return (SpringCamelContext) ctx; } catch (Exception e) { throw new FlowableException("Expecting a SpringProcessEngineConfiguration for the Camel module.", e); } } } }
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\SpringCamelBehavior.java
1
请完成以下Java代码
public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; return Objects.equals(id, book.id); } @Override public int hashCode() { return Objects.hash(id); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\logging\model\Book.java
1
请完成以下Java代码
public Optional<Amount> getServiceFeeInREMADVCurrency(@NonNull final RemittanceAdviceLine remittanceAdviceLine) { if (remittanceAdviceLine.getServiceFeeAmount() == null || remittanceAdviceLine.getServiceFeeAmount().isZero()) { return Optional.empty(); } final Amount serviceFeeAmount = remittanceAdviceLine.getServiceFeeAmount(); if (serviceFeeAmount.getCurrencyCode().equals(remittanceAdviceLine.getRemittedAmount().getCurrencyCode())) { return Optional.of(serviceFeeAmount); } final Instant conversionDate = SystemTime.asInstant(); final CurrencyConversionContext currencyConversionContext = currencyConversionBL.createCurrencyConversionContext(conversionDate, ConversionTypeMethod.Spot,
Env.getClientId(), remittanceAdviceLine.getOrgId()); final Currency serviceFeeCurrency = currencyDAO.getByCurrencyCode(serviceFeeAmount.getCurrencyCode()); final Currency remittedCurrency = currencyDAO.getByCurrencyCode(remittanceAdviceLine.getRemittedAmount().getCurrencyCode()); final Money serviceFeeMoney = Money.of(serviceFeeAmount.toBigDecimal(), serviceFeeCurrency.getId()); final Money serviceFeeInRemittedCurrency = moneyService .convertMoneyToCurrency(serviceFeeMoney, remittedCurrency.getId(), currencyConversionContext); final Amount serviceFeeAmountInRemadvCurr = Amount.of(serviceFeeInRemittedCurrency.toBigDecimal(), remittedCurrency.getCurrencyCode()); return Optional.of(serviceFeeAmountInRemadvCurr); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\RemittanceAdviceService.java
1
请完成以下Java代码
public static <T> Set<T> asHashSet(T... elements) { Set<T> set = new HashSet<>(); Collections.addAll(set, elements); return set; } public static <S, T> void addToMapOfLists(Map<S, List<T>> map, S key, T value) { List<T> list = map.get(key); if (list == null) { list = new ArrayList<>(); map.put(key, list); } list.add(value); } public static <S, T> void mergeMapsOfLists(Map<S, List<T>> map, Map<S, List<T>> toAdd) { for (Entry<S, List<T>> entry : toAdd.entrySet()) { for (T listener : entry.getValue()) { CollectionUtil.addToMapOfLists(map, entry.getKey(), listener); } } } public static <S, T> void addToMapOfSets(Map<S, Set<T>> map, S key, T value) { Set<T> set = map.get(key); if (set == null) { set = new HashSet<>(); map.put(key, set); } set.add(value); } public static <S, T> void addCollectionToMapOfSets(Map<S, Set<T>> map, S key, Collection<T> values) { Set<T> set = map.get(key); if (set == null) { set = new HashSet<>(); map.put(key, set); } set.addAll(values); } /** * Chops a list into non-view sublists of length partitionSize. Note: the argument list * may be included in the result. */ public static <T> List<List<T>> partition(List<T> list, final int partitionSize) {
List<List<T>> parts = new ArrayList<>(); final int listSize = list.size(); if (listSize <= partitionSize) { // no need for partitioning parts.add(list); } else { for (int i = 0; i < listSize; i += partitionSize) { parts.add(new ArrayList<>(list.subList(i, Math.min(listSize, i + partitionSize)))); } } return parts; } public static <T> List<T> collectInList(Iterator<T> iterator) { List<T> result = new ArrayList<>(); while (iterator.hasNext()) { result.add(iterator.next()); } return result; } public static <T> T getLastElement(final Iterable<T> elements) { T lastElement = null; if (elements instanceof List) { return ((List<T>) elements).get(((List<T>) elements).size() - 1); } for (T element : elements) { lastElement = element; } return lastElement; } public static boolean isEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CollectionUtil.java
1
请完成以下Java代码
public boolean isPrintoutForOtherUser() { return get_ValueAsBoolean(COLUMNNAME_IsPrintoutForOtherUser); } /** * ItemName AD_Reference_ID=540735 * Reference name: ItemName */ public static final int ITEMNAME_AD_Reference_ID=540735; /** Rechnung = Rechnung */ public static final String ITEMNAME_Rechnung = "Rechnung"; /** Mahnung = Mahnung */ public static final String ITEMNAME_Mahnung = "Mahnung"; /** Mitgliedsausweis = Mitgliedsausweis */ public static final String ITEMNAME_Mitgliedsausweis = "Mitgliedsausweis"; /** Brief = Brief */ public static final String ITEMNAME_Brief = "Brief"; /** Sofort-Druck PDF = Sofort-Druck PDF */ public static final String ITEMNAME_Sofort_DruckPDF = "Sofort-Druck PDF"; /** PDF = PDF */ public static final String ITEMNAME_PDF = "PDF"; /** Versand/Wareneingang = Versand/Wareneingang */ public static final String ITEMNAME_VersandWareneingang = "Versand/Wareneingang"; @Override public void setItemName (final @Nullable java.lang.String ItemName) { set_Value (COLUMNNAME_ItemName, ItemName); } @Override public java.lang.String getItemName() { return get_ValueAsString(COLUMNNAME_ItemName); } @Override public void setPrintingQueueAggregationKey (final @Nullable java.lang.String PrintingQueueAggregationKey) { set_Value (COLUMNNAME_PrintingQueueAggregationKey, PrintingQueueAggregationKey); }
@Override public java.lang.String getPrintingQueueAggregationKey() { return get_ValueAsString(COLUMNNAME_PrintingQueueAggregationKey); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue.java
1
请完成以下Java代码
public HUEditorViewBuilder setFilters(final DocumentFilterList filters) { this.filters = filters; return this; } DocumentFilterList getFilters() { return filters != null ? filters : DocumentFilterList.EMPTY; } public HUEditorViewBuilder orderBy(@NonNull final DocumentQueryOrderBy orderBy) { if (orderBys == null) { orderBys = new ArrayList<>(); } orderBys.add(orderBy); return this; } public HUEditorViewBuilder orderBys(@NonNull final DocumentQueryOrderByList orderBys) { this.orderBys = new ArrayList<>(orderBys.toList()); return this; } public HUEditorViewBuilder clearOrderBys() { this.orderBys = null; return this; } private DocumentQueryOrderByList getOrderBys() { return DocumentQueryOrderByList.ofList(orderBys); } public HUEditorViewBuilder setParameter(final String name, @Nullable final Object value) { if (value == null) { if (parameters != null) { parameters.remove(name); } } else { if (parameters == null) { parameters = new LinkedHashMap<>(); } parameters.put(name, value); } return this; } public HUEditorViewBuilder setParameters(final Map<String, Object> parameters) { parameters.forEach(this::setParameter); return this; } ImmutableMap<String, Object> getParameters()
{ return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of(); } @Nullable public <T> T getParameter(@NonNull final String name) { if (parameters == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)parameters.get(name); return value; } public void assertParameterSet(final String name) { final Object value = getParameter(name); if (value == null) { throw new AdempiereException("Parameter " + name + " is expected to be set in " + parameters + " for " + this); } } public HUEditorViewBuilder setHUEditorViewRepository(final HUEditorViewRepository huEditorViewRepository) { this.huEditorViewRepository = huEditorViewRepository; return this; } HUEditorViewBuffer createRowsBuffer(@NonNull final SqlDocumentFilterConverterContext context) { final ViewId viewId = getViewId(); final DocumentFilterList stickyFilters = getStickyFilters(); final DocumentFilterList filters = getFilters(); if (HUEditorViewBuffer_HighVolume.isHighVolume(stickyFilters)) { return new HUEditorViewBuffer_HighVolume(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context); } else { return new HUEditorViewBuffer_FullyCached(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context); } } public HUEditorViewBuilder setUseAutoFilters(final boolean useAutoFilters) { this.useAutoFilters = useAutoFilters; return this; } public boolean isUseAutoFilters() { return useAutoFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class X_C_Project_Repair_Consumption_Summary extends org.compiere.model.PO implements I_C_Project_Repair_Consumption_Summary, org.compiere.model.I_Persistent { private static final long serialVersionUID = 866752045L; /** Standard Constructor */ public X_C_Project_Repair_Consumption_Summary (final Properties ctx, final int C_Project_Repair_Consumption_Summary_ID, @Nullable final String trxName) { super (ctx, C_Project_Repair_Consumption_Summary_ID, trxName); } /** Load Constructor */ public X_C_Project_Repair_Consumption_Summary (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public void setC_Project_Repair_Consumption_Summary_ID (final int C_Project_Repair_Consumption_Summary_ID) { if (C_Project_Repair_Consumption_Summary_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, C_Project_Repair_Consumption_Summary_ID); } @Override public int getC_Project_Repair_Consumption_Summary_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_Repair_Consumption_Summary_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null);
else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请在Spring Boot框架中完成以下Java代码
public class BookReview extends AbstractAggregateRoot<BookReview> implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String content; private String email; @Enumerated(EnumType.STRING) private ReviewStatus status; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "book_id") private Book book; public void registerReviewEvent() { registerEvent(new CheckReviewEvent(this)); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } public ReviewStatus getStatus() { return status; } public void setStatus(ReviewStatus status) { this.status = status; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof BookReview)) { return false; } return id != null && id.equals(((BookReview) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\entity\BookReview.java
2
请完成以下Java代码
public class MeterLogEntity implements DbEntity, HasDbReferences, Serializable { private static final long serialVersionUID = 1L; protected String id; protected Date timestamp; protected Long milliseconds; protected String name; protected String reporter; protected long value; public MeterLogEntity(String name, long value, Date timestamp) { this(name, null, value, timestamp); } public MeterLogEntity(String name, String reporter, long value, Date timestamp) { this.name = name; this.reporter = reporter; this.value = value; this.timestamp = timestamp; this.milliseconds = timestamp.getTime(); } public MeterLogEntity() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Long getMilliseconds() { return milliseconds; } public void setMilliseconds(Long milliseconds) { this.milliseconds = milliseconds; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } public String getReporter() { return reporter; } public void setReporter(String reporter) { this.reporter = reporter; } public Object getPersistentState() { // immutable return MeterLogEntity.class; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogEntity.java
1
请完成以下Java代码
public DocumentType3Code getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link DocumentType3Code } * */ public void setCd(DocumentType3Code 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.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CreditorReferenceType1Choice.java
1
请完成以下Java代码
public void completeNonScopeEventSubprocess() { logDebug( "039", "Destroy non-socpe event subprocess"); } public void endConcurrentExecutionInEventSubprocess() { logDebug( "040", "End concurrent execution in event subprocess"); } public ProcessEngineException missingDelegateVariableMappingParentClassException(String className, String delegateVarMapping) { return new ProcessEngineException( exceptionMessage("041", "Class '{}' doesn't implement '{}'.", className, delegateVarMapping)); } public ProcessEngineException missingBoundaryCatchEventError(String executionId, String errorCode, String errorMessage) { return new ProcessEngineException( exceptionMessage(
"042", "Execution with id '{}' throws an error event with errorCode '{}' and errorMessage '{}', but no error handler was defined. ", executionId, errorCode, errorMessage)); } public ProcessEngineException missingBoundaryCatchEventEscalation(String executionId, String escalationCode) { return new ProcessEngineException( exceptionMessage( "043", "Execution with id '{}' throws an escalation event with escalationCode '{}', but no escalation handler was defined. ", executionId, escalationCode)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnBehaviorLogger.java
1
请在Spring Boot框架中完成以下Java代码
private LUPickingTarget reinitializeLUPickingTarget(@Nullable final LUPickingTarget luPickingTarget) { if (luPickingTarget == null) { return null; } final HuId luId = luPickingTarget.getLuId(); if (luId == null) { return luPickingTarget; } final I_M_HU lu = huService.getById(luId); if (!huService.isDestroyedOrEmptyStorage(lu)) { return luPickingTarget; }
final HuPackingInstructionsIdAndCaption luPI = huService.getEffectivePackingInstructionsIdAndCaption(lu); return LUPickingTarget.ofPackingInstructions(luPI); } // // // @Value @Builder private static class StepUnpickInstructions { @NonNull PickingJobStepId stepId; @NonNull PickingJobStepPickFromKey pickFromKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobUnPickCommand.java
2
请完成以下Java代码
public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID) { if (PA_SLA_Criteria_ID < 1) set_Value (COLUMNNAME_PA_SLA_Criteria_ID, null); else set_Value (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID)); } /** Get SLA Criteria. @return Service Level Agreement Criteria */ public int getPA_SLA_Criteria_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID); if (ii == null) return 0; return ii.intValue(); } /** Set SLA Goal. @param PA_SLA_Goal_ID Service Level Agreement Goal */ public void setPA_SLA_Goal_ID (int PA_SLA_Goal_ID) { if (PA_SLA_Goal_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, Integer.valueOf(PA_SLA_Goal_ID)); } /** Get SLA Goal. @return Service Level Agreement Goal */ public int getPA_SLA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Goal_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 Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Goal.java
1
请完成以下Java代码
public void addLUId(@NonNull final HuId luId) { allTopLevelHUIds.add(luId); luIds.add(luId); } public void addTopLevelTUId(@NonNull final HuId tuId) { allTopLevelHUIds.add(tuId); topLevelTUIds.add(tuId); } public boolean isEmpty() { return allTopLevelHUIds.isEmpty(); }
public ImmutableSet<HuId> getAllTopLevelHUIds() { return ImmutableSet.copyOf(allTopLevelHUIds); } public ImmutableSet<HuId> getLUIds() { return ImmutableSet.copyOf(luIds); } public ImmutableSet<HuId> getTopLevelTUIds() { return ImmutableSet.copyOf(topLevelTUIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\LUIdsAndTopLevelTUIdsCollector.java
1
请完成以下Java代码
public class CaseCallActivityBehavior extends CallableElementActivityBehavior implements MigrationObserverBehavior { protected void startInstance(ActivityExecution execution, VariableMap variables, String businessKey) { ExecutionEntity executionEntity = (ExecutionEntity) execution; CmmnCaseDefinition definition = getCaseDefinitionToCall(executionEntity, executionEntity.getProcessDefinitionTenantId(), getCallableElement()); CmmnCaseInstance caseInstance = execution.createSubCaseInstance(definition, businessKey); caseInstance.create(variables); } @Override public void migrateScope(ActivityExecution scopeExecution) { } @Override
public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) { ActivityImpl callActivity = (ActivityImpl) migratingInstance.getSourceScope(); // A call activity is typically scope and since we guarantee stability of scope executions during migration, // the superExecution link does not have to be maintained during migration. // There are some exceptions, though: A multi-instance call activity is not scope and therefore // does not have a dedicated scope execution. In this case, the link to the super execution // must be maintained throughout migration if (!callActivity.isScope()) { ExecutionEntity callActivityExecution = migratingInstance.resolveRepresentativeExecution(); CaseExecutionEntity calledCaseInstance = callActivityExecution.getSubCaseInstance(); migratingInstance.addMigratingDependentInstance(new MigratingCalledCaseInstance(calledCaseInstance)); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CaseCallActivityBehavior.java
1
请完成以下Java代码
protected I_C_RfQResponseLine createRfqResponseLine(final Supplier<I_C_RfQResponse> responseSupplier, final I_C_RfQLine rfqLine) { final I_C_RfQResponse rfqResponse = responseSupplier.get(); final Properties ctx = InterfaceWrapperHelper.getCtx(rfqResponse); final I_C_RfQResponseLine rfqResponseLine = InterfaceWrapperHelper.create(ctx, I_C_RfQResponseLine.class, ITrx.TRXNAME_ThreadInherited); // // Defaults rfqResponseLine.setIsSelectedWinner(false); rfqResponseLine.setIsSelfService(false); rfqResponseLine.setDocStatus(rfqResponse.getDocStatus()); rfqResponseLine.setProcessed(rfqResponse.isProcessed()); // // From RfQ Response header rfqResponseLine.setC_RfQResponse(rfqResponse); rfqResponseLine.setAD_Org_ID(rfqResponse.getAD_Org_ID()); rfqResponseLine.setC_BPartner_ID(rfqResponse.getC_BPartner_ID()); rfqResponseLine.setC_Currency_ID(rfqResponse.getC_Currency_ID()); // // From RfQ header final I_C_RfQ rfq = rfqLine.getC_RfQ(); rfqResponseLine.setC_RfQ(rfq); rfqResponseLine.setDateResponse(rfq.getDateResponse()); rfqResponseLine.setDateWorkStart(rfq.getDateWorkStart()); rfqResponseLine.setDeliveryDays(rfq.getDeliveryDays()); //
// From RfQ Line rfqResponseLine.setC_RfQLine(rfqLine); rfqResponseLine.setLine(rfqLine.getLine()); rfqResponseLine.setM_Product_ID(rfqLine.getM_Product_ID()); rfqResponseLine.setC_UOM_ID(rfqLine.getC_UOM_ID()); rfqResponseLine.setQtyRequiered(rfqLine.getQty()); rfqResponseLine.setDescription(rfqLine.getDescription()); rfqResponseLine.setUseLineQty(rfqLine.isUseLineQty()); // NOTE: don't save it! return rfqResponseLine; } private I_C_RfQResponseLineQty createRfQResponseLineQty(final Supplier<I_C_RfQResponseLine> responseLineSupplier, final I_C_RfQLineQty lineQty) { final I_C_RfQResponseLine responseLine = responseLineSupplier.get(); final Properties ctx = InterfaceWrapperHelper.getCtx(responseLine); final I_C_RfQResponseLineQty responseQty = InterfaceWrapperHelper.create(ctx, I_C_RfQResponseLineQty.class, ITrx.TRXNAME_ThreadInherited); responseQty.setAD_Org_ID(responseLine.getAD_Org_ID()); responseQty.setC_RfQResponseLine(responseLine); responseQty.setC_RfQLineQty(lineQty); InterfaceWrapperHelper.save(responseQty); return responseQty; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\DefaultRfQResponseProducer.java
1
请完成以下Java代码
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return false; } /** * Creates an ADR attribute value for the C_BPartner which is specified by <code>tableId</code> and <code>recordId</code>. */ @Override public AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName) { final IContextAware context = new PlainContextAware(ctx, trxName); final ITableRecordReference record = TableRecordReference.of(tableId, recordId); final I_C_BPartner partner = record.getModel(context, I_C_BPartner.class); Check.assumeNotNull(partner, "partner not null"); final I_M_Attribute adrAttribute = Services.get(IADRAttributeDAO.class).retrieveADRAttribute(partner); if (adrAttribute == null) { // ADR Attribute was not configured, nothing to do return null; }
final String adrRegionValue = Services.get(IADRAttributeBL.class).getADRForBPartner(partner, isSOTrx); if (Check.isEmpty(adrRegionValue, true)) { return null; } // // Fetched AD_Ref_List record final ADRefListItem adRefList = ADReferenceService.get().retrieveListItemOrNull(I_C_BPartner.ADRZertifizierung_L_AD_Reference_ID, adrRegionValue); Check.assumeNotNull(adRefList, "adRefList not null"); final String adrRegionName = adRefList.getName().getDefaultValue(); return Services.get(IAttributeDAO.class).createAttributeValue(AttributeListValueCreateRequest.builder() .attributeId(AttributeId.ofRepoId(adrAttribute.getM_Attribute_ID())) .value(adrRegionValue) .name(adrRegionName) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\spi\impl\ADRAttributeGenerator.java
1
请完成以下Java代码
public class MongoReactiveHealthIndicator extends AbstractReactiveHealthIndicator { private static final Document HELLO_COMMAND = Document.parse("{ hello: 1 }"); private final MongoClient mongoClient; public MongoReactiveHealthIndicator(MongoClient mongoClient) { super("Mongo health check failed"); Assert.notNull(mongoClient, "'mongoClient' must not be null"); this.mongoClient = mongoClient; } @Override protected Mono<Health> doHealthCheck(Health.Builder builder) { Mono<Map<String, Object>> healthDetails = Flux.from(this.mongoClient.listDatabaseNames()) .flatMap((database) -> Mono.from(this.mongoClient.getDatabase(database).runCommand(HELLO_COMMAND)) .map((document) -> new HelloResponse(database, document))) .collectList() .map((responses) -> { Map<String, Object> databaseDetails = new LinkedHashMap<>();
List<String> databases = new ArrayList<>(); databaseDetails.put("databases", databases); for (HelloResponse response : responses) { databases.add(response.database()); databaseDetails.putIfAbsent("maxWireVersion", response.document().getInteger("maxWireVersion")); } return databaseDetails; }); return healthDetails.map((details) -> builder.up().withDetails(details).build()); } private record HelloResponse(String database, Document document) { } }
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\health\MongoReactiveHealthIndicator.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Seller seller = (Seller) o; return Objects.equals(sellerName, seller.sellerName); } @Override public int hashCode() { return Objects.hash(sellerName); } }
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkeyjoincolumn\Seller.java
1
请完成以下Java代码
public DocumentFieldDependencyMap build() { if (type2name2dependencies.isEmpty()) { return EMPTY; } return new DocumentFieldDependencyMap(this); } private ImmutableMap<DependencyType, Multimap<String, String>> getType2Name2DependenciesMap() { final ImmutableMap.Builder<DependencyType, Multimap<String, String>> builder = ImmutableMap.builder(); for (final Entry<DependencyType, ImmutableSetMultimap.Builder<String, String>> e : type2name2dependencies.entrySet()) { final DependencyType dependencyType = e.getKey(); final Multimap<String, String> name2dependencies = e.getValue().build(); if (name2dependencies.isEmpty()) { continue; } builder.put(dependencyType, name2dependencies); } return builder.build(); } public Builder add( @NonNull final String fieldName, @Nullable final Collection<String> dependsOnFieldNames, @NonNull final DependencyType dependencyType) { if (dependsOnFieldNames == null || dependsOnFieldNames.isEmpty()) { return this; } final ImmutableSetMultimap.Builder<String, String> fieldName2dependsOnFieldNames = type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder());
for (final String dependsOnFieldName : dependsOnFieldNames) { fieldName2dependsOnFieldNames.put(dependsOnFieldName, fieldName); } return this; } public Builder add(@Nullable final DocumentFieldDependencyMap dependencies) { if (dependencies == null || dependencies == EMPTY) { return this; } for (final Map.Entry<DependencyType, Multimap<String, String>> l1 : dependencies.type2name2dependencies.entrySet()) { final DependencyType dependencyType = l1.getKey(); final ImmutableSetMultimap.Builder<String, String> name2dependencies = type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder()); name2dependencies.putAll(l1.getValue()); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDependencyMap.java
1
请完成以下Java代码
public Response getPojoResponse() { Person person = new Person("Abh", "Nepal"); return Response .status(Response.Status.OK) .entity(person) .build(); } @GET @Path("/json") public Response getJsonResponse() { String message = "{\"hello\": \"This is a JSON response\"}"; return Response .status(Response.Status.OK) .entity(message)
.type(MediaType.APPLICATION_JSON) .build(); } @GET @Path("/xml") @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> This is a xml response </hello>"; } @GET @Path("/html") @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + " This is a html title </title>" + "<body><h1>" + " This is a html response body " + "</body></h1>" + "</html> "; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\Responder.java
1
请在Spring Boot框架中完成以下Java代码
public CacheManager cacheManager() { return new ConcurrentMapCacheManager("books"); } // tag::customization-instance-exchange-filter-function[] @Bean public InstanceExchangeFilterFunction auditLog() { return (instance, request, next) -> next.exchange(request).doOnSubscribe((s) -> { if (HttpMethod.DELETE.equals(request.method()) || HttpMethod.POST.equals(request.method())) { log.info("{} for {} on {}", request.method(), instance.getId(), request.url()); } }); } // end::customization-instance-exchange-filter-function[] @Bean public CustomNotifier customNotifier(InstanceRepository repository) { return new CustomNotifier(repository); } @Bean public CustomEndpoint customEndpoint() { return new CustomEndpoint(); } // tag::customization-http-headers-providers[] @Bean
public HttpHeadersProvider customHttpHeadersProvider() { return (instance) -> { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("X-CUSTOM", "My Custom Value"); return httpHeaders; }; } // end::customization-http-headers-providers[] @Bean public HttpExchangeRepository httpTraceRepository() { return new InMemoryHttpExchangeRepository(); } @Bean public AuditEventRepository auditEventRepository() { return new InMemoryAuditEventRepository(); } @Bean public EmbeddedDatabase dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) .addScript("org/springframework/session/jdbc/schema-hsqldb.sql") .build(); } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminServletApplication.java
2
请在Spring Boot框架中完成以下Java代码
public class XmlServiceEx implements XmlService { @Nullable XmlXtraServiceExType xtraServiceExType; @NonNull Integer recordId; @NonNull String tariffType; @NonNull String code; @Nullable String refCode; @NonNull String name; @Nullable Integer session; @NonNull BigDecimal quantity; @NonNull XMLGregorianCalendar dateBegin; @Nullable XMLGregorianCalendar dateEnd; @NonNull String providerId; @NonNull String responsibleId; @Nullable String billingRole; @Nullable String medicalRole; @Nullable String bodyLocation; @Nullable String treatment; @NonNull BigDecimal unitMt; @NonNull BigDecimal unitFactorMt; /** * expecting default = 1 */ @NonNull BigDecimal scaleFactorMt; /** * expecting default = 1 */ @NonNull BigDecimal externalFactorMt; /** * expecting default = 0 */ @NonNull BigDecimal amountMt; @NonNull BigDecimal unitTt; @NonNull BigDecimal unitFactorTt; /** * expecting default = 1 */ @NonNull BigDecimal scaleFactorTt; /** * expecting default = 1 */ @NonNull BigDecimal externalFactorTt; /** * expecting default = 0
*/ @NonNull BigDecimal amountTt; @NonNull BigDecimal amount; /** * expecting default = 0 */ @NonNull BigDecimal vatRate; /** * expecting default = false */ @Nullable Boolean validate; /** * expecting default = true */ @NonNull Boolean obligation; @Nullable String sectionCode; @Nullable String remark; /** * expecting default = 0 */ @NonNull Long serviceAttributes; @Override public BigDecimal getExternalFactor() { throw new UnsupportedOperationException("XmlServiceEx has two external factors, not one"); } @Override public XmlService withModNonNull(@NonNull final ServiceMod serviceMod) { throw new UnsupportedOperationException("XmlServiceEx can't be modified unless we take care of both the MT and TT parts"); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\service\XmlServiceEx.java
2
请完成以下Java代码
private LookupValue convertRawFieldValueToLookupValue(final Object fieldValue) { if (fieldValue == null) { return null; } else if (fieldValue instanceof LookupValue) { return (LookupValue)fieldValue; } else if (fieldValue instanceof LocalDate) { final LocalDate date = (LocalDate)fieldValue; return StringLookupValue.of( Values.localDateToJson(date), TranslatableStrings.date(date)); } else if (fieldValue instanceof Boolean) { final boolean booleanValue = StringUtils.toBoolean(fieldValue); return StringLookupValue.of(
DisplayType.toBooleanString(booleanValue), msgBL.getTranslatableMsgText(booleanValue)); } else if (fieldValue instanceof String) { final String stringValue = (String)fieldValue; return StringLookupValue.of(stringValue, stringValue); } else { throw new AdempiereException("Value not supported: " + fieldValue + " (" + fieldValue.getClass() + ")") .appendParametersToMessage() .setParameter("fieldName", fieldName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\standard\FacetsFilterLookupDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final BookRepository bookRepository; public BookstoreService(BookRepository bookRepository) { this.bookRepository = bookRepository; } @Transactional public void persistTwoBooks() { Book ar = new Book(); ar.setIsbn("001-AR"); ar.setTitle("Ancient Rome"); ar.setPrice(25); Book rh = new Book(); rh.setIsbn("001-RH"); rh.setTitle("Rush Hour");
rh.setPrice(31); bookRepository.save(ar); bookRepository.save(rh); } // cache entities in SLC public void fetchBook() { Book book = bookRepository.findById(1L).orElseThrow(); } // cache query results in SLC public void fetchBookByPrice() { List<Book> books = bookRepository.fetchByPrice(30); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootHibernateSLCEhCacheKickoff\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
protected void marshalNonRootElement(Object parameter, Marshaller marshaller, DOMResult domResult) throws JAXBException { Class<?> parameterClass = parameter.getClass(); String simpleName = Introspector.decapitalize(parameterClass.getSimpleName()); JAXBElement<?> root = new JAXBElement(new QName(simpleName), parameterClass, parameter); marshaller.marshal(root, domResult); } @Override public <T> T mapInternalToJava(Object parameter, Class<T> javaClass) { return mapInternalToJava(parameter, javaClass, null); } @Override public <T> T mapInternalToJava(Object parameter, Class<T> javaClass, DeserializationTypeValidator validator) { ensureNotNull("Parameter", parameter); ensureNotNull("Type", javaClass); Node xmlNode = (Node) parameter; try { validateType(javaClass, validator); Unmarshaller unmarshaller = getUnmarshaller(javaClass); JAXBElement<T> root = unmarshaller.unmarshal(new DOMSource(xmlNode), javaClass); return root.getValue(); } catch (JAXBException e) { throw LOG.unableToDeserialize(parameter, javaClass.getCanonicalName(), e); } } protected void validateType(Class<?> type, DeserializationTypeValidator validator) { if (validator != null) { // validate the outer class if (!type.isPrimitive()) { Class<?> typeToValidate = type; if (type.isArray()) { typeToValidate = type.getComponentType(); } String className = typeToValidate.getName(); if (!validator.validate(className)) {
throw new SpinRuntimeException("The class '" + className + "' is not whitelisted for deserialization."); } } } } @Override public <T> T mapInternalToJava(Object parameter, String classIdentifier) { return mapInternalToJava(parameter, classIdentifier, null); } @SuppressWarnings("unchecked") @Override public <T> T mapInternalToJava(Object parameter, String classIdentifier, DeserializationTypeValidator validator) { ensureNotNull("Parameter", parameter); ensureNotNull("classIdentifier", classIdentifier); try { Class<?> javaClass = SpinReflectUtil.loadClass(classIdentifier, dataFormat); return (T) mapInternalToJava(parameter, javaClass, validator); } catch (Exception e) { throw LOG.unableToDeserialize(parameter, classIdentifier, e); } } protected Marshaller getMarshaller(Class<?> parameter) throws JAXBException { JaxBContextProvider jaxBContextProvider = dataFormat.getJaxBContextProvider(); return jaxBContextProvider.createMarshaller(parameter); } protected Unmarshaller getUnmarshaller(Class<?> parameter) throws JAXBException { JaxBContextProvider jaxBContextProvider = dataFormat.getJaxBContextProvider(); return jaxBContextProvider.createUnmarshaller(parameter); } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatMapper.java
1
请完成以下Java代码
public void movePlanItemInstanceState(ChangePlanItemStateBuilderImpl changePlanItemStateBuilder, CommandContext commandContext) { String caseInstanceId = changePlanItemStateBuilder.getCaseInstanceId(); if (caseInstanceId == null) { throw new FlowableException("Could not resolve case instance id"); } CaseInstanceEntityManager caseInstanceEntityManager = CommandContextUtil.getCaseInstanceEntityManager(commandContext); CaseInstanceEntity caseInstance = caseInstanceEntityManager.findById(caseInstanceId); String originalCaseDefinitionId = caseInstance.getCaseDefinitionId(); CaseInstanceChangeState caseInstanceChangeState = new CaseInstanceChangeState() .setCaseInstanceId(caseInstanceId) .setActivatePlanItemDefinitions(changePlanItemStateBuilder.getActivatePlanItemDefinitions()) .setTerminatePlanItemDefinitions(changePlanItemStateBuilder.getTerminatePlanItemDefinitions())
.setChangePlanItemDefinitionsToAvailable(changePlanItemStateBuilder.getChangeToAvailableStatePlanItemDefinitions()) .setWaitingForRepetitionPlanItemDefinitions(changePlanItemStateBuilder.getWaitingForRepetitionPlanItemDefinitions()) .setRemoveWaitingForRepetitionPlanItemDefinitions(changePlanItemStateBuilder.getRemoveWaitingForRepetitionPlanItemDefinitions()) .setCaseVariables(changePlanItemStateBuilder.getCaseVariables()) .setChildInstanceTaskVariables(changePlanItemStateBuilder.getChildInstanceTaskVariables()); doMovePlanItemState(caseInstanceChangeState, originalCaseDefinitionId, commandContext); } @Override protected boolean isDirectPlanItemDefinitionMigration(PlanItemDefinition currentPlanItemDefinition, PlanItemDefinition newPlanItemDefinition) { return false; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\DefaultCmmnDynamicStateManager.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }
public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + ", price=" + price + '}'; } }
repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\Book.java
1
请完成以下Java代码
public String getStrokeValue() { return "#585858"; } @Override public String getDValue() { return " M21.820839 10.171502 L18.36734 23.58992 L12.541380000000002 13.281818999999999 L8.338651200000001 19.071607 L12.048949000000002 5.832305699999999 L17.996148000000005 15.132659 L21.820839 10.171502 z"; } public void drawIcon( final int imageX, final int imageY, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 6) + "," + (imageY - 3) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "style", this.getStyleValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag); } @Override public String getAnchorValue() { return null; }
@Override public String getStyleValue() { return "fill:none;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10"; } @Override public Integer getWidth() { return 17; } @Override public Integer getHeight() { return 22; } @Override public String getStrokeWidth() { return null; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\ErrorIconType.java
1
请完成以下Java代码
public void close() throws IOException { inputStream.close(); } @Override public synchronized void mark(int readlimit) { inputStream.mark(readlimit); } @Override public synchronized void reset() throws IOException { inputStream.reset(); } @Override public boolean markSupported() {
return inputStream.markSupported(); } }; } @Override public BufferedReader getReader() throws IOException { return EmptyBodyFilter.this.getReader(this.getInputStream()); } }; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\filter\EmptyBodyFilter.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { return (exchange, chain) -> { if (exchange.getRequest() .getHeaders() .getAcceptLanguage() .isEmpty()) { String queryParamLocale = exchange.getRequest() .getQueryParams() .getFirst("locale"); Locale requestLocale = Optional.ofNullable(queryParamLocale) .map(l -> Locale.forLanguageTag(l)) .orElse(config.getDefaultLocale()); exchange.getRequest() .mutate() .headers(h -> h.setAcceptLanguageAsLocales(Collections.singletonList(requestLocale))); } String allOutgoingRequestLanguages = exchange.getRequest() .getHeaders() .getAcceptLanguage() .stream() .map(range -> range.getRange()) .collect(Collectors.joining(",")); logger.info("Modify request output - Request contains Accept-Language header: {}", allOutgoingRequestLanguages); ServerWebExchange modifiedExchange = exchange.mutate() .request(originalRequest -> originalRequest.uri(UriComponentsBuilder.fromUri(exchange.getRequest() .getURI())
.replaceQueryParams(new LinkedMultiValueMap<String, String>()) .build() .toUri())) .build(); logger.info("Removed all query params: {}", modifiedExchange.getRequest() .getURI()); return chain.filter(modifiedExchange); }; } public static class Config { private Locale defaultLocale; public Config() { } public Locale getDefaultLocale() { return defaultLocale; } public void setDefaultLocale(String defaultLocale) { this.defaultLocale = Locale.forLanguageTag(defaultLocale); }; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ModifyRequestGatewayFilterFactory.java
1
请完成以下Java代码
public void bulkMove(@RequestBody @NonNull final JsonBulkMoveHURequest request) { assertActionAccess(HUManagerAction.BulkActions); handlingUnitsService.bulkMove( BulkMoveHURequest.builder() .huQrCodes(request.getHuQRCodes().stream() .map(HUQRCode::fromGlobalQRCodeJsonString) .collect(ImmutableList.toImmutableList())) .targetQRCode(ScannedCode.ofString(request.getTargetQRCode())) .build() ); } @PostMapping("/huLabels/print") public JsonPrintHULabelResponse printHULabels(@RequestBody @NonNull final JsonPrintHULabelRequest request) { assertActionAccess(HUManagerAction.PrintLabels); try (final FrontendPrinter frontendPrinter = FrontendPrinter.start())
{ handlingUnitsService.printHULabels(request); final FrontendPrinterData printData = frontendPrinter.getDataAndClear(); return JsonPrintHULabelResponse.builder() .printData(JsonPrintHULabelResponse.JsonPrintDataItem.of(printData)) .build(); } } @GetMapping("/huLabels/printingOptions") public List<JsonHULabelPrintingOption> getPrintingOptions() { final String adLanguage = Env.getADLanguageOrBaseLanguage(); return handlingUnitsService.getLabelPrintingOptions(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\mobileui\HUManagerRestController.java
1
请完成以下Spring Boot application配置
spring: datasource: # dynamic-datasource-spring-boot-starter 动态数据源的配置内容 dynamic: primary: users # 设置默认的数据源或者数据源组,默认值即为 master datasource: # 订单 orders 数据源配置 orders: url: jdbc:mysql://127.0.0.1:3306/test_orders?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root password: # 用户 users 数据源配置 users: url: jdbc:mysql://127.0.0.1:3306/test_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: roo
t password: # mybatis 配置内容 mybatis: config-location: classpath:mybatis-config.xml # 配置 MyBatis 配置文件路径 mapper-locations: classpath:mapper/*.xml # 配置 Mapper XML 地址 type-aliases-package: cn.iocoder.springboot.lab17.dynamicdatasource.dataobject # 配置数据库实体包路径
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-baomidou-01\src\main\resources\application.yaml
2
请完成以下Java代码
public java.math.BigDecimal getPrev_CumulatedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CumulatedAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Previous Cumulated Quantity. @param Prev_CumulatedQty Previous Cumulated Quantity */ @Override public void setPrev_CumulatedQty (java.math.BigDecimal Prev_CumulatedQty) { set_Value (COLUMNNAME_Prev_CumulatedQty, Prev_CumulatedQty); } /** Get Previous Cumulated Quantity. @return Previous Cumulated Quantity */ @Override public java.math.BigDecimal getPrev_CumulatedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CumulatedQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Previous Current Cost Price. @param Prev_CurrentCostPrice Previous Current Cost Price */ @Override public void setPrev_CurrentCostPrice (java.math.BigDecimal Prev_CurrentCostPrice) { set_Value (COLUMNNAME_Prev_CurrentCostPrice, Prev_CurrentCostPrice); } /** Get Previous Current Cost Price. @return Previous Current Cost Price */ @Override public java.math.BigDecimal getPrev_CurrentCostPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentCostPrice); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Previous Current Cost Price LL. @param Prev_CurrentCostPriceLL Previous Current Cost Price LL */ @Override public void setPrev_CurrentCostPriceLL (java.math.BigDecimal Prev_CurrentCostPriceLL) { set_Value (COLUMNNAME_Prev_CurrentCostPriceLL, Prev_CurrentCostPriceLL); } /** Get Previous Current Cost Price LL. @return Previous Current Cost Price LL */
@Override public java.math.BigDecimal getPrev_CurrentCostPriceLL () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentCostPriceLL); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Previous Current Qty. @param Prev_CurrentQty Previous Current Qty */ @Override public void setPrev_CurrentQty (java.math.BigDecimal Prev_CurrentQty) { set_Value (COLUMNNAME_Prev_CurrentQty, Prev_CurrentQty); } /** Get Previous Current Qty. @return Previous Current Qty */ @Override public java.math.BigDecimal getPrev_CurrentQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_CostDetailAdjust.java
1
请在Spring Boot框架中完成以下Java代码
private static class ParameterNameFQ { @Nullable DetailId tabId; @Nullable String includedFilterId; @NonNull String parameterName; private static final Splitter SPLITTER = Splitter.on("."); public static ParameterNameFQ ofParameterNameFQ(@NonNull String parameterNameFQ) { final List<String> parts = SPLITTER.splitToList(parameterNameFQ); if (parts.size() == 1) { return of(null, null, parameterNameFQ); } else if (parts.size() == 3) { return of( DetailId.fromJson(parts.get(0)), parts.get(1), parts.get(2) ); } else { throw new AdempiereException("Invalid parameter name `" + parameterNameFQ + "`"); }
} public String getAsString() { if (tabId == null) { return parameterName; } else { return tabId.toJson() + "." + includedFilterId + "." + parameterName; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDefaultDocumentFilterConverter.java
2
请完成以下Java代码
public Timestamp getDateReval () { return (Timestamp)get_Value(COLUMNNAME_DateReval); } /** Set Accounting Fact. @param Fact_Acct_ID Accounting Fact */ public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Grand Total. @param GrandTotal Total amount of document */ public void setGrandTotal (BigDecimal GrandTotal) { set_Value (COLUMNNAME_GrandTotal, GrandTotal); } /** Get Grand Total. @return Total amount of document */ public BigDecimal getGrandTotal () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal); if (bd == null) return Env.ZERO; return bd; } /** Set Include All Currencies. @param IsAllCurrencies Report not just foreign currency Invoices */ public void setIsAllCurrencies (boolean IsAllCurrencies) { set_Value (COLUMNNAME_IsAllCurrencies, Boolean.valueOf(IsAllCurrencies)); } /** Get Include All Currencies. @return Report not just foreign currency Invoices */ public boolean isAllCurrencies () { Object oo = get_Value(COLUMNNAME_IsAllCurrencies); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open Amount. @param OpenAmt
Open item amount */ public void setOpenAmt (BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Open Amount. @return Open item amount */ public BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Percent. @param Percent Percentage */ public void setPercent (BigDecimal Percent) { set_Value (COLUMNNAME_Percent, Percent); } /** Get Percent. @return Percentage */ public BigDecimal getPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent); 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_T_InvoiceGL.java
1
请在Spring Boot框架中完成以下Java代码
private static final String extractUserName(final UserSession userSession) { final String userName = userSession.getUserName(); if (!Check.isEmpty(userName, true)) { return userName; } final UserId loggedUserId = userSession.getLoggedUserIdIfExists().orElse(null); if (loggedUserId != null) { return String.valueOf(loggedUserId.getRepoId()); } return "?"; } private static final String extractUserAgent(final HttpServletRequest httpRequest) { try
{ final String userAgent = httpRequest.getHeader("User-Agent"); return userAgent; } catch (final Exception e) { e.printStackTrace(); return "?"; } } private static final String extractLoggedUserAndRemoteAddr(final String loggedUser, final String remoteAddr) { // NOTE: guard against null parameters, if those at this point they shall not return (loggedUser == null ? "?" : loggedUser) + "/" + (remoteAddr == null ? "?" : remoteAddr); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\ServletLoggingFilter.java
2
请完成以下Java代码
public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** 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); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept.java
1
请完成以下Java代码
public class FootballPlayer implements Comparable<FootballPlayer> { private final String name; private final int goalsScored; public FootballPlayer(String name, int goalsScored) { this.name = name; this.goalsScored = goalsScored; } public String getName() { return name; } @Override
public int compareTo(FootballPlayer anotherPlayer) { return Integer.compare(this.goalsScored, anotherPlayer.goalsScored); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; FootballPlayer player = (FootballPlayer) object; return name.equals(player.name); } }
repos\tutorials-master\core-java-modules\core-java-lang-3\src\main\java\com\baeldung\compareto\FootballPlayer.java
1
请在Spring Boot框架中完成以下Java代码
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { /** * 用户认证 Manager */ @Autowired private AuthenticationManager authenticationManager; /** * Redis 连接的工厂 */ @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public TokenStore redisTokenStore() { return new RedisTokenStore(redisConnectionFactory); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .tokenStore(redisTokenStore()); }
@Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.checkTokenAccess("isAuthenticated()"); // oauthServer.tokenKeyAccess("isAuthenticated()") // .checkTokenAccess("isAuthenticated()"); // oauthServer.tokenKeyAccess("permitAll()") // .checkTokenAccess("permitAll()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("clientapp").secret("112233") // Client 账号、密码。 .authorizedGrantTypes("password", "refresh_token") // 密码模式 .scopes("read_userinfo", "read_contacts") // 可授权的 Scope // .and().withClient() // 可以继续配置新的 Client ; } }
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo11-authorization-server-by-redis-store\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\OAuth2AuthorizationServerConfig.java
2
请完成以下Java代码
public static void setContext(SecurityContext context) { strategy.setContext(context); } /** * Sets a {@link Supplier} that will return the current context. Implementations can * override the default to avoid invoking {@link Supplier#get()}. * @param deferredContext a {@link Supplier} that returns the {@link SecurityContext} * @since 5.8 */ public static void setDeferredContext(Supplier<SecurityContext> deferredContext) { strategy.setDeferredContext(deferredContext); } /** * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for * a given JVM, as it will re-initialize the strategy and adversely affect any * existing threads using the old strategy. * @param strategyName the fully qualified class name of the strategy that should be * used. */ public static void setStrategyName(String strategyName) { SecurityContextHolder.strategyName = strategyName; initialize(); } /** * Use this {@link SecurityContextHolderStrategy}. * * Call either {@link #setStrategyName(String)} or this method, but not both. * * This method is not thread safe. Changing the strategy while requests are in-flight * may cause race conditions. * * {@link SecurityContextHolder} maintains a static reference to the provided * {@link SecurityContextHolderStrategy}. This means that the strategy and its members * will not be garbage collected until you remove your strategy. * * To ensure garbage collection, remember the original strategy like so: * * <pre> * SecurityContextHolderStrategy original = SecurityContextHolder.getContextHolderStrategy(); * SecurityContextHolder.setContextHolderStrategy(myStrategy); * </pre> * * And then when you are ready for {@code myStrategy} to be garbage collected you can * do: * * <pre> * SecurityContextHolder.setContextHolderStrategy(original); * </pre> * @param strategy the {@link SecurityContextHolderStrategy} to use * @since 5.6 */ public static void setContextHolderStrategy(SecurityContextHolderStrategy strategy) { Assert.notNull(strategy, "securityContextHolderStrategy cannot be null"); SecurityContextHolder.strategyName = MODE_PRE_INITIALIZED;
SecurityContextHolder.strategy = strategy; initialize(); } /** * Allows retrieval of the context strategy. See SEC-1188. * @return the configured strategy for storing the security context. */ public static SecurityContextHolderStrategy getContextHolderStrategy() { return strategy; } /** * Delegates the creation of a new, empty context to the configured strategy. */ public static SecurityContext createEmptyContext() { return strategy.createEmptyContext(); } @Override public String toString() { return "SecurityContextHolder[strategy='" + strategy.getClass().getSimpleName() + "'; initializeCount=" + initializeCount + "]"; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\SecurityContextHolder.java
1
请在Spring Boot框架中完成以下Java代码
public String getBankAccountAddress() { return bankAccountAddress; } /** * 开户行全称 * * @param bankAccountAddress */ public void setBankAccountAddress(String bankAccountAddress) { this.bankAccountAddress = bankAccountAddress == null ? null : bankAccountAddress.trim(); } /** * 结算金额 * * @return */ public BigDecimal getSettAmount() { return settAmount; } /** * 结算金额 * * @param settAmount */ public void setSettAmount(BigDecimal settAmount) { this.settAmount = settAmount; } /** * 结算手续费 * * @return */ public BigDecimal getSettFee() { return settFee; } /** * 结算手续费 * * @param settFee */ public void setSettFee(BigDecimal settFee) { this.settFee = settFee; } /** * 结算打款金额 * * @return */ public BigDecimal getRemitAmount() { return remitAmount; } /** * 结算打款金额 * * @param remitAmount */ public void setRemitAmount(BigDecimal remitAmount) { this.remitAmount = remitAmount; } /** 结算状态(参考枚举:SettRecordStatusEnum) **/ public String getSettStatus() { return settStatus; } /** 结算状态(参考枚举:SettRecordStatusEnum) **/ public void setSettStatus(String settStatus) { this.settStatus = settStatus; } /** * 打款发送时间 * * @return */ public Date getRemitRequestTime() { return remitRequestTime; } /** * 打款发送时间 * * @param remitRequestTime */ public void setRemitRequestTime(Date remitRequestTime) { this.remitRequestTime = remitRequestTime; } /** * 打款确认时间 * * @return */ public Date getRemitConfirmTime() { return remitConfirmTime; }
/** * 打款确认时间 * * @param remitConfirmTime */ public void setRemitConfirmTime(Date remitConfirmTime) { this.remitConfirmTime = remitConfirmTime; } /** * 打款备注 * * @return */ public String getRemitRemark() { return remitRemark; } /** * 打款备注 * * @param remitRemark */ public void setRemitRemark(String remitRemark) { this.remitRemark = remitRemark == null ? null : remitRemark.trim(); } /** * 操作员登录名 * * @return */ public String getOperatorLoginname() { return operatorLoginname; } /** * 操作员登录名 * * @param operatorLoginname */ public void setOperatorLoginname(String operatorLoginname) { this.operatorLoginname = operatorLoginname == null ? null : operatorLoginname.trim(); } /** * 操作员姓名 * * @return */ public String getOperatorRealname() { return operatorRealname; } /** * 操作员姓名 * * @param operatorRealname */ public void setOperatorRealname(String operatorRealname) { this.operatorRealname = operatorRealname == null ? null : operatorRealname.trim(); } public String getSettStatusDesc() { return SettRecordStatusEnum.getEnum(this.getSettStatus()).getDesc(); } public String getCreateTimeDesc() { return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss"); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettRecord.java
2
请完成以下Java代码
public int getType() { return type; } public void setType(int type) { this.type = type; } public String getTemplatePath() { return templatePath; } public void setTemplatePath(String templatePath) { this.templatePath = templatePath; } public String getStylePath() { return stylePath; } public void setStylePath(String stylePath) { this.stylePath = stylePath; } public String[] getVueStyle() { return vueStyle; } public void setVueStyle(String[] vueStyle) { this.vueStyle = vueStyle; } /** * 根据code找枚举 * * @param code
* @return */ public static CgformEnum getCgformEnumByConfig(String code) { for (CgformEnum e : CgformEnum.values()) { if (e.code.equals(code)) { return e; } } return null; } /** * 根据类型找所有 * * @param type * @return */ public static List<Map<String, Object>> getJspModelList(int type) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); for (CgformEnum e : CgformEnum.values()) { if (e.type == type) { Map<String, Object> map = new HashMap<String, Object>(); map.put("code", e.code); map.put("note", e.note); ls.add(map); } } return ls; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\CgformEnum.java
1
请完成以下Java代码
public String getTariffType() { return tariffType; } /** * Sets the value of the tariffType property. * * @param value * allowed object is * {@link String } * */ public void setTariffType(String value) { this.tariffType = value; } /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the dateBegin property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDateBegin() { return dateBegin; } /** * Sets the value of the dateBegin property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateBegin(XMLGregorianCalendar value) { this.dateBegin = value;
} /** * Gets the value of the dateEnd property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDateEnd() { return dateEnd; } /** * Sets the value of the dateEnd property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateEnd(XMLGregorianCalendar value) { this.dateEnd = value; } /** * Gets the value of the acid property. * * @return * possible object is * {@link String } * */ public String getAcid() { return acid; } /** * Sets the value of the acid property. * * @param value * allowed object is * {@link String } * */ public void setAcid(String value) { this.acid = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CaseDetailType.java
1
请完成以下Java代码
public class SetDeploymentCategoryCmd implements Command<Void> { protected String deploymentId; protected String category; public SetDeploymentCategoryCmd(String deploymentId, String category) { this.deploymentId = deploymentId; this.category = category; } @Override public Void execute(CommandContext commandContext) { if (deploymentId == null) { throw new FlowableIllegalArgumentException("Deployment id is null"); } DmnDeploymentEntity deployment = CommandContextUtil.getDeploymentEntityManager(commandContext).findById(deploymentId); if (deployment == null) { throw new FlowableObjectNotFoundException("No deployment found for id = '" + deploymentId + "'"); } // Update category deployment.setCategory(category); CommandContextUtil.getDeploymentEntityManager(commandContext).update(deployment);
return null; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\SetDeploymentCategoryCmd.java
1
请完成以下Java代码
private boolean selectedRowIsNotATopHU() { return getView(HUEditorView.class) .streamByIds(getSelectedRowIds()) .noneMatch(HUEditorRow::isTopLevel); } @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final I_DD_OrderLine ddOrderLine = getViewSelectedDDOrderLine(); final String parameterName = parameter.getColumnName(); if (PARAM_M_HU_ID.equals(parameterName)) { return getRecord_ID(); } else if (PARAM_DD_ORDER_LINE_ID.equals(parameterName)) { return ddOrderLine.getDD_OrderLine_ID(); } else if (PARAM_LOCATOR_TO_ID.equals(parameterName)) { return ddOrderLine.getM_LocatorTo_ID(); } else { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } private I_DD_OrderLine getViewSelectedDDOrderLine() { final DDOrderLineId ddOrderLineId = getViewSelectedDDOrderLineId(); return ddOrderService.getLineById(ddOrderLineId); }
@NonNull private DDOrderLineId getViewSelectedDDOrderLineId() { final ViewId parentViewId = getView().getParentViewId(); final DocumentIdsSelection selectedParentRow = DocumentIdsSelection.of(ImmutableList.of(getView().getParentRowId())); final int selectedOrderLineId = viewsRepository.getView(parentViewId) .streamByIds(selectedParentRow) .findFirst() .orElseThrow(() -> new AdempiereException("No DD_OrderLine was selected!")) .getFieldValueAsInt(I_DD_OrderLine.COLUMNNAME_DD_OrderLine_ID, -1); return DDOrderLineId.ofRepoId(selectedOrderLineId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ddorder\process\WEBUI_DD_OrderLine_MoveSelected_HU.java
1
请在Spring Boot框架中完成以下Java代码
public String getDATEFROM() { return datefrom; } /** * Sets the value of the datefrom property. * * @param value * allowed object is * {@link String } * */ public void setDATEFROM(String value) { this.datefrom = value; } /** * Gets the value of the dateto property. * * @return * possible object is * {@link String } * */ public String getDATETO() { return dateto; } /** * Sets the value of the dateto property. * * @param value * allowed object is * {@link String } *
*/ public void setDATETO(String value) { this.dateto = value; } /** * Gets the value of the days property. * * @return * possible object is * {@link String } * */ public String getDAYS() { return days; } /** * Sets the value of the days property. * * @param value * allowed object is * {@link String } * */ public void setDAYS(String value) { this.days = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DDATE1.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDatePublished() {
return datePublished; } public void setDatePublished(String datePublished) { this.datePublished = datePublished; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } }
repos\tutorials-master\vertx-modules\vertx\src\main\java\com\baeldung\model\Article.java
1
请完成以下Java代码
public class Person { @Id @GeneratedValue Long id; private String name; private int born; @Relationship(type = "ACTED_IN") private List<Movie> movies; public Person() { } public String getName() { return name; } public int getBorn() { return born;
} public List<Movie> getMovies() { return movies; } public void setName(String name) { this.name = name; } public void setBorn(int born) { this.born = born; } public void setMovies(List<Movie> movies) { this.movies = movies; } }
repos\tutorials-master\persistence-modules\neo4j\src\main\java\com\baeldung\neo4j\domain\Person.java
1
请在Spring Boot框架中完成以下Java代码
private ShipmentScheduleInfo fromRecord(final I_M_ShipmentSchedule shipmentSchedule) { return ShipmentScheduleInfo.builder() .clientAndOrgId(ClientAndOrgId.ofClientAndOrg(shipmentSchedule.getAD_Client_ID(), shipmentSchedule.getAD_Org_ID())) .warehouseId(shipmentScheduleBL.getWarehouseId(shipmentSchedule)) .bpartnerId(shipmentScheduleBL.getBPartnerId(shipmentSchedule)) .salesOrderLineId(Optional.ofNullable(OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID()))) .productId(ProductId.ofRepoId(shipmentSchedule.getM_Product_ID())) .asiId(AttributeSetInstanceId.ofRepoIdOrNone(shipmentSchedule.getM_AttributeSetInstance_ID())) .bestBeforePolicy(ShipmentAllocationBestBeforePolicy.optionalOfNullableCode(shipmentSchedule.getShipmentAllocation_BestBefore_Policy())) .record(shipmentSchedule) .build(); } public void addQtyPickedAndUpdateHU(final AddQtyPickedRequest request) { huShipmentScheduleBL.addQtyPickedAndUpdateHU(request); } public void deleteByTopLevelHUsAndShipmentScheduleId(@NonNull final Collection<I_M_HU> topLevelHUs, @NonNull final ShipmentScheduleId shipmentScheduleId) { huShipmentScheduleBL.deleteByTopLevelHUsAndShipmentScheduleId(topLevelHUs, shipmentScheduleId); }
public Stream<Packageable> stream(@NonNull final PackageableQuery query) { return packagingDAO.stream(query); } public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord) { return huShipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord); } public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { huShipmentScheduleBL.flagForRecompute(shipmentScheduleIds); } public ShipmentScheduleLoadingCache<de.metas.handlingunits.model.I_M_ShipmentSchedule> newHuShipmentLoadingCache() { return huShipmentScheduleBL.newLoadingCache(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\shipmentschedule\PickingJobShipmentScheduleService.java
2
请在Spring Boot框架中完成以下Java代码
public Result<SysDictItem> deleteBatch(@RequestParam(name="ids",required=true) String ids) { Result<SysDictItem> result = new Result<SysDictItem>(); if(ids==null || "".equals(ids.trim())) { result.error500("参数不识别!"); }else { this.sysDictItemService.removeByIds(Arrays.asList(ids.split(","))); result.success("删除成功!"); } return result; } /** * 字典值重复校验 * @param sysDictItem * @param request * @return */ @RequestMapping(value = "/dictItemCheck", method = RequestMethod.GET) @Operation(summary="字典重复校验接口") public Result<Object> doDictItemCheck(SysDictItem sysDictItem, HttpServletRequest request) { Long num = Long.valueOf(0);
LambdaQueryWrapper<SysDictItem> queryWrapper = new LambdaQueryWrapper<SysDictItem>(); queryWrapper.eq(SysDictItem::getItemValue,sysDictItem.getItemValue()); queryWrapper.eq(SysDictItem::getDictId,sysDictItem.getDictId()); if (StringUtils.isNotBlank(sysDictItem.getId())) { // 编辑页面校验 queryWrapper.ne(SysDictItem::getId,sysDictItem.getId()); } num = sysDictItemService.count(queryWrapper); if (num == 0) { // 该值可用 return Result.ok("该值可用!"); } else { // 该值不可用 log.info("该值不可用,系统中已存在!"); return Result.error("该值不可用,系统中已存在!"); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDictItemController.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender;
} public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } @Override public String toString() { return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", gender=" + gender + ", grade=" + grade + '}'; } }
repos\tutorials-master\persistence-modules\spring-data-redis\src\main\java\com\baeldung\spring\data\redis\model\Student.java
1
请在Spring Boot框架中完成以下Java代码
public class XxlJobConfig { @Value("${xxl.job.admin.addresses}") private String adminAddresses; @Value("${xxl.job.accessToken}") private String accessToken; @Value("${xxl.job.executor.appname}") private String appname; @Value("${xxl.job.executor.address}") private String address; @Value("${xxl.job.executor.ip}") private String ip; @Value("${xxl.job.executor.port}") private int port; @Value("${xxl.job.executor.logpath}") private String logPath; @Value("${xxl.job.executor.logretentiondays}") private int logRetentionDays;
@Bean public XxlJobSpringExecutor xxlJobExecutor() { log.info(">>>>>>>>>>> start xxl-job config init"); XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); xxlJobSpringExecutor.setAdminAddresses(adminAddresses); xxlJobSpringExecutor.setAppname(appname); xxlJobSpringExecutor.setAddress(address); xxlJobSpringExecutor.setIp(ip); xxlJobSpringExecutor.setPort(port); xxlJobSpringExecutor.setAccessToken(accessToken); xxlJobSpringExecutor.setLogPath(logPath); xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays); return xxlJobSpringExecutor; } }
repos\springboot-demo-master\xxl-job\src\main\java\com\et\xxljob\config\XxlJobConfig.java
2
请完成以下Java代码
public Optional<DistributedMember> getDistributedMember() { return Optional.ofNullable(this.distributedMember); } /** * Returns an {@link Optional} reference to the {@link DistributedSystem} (cluster) to which the {@literal peer} * {@link Cache} is connected. * * @return an {@link Optional} reference to the {@link DistributedSystem}. * @see org.apache.geode.distributed.DistributedSystem * @see #getDistributionManager() * @see java.util.Optional */ public Optional<DistributedSystem> getDistributedSystem() { return Optional.ofNullable(getDistributionManager().getSystem()); } /** * Returns a reference to the configured {@link DistributionManager} which is use as the {@link #getSource() source} * of this event. * * @return a reference to the {@link DistributionManager}. * @see org.apache.geode.distributed.internal.DistributionManager */ public DistributionManager getDistributionManager() { return (DistributionManager) getSource(); } /** * Returns the {@link Type} of this {@link MembershipEvent}, such as {@link Type#MEMBER_JOINED}. * * @return the {@link MembershipEvent.Type}. */ public Type getType() { return Type.UNQUALIFIED; } /** * Null-safe builder method used to configure the {@link DistributedMember member} that is the subject * of this event. * * @param distributedMember {@link DistributedMember} that is the subject of this event. * @return this {@link MembershipEvent}. * @see org.apache.geode.distributed.DistributedMember
* @see #getDistributedMember() */ @SuppressWarnings("unchecked") public T withMember(DistributedMember distributedMember) { this.distributedMember = distributedMember; return (T) this; } /** * An {@link Enum enumeration} of different type of {@link MembershipEvent MembershipEvents}. */ public enum Type { MEMBER_DEPARTED, MEMBER_JOINED, MEMBER_SUSPECT, QUORUM_LOST, UNQUALIFIED; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class FlatrateDataEntryId implements RepoIdAware { FlatrateTermId flatrateTermId; int repoId; @JsonCreator public static FlatrateDataEntryId ofRepoId(@NonNull final FlatrateTermId flatrateTermId, final int repoId) { return new FlatrateDataEntryId(flatrateTermId, repoId); } @Nullable public static FlatrateDataEntryId ofRepoIdOrNull(@NonNull final FlatrateTermId flatrateTermId, final int repoId) { return repoId > 0 ? ofRepoId(flatrateTermId, repoId) : null; } public static int toRepoId(@Nullable final FlatrateDataEntryId dataEntryId) { return dataEntryId != null ? dataEntryId.getRepoId() : -1;
} private FlatrateDataEntryId(@NonNull final FlatrateTermId flatrateTermId, final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); this.flatrateTermId = flatrateTermId; } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\FlatrateDataEntryId.java
2
请完成以下Java代码
public boolean supports(Class<? extends Object> auth) { return KerberosServiceRequestToken.class.isAssignableFrom(auth); } @Override public void afterPropertiesSet() throws Exception { Assert.notNull(this.ticketValidator, "ticketValidator must be specified"); Assert.notNull(this.userDetailsService, "userDetailsService must be specified"); } /** * The <code>UserDetailsService</code> to use, for loading the user properties and the * <code>GrantedAuthorities</code>. * @param userDetailsService the new user details service */ public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } /** * The <code>KerberosTicketValidator</code> to use, for validating the Kerberos/SPNEGO * tickets. * @param ticketValidator the new ticket validator */ public void setTicketValidator(KerberosTicketValidator ticketValidator) {
this.ticketValidator = ticketValidator; } /** * Allows subclasses to perform any additional checks of a returned * <code>UserDetails</code> for a given authentication request. * @param userDetails as retrieved from the {@link UserDetailsService} * @param authentication validated {@link KerberosServiceRequestToken} * @throws AuthenticationException AuthenticationException if the credentials could * not be validated (generally a <code>BadCredentialsException</code>, an * <code>AuthenticationServiceException</code>) */ protected void additionalAuthenticationChecks(UserDetails userDetails, KerberosServiceRequestToken authentication) throws AuthenticationException { } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceAuthenticationProvider.java
1
请完成以下Java代码
public String getParameter_ToAsString(final String parameterName) { return valuesTo.getParameterAsString(parameterName); } @Override public int getParameter_ToAsInt(final String parameterName, final int defaultValue) { return valuesTo.getParameterAsInt(parameterName, defaultValue); } @Override public boolean getParameter_ToAsBool(final String parameterName) { return valuesTo.getParameterAsBool(parameterName); } @Override public Timestamp getParameter_ToAsTimestamp(final String parameterName) { return valuesTo.getParameterAsTimestamp(parameterName); } @Override public BigDecimal getParameter_ToAsBigDecimal(final String parameterName) { return valuesTo.getParameterAsBigDecimal(parameterName); } @Override public LocalDate getParameterAsLocalDate(String parameterName) { return values.getParameterAsLocalDate(parameterName); } @Override
public LocalDate getParameter_ToAsLocalDate(String parameterName) { return valuesTo.getParameterAsLocalDate(parameterName); } @Override public ZonedDateTime getParameterAsZonedDateTime(String parameterName) { return values.getParameterAsZonedDateTime(parameterName); } @Nullable @Override public Instant getParameterAsInstant(final String parameterName) { return values.getParameterAsInstant(parameterName); } @Override public ZonedDateTime getParameter_ToAsZonedDateTime(String parameterName) { return valuesTo.getParameterAsZonedDateTime(parameterName); } @Override public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { return values.getParameterAsEnum(parameterName, enumType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\RangeAwareParams.java
1
请完成以下Java代码
public void add(final PurchaseCandidate candidate) { final BigDecimal qty = candidate.getQtyToOrder(); if (qty.signum() == 0) { return; } if (orderLine == null) { orderLine = createOrderLine(candidate); } orderLine.setQtyEntered(orderLine.getQtyEntered().add(qty)); // NOTE: we are not touching QtyOrdered. We expect to be automatically maintained. purchaseCandidates.add(candidate); } private I_C_OrderLine createOrderLine(final PurchaseCandidate candidate) { final int flatrateDataEntryId = candidate.getC_Flatrate_DataEntry_ID(); final int huPIItemProductId = candidate.getM_HU_PI_Item_Product_ID(); final Timestamp datePromised = candidate.getDatePromised(); final BigDecimal price = candidate.getPrice(); final I_C_OrderLine orderLine = orderLineBL.createOrderLine(order, I_C_OrderLine.class); orderLine.setIsMFProcurement(true); // // BPartner/Location/Contact OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).setFromOrderHeader(order); // // PMM Contract if (flatrateDataEntryId > 0) { orderLine.setC_Flatrate_DataEntry_ID(flatrateDataEntryId); } // // Product/UOM/Handling unit orderLine.setM_Product_ID(candidate.getM_Product_ID()); orderLine.setC_UOM_ID(candidate.getC_UOM_ID()); if (huPIItemProductId > 0) { orderLine.setM_HU_PI_Item_Product_ID(huPIItemProductId); } // // ASI final IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class); final AttributeSetInstanceId attributeSetInstanceId = candidate.getAttributeSetInstanceId(); final I_M_AttributeSetInstance contractASI = attributeSetInstanceId.isRegular() ? attributeSetInstanceBL.getById(attributeSetInstanceId) : null;
final I_M_AttributeSetInstance asi; if (contractASI != null) { asi = attributeSetInstanceBL.copy(contractASI); } else { asi = null; } orderLine.setPMM_Contract_ASI(contractASI); orderLine.setM_AttributeSetInstance(asi); // // Quantities orderLine.setQtyEntered(BigDecimal.ZERO); orderLine.setQtyOrdered(BigDecimal.ZERO); // // Dates orderLine.setDatePromised(datePromised); // // Pricing orderLine.setIsManualPrice(true); // go with the candidate's price. e.g. don't reset it to 0 because we have no PL orderLine.setPriceEntered(price); orderLine.setPriceActual(price); // // BPartner/Location/Contact return orderLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrderLineAggregation.java
1
请完成以下Java代码
public class Movie { private String name; private String year; private String director; private Double rating; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getYear() { return year; }
public void setYear(String year) { this.year = year; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } }
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\model\Movie.java
1