instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public org.compiere.model.I_C_ValidCombination getT_Revenue_A() { return get_ValueAsPO(COLUMNNAME_T_Revenue_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setT_Revenue_A(org.compiere.model.I_C_ValidCombination T_Revenue_A) { set_ValueFromPO(COLUMNNAME_T_Revenue_Acct, org.compiere.model.I_C_ValidCombination.class, T_Revenue_A); } /** Set Erlös Konto. @param T_Revenue_Acct Steuerabhängiges Konto zur Verbuchung Erlöse */ @Override public void setT_Revenue_Acct (int T_Revenue_Acct)
{ set_Value (COLUMNNAME_T_Revenue_Acct, Integer.valueOf(T_Revenue_Acct)); } /** Get Erlös Konto. @return Steuerabhängiges Konto zur Verbuchung Erlöse */ @Override public int getT_Revenue_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_T_Revenue_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Tax_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter { public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER"; private final EntityManagerFactory entityManagerFactory; @Context private HttpServletRequest httpRequest; public EntityManagerFilter(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } @Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { EntityManager entityManager = this.entityManagerFactory.createEntityManager(); httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, entityManager); if (!"GET".equalsIgnoreCase(containerRequestContext.getMethod())) { entityManager.getTransaction().begin(); }
} @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { EntityManager entityManager = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE); if (!"GET".equalsIgnoreCase(requestContext.getMethod())) { EntityTransaction entityTransaction = entityManager.getTransaction(); //we do not commit because it's just a READ if (entityTransaction.isActive() && !entityTransaction.getRollbackOnly()) { entityTransaction.commit(); } } entityManager.close(); } } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\config\JerseyConfig.java
2
请完成以下Java代码
public List<I_C_OrderLine> retrieveOrderLines(@NonNull final I_C_Order order, final boolean allowMultiplePOOrders, final String purchaseQtySource) { Check.assumeNotEmpty(purchaseQtySource, "Param purchaseQtySource is not empty"); Check.assume(I_C_OrderLine.COLUMNNAME_QtyOrdered.equals(purchaseQtySource) || I_C_OrderLine.COLUMNNAME_QtyReserved.equals(purchaseQtySource), "Param purchaseQtySource={} needs to be either {} or {}", purchaseQtySource, I_C_OrderLine.COLUMNNAME_QtyOrdered, I_C_OrderLine.COLUMNNAME_QtyReserved ); final IQueryBL queryBL = Services.get(IQueryBL.class); final List<I_C_OrderLine> salesOrderLines = queryBL.createQueryBuilder(I_C_OrderLine.class, order) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, order.getC_Order_ID()) .addCompareFilter(purchaseQtySource, Operator.GREATER, BigDecimal.ZERO) .filter(additionalFilters) .orderBy().addColumn(I_C_OrderLine.COLUMNNAME_C_OrderLine_ID).endOrderBy() .create() .list(I_C_OrderLine.class); if (allowMultiplePOOrders) { return salesOrderLines; } // exclude sales order lines that are already linked to a purchase order line final Set<OrderLineId> salesOrderLineIds = salesOrderLines.stream() .map(I_C_OrderLine::getC_OrderLine_ID) .map(OrderLineId::ofRepoId) .collect(ImmutableSet.toImmutableSet());
final Set<OrderLineId> alreadyAllocatedSOLineIds = queryBL.createQueryBuilder(I_C_PO_OrderLine_Alloc.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_PO_OrderLine_Alloc.COLUMNNAME_C_SO_OrderLine_ID, salesOrderLineIds) .create() .stream() .map(I_C_PO_OrderLine_Alloc::getC_SO_OrderLine_ID) .map(OrderLineId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); return salesOrderLines.stream() .filter(salesOrderLine -> !alreadyAllocatedSOLineIds.contains(OrderLineId.ofRepoId(salesOrderLine.getC_OrderLine_ID()))) .collect(ImmutableList.toImmutableList()); } @Override public void addAdditionalOrderLinesFilter(final IQueryFilter<I_C_OrderLine> filter) { additionalFilters.addFilter(filter); } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\po_from_so\impl\C_Order_CreatePOFromSOsDAO.java
1
请在Spring Boot框架中完成以下Java代码
public DirectExchange delayQueueExchange() { return new DirectExchange(DELAY_QUEUE_EXCHANGE_NAME); } /** * 存放消息的延迟队列 最后将会转发给exchange(实际消费队列对应的) * @return */ @Bean public Queue delayQueue4Queue() { return QueueBuilder.durable(DELAY_QUEUE_NAME) .withArgument("x-dead-letter-exchange", PROCESS_EXCHANGE_NAME) // DLX .withArgument("x-dead-letter-routing-key", ROUTING_KEY) // dead letter携带的routing key .withArgument("x-message-ttl", 3000) // 设置队列的过期时间 .build(); } @Bean Binding delayQueueBind() { return BindingBuilder.bind(delayQueue4Queue()) .to(delayQueueExchange()) .with(ROUTING_KEY); } @Bean public Queue helloQueue() { return new Queue("helloQueue"); } @Bean public Queue msgQueue() { return new Queue("msgQueue"); } //===============以下是验证topic Exchange的队列========== @Bean public Queue queueMessage() { return new Queue("topic.message"); } @Bean public Queue queueMessages() { return new Queue("topic.messages"); } //===============以上是验证topic Exchange的队列========== //===============以下是验证Fanout Exchange的队列========== @Bean public Queue AMessage() { return new Queue("fanout.A"); } @Bean public Queue BMessage() { return new Queue("fanout.B"); } @Bean public Queue CMessage() { return new Queue("fanout.C"); } //===============以上是验证Fanout Exchange的队列==========
@Bean TopicExchange exchange() { return new TopicExchange("exchange"); } @Bean FanoutExchange fanoutExchange() { return new FanoutExchange("fanoutExchange"); } /** * 将队列topic.message与exchange绑定,binding_key为topic.message,就是完全匹配 * @param queueMessage * @param exchange * @return */ @Bean Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message"); } /** * 将队列topic.messages与exchange绑定,binding_key为topic.#,模糊匹配 * @param queueMessages * @param exchange * @return */ @Bean Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) { return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#"); } @Bean Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(AMessage).to(fanoutExchange); } @Bean Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(BMessage).to(fanoutExchange); } @Bean Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(CMessage).to(fanoutExchange); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //必须是prototype类型 public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); return template; } }
repos\spring-boot-quick-master\quick-rabbitmq\src\main\java\com\quick\mq\config\RabbitConfig.java
2
请完成以下Java代码
public class Row { private final LinkedHashMap<String, Cell> map; public Row() { this.map = new LinkedHashMap<>(); } Set<String> getColumnNames() { return map.keySet(); } @NonNull public Cell getCell(@NonNull final String columnName) { final Cell value = map.get(columnName); return value != null ? value : Cell.NULL; } public boolean isBlankColumn(final String columnName) { final Cell cell = getCell(columnName); return cell.isBlank(); } public int getColumnWidth(final String columnName) { final Cell cell = getCell(columnName); return cell.getWidth(); } public String getCellValue(@NonNull final String columnName) { final Cell cell = getCell(columnName); return cell.getAsString(); }
public void put(@NonNull final String columnName, @NonNull final Cell value) { map.put(columnName, value); } public void put(@NonNull final String columnName, @Nullable final Object valueObj) { map.put(columnName, Cell.ofNullable(valueObj)); } public void putAll(@NonNull final Map<String, ?> map) { map.forEach((columnName, value) -> this.map.put(columnName, Cell.ofNullable(value))); } public boolean containsColumn(final String columnName) { return map.containsKey(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Row.java
1
请完成以下Java代码
/* package */ class BPartnerBankAccountImportHelper { private final ICurrencyBL currencyBL = Services.get(ICurrencyBL.class); private final BankRepository bankRepository; private BPartnerImportProcess process; @Builder private BPartnerBankAccountImportHelper( @NonNull final BankRepository bankRepository) { this.bankRepository = bankRepository; } public BPartnerBankAccountImportHelper setProcess(final BPartnerImportProcess process) { this.process = process; return this; } @Nullable public I_C_BP_BankAccount importRecord(final I_I_BPartner importRecord) { final BPartnerId bpartnerId = BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()); I_C_BP_BankAccount bankAccount = BankAccountId.optionalOfRepoId(importRecord.getC_BP_BankAccount_ID()) .map(bankAccountId -> InterfaceWrapperHelper.load(bankAccountId, I_C_BP_BankAccount.class)) .orElse(null); if (bankAccount != null) { bankAccount.setIBAN(importRecord.getIBAN()); ModelValidationEngine.get().fireImportValidate(process, importRecord, bankAccount, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(bankAccount); } else if (!Check.isEmpty(importRecord.getSwiftCode(), true) && !Check.isEmpty(importRecord.getIBAN(), true)) { bankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class);
bankAccount.setC_BPartner_ID(bpartnerId.getRepoId()); bankAccount.setIBAN(importRecord.getIBAN()); bankAccount.setA_Name(importRecord.getSwiftCode()); bankAccount.setC_Currency_ID(currencyBL.getBaseCurrency(process.getCtx()).getId().getRepoId()); final BankId bankId = bankRepository.getBankIdBySwiftCode(importRecord.getSwiftCode()).orElse(null); if (bankId != null) { bankAccount.setC_Bank_ID(bankId.getRepoId()); } ModelValidationEngine.get().fireImportValidate(process, importRecord, bankAccount, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(bankAccount); importRecord.setC_BP_BankAccount_ID(bankAccount.getC_BP_BankAccount_ID()); } return bankAccount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerBankAccountImportHelper.java
1
请完成以下Java代码
public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Map<Vertex, Edge> getEdges() { return edges; } public void addEdge(Vertex vertex, Edge edge){ if (this.edges.containsKey(vertex)){ if (edge.getWeight() < this.edges.get(vertex).getWeight()){ this.edges.replace(vertex, edge); } } else { this.edges.put(vertex, edge); } } public boolean isVisited() { return isVisited; } public void setVisited(boolean visited) { isVisited = visited; } public Pair<Vertex, Edge> nextMinimum(){ Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = this; Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getKey().isVisited()){ if (!pair.getValue().isIncluded()) { if (pair.getValue().getWeight() < nextMinimum.getWeight()) { nextMinimum = pair.getValue(); nextVertex = pair.getKey(); } } } } return new Pair<>(nextVertex, nextMinimum); }
public String originalToString(){ StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getValue().isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(pair.getValue().getWeight()); sb.append(" --- "); sb.append(pair.getKey().getLabel()); sb.append("\n"); pair.getValue().setPrinted(true); } } return sb.toString(); } public String includedToString(){ StringBuilder sb = new StringBuilder(); if (isVisited()) { Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (pair.getValue().isIncluded()) { if (!pair.getValue().isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(pair.getValue().getWeight()); sb.append(" --- "); sb.append(pair.getKey().getLabel()); sb.append("\n"); pair.getValue().setPrinted(true); } } } } return sb.toString(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\prim\Vertex.java
1
请完成以下Java代码
public void onComplete(final I_M_InOut shipment) { shipmentDAO.retrieveLines(shipment).forEach(this::syncInOutLine); } @Override public void onReverse(final I_M_InOut shipment) { shipmentDAO.retrieveLines(shipment).forEach(this::syncInOutLine); } @Override public void onReactivate(final I_M_InOut shipment) { detailRepo.resetDeliveredQtyForShipment(InOutId.ofRepoId(shipment.getM_InOut_ID())); } private void syncInOutLine(@NonNull final I_M_InOutLine inOutLine) { final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoIdOrNull(inOutLine.getC_Flatrate_Term_ID());
if (flatrateTermId == null) { return; } if (!callOrderContractService.isCallOrderContract(flatrateTermId)) { return; } callOrderContractService.validateCallOrderInOutLine(inOutLine, flatrateTermId); final UpsertCallOrderDetailRequest request = UpsertCallOrderDetailRequest.builder() .callOrderContractId(flatrateTermId) .shipmentLine(inOutLine) .build(); callOrderService.handleCallOrderDetailUpsert(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\document\DocumentChangeHandler_InOut.java
1
请完成以下Java代码
public class InsertionSort { public static void insertionSortImperative(int[] input) { for (int i = 1; i < input.length; i++) { int key = input[i]; int j = i - 1; while (j >= 0 && input[j] > key) { input[j + 1] = input[j]; j = j - 1; } input[j + 1] = key; } } public static void insertionSortRecursive(int[] input) { insertionSortRecursive(input, input.length); } private static void insertionSortRecursive(int[] input, int i) { // base case if (i <= 1) { return;
} // sort the first i - 1 elements of the array insertionSortRecursive(input, i - 1); // then find the correct position of the element at position i int key = input[i - 1]; int j = i - 2; // shifting the elements from their position by 1 while (j >= 0 && input[j] > key) { input[j + 1] = input[j]; j = j - 1; } // inserting the key at the appropriate position input[j + 1] = key; } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\insertionsort\InsertionSort.java
1
请完成以下Java代码
public boolean markAsRead(@NonNull final UserNotification notification) { final boolean alreadyRead = notification.setRead(true); if (alreadyRead) { logger.debug("Skip marking notification as read because it's already read: {}", notification); return false; } return markAsReadById(notification.getId()); } @Override public boolean markAsReadById(final int notificationId) { final I_AD_Note notificationPO = retrieveAD_Note(notificationId); if (notificationPO == null) { return false; } return markAsRead(notificationPO); } private boolean markAsRead(@NonNull final I_AD_Note notificationPO) { if (notificationPO.isProcessed()) { return false; } if (!markAsReadNoSave(notificationPO)) { return false; } InterfaceWrapperHelper.save(notificationPO); logger.debug("Marked notification read: {}", notificationPO); return true; } private boolean markAsReadNoSave(@NonNull final I_AD_Note notificationPO) { if (notificationPO.isProcessed()) { return false; } notificationPO.setProcessed(true); return true; } @Override public void markAllAsReadByUserId(final UserId adUserId) { retrieveNotesByUserId(adUserId) .create() .update(this::markAsReadNoSave); } private I_AD_Note retrieveAD_Note(final int adNoteId) { Check.assumeGreaterThanZero(adNoteId, "adNoteId"); return InterfaceWrapperHelper.loadOutOfTrx(adNoteId, I_AD_Note.class); } @Override public boolean deleteById(final int notificationId) { final I_AD_Note notificationPO = retrieveAD_Note(notificationId); if (notificationPO == null) { return false; } deleteNotification(notificationPO); return true; } @Override public void deleteByUserAndTableRecordRef(final @NonNull UserId adUserId, final @NonNull TableRecordReference tableRecordReference) { retrieveNotesByUserId(adUserId) .addEqualsFilter(I_AD_Note.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId()) .addEqualsFilter(I_AD_Note.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID())
.create() .delete(false); } @Override public void deleteAllByUserId(final UserId adUserId) { retrieveNotesByUserId(adUserId) .create() .list() .forEach(this::deleteNotification); } private void deleteNotification(final I_AD_Note notificationPO) { notificationPO.setProcessed(false); InterfaceWrapperHelper.delete(notificationPO); } @Override public int getUnreadCountByUserId(final UserId adUserId) { return retrieveNotesByUserId(adUserId) .addEqualsFilter(I_AD_Note.COLUMN_Processed, false) .create() .count(); } @Override public int getTotalCountByUserId(final UserId adUserId) { return retrieveNotesByUserId(adUserId) .create() .count(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationRepository.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { // only showing the action if there are rows in the view if (getView().size() <= 0) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final SqlOptions sqlOptions = SqlOptions.usingTableName(I_PMM_PurchaseCandidate.Table_Name); final SqlViewRowsWhereClause sqlWhereClause = getView().getSqlWhereClause(DocumentIdsSelection.ALL, sqlOptions); final ICompositeQueryFilter<I_PMM_PurchaseCandidate> procurementPurchaseCandidateQueryFilter = queryBL.createCompositeQueryFilter(I_PMM_PurchaseCandidate.class) .addCompareFilter(I_PMM_PurchaseCandidate.COLUMNNAME_QtyToOrder, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .addFilter(sqlWhereClause.toQueryFilter()); recordsEnqueued = PMM_GenerateOrders.prepareEnqueuing()
.filter(procurementPurchaseCandidateQueryFilter) .enqueue(); return MSG_OK; } @Override protected void postProcess(final boolean success) { if (!success) { return; } // // Notify frontend that the view shall be refreshed because we changed some candidates if (recordsEnqueued > 0) { invalidateView(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\procurement\process\PMM_Purchase_Candidate_CreatePurchaseOrder.java
1
请完成以下Java代码
public boolean isVariant() { return getComponentType().isVariant(); } public Quantity getQtyIncludingScrap() { return getQty().add(getScrapPercent()); } @Nullable public CostAmount getCostAmountOrNull(final CostElementId costElementId) { final BOMCostElementPrice costPriceHolder = getCostPrice().getCostElementPriceOrNull(costElementId); if (costPriceHolder == null) { return null; } final CostPrice costPrice; if (isByProduct()) { costPrice = costPriceHolder.getCostPrice().withZeroComponentsCostPrice(); } else { costPrice = costPriceHolder.getCostPrice(); } final Quantity qty = getQtyIncludingScrap(); return costPrice.multiply(qty); } void setComponentsCostPrice( @NonNull final CostAmount elementCostPrice,
@NonNull final CostElementId costElementId) { getCostPrice().setComponentsCostPrice(elementCostPrice, costElementId); } void clearComponentsCostPrice(@NonNull final CostElementId costElementId) { getCostPrice().clearComponentsCostPrice(costElementId); } public ImmutableList<BOMCostElementPrice> getElementPrices() { return getCostPrice().getElementPrices(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMLine.java
1
请完成以下Java代码
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return getScannedQRCode(wfProcess, wfActivity) != null ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(final @NonNull SetScannedBarcodeRequest request) { final GlobalQRCode scannedQRCode = GlobalQRCode.ofString(request.getScannedBarcode()); final IExternalSystemChildConfigId childConfigId = getExternalSystemChildConfigId(scannedQRCode); final WFActivity wfActivity = request.getWfActivity(); wfActivity.getWfActivityType().assertExpected(HANDLED_ACTIVITY_TYPE); final ManufacturingJobActivityId jobActivityId = getManufacturingJobActivityId(wfActivity); final ManufacturingJob job = getManufacturingJob(request.getWfProcess()); callExternalSystem(childConfigId, job); final ManufacturingJob changedJob = manufacturingJobService.withScannedQRCode(job, jobActivityId, scannedQRCode); return ManufacturingRestService.toWFProcess(changedJob); } private void callExternalSystem(final IExternalSystemChildConfigId childConfigId, final ManufacturingJob job) { final PPOrderId ppOrderId = job.getPpOrderId(); final PInstanceId pInstanceId = adPInstanceDAO.createSelectionId(); exportToExternalSystemService.exportToExternalSystem( childConfigId, TableRecordReference.of(I_PP_Order.Table_Name, ppOrderId), pInstanceId); }
@NonNull private IExternalSystemChildConfigId getExternalSystemChildConfigId(@NonNull final GlobalQRCode scannedQRCode) { if (ResourceQRCode.isTypeMatching(scannedQRCode)) { return getExternalSystemChildConfigId(ResourceQRCode.ofGlobalQRCode(scannedQRCode)); } else if (ExternalSystemConfigQRCode.isTypeMatching(scannedQRCode)) { final ExternalSystemConfigQRCode configQRCode = ExternalSystemConfigQRCode.ofGlobalQRCode(scannedQRCode); return configQRCode.getChildConfigId(); } else { throw new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY); } } @NonNull private IExternalSystemChildConfigId getExternalSystemChildConfigId(@NonNull final ResourceQRCode resourceQRCode) { final Resource externalSystemResource = resourceService.getById(resourceQRCode.getResourceId()); if (!externalSystemResource.isExternalSystem()) { throw new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY); } return ExternalSystemParentConfigId.ofRepoIdOptional(externalSystemResource.getExternalSystemParentConfigId()) .flatMap(externalSystemConfigRepo::getChildByParentId) .map(IExternalSystemChildConfig::getId) .orElseThrow(() -> new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\callExternalSystem\CallExternalSystemActivityHandler.java
1
请完成以下Java代码
protected void prepare() { } @Override protected String doIt() throws Exception { String whereClause = I_C_Location.COLUMNNAME_IsPostalValidated + "=?"; Iterator<I_C_Location> it = new Query(getCtx(), I_C_Location.Table_Name, whereClause, null) .setParameters(false) .setRequiredAccess(Access.WRITE) .iterate(I_C_Location.class); while (it.hasNext()) { cnt_all++; validate(it.next()); if (cnt_all % 100 == 0) { log.info("Progress: OK/Error/Total = " + cnt_ok + "/" + cnt_err + "/" + cnt_all); } }
return "@Updated@ OK/Error/Total = " + cnt_ok + "/" + cnt_err + "/" + cnt_all; } private void validate(I_C_Location location) { try { Services.get(ILocationBL.class).validatePostal(location); InterfaceWrapperHelper.save(location); cnt_ok++; } catch (Exception e) { addLog("Error on " + location + ": " + e.getLocalizedMessage()); cnt_err++; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\process\C_Location_Postal_Validate.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable List<String> getIgnorePaths() { return this.ignorePaths; } public void setIgnorePaths(@Nullable List<String> ignorePaths) { this.ignorePaths = ignorePaths; } /** * Log format for Jetty access logs. */ public enum Format { /** * NCSA format, as defined in CustomRequestLog#NCSA_FORMAT. */ NCSA, /** * Extended NCSA format, as defined in CustomRequestLog#EXTENDED_NCSA_FORMAT. */ EXTENDED_NCSA } } /** * Jetty thread properties. */ public static class Threads { /** * Number of acceptor threads to use. When the value is -1, the default, the * number of acceptors is derived from the operating environment. */ private Integer acceptors = -1; /** * Number of selector threads to use. When the value is -1, the default, the * number of selectors is derived from the operating environment. */ private Integer selectors = -1; /** * Maximum number of threads. Doesn't have an effect if virtual threads are * enabled. */ private Integer max = 200; /** * Minimum number of threads. Doesn't have an effect if virtual threads are * enabled. */ private Integer min = 8; /** * Maximum capacity of the thread pool's backing queue. A default is computed * based on the threading configuration. */ private @Nullable Integer maxQueueCapacity; /** * Maximum thread idle time. */ private Duration idleTimeout = Duration.ofMillis(60000); public Integer getAcceptors() { return this.acceptors; } public void setAcceptors(Integer acceptors) { this.acceptors = acceptors;
} public Integer getSelectors() { return this.selectors; } public void setSelectors(Integer selectors) { this.selectors = selectors; } public void setMin(Integer min) { this.min = min; } public Integer getMin() { return this.min; } public void setMax(Integer max) { this.max = max; } public Integer getMax() { return this.max; } public @Nullable Integer getMaxQueueCapacity() { return this.maxQueueCapacity; } public void setMaxQueueCapacity(@Nullable Integer maxQueueCapacity) { this.maxQueueCapacity = maxQueueCapacity; } public void setIdleTimeout(Duration idleTimeout) { this.idleTimeout = idleTimeout; } public Duration getIdleTimeout() { return this.idleTimeout; } } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\autoconfigure\JettyServerProperties.java
2
请完成以下Java代码
public ReturnsInOutHeaderFiller setWarehouseId(final int warehouseId) { this.warehouseId = warehouseId; return this; } private int getWarehouseId() { return warehouseId; } public ReturnsInOutHeaderFiller setOrder(@Nullable final I_C_Order order) { this.order = order; return this; } private I_C_Order getOrder() { return order; } public ReturnsInOutHeaderFiller setExternalId(@Nullable final String externalId) { this.externalId = externalId; return this; } private String getExternalId() { return this.externalId;
} private String getExternalResourceURL() { return this.externalResourceURL; } public ReturnsInOutHeaderFiller setExternalResourceURL(@Nullable final String externalResourceURL) { this.externalResourceURL = externalResourceURL; return this; } public ReturnsInOutHeaderFiller setDateReceived(@Nullable final Timestamp dateReceived) { this.dateReceived = dateReceived; return this; } private Timestamp getDateReceived() { return dateReceived; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsInOutHeaderFiller.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isStop() { return isStop; } public void setStop(boolean stop) { isStop = stop; } public OrderProcessReq getOrderProcessReq() { return orderProcessReq; } public void setOrderProcessReq(OrderProcessReq orderProcessReq) { this.orderProcessReq = orderProcessReq; } public T getOrderProcessRsp() { return orderProcessRsp;
} public void setOrderProcessRsp(T orderProcessRsp) { this.orderProcessRsp = orderProcessRsp; } @Override public String toString() { return "OrderProcessContext{" + "isStop=" + isStop + ", orderProcessReq=" + orderProcessReq + ", orderProcessRsp=" + orderProcessRsp + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\context\OrderProcessContext.java
2
请完成以下Java代码
public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** ReplicationType AD_Reference_ID=126 */ public static final int REPLICATIONTYPE_AD_Reference_ID=126; /** Local = L */ public static final String REPLICATIONTYPE_Local = "L"; /** Merge = M */ public static final String REPLICATIONTYPE_Merge = "M"; /** Reference = R */ public static final String REPLICATIONTYPE_Reference = "R"; /** Broadcast = B */ public static final String REPLICATIONTYPE_Broadcast = "B"; /** Set Replication Type. @param ReplicationType Type of Data Replication */ public void setReplicationType (String ReplicationType) { set_Value (COLUMNNAME_ReplicationType, ReplicationType); } /** Get Replication Type. @return Type of Data Replication */ public String getReplicationType () { return (String)get_Value(COLUMNNAME_ReplicationType); }
public I_EXP_Format getEXP_Format() throws RuntimeException { return (I_EXP_Format)MTable.get(getCtx(), I_EXP_Format.Table_Name) .getPO(getEXP_Format_ID(), get_TrxName()); } public void setEXP_Format_ID (int EXP_Format_ID) { if (EXP_Format_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_Format_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_Format_ID, Integer.valueOf(EXP_Format_ID)); } public int getEXP_Format_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Format_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationTable.java
1
请完成以下Java代码
public static void checkAccountAndIpLock(BladeRedis bladeRedis, String tenantId, String account) { String ip = WebUtil.getIP(); // 检查账号锁定 int userFailCount = Func.toInt(bladeRedis.get(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, account)), 0); if (userFailCount >= FAIL_COUNT) { throw new ServiceException(USER_HAS_TOO_MANY_FAILS); } // 检查IP锁定 int ipFailCount = Func.toInt(bladeRedis.get(CacheNames.IP_FAIL_KEY + ip), 0); if (ipFailCount >= FAIL_COUNT) { throw new ServiceException(IP_HAS_TOO_MANY_FAILS); } } /** * 处理登录失败,增加失败次数 * * @param bladeRedis Redis缓存 * @param tenantId 租户ID * @param account 账号 */ public static void handleLoginFailure(BladeRedis bladeRedis, String tenantId, String account) { String ip = WebUtil.getIP(); // 增加账号错误锁定次数 int userFailCount = Func.toInt(bladeRedis.get(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, account)), 0); bladeRedis.setEx(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, account), userFailCount + 1, Duration.ofMinutes(30)); // 增加IP错误锁定次数 int ipFailCount = Func.toInt(bladeRedis.get(CacheNames.IP_FAIL_KEY + ip), 0); bladeRedis.setEx(CacheNames.IP_FAIL_KEY + ip, ipFailCount + 1, Duration.ofMinutes(30));
} /** * 处理登录成功,清除失败缓存 * * @param bladeRedis Redis缓存 * @param tenantId 租户ID * @param account 账号 */ public static void handleLoginSuccess(BladeRedis bladeRedis, String tenantId, String account) { String ip = WebUtil.getIP(); // 清除账号登录失败缓存 bladeRedis.del(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, account)); // 清除IP登录失败缓存 bladeRedis.del(CacheNames.IP_FAIL_KEY + ip); } }
repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\utils\TokenUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); // 配置规则. initFlowRules(); /*while (true) { // 1.5.0 版本开始可以直接利用 try-with-resources 特性 try (Entry entry = SphU.entry("HelloWorld")) { // 被保护的逻辑 Thread.sleep(300); System.out.println("hello world"); } catch (BlockException | InterruptedException ex) { // 处理被流控的逻辑 System.out.println("blocked!"); }
}*/ } private static void initFlowRules(){ List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("HelloWorld"); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // Set limit QPS to 20. rule.setCount(2); rules.add(rule); FlowRuleManager.loadRules(rules); } }
repos\springboot-demo-master\sentinel\src\main\java\com\et\sentinel\DemoApplication.java
2
请完成以下Java代码
public class MAdvertisement extends X_W_Advertisement { /** * */ private static final long serialVersionUID = 8129122675267734690L; /** * Default Constructor * @param ctx context * @param W_Advertisement_ID id * @param trxName transaction */ public MAdvertisement (Properties ctx, int W_Advertisement_ID, String trxName) { super (ctx, W_Advertisement_ID, trxName); /** if (W_Advertisement_ID == 0) { setC_BPartner_ID (0); setIsSelfService (false); setName (null); setW_Advertisement_ID (0); } **/ } // MAdvertisement /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MAdvertisement (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MAdvertisement /** Click Count */ private MClickCount m_clickCount = null; /** Counter Count */ private MCounterCount m_counterCount = null; /** Sales Rep */ private int m_SalesRep_ID = 0; /************************************************************************** * Get ClickCount * @return Click Count */ public MClickCount getMClickCount() { if (getW_ClickCount_ID() == 0) return null; if (m_clickCount == null) m_clickCount = new MClickCount (getCtx(), getW_ClickCount_ID(), get_TrxName()); return m_clickCount; } // MClickCount /** * Get Click Target URL (from ClickCount) * @return URL */ public String getClickTargetURL() { getMClickCount(); if (m_clickCount == null) return "-"; return m_clickCount.getTargetURL(); } // getClickTargetURL /** * Set Click Target URL (in ClickCount) * @param TargetURL url */ public void setClickTargetURL(String TargetURL) { getMClickCount(); if (m_clickCount == null) m_clickCount = new MClickCount(this);
if (m_clickCount != null) { m_clickCount.setTargetURL(TargetURL); m_clickCount.save(get_TrxName()); } } // getClickTargetURL /** * Get Weekly Count * @return weekly count */ public ValueNamePair[] getClickCountWeek () { getMClickCount(); if (m_clickCount == null) return new ValueNamePair[0]; return m_clickCount.getCountWeek(); } // getClickCountWeek /** * Get CounterCount * @return Counter Count */ public MCounterCount getMCounterCount() { if (getW_CounterCount_ID() == 0) return null; if (m_counterCount == null) m_counterCount = new MCounterCount (getCtx(), getW_CounterCount_ID(), get_TrxName()); return m_counterCount; } // MCounterCount /** * Get Sales Rep ID. * (AD_User_ID of oldest BP user) * @return Sales Rep ID */ public int getSalesRep_ID() { if (m_SalesRep_ID == 0) { m_SalesRep_ID = getAD_User_ID(); if (m_SalesRep_ID == 0) m_SalesRep_ID = DB.getSQLValue(null, "SELECT AD_User_ID FROM AD_User " + "WHERE C_BPartner_ID=? AND IsActive='Y' ORDER BY AD_User_ID", getC_BPartner_ID()); } return m_SalesRep_ID; } // getSalesRep_ID } // MAdvertisement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAdvertisement.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Boolean> blockingSearch(String fileName, String searchTerm) { String fileContent = fileService.getFileContentAsString(fileName) .doOnNext(content -> ThreadLogger.log("1. BlockingSearch")) .block(); boolean isSearchTermPresent = fileContent.contains(searchTerm); return Mono.just(isSearchTermPresent); } public Mono<Boolean> workableBlockingSearch(String fileName, String searchTerm) { return Mono.just("") .doOnNext(s -> ThreadLogger.log("1. WorkableBlockingSearch")) .publishOn(Schedulers.boundedElastic()) .doOnNext(s -> ThreadLogger.log("2. WorkableBlockingSearch")) .map(s -> fileService.getFileContentAsString(fileName) .block() .contains(searchTerm)) .doOnNext(s -> ThreadLogger.log("3. WorkableBlockingSearch")); } public Mono<Boolean> incorrectUseOfSchedulersSearch(String fileName, String searchTerm) { String fileContent = fileService.getFileContentAsString(fileName) .doOnNext(content -> ThreadLogger.log("1. IncorrectUseOfSchedulersSearch")) .publishOn(Schedulers.boundedElastic()) .doOnNext(content -> ThreadLogger.log("2. IncorrectUseOfSchedulersSearch")) .block(); boolean isSearchTermPresent = fileContent.contains(searchTerm); return Mono.just(isSearchTermPresent); } public Mono<Boolean> blockingSearchOnCustomThreadPool(String fileName, String searchTerm) { return Mono.just("") .doOnNext(s -> ThreadLogger.log("1. BlockingSearchOnCustomThreadPool")) .publishOn(Schedulers.fromExecutorService(executorService)) .doOnNext(s -> ThreadLogger.log("2. BlockingSearchOnCustomThreadPool"))
.map(s -> fileService.getFileContentAsString(fileName) .block() .contains(searchTerm)) .doOnNext(s -> ThreadLogger.log("3. BlockingSearchOnCustomThreadPool")); } public Mono<Boolean> blockingSearchOnParallelThreadPool(String fileName, String searchTerm) { return Mono.just("") .doOnNext(s -> ThreadLogger.log("1. BlockingSearchOnParallelThreadPool")) .publishOn(Schedulers.parallel()) .doOnNext(s -> ThreadLogger.log("2. BlockingSearchOnParallelThreadPool")) .map(s -> fileService.getFileContentAsString(fileName) .block() .contains(searchTerm)) .doOnNext(s -> ThreadLogger.log("3. BlockingSearchOnParallelThreadPool")); } public Mono<Boolean> nonBlockingSearch(String fileName, String searchTerm) { return fileService.getFileContentAsString(fileName) .doOnNext(content -> ThreadLogger.log("1. NonBlockingSearch")) .map(content -> content.contains(searchTerm)) .doOnNext(content -> ThreadLogger.log("2. NonBlockingSearch")); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-4\src\main\java\com\baeldung\webflux\block\service\FileContentSearchService.java
2
请完成以下Java代码
public boolean isDetached() { return userTask.getExecutionId() == null; } @Override public void detachState() { userTask.getExecution().removeTask(userTask); userTask.setExecution(null); } @Override public void attachState(MigratingScopeInstance owningInstance) { ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution(); representativeExecution.addTask(userTask); for (VariableInstanceEntity variable : userTask.getVariablesInternal()) { variable.setExecution(representativeExecution); } userTask.setExecution(representativeExecution); } @Override public void attachState(MigratingTransitionInstance targetTransitionInstance) { throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this); } @Override public void migrateState() { userTask.setProcessDefinitionId(migratingActivityInstance.getTargetScope().getProcessDefinition().getId()); userTask.setTaskDefinitionKey(migratingActivityInstance.getTargetScope().getId());
migrateHistory(); } protected void migrateHistory() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); if (historyLevel.isHistoryEventProduced(HistoryEventTypes.TASK_INSTANCE_MIGRATE, this)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createTaskInstanceMigrateEvt(userTask); } }); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingUserTaskInstance.java
1
请在Spring Boot框架中完成以下Java代码
protected final boolean isSslEnabled() { return getProperties().getSsl().isEnabled(); } protected final boolean urlUsesSsl(String url) { return DataRedisUrl.of(url).useSsl(); } protected boolean isPoolEnabled(Pool pool) { Boolean enabled = pool.getEnabled(); return (enabled != null) ? enabled : COMMONS_POOL2_AVAILABLE; } private List<RedisNode> createSentinels(Sentinel sentinel) { List<RedisNode> nodes = new ArrayList<>(); for (Node node : sentinel.getNodes()) { nodes.add(asRedisNode(node)); } return nodes; } protected final DataRedisConnectionDetails getConnectionDetails() { return this.connectionDetails;
} private Mode determineMode() { if (getSentinelConfig() != null) { return Mode.SENTINEL; } if (getClusterConfiguration() != null) { return Mode.CLUSTER; } if (getMasterReplicaConfiguration() != null) { return Mode.MASTER_REPLICA; } return Mode.STANDALONE; } enum Mode { STANDALONE, CLUSTER, MASTER_REPLICA, SENTINEL } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionConfiguration.java
2
请完成以下Java代码
public void assertQtyToIssueToleranceIsRespected() { assertQtyToIssueToleranceIsRespected_LowerBound(qtyIssuedOrReceivedActual); assertQtyToIssueToleranceIsRespected_UpperBound(qtyIssuedOrReceivedActual); } private void assertQtyToIssueToleranceIsRespected_LowerBound(final Quantity qtyIssuedOrReceivedActual) { if (issuingToleranceSpec == null) { return; } final Quantity qtyIssuedOrReceivedActualMin = issuingToleranceSpec.subtractFrom(qtyRequired); if (qtyIssuedOrReceivedActual.compareTo(qtyIssuedOrReceivedActualMin) < 0) { final ITranslatableString qtyStr = TranslatableStrings.builder() .appendQty(qtyIssuedOrReceivedActualMin.toBigDecimal(), qtyIssuedOrReceivedActualMin.getUOMSymbol()) .append(" (") .appendQty(qtyRequired.toBigDecimal(), qtyRequired.getUOMSymbol()) .append(" - ") .append(issuingToleranceSpec.toTranslatableString()) .append(")") .build(); throw new AdempiereException(MSG_CannotIssueLessThan, qtyStr) .markAsUserValidationError(); } } private void assertQtyToIssueToleranceIsRespected_UpperBound(final Quantity qtyIssuedOrReceivedActual) { if (issuingToleranceSpec == null) { return; } final Quantity qtyIssuedOrReceivedActualMax = issuingToleranceSpec.addTo(qtyRequired); if (qtyIssuedOrReceivedActual.compareTo(qtyIssuedOrReceivedActualMax) > 0) { final ITranslatableString qtyStr = TranslatableStrings.builder()
.appendQty(qtyIssuedOrReceivedActualMax.toBigDecimal(), qtyIssuedOrReceivedActualMax.getUOMSymbol()) .append(" (") .appendQty(qtyRequired.toBigDecimal(), qtyRequired.getUOMSymbol()) .append(" + ") .append(issuingToleranceSpec.toTranslatableString()) .append(")") .build(); throw new AdempiereException(MSG_CannotIssueMoreThan, qtyStr) .markAsUserValidationError(); } } @NonNull public OrderBOMLineQuantities convertQuantities(@NonNull final UnaryOperator<Quantity> converter) { return toBuilder() .qtyRequired(converter.apply(qtyRequired)) .qtyRequiredBeforeClose(converter.apply(qtyRequiredBeforeClose)) .qtyIssuedOrReceived(converter.apply(qtyIssuedOrReceived)) .qtyIssuedOrReceivedActual(converter.apply(qtyIssuedOrReceivedActual)) .qtyReject(converter.apply(qtyReject)) .qtyScrap(converter.apply(qtyScrap)) .qtyUsageVariance(converter.apply(qtyUsageVariance)) .qtyPost(converter.apply(qtyPost)) .qtyReserved(converter.apply(qtyReserved)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\OrderBOMLineQuantities.java
1
请完成以下Java代码
private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties(); sys.setComputerName(IpUtil.getHostName()); sys.setComputerIp(IpUtil.getHostIp()); sys.setOsName(props.getProperty("os.name")); sys.setOsArch(props.getProperty("os.arch")); sys.setUserDir(props.getProperty("user.dir")); } /** * 设置Java虚拟机 */ private void setJvmInfo() throws UnknownHostException { Properties props = System.getProperties(); jvm.setTotal(Runtime.getRuntime().totalMemory()); jvm.setMax(Runtime.getRuntime().maxMemory()); jvm.setFree(Runtime.getRuntime().freeMemory()); jvm.setVersion(props.getProperty("java.version")); jvm.setHome(props.getProperty("java.home")); } /** * 设置磁盘信息 */ private void setSysFiles(OperatingSystem os) { FileSystem fileSystem = os.getFileSystem(); OSFileStore[] fsArray = fileSystem.getFileStores(); for (OSFileStore fs : fsArray) {
long free = fs.getUsableSpace(); long total = fs.getTotalSpace(); long used = total - free; SysFile sysFile = new SysFile(); sysFile.setDirName(fs.getMount()); sysFile.setSysTypeName(fs.getType()); sysFile.setTypeName(fs.getName()); sysFile.setTotal(convertFileSize(total)); sysFile.setFree(convertFileSize(free)); sysFile.setUsed(convertFileSize(used)); sysFile.setUsage(NumberUtil.mul(NumberUtil.div(used, total, 4), 100)); sysFiles.add(sysFile); } } /** * 字节转换 * * @param size 字节大小 * @return 转换后值 */ public String convertFileSize(long size) { long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; if (size >= gb) { return String.format("%.1f GB", (float) size / gb); } else if (size >= mb) { float f = (float) size / mb; return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); } else if (size >= kb) { float f = (float) size / kb; return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); } else { return String.format("%d B", size); } } }
repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\Server.java
1
请完成以下Java代码
public ITrxListenerManager getTrxListenerManager() { throw new UnsupportedOperationException(); } @Override public ITrxManager getTrxManager() { throw new UnsupportedOperationException(); } @Override public <T> T setProperty(final String name, final Object value) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name) { throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name, final Supplier<T> valueInitializer)
{ throw new UnsupportedOperationException(); } @Override public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer) { throw new UnsupportedOperationException(); } @Override public <T> T setAndGetProperty(final String name, final Function<T, T> valueRemappingFunction) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\NullTrxPlaceholder.java
1
请在Spring Boot框架中完成以下Java代码
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { SysUser sysUser = sysUserRepository.findFirstByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found!")); List<SimpleGrantedAuthority> roles = sysUser.getRoles().stream().map(sysRole -> new SimpleGrantedAuthority(sysRole.getName())).collect(Collectors.toList()); // 在这里手动构建 UserDetails 的默认实现 return new User(sysUser.getUsername(), sysUser.getPassword(), roles); } @Override public List<SysUser> findAll() { return sysUserRepository.findAll(); } @Override public SysUser findById(Long id) { return sysUserRepository.findById(id).orElseThrow(() -> new RuntimeException("找不到用户")); } @Override public void createUser(SysUser sysUser) { sysUser.setId(null); sysUserRepository.save(sysUser); }
@Override public void updateUser(SysUser sysUser) { sysUser.setPassword(null); sysUserRepository.save(sysUser); } @Override public void updatePassword(Long id, String password) { SysUser exist = findById(id); exist.setPassword(passwordEncoder.encode(password)); sysUserRepository.save(exist); } @Override public void deleteUser(Long id) { sysUserRepository.deleteById(id); } }
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\service\impl\SysUserServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getStateOrProvince() { return stateOrProvince; } public void setStateOrProvince(String stateOrProvince) { this.stateOrProvince = stateOrProvince; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TaxAddress taxAddress = (TaxAddress)o; return Objects.equals(this.city, taxAddress.city) && Objects.equals(this.countryCode, taxAddress.countryCode) && Objects.equals(this.postalCode, taxAddress.postalCode) && Objects.equals(this.stateOrProvince, taxAddress.stateOrProvince); } @Override public int hashCode() { return Objects.hash(city, countryCode, postalCode, stateOrProvince); } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TaxAddress {\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" stateOrProvince: ").append(toIndentedString(stateOrProvince)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\TaxAddress.java
2
请在Spring Boot框架中完成以下Java代码
public Job deciderJob() { return jobBuilderFactory.get("deciderJob") .start(step1()) .next(myDecider) .from(myDecider).on("weekend").to(step2()) .from(myDecider).on("workingDay").to(step3()) .from(step3()).on("*").to(step4()) .end() .build(); } private Step step1() { return stepBuilderFactory.get("step1") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤一操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step2() { return stepBuilderFactory.get("step2") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤二操作。。。"); return RepeatStatus.FINISHED;
}).build(); } private Step step3() { return stepBuilderFactory.get("step3") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤三操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step4() { return stepBuilderFactory.get("step4") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤四操作。。。"); return RepeatStatus.FINISHED; }).build(); } }
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\DeciderJobDemo.java
2
请完成以下Java代码
public void exportJob(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { jobService.download(jobService.queryAll(criteria), response); } @ApiOperation("查询岗位") @GetMapping @PreAuthorize("@el.check('job:list','user:list')") public ResponseEntity<PageResult<JobDto>> queryJob(JobQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK); } @Log("新增岗位") @ApiOperation("新增岗位") @PostMapping @PreAuthorize("@el.check('job:add')") public ResponseEntity<Object> createJob(@Validated @RequestBody Job resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } jobService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改岗位")
@ApiOperation("修改岗位") @PutMapping @PreAuthorize("@el.check('job:edit')") public ResponseEntity<Object> updateJob(@Validated(Job.Update.class) @RequestBody Job resources){ jobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除岗位") @ApiOperation("删除岗位") @DeleteMapping @PreAuthorize("@el.check('job:del')") public ResponseEntity<Object> deleteJob(@RequestBody Set<Long> ids){ // 验证是否被用户关联 jobService.verification(ids); jobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\JobController.java
1
请在Spring Boot框架中完成以下Java代码
public @ResponseBody byte[] getImage() throws IOException { final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg"); return IOUtils.toByteArray(in); } @GetMapping(value = "/get-image-with-media-type", produces = MediaType.IMAGE_JPEG_VALUE) public @ResponseBody byte[] getImageWithMediaType() throws IOException { final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg"); return IOUtils.toByteArray(in); } @GetMapping("/get-image-dynamic-type") @ResponseBody public ResponseEntity<InputStreamResource> getImageDynamicType(@RequestParam("jpg") boolean jpg) { final MediaType contentType = jpg ? MediaType.IMAGE_JPEG : MediaType.IMAGE_PNG;
final InputStream in = jpg ? getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg") : getClass().getResourceAsStream("/com/baeldung/produceimage/image.png"); return ResponseEntity.ok() .contentType(contentType) .body(new InputStreamResource(in)); } @GetMapping(value = "/get-file", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public @ResponseBody byte[] getFile() throws IOException { final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/data.txt"); return IOUtils.toByteArray(in); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\produceimage\controller\DataProducerController.java
2
请在Spring Boot框架中完成以下Java代码
public class ProductPriceId implements RepoIdAware { @JsonCreator public static ProductPriceId ofRepoId(final int repoId) { return new ProductPriceId(repoId); } public static ProductPriceId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } int repoId; private ProductPriceId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "M_ProductPrice_ID"); } public static int toRepoId(final ProductPriceId id) { return id != null ? id.getRepoId() : -1; } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\ProductPriceId.java
2
请完成以下Java代码
public String toString() { final StringBuilder sb = new StringBuilder("MIssue["); sb.append(get_ID()) .append("-").append(getIssueSummary()) .append(",Record=").append(getRecord_ID()) .append("]"); return sb.toString(); } @Override public void setIssueSummary(String IssueSummary) { final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_IssueSummary); super.setIssueSummary(truncateExceptionsRelatedString(IssueSummary, maxLength)); } @Override public void setStackTrace(String StackTrace) { final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_StackTrace); super.setStackTrace(truncateExceptionsRelatedString(StackTrace, maxLength)); } @Override public void setErrorTrace(String ErrorTrace) { final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_ErrorTrace); super.setErrorTrace(truncateExceptionsRelatedString(ErrorTrace, maxLength)); } private static String truncateExceptionsRelatedString(final String string, final int maxLength)
{ if (string == null || string.isEmpty()) { return string; } String stringNorm = string; stringNorm = stringNorm.replace("java.lang.", ""); stringNorm = stringNorm.replace("java.sql.", ""); // Truncate the string if necessary if (maxLength > 0 && stringNorm.length() > maxLength) { stringNorm = stringNorm.substring(0, maxLength - 1); } return stringNorm; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MIssue.java
1
请完成以下Java代码
public void execute(JobExecutionContext context) { //获取当前时间5个月前的时间 // 获取当前日期 Calendar calendar = Calendar.getInstance(); // 减去5个月 calendar.add(Calendar.MONTH, -5); // 格式化输出 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = sdf.format(calendar.getTime()); String startTime = formattedDate + " 00:00:00"; String endTime = formattedDate + " 23:59:59"; LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.between(SysUser::getLastPwdUpdateTime, startTime, endTime); queryWrapper.select(SysUser::getUsername,SysUser::getRealname); List<SysUser> list = userService.list(queryWrapper); if (CollectionUtil.isNotEmpty(list)){ for (SysUser sysUser : list) { this.sendSysMessage(sysUser.getUsername(), sysUser.getRealname()); }
} } /** * 发送系统消息 */ private void sendSysMessage(String username, String realname) { String fromUser = "system"; String title = "尊敬的"+realname+"您的密码已经5个月未修改了,请修改密码"; MessageDTO messageDTO = new MessageDTO(fromUser, username, title, title); messageDTO.setNoticeType(NoticeTypeEnum.NOTICE_TYPE_PLAN.getValue()); sysBaseAPI.sendSysAnnouncement(messageDTO); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\job\UserUpadtePwdJob.java
1
请完成以下Java代码
private long getNextLongInRange(Range<Long> range) { OptionalLong first = getSource().longs(1, range.getMin(), range.getMax()).findFirst(); assertPresent(first.isPresent(), range); return first.getAsLong(); } private void assertPresent(boolean present, Range<?> range) { Assert.state(present, () -> "Could not get random number for range '" + range + "'"); } private Object getRandomBytes() { byte[] bytes = new byte[16]; getSource().nextBytes(bytes); return HexFormat.of().withLowerCase().formatHex(bytes); } /** * Add a {@link RandomValuePropertySource} to the given {@link Environment}. * @param environment the environment to add the random property source to */ public static void addToEnvironment(ConfigurableEnvironment environment) { addToEnvironment(environment, logger); } /** * Add a {@link RandomValuePropertySource} to the given {@link Environment}. * @param environment the environment to add the random property source to * @param logger logger used for debug and trace information * @since 4.0.0 */ public static void addToEnvironment(ConfigurableEnvironment environment, Log logger) { MutablePropertySources sources = environment.getPropertySources(); PropertySource<?> existing = sources.get(RANDOM_PROPERTY_SOURCE_NAME); if (existing != null) { logger.trace("RandomValuePropertySource already present"); return; } RandomValuePropertySource randomSource = new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME); if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) != null) { sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource); } else { sources.addLast(randomSource); } logger.trace("RandomValuePropertySource add to Environment"); } static final class Range<T extends Number> { private final String value; private final T min; private final T max;
private Range(String value, T min, T max) { this.value = value; this.min = min; this.max = max; } T getMin() { return this.min; } T getMax() { return this.max; } @Override public String toString() { return this.value; } static <T extends Number & Comparable<T>> Range<T> of(String value, Function<String, T> parse) { T zero = parse.apply("0"); String[] tokens = StringUtils.commaDelimitedListToStringArray(value); T min = parse.apply(tokens[0]); if (tokens.length == 1) { Assert.state(min.compareTo(zero) > 0, "Bound must be positive."); return new Range<>(value, zero, min); } T max = parse.apply(tokens[1]); Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound."); return new Range<>(value, min, max); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\RandomValuePropertySource.java
1
请在Spring Boot框架中完成以下Java代码
public class AdTableId implements RepoIdAware { @JsonCreator public static AdTableId ofRepoId(final int repoId) { return new AdTableId(repoId); } @Nullable public static AdTableId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new AdTableId(repoId) : null; } public static int toRepoId(@Nullable final AdTableId id) { return id != null ? id.getRepoId() : -1; } int repoId; private AdTableId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Table_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final AdTableId o1, @Nullable final AdTableId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\AdTableId.java
2
请完成以下Java代码
public DataFetcherResult<UserResult> createUser(@InputArgument("input") CreateUserInput input) { RegisterParam registerParam = new RegisterParam(input.getEmail(), input.getUsername(), input.getPassword()); User user; try { user = userService.createUser(registerParam); } catch (ConstraintViolationException cve) { return DataFetcherResult.<UserResult>newResult() .data(GraphQLCustomizeExceptionHandler.getErrorsAsData(cve)) .build(); } return DataFetcherResult.<UserResult>newResult() .data(UserPayload.newBuilder().build()) .localContext(user) .build(); } @DgsData(parentType = MUTATION.TYPE_NAME, field = MUTATION.Login) public DataFetcherResult<UserPayload> login( @InputArgument("password") String password, @InputArgument("email") String email) { Optional<User> optional = userRepository.findByEmail(email); if (optional.isPresent() && encryptService.matches(password, optional.get().getPassword())) { return DataFetcherResult.<UserPayload>newResult() .data(UserPayload.newBuilder().build()) .localContext(optional.get()) .build(); } else { throw new InvalidAuthenticationException(); } } @DgsData(parentType = MUTATION.TYPE_NAME, field = MUTATION.UpdateUser) public DataFetcherResult<UserPayload> updateUser( @InputArgument("changes") UpdateUserInput updateUserInput) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof AnonymousAuthenticationToken
|| authentication.getPrincipal() == null) { return null; } io.spring.core.user.User currentUser = (io.spring.core.user.User) authentication.getPrincipal(); UpdateUserParam param = UpdateUserParam.builder() .username(updateUserInput.getUsername()) .email(updateUserInput.getEmail()) .bio(updateUserInput.getBio()) .password(updateUserInput.getPassword()) .image(updateUserInput.getImage()) .build(); userService.updateUser(new UpdateUserCommand(currentUser, param)); return DataFetcherResult.<UserPayload>newResult() .data(UserPayload.newBuilder().build()) .localContext(currentUser) .build(); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\UserMutation.java
1
请完成以下Java代码
public class UpdateProcessInstancesSuspendStateBatchConfigurationJsonConverter extends AbstractBatchConfigurationObjectConverter<UpdateProcessInstancesSuspendStateBatchConfiguration> { public static final UpdateProcessInstancesSuspendStateBatchConfigurationJsonConverter INSTANCE = new UpdateProcessInstancesSuspendStateBatchConfigurationJsonConverter(); public static final String PROCESS_INSTANCE_IDS = "processInstanceIds"; public static final String PROCESS_INSTANCE_ID_MAPPINGS = "processInstanceIdMappings"; public static final String SUSPENDING = "suspended"; @Override public JsonObject writeConfiguration(UpdateProcessInstancesSuspendStateBatchConfiguration configuration) { JsonObject json = JsonUtil.createObject(); JsonUtil.addListField(json, PROCESS_INSTANCE_IDS, configuration.getIds()); JsonUtil.addListField(json, PROCESS_INSTANCE_ID_MAPPINGS, DeploymentMappingJsonConverter.INSTANCE, configuration.getIdMappings()); JsonUtil.addField(json, SUSPENDING, configuration.getSuspended()); return json; }
@Override public UpdateProcessInstancesSuspendStateBatchConfiguration readConfiguration(JsonObject json) { UpdateProcessInstancesSuspendStateBatchConfiguration configuration = new UpdateProcessInstancesSuspendStateBatchConfiguration(readProcessInstanceIds(json), readMappings(json), JsonUtil.getBoolean(json, SUSPENDING)); return configuration; } protected List<String> readProcessInstanceIds(JsonObject jsonObject) { return JsonUtil.asStringList(JsonUtil.getArray(jsonObject, PROCESS_INSTANCE_IDS)); } protected DeploymentMappings readMappings(JsonObject jsonObject) { return JsonUtil.asList(JsonUtil.getArray(jsonObject, PROCESS_INSTANCE_ID_MAPPINGS), DeploymentMappingJsonConverter.INSTANCE, DeploymentMappings::new); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\update\UpdateProcessInstancesSuspendStateBatchConfigurationJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public static class ScheduledQuantity { @XmlValue protected BigDecimal value; @XmlAttribute(name = "Date", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar date; /** * Gets the value of the value property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; } /** * Gets the value of the date property. *
* @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDate() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDate(XMLGregorianCalendar value) { this.date = 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\ORDERSListLineItemExtensionType.java
2
请完成以下Java代码
public static Date getLastMonthStartDay() { return DateUtil.beginOfMonth(DateUtil.lastMonth()); } /** * 获得上月最后一天 23:59:59 */ public static Date getLastMonthEndDay() { return DateUtil.endOfMonth(DateUtil.lastMonth()); } /** * 获得上周第一天 周一 00:00:00 */ public static Date getLastWeekStartDay() { return DateUtil.beginOfWeek(DateUtil.lastWeek()); } /** * 获得上周最后一天 周日 23:59:59 */ public static Date getLastWeekEndDay() { return DateUtil.endOfWeek(DateUtil.lastWeek()); } /** * 获得本周第一天 周一 00:00:00 */ public static Date getThisWeekStartDay() { Date today = new Date(); return DateUtil.beginOfWeek(today); } /** * 获得本周最后一天 周日 23:59:59 */ public static Date getThisWeekEndDay() { Date today = new Date(); return DateUtil.endOfWeek(today); } /** * 获得下周第一天 周一 00:00:00 */ public static Date getNextWeekStartDay() { return DateUtil.beginOfWeek(DateUtil.nextWeek()); } /** * 获得下周最后一天 周日 23:59:59 */ public static Date getNextWeekEndDay() { return DateUtil.endOfWeek(DateUtil.nextWeek()); } /** * 过去七天开始时间(不含今天) * * @return */ public static Date getLast7DaysStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -7); return DateUtil.beginOfDay(calendar.getTime()); } /** * 过去七天结束时间(不含今天) * * @return */ public static Date getLast7DaysEndTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getLast7DaysStartTime()); calendar.add(Calendar.DATE, 6); return DateUtil.endOfDay(calendar.getTime()); } /**
* 昨天开始时间 * * @return */ public static Date getYesterdayStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -1); return DateUtil.beginOfDay(calendar.getTime()); } /** * 昨天结束时间 * * @return */ public static Date getYesterdayEndTime() { return DateUtil.endOfDay(getYesterdayStartTime()); } /** * 明天开始时间 * * @return */ public static Date getTomorrowStartTime() { return DateUtil.beginOfDay(DateUtil.tomorrow()); } /** * 明天结束时间 * * @return */ public static Date getTomorrowEndTime() { return DateUtil.endOfDay(DateUtil.tomorrow()); } /** * 今天开始时间 * * @return */ public static Date getTodayStartTime() { return DateUtil.beginOfDay(new Date()); } /** * 今天结束时间 * * @return */ public static Date getTodayEndTime() { return DateUtil.endOfDay(new Date()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateRangeUtils.java
1
请完成以下Java代码
public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQtyProcessed_OnDate (final @Nullable BigDecimal QtyProcessed_OnDate) { set_Value (COLUMNNAME_QtyProcessed_OnDate, QtyProcessed_OnDate); } @Override public BigDecimal getQtyProcessed_OnDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed_OnDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (final int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, S_Resource_ID); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setStorageAttributesKey (final @Nullable java.lang.String StorageAttributesKey) { set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return get_ValueAsString(COLUMNNAME_StorageAttributesKey); } @Override public void setTransfertTime (final @Nullable BigDecimal TransfertTime) { set_Value (COLUMNNAME_TransfertTime, TransfertTime); } @Override public BigDecimal getTransfertTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setWorkingTime (final @Nullable BigDecimal WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public BigDecimal getWorkingTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WorkingTime); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } @Override public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID) { if (C_Manufacturing_Aggregation_ID < 1) set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null); else set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID); } @Override public int getC_Manufacturing_Aggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_Planning.java
1
请完成以下Java代码
public Date getCreateTime() { return createTime; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricDecisionInputInstanceDto fromHistoricDecisionInputInstance(HistoricDecisionInputInstance historicDecisionInputInstance) { HistoricDecisionInputInstanceDto dto = new HistoricDecisionInputInstanceDto(); dto.id = historicDecisionInputInstance.getId(); dto.decisionInstanceId = historicDecisionInputInstance.getDecisionInstanceId(); dto.clauseId = historicDecisionInputInstance.getClauseId(); dto.clauseName = historicDecisionInputInstance.getClauseName();
dto.createTime = historicDecisionInputInstance.getCreateTime(); dto.removalTime = historicDecisionInputInstance.getRemovalTime(); dto.rootProcessInstanceId = historicDecisionInputInstance.getRootProcessInstanceId(); if(historicDecisionInputInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, historicDecisionInputInstance.getTypedValue()); } else { dto.errorMessage = historicDecisionInputInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(historicDecisionInputInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionInputInstanceDto.java
1
请完成以下Java代码
public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Withholding getC_Withholding() throws RuntimeException { return (I_C_Withholding)MTable.get(getCtx(), I_C_Withholding.Table_Name) .getPO(getC_Withholding_ID(), get_TrxName()); } /** Set Withholding. @param C_Withholding_ID Withholding type defined */ public void setC_Withholding_ID (int C_Withholding_ID) { if (C_Withholding_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Withholding_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Withholding_ID, Integer.valueOf(C_Withholding_ID)); } /** Get Withholding. @return Withholding type defined */ public int getC_Withholding_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Withholding_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Exempt reason. @param ExemptReason Reason for not withholding */ public void setExemptReason (String ExemptReason) { set_Value (COLUMNNAME_ExemptReason, ExemptReason); } /** Get Exempt reason. @return Reason for not withholding */ public String getExemptReason () { return (String)get_Value(COLUMNNAME_ExemptReason); } /** Set Mandatory Withholding. @param IsMandatoryWithholding Monies must be withheld */
public void setIsMandatoryWithholding (boolean IsMandatoryWithholding) { set_Value (COLUMNNAME_IsMandatoryWithholding, Boolean.valueOf(IsMandatoryWithholding)); } /** Get Mandatory Withholding. @return Monies must be withheld */ public boolean isMandatoryWithholding () { Object oo = get_Value(COLUMNNAME_IsMandatoryWithholding); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Temporary exempt. @param IsTemporaryExempt Temporarily do not withhold taxes */ public void setIsTemporaryExempt (boolean IsTemporaryExempt) { set_Value (COLUMNNAME_IsTemporaryExempt, Boolean.valueOf(IsTemporaryExempt)); } /** Get Temporary exempt. @return Temporarily do not withhold taxes */ public boolean isTemporaryExempt () { Object oo = get_Value(COLUMNNAME_IsTemporaryExempt); 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_C_BP_Withholding.java
1
请完成以下Java代码
public void addAccessToRolesWithAutomaticMaintenance(final I_AD_Org org) { final ClientId orgClientId = ClientId.ofRepoId(org.getAD_Client_ID()); int orgAccessCreatedCounter = 0; final IUserRolePermissionsDAO permissionsDAO = Services.get(IUserRolePermissionsDAO.class); for (final Role role : Services.get(IRoleDAO.class).retrieveAllRolesWithAutoMaintenance()) { // Don't create org access for system role if (role.getId().isSystem()) { continue; } // Don't create org access for roles which are not defined on system level nor on org's AD_Client_ID level final ClientId roleClientId = role.getClientId(); if (!roleClientId.equals(orgClientId) && !roleClientId.isSystem()) {
continue; } final OrgId orgId = OrgId.ofRepoId(org.getAD_Org_ID()); permissionsDAO.createOrgAccess(role.getId(), orgId); orgAccessCreatedCounter++; } logger.info("{} - created #{} role org access entries", org, orgAccessCreatedCounter); // Reset role permissions, just to make sure we are on the safe side // NOTE: not needed shall be triggered automatically // if (orgAccessCreatedCounter > 0) // { // Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit(); // } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Org.java
1
请完成以下Java代码
public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setLevel (final java.lang.String Level) { set_ValueNoCheck (COLUMNNAME_Level, Level); } @Override public java.lang.String getLevel() { return get_ValueAsString(COLUMNNAME_Level); } @Override public void setModule (final @Nullable java.lang.String Module) { set_Value (COLUMNNAME_Module, Module); } @Override public java.lang.String getModule() { return get_ValueAsString(COLUMNNAME_Module); } @Override public void setMsgText (final @Nullable java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setSource_Record_ID (final int Source_Record_ID) { if (Source_Record_ID < 1) set_Value (COLUMNNAME_Source_Record_ID, null); else set_Value (COLUMNNAME_Source_Record_ID, Source_Record_ID); } @Override
public int getSource_Record_ID() { return get_ValueAsInt(COLUMNNAME_Source_Record_ID); } @Override public void setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_Value (COLUMNNAME_Source_Table_ID, null); else set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID); } @Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setTarget_Record_ID (final int Target_Record_ID) { if (Target_Record_ID < 1) set_Value (COLUMNNAME_Target_Record_ID, null); else set_Value (COLUMNNAME_Target_Record_ID, Target_Record_ID); } @Override public int getTarget_Record_ID() { return get_ValueAsInt(COLUMNNAME_Target_Record_ID); } @Override public void setTarget_Table_ID (final int Target_Table_ID) { if (Target_Table_ID < 1) set_Value (COLUMNNAME_Target_Table_ID, null); else set_Value (COLUMNNAME_Target_Table_ID, Target_Table_ID); } @Override public int getTarget_Table_ID() { return get_ValueAsInt(COLUMNNAME_Target_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Log.java
1
请完成以下Java代码
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public IdentityLinkQueryObject getInvolvedUserIdentityLink() { return involvedUserIdentityLink; } public IdentityLinkQueryObject getInvolvedGroupIdentityLink() { return involvedGroupIdentityLink; } public boolean isWithJobException() { return withJobException; } public String getLocale() { return locale; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(HistoricProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); }
public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ResourceRole.class, BPMN_ELEMENT_RESOURCE_ROLE) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<ResourceRole>() { public ResourceRole newInstance(ModelTypeInstanceContext instanceContext) { return new ResourceRoleImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); resourceRefChild = sequenceBuilder.element(ResourceRef.class) .qNameElementReference(Resource.class) .build(); resourceParameterBindingCollection = sequenceBuilder.elementCollection(ResourceParameterBinding.class) .build(); resourceAssignmentExpressionChild = sequenceBuilder.element(ResourceAssignmentExpression.class) .build(); typeBuilder.build(); } public ResourceRoleImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext);
} public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Resource getResource() { return resourceRefChild.getReferenceTargetElement(this); } public void setResource(Resource resource) { resourceRefChild.setReferenceTargetElement(this, resource); } public Collection<ResourceParameterBinding> getResourceParameterBinding() { return resourceParameterBindingCollection.get(this); } public ResourceAssignmentExpression getResourceAssignmentExpression() { return resourceAssignmentExpressionChild.getChild(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceRoleImpl.java
1
请完成以下Java代码
public void setFaxNb(String value) { this.faxNb = value; } /** * Gets the value of the emailAdr property. * * @return * possible object is * {@link String } * */ public String getEmailAdr() { return emailAdr; } /** * Sets the value of the emailAdr property. * * @param value * allowed object is * {@link String } * */ public void setEmailAdr(String value) { this.emailAdr = value; } /** * Gets the value of the othr property. * * @return * possible object is
* {@link String } * */ public String getOthr() { return othr; } /** * Sets the value of the othr property. * * @param value * allowed object is * {@link String } * */ public void setOthr(String value) { this.othr = 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\ContactDetails2.java
1
请完成以下Java代码
public class OperationMethod { private static final ParameterNameDiscoverer DEFAULT_PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer(); private final Method method; private final OperationType operationType; private final OperationParameters operationParameters; /** * Create a new {@link OperationMethod} instance. * @param method the source method * @param operationType the operation type */ public OperationMethod(Method method, OperationType operationType) { Assert.notNull(method, "'method' must not be null"); Assert.notNull(operationType, "'operationType' must not be null"); this.method = method; this.operationType = operationType; this.operationParameters = new OperationMethodParameters(method, DEFAULT_PARAMETER_NAME_DISCOVERER); } /** * Return the source Java method. * @return the method */ public Method getMethod() { return this.method; }
/** * Return the operation type. * @return the operation type */ public OperationType getOperationType() { return this.operationType; } /** * Return the operation parameters. * @return the operation parameters */ public OperationParameters getParameters() { return this.operationParameters; } @Override public String toString() { return "Operation " + this.operationType.name().toLowerCase(Locale.ENGLISH) + " method " + this.method; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\reflect\OperationMethod.java
1
请在Spring Boot框架中完成以下Java代码
public ProfileVO getProfile(User me, String targetUsername) { return this.getProfile(me, findUserByUsername(targetUsername)); } @Transactional(readOnly = true) public ProfileVO getProfile(User me, User target) { return new ProfileVO(me, target); } @Transactional public ProfileVO follow(User me, String targetUsername) { return this.follow(me, findUserByUsername(targetUsername)); } @Transactional public ProfileVO follow(User me, User target) { return me.follow(target); }
@Transactional public ProfileVO unfollow(User me, String targetUsername) { return this.unfollow(me, findUserByUsername(targetUsername)); } @Transactional public ProfileVO unfollow(User me, User target) { return me.unfollow(target); } private User findUserByUsername(String username) { String message = "User(`%s`) not found".formatted(username); return userRepository.findByUsername(username).orElseThrow(() -> new NoSuchElementException(message)); } }
repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\user\service\ProfileService.java
2
请完成以下Java代码
public StopCommand getCommand() { return this.command; } public void setCommand(StopCommand command) { this.command = command; } public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; } public List<String> getArguments() { return this.arguments; } } /** * Profiles properties. */ public static class Profiles { /** * Docker compose profiles that should be active. */ private Set<String> active = new LinkedHashSet<>(); public Set<String> getActive() { return this.active; } public void setActive(Set<String> active) { this.active = active; } } /** * Skip options. */ public static class Skip { /** * Whether to skip in tests. */ private boolean inTests = true; public boolean isInTests() { return this.inTests; } public void setInTests(boolean inTests) { this.inTests = inTests; } } /** * Readiness properties. */ public static class Readiness { /** * Wait strategy to use. */ private Wait wait = Wait.ALWAYS; /** * Timeout of the readiness checks. */ private Duration timeout = Duration.ofMinutes(2); /** * TCP properties. */ private final Tcp tcp = new Tcp(); public Wait getWait() { return this.wait; } public void setWait(Wait wait) { this.wait = wait; } public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; }
public Tcp getTcp() { return this.tcp; } /** * Readiness wait strategies. */ public enum Wait { /** * Always perform readiness checks. */ ALWAYS, /** * Never perform readiness checks. */ NEVER, /** * Only perform readiness checks if docker was started with lifecycle * management. */ ONLY_IF_STARTED } /** * TCP properties. */ public static class Tcp { /** * Timeout for connections. */ private Duration connectTimeout = Duration.ofMillis(200); /** * Timeout for reads. */ private Duration readTimeout = Duration.ofMillis(200); public Duration getConnectTimeout() { return this.connectTimeout; } public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } public Duration getReadTimeout() { return this.readTimeout; } public void setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; } } } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeProperties.java
1
请完成以下Java代码
public String getCompletionCondition() { return completionCondition; } public void setCompletionCondition(String completionCondition) { this.completionCondition = completionCondition; } public String getElementVariable() { return elementVariable; } public void setElementVariable(String elementVariable) { this.elementVariable = elementVariable; } public String getElementIndexVariable() { return elementIndexVariable; } public void setElementIndexVariable(String elementIndexVariable) { this.elementIndexVariable = elementIndexVariable; } public boolean isSequential() { return sequential; } public void setSequential(boolean sequential) { this.sequential = sequential; } public String getLoopDataOutputRef() { return loopDataOutputRef; } public void setLoopDataOutputRef(String loopDataOutputRef) { this.loopDataOutputRef = loopDataOutputRef; } public String getOutputDataItem() {
return outputDataItem; } public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; } public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; } public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setLoopDataOutputRef(otherLoopCharacteristics.getLoopDataOutputRef()); setOutputDataItem(otherLoopCharacteristics.getOutputDataItem()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请在Spring Boot框架中完成以下Java代码
public String getAMOUNTQUAL() { return amountqual; } /** * Sets the value of the amountqual property. * * @param value * allowed object is * {@link String } * */ public void setAMOUNTQUAL(String value) { this.amountqual = value; } /** * Gets the value of the amount property. * * @return * possible object is * {@link String } * */ public String getAMOUNT() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link String } *
*/ public void setAMOUNT(String value) { this.amount = value; } /** * Gets the value of the currency property. * * @return * possible object is * {@link String } * */ public String getCURRENCY() { return currency; } /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCURRENCY(String value) { this.currency = 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\DAMOU1.java
2
请完成以下Java代码
public LocatorScannedCodeResolverResult resolve(@NonNull final ScannedCode scannedCode) { return resolve(LocatorScannedCodeResolverRequest.ofScannedCode(scannedCode)); } public LocatorScannedCodeResolverResult resolve(@NonNull LocatorScannedCodeResolverRequest request) { final ScannedCode scannedCode = request.getScannedCode(); final LocatorScannedCodeResolveContext context = request.getContext(); final ArrayList<LocatorNotResolvedReason> notFoundReasons = new ArrayList<>(); final GlobalQRCode globalQRCode = scannedCode.toGlobalQRCodeIfMatching().orNullIfError(); if (globalQRCode != null) { for (LocatorGlobalQRCodeResolver globalQRCodeResolver : globalQRCodeResolvers) { final LocatorScannedCodeResolverResult result = globalQRCodeResolver.resolve(globalQRCode, context); if (result.isFound()) { return result; } else { notFoundReasons.addAll(result.getNotResolvedReasons()); } } } // // Try searching by locator value { final LocatorScannedCodeResolverResult result = resolveByLocatorValue(scannedCode, context); if (result.isFound()) { return result; } else { notFoundReasons.addAll(result.getNotResolvedReasons()); } } return LocatorScannedCodeResolverResult.notFound(notFoundReasons); } private LocatorScannedCodeResolverResult resolveByLocatorValue(final @NotNull ScannedCode scannedCode, final @NotNull LocatorScannedCodeResolveContext context)
{ final ImmutableList<LocatorQRCode> locatorQRCodes = warehouseBL.getActiveLocatorsByValue(scannedCode.getAsString()) .stream() .map(LocatorQRCode::ofLocator) .filter(context::isMatching) .distinct() .collect(ImmutableList.toImmutableList()); if (locatorQRCodes.isEmpty()) { return LocatorScannedCodeResolverResult.notFound(RESOLVER_KEY_resolveByLocatorValue, "No locator found for " + scannedCode.getAsString()); } else if (locatorQRCodes.size() > 1) { return LocatorScannedCodeResolverResult.notFound(RESOLVER_KEY_resolveByLocatorValue, "Multiple locatorQRCodes found for " + scannedCode.getAsString()); } else { return LocatorScannedCodeResolverResult.found(locatorQRCodes.get(0)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\resolver\LocatorScannedCodeResolverService.java
1
请完成以下Java代码
final class AllergenMap { private final ImmutableMap<AllergenId, Allergen> byId; public AllergenMap(@NonNull final List<Allergen> list) { byId = Maps.uniqueIndex(list, Allergen::getId); } public ImmutableList<Allergen> getByIds(@NonNull final Collection<AllergenId> ids) { if (ids.isEmpty()) { return ImmutableList.of(); }
return ids.stream() .map(this::getById) .collect(ImmutableList.toImmutableList()); } public Allergen getById(@NonNull final AllergenId id) { final Allergen Allergen = byId.get(id); if (Allergen == null) { throw new AdempiereException("No Hazard Symbol found for " + id); } return Allergen; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\allergen\AllergenMap.java
1
请完成以下Java代码
public void setUsernameBasedPrimaryKey(boolean usernameBasedPrimaryKey) { this.usernameBasedPrimaryKey = usernameBasedPrimaryKey; } protected boolean isUsernameBasedPrimaryKey() { return this.usernameBasedPrimaryKey; } /** * Allows the default query string used to retrieve users based on username to be * overridden, if default table or column names need to be changed. The default query * is {@link #DEF_USERS_BY_USERNAME_QUERY}; when modifying this query, ensure that all * returned columns are mapped back to the same column positions as in the default * query. If the 'enabled' column does not exist in the source database, a permanent * true value for this column may be returned by using a query similar to * * <pre> * &quot;select username,password,'true' as enabled from users where username = ?&quot; * </pre> * @param usersByUsernameQueryString The query string to set */ public void setUsersByUsernameQuery(String usersByUsernameQueryString) { this.usersByUsernameQuery = usersByUsernameQueryString; } protected boolean getEnableAuthorities() { return this.enableAuthorities; } /** * Enables loading of authorities (roles) from the authorities table. Defaults to true */ public void setEnableAuthorities(boolean enableAuthorities) { this.enableAuthorities = enableAuthorities; } protected boolean getEnableGroups() { return this.enableGroups; }
/** * Enables support for group authorities. Defaults to false * @param enableGroups */ public void setEnableGroups(boolean enableGroups) { this.enableGroups = enableGroups; } @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } private JdbcTemplate getJdbc() { JdbcTemplate template = getJdbcTemplate(); Assert.notNull(template, "JdbcTemplate cannot be null"); return template; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\jdbc\JdbcDaoImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getTopCateEntityID() { return topCateEntityID; } public void setTopCateEntityID(String topCateEntityID) { this.topCateEntityID = topCateEntityID; } public String getSubCategEntityID() { return subCategEntityID; } public void setSubCategEntityID(String subCategEntityID) { this.subCategEntityID = subCategEntityID; } public String getBrandEntityID() { return brandEntityID; } public void setBrandEntityID(String brandEntityID) { this.brandEntityID = brandEntityID; } public Integer getProdState() { return prodState; } public void setProdState(Integer prodState) { this.prodState = prodState; } public String getContent() { return content; } public void setContent(String content) { this.content = content;
} public String getCompanyEntityID() { return companyEntityID; } public void setCompanyEntityID(String companyEntityID) { this.companyEntityID = companyEntityID; } @Override public String toString() { return "ProdInsertReq{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntityID='" + topCateEntityID + '\'' + ", subCategEntityID='" + subCategEntityID + '\'' + ", brandEntityID='" + brandEntityID + '\'' + ", prodState=" + prodState + ", content='" + content + '\'' + ", companyEntityID='" + companyEntityID + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdInsertReq.java
2
请完成以下Java代码
public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } /** * Version AD_Reference_ID=540904 * Reference name: MSV3_Version */ public static final int VERSION_AD_Reference_ID=540904; /** 1 = 1 */ public static final String VERSION_1 = "1"; /** 2 = 2 */ public static final String VERSION_2 = "2"; /** Set Version. @param Version Version of the table definition */
@Override public void setVersion (java.lang.String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Vendor_Config.java
1
请完成以下Java代码
public Optional<ProductId> getProductIdByEAN13(@NonNull final EAN13 ean13) {return getProductIdByEAN13(ean13, null, ClientId.METASFRESH);} @Override public Optional<ProductId> getProductIdByEAN13(@NonNull final EAN13 ean13, @Nullable final BPartnerId bpartnerId, @NonNull final ClientId clientId) { return getProductIdByGTIN(ean13.toGTIN(), bpartnerId, clientId); } private Optional<ProductId> getProductIdByEAN13ProductCode( @NonNull final EAN13ProductCode ean13ProductCode, @Nullable final BPartnerId bpartnerId, @NonNull final ClientId clientId) { if (bpartnerId != null) { final ImmutableSet<ProductId> productIds = partnerProductDAO.retrieveByEAN13ProductCode(ean13ProductCode, bpartnerId) .stream() .map(partnerProduct -> ProductId.ofRepoId(partnerProduct.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); if (productIds.size() == 1) { return Optional.of(productIds.iterator().next()); } } return productsRepo.getProductIdByEAN13ProductCode(ean13ProductCode, clientId); } @Override public boolean isValidEAN13Product(@NonNull final EAN13 ean13, @NonNull final ProductId expectedProductId) { return getGS1ProductCodesCollection(expectedProductId).isValidProductNo(ean13, null); } @Override public boolean isValidEAN13Product(@NonNull final EAN13 ean13, @NonNull final ProductId expectedProductId, @Nullable final BPartnerId bpartnerId) { return getGS1ProductCodesCollection(expectedProductId).isValidProductNo(ean13, bpartnerId); } @Override public Set<ProductId> getProductIdsMatchingQueryString( @NonNull final String queryString, @NonNull final ClientId clientId, @NonNull final QueryLimit limit) { return productsRepo.getProductIdsMatchingQueryString(queryString, clientId, limit); } @Override @NonNull public List<I_M_Product> getByIds(@NonNull final Set<ProductId> productIds) { return productsRepo.getByIds(productIds);
} @Override public boolean isExistingValue(@NonNull final String value, @NonNull final ClientId clientId) { return productsRepo.isExistingValue(value, clientId); } @Override public void setProductCodeFieldsFromGTIN(@NonNull final I_M_Product record, @Nullable final GTIN gtin) { record.setGTIN(gtin != null ? gtin.getAsString() : null); record.setUPC(gtin != null ? gtin.getAsString() : null); if (gtin != null) { record.setEAN13_ProductCode(null); } } @Override public void setProductCodeFieldsFromEAN13ProductCode(@NonNull final I_M_Product record, @Nullable final EAN13ProductCode ean13ProductCode) { record.setEAN13_ProductCode(ean13ProductCode != null ? ean13ProductCode.getAsString() : null); if (ean13ProductCode != null) { record.setGTIN(null); record.setUPC(null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductBL.java
1
请完成以下Java代码
public void receiveConfigInfo(String configInfo) { log.info("进行网关更新:\n\r{}", configInfo); List<MyRouteDefinition> definitionList = JSON.parseArray(configInfo, MyRouteDefinition.class); for (MyRouteDefinition definition : definitionList) { log.info("update route : {}", definition.toString()); dynamicRouteService.update(definition); } } @Override public Executor getExecutor() { log.info("getExecutor\n\r"); return null; } }); } catch (Exception e) { log.error("从nacos接收动态路由配置出错!!!", e); } } /** * 创建ConfigService * * @return */ private ConfigService createConfigService() { try {
Properties properties = new Properties(); properties.setProperty("serverAddr", gatewayRoutersConfig.getServerAddr()); if(StringUtils.isNotBlank(gatewayRoutersConfig.getNamespace())){ properties.setProperty("namespace", gatewayRoutersConfig.getNamespace()); } if(StringUtils.isNotBlank( gatewayRoutersConfig.getUsername())){ properties.setProperty("username", gatewayRoutersConfig.getUsername()); } if(StringUtils.isNotBlank(gatewayRoutersConfig.getPassword())){ properties.setProperty("password", gatewayRoutersConfig.getPassword()); } return configService = NacosFactory.createConfigService(properties); } catch (Exception e) { log.error("创建ConfigService异常", e); return null; } } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\DynamicRouteLoader.java
1
请完成以下Java代码
public Flux<?> receiveMessagesFromTopic(@PathVariable String name) { DestinationsConfig.DestinationInfo d = destinationsConfig.getTopics() .get(name); if (d == null) { return Flux.just(ResponseEntity.notFound() .build()); } Queue topicQueue = createTopicQueue(d); String qname = topicQueue.getName(); MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(qname); Flux<String> f = Flux.create(emitter -> { log.info("[I168] Adding listener, queue={}", qname); mlc.setupMessageListener(m -> { log.info("[I137] Message received, queue={}", qname); if (emitter.isCancelled()) { log.info("[I166] cancelled, queue={}", qname); mlc.stop(); return; } String payload = new String(m.getBody()); emitter.next(payload); log.info("[I176] Message sent to client, queue={}", qname); }); emitter.onRequest(v -> { log.info("[I171] Starting container, queue={}", qname); mlc.start(); }); emitter.onDispose(() -> { log.info("[I176] onDispose: queue={}", qname);
amqpAdmin.deleteQueue(qname); mlc.stop(); }); log.info("[I171] Container started, queue={}", qname); }); return Flux.interval(Duration.ofSeconds(5)) .map(v -> { log.info("[I209] sending keepalive message..."); return "No news is good news"; }) .mergeWith(f); } private Queue createTopicQueue(DestinationsConfig.DestinationInfo destination) { Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) .durable(true) .build(); amqpAdmin.declareExchange(ex); Queue q = QueueBuilder.nonDurable() .build(); amqpAdmin.declareQueue(q); Binding b = BindingBuilder.bind(q) .to(ex) .with(destination.getRoutingKey()) .noargs(); amqpAdmin.declareBinding(b); return q; } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-amqp\src\main\java\com\baeldung\spring\amqp\AmqpReactiveController.java
1
请完成以下Java代码
private boolean shouldTriggerRefresh(ApplicationEvent event) { String className = event.getClass().getName(); if (!eventTriggersCache.containsKey(className)) { eventTriggersCache.put(className, eventClasses.stream().anyMatch(clazz -> this.isAssignable(clazz, event))); } return eventTriggersCache.get(className); } private void decorateNewSources() { MutablePropertySources propSources = environment.getPropertySources(); converter.convertPropertySources(propSources); } boolean isAssignable(Class<?> clazz, Object value) { return ClassUtils.isAssignableValue(clazz, value); } private void refreshCachedProperties() { PropertySources propertySources = environment.getPropertySources(); propertySources.forEach(this::refreshPropertySource); } @SuppressWarnings("rawtypes") private void refreshPropertySource(PropertySource<?> propertySource) { if (propertySource instanceof CompositePropertySource) { CompositePropertySource cps = (CompositePropertySource) propertySource; cps.getPropertySources().forEach(this::refreshPropertySource);
} else if (propertySource instanceof EncryptablePropertySource) { EncryptablePropertySource eps = (EncryptablePropertySource) propertySource; eps.refresh(); } } private Class<?> getClassSafe(String className) { try { return ClassUtils.forName(className, null); } catch (ClassNotFoundException e) { return null; } } /** {@inheritDoc} */ @Override public void afterPropertiesSet() throws Exception { Stream .concat(EVENT_CLASS_NAMES.stream(), this.config.getRefreshedEventClasses().stream()) .map(this::getClassSafe).filter(Objects::nonNull) .collect(Collectors.toCollection(() -> this.eventClasses)); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\RefreshScopeRefreshedEventListener.java
1
请完成以下Java代码
public void stop() { this.state = "stop"; } public void fuel() { Assert.state(this.state.equals("stop"), "car must be stopped"); // ... } public void fuelwithSupplier() { Assert.state(this.state.equals("stop"), () -> "car must be stopped"); // ... } public void сhangeOil(String oil) { Assert.notNull(oil, "oil mustn't be null"); // ... } public void replaceBattery(CarBattery carBattery) { Assert.isNull(carBattery.getCharge(), "to replace battery the charge must be null"); // ... } public void сhangeEngine(Engine engine) { Assert.isInstanceOf(ToyotaEngine.class, engine); // ... } public void repairEngine(Engine engine) { Assert.isAssignable(Engine.class, ToyotaEngine.class); // ... } public void startWithHasLength(String key) { Assert.hasLength(key, "key must not be null and must not the empty"); // ... } public void startWithHasText(String key) { Assert.hasText(key, "key must not be null and must contain at least one non-whitespace character"); // ... } public void startWithNotContain(String key) { Assert.doesNotContain(key, "123", "key must not contain 123"); // ... } public void repair(Collection<String> repairParts) { Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty"); // ... } public void repair(Map<String, String> repairParts) { Assert.notEmpty(repairParts, "map of repairParts mustn't be empty"); // ... } public void repair(String[] repairParts) { Assert.notEmpty(repairParts, "array of repairParts must not be empty"); // ... } public void repairWithNoNull(String[] repairParts) { Assert.noNullElements(repairParts, "array of repairParts must not contain null elements"); // ...
} public static void main(String[] args) { Car car = new Car(); car.drive(50); car.stop(); car.fuel(); car.сhangeOil("oil"); CarBattery carBattery = new CarBattery(); car.replaceBattery(carBattery); car.сhangeEngine(new ToyotaEngine()); car.startWithHasLength(" "); car.startWithHasText("t"); car.startWithNotContain("132"); List<String> repairPartsCollection = new ArrayList<>(); repairPartsCollection.add("part"); car.repair(repairPartsCollection); Map<String, String> repairPartsMap = new HashMap<>(); repairPartsMap.put("1", "part"); car.repair(repairPartsMap); String[] repairPartsArray = { "part" }; car.repair(repairPartsArray); } }
repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java
1
请完成以下Java代码
public OrderFactory dateOrdered(final LocalDate dateOrdered) { assertNotBuilt(); order.setDateOrdered(TimeUtil.asTimestamp(dateOrdered)); return this; } public OrderFactory datePromised(final ZonedDateTime datePromised) { assertNotBuilt(); order.setDatePromised(TimeUtil.asTimestamp(datePromised)); return this; } public ZonedDateTime getDatePromised() { final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())); return TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone); } public OrderFactory shipBPartner( @NonNull final BPartnerId bpartnerId, @Nullable final BPartnerLocationId bpartnerLocationId, @Nullable final BPartnerContactId contactId) { assertNotBuilt(); OrderDocumentLocationAdapterFactory .locationAdapter(order) .setFrom(DocumentLocation.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(bpartnerLocationId) .contactId(contactId) .build()); return this; } public OrderFactory shipBPartner(final BPartnerId bpartnerId) { shipBPartner(bpartnerId, null, null); return this; } public BPartnerId getShipBPartnerId() { return BPartnerId.ofRepoId(order.getC_BPartner_ID());
} public OrderFactory pricingSystemId(@NonNull final PricingSystemId pricingSystemId) { assertNotBuilt(); order.setM_PricingSystem_ID(pricingSystemId.getRepoId()); return this; } public OrderFactory poReference(@Nullable final String poReference) { assertNotBuilt(); order.setPOReference(poReference); return this; } public OrderFactory salesRepId(@Nullable final UserId salesRepId) { assertNotBuilt(); order.setSalesRep_ID(UserId.toRepoId(salesRepId)); return this; } public OrderFactory projectId(@Nullable final ProjectId projectId) { assertNotBuilt(); order.setC_Project_ID(ProjectId.toRepoId(projectId)); return this; } public OrderFactory campaignId(final int campaignId) { assertNotBuilt(); order.setC_Campaign_ID(campaignId); return this; } public DocTypeId getDocTypeTargetId() { return docTypeTargetId; } public void setDocTypeTargetId(final DocTypeId docTypeTargetId) { this.docTypeTargetId = docTypeTargetId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderFactory.java
1
请完成以下Java代码
public void setPP_Plant_From_ID(final I_DD_OrderLine ddOrderLine) { ResourceId plantFromId = ddOrderLowLevelService.findPlantFromOrNull(ddOrderLine); // // If no plant was found for "Warehouse From" we shall use the Destination Plant. // // Example when applies: MRP generated a DD order to move materials from a Raw materials warehouse to Plant warehouse. // The raw materials warehouse is not assigned to a Plant so no further planning will be calculated. // I see it as perfectly normal to use the Destination Plant in this case. if (plantFromId == null) { final ResourceId plantToId = ResourceId.ofRepoIdOrNull(ddOrderLine.getDD_Order().getPP_Plant_ID()); plantFromId = plantToId; } if (plantFromId == null) { final LiberoException ex = new LiberoException("@NotFound@ @PP_Plant_ID@" + "\n @M_Locator_ID@: " + ddOrderLine.getM_Locator_ID() + "\n @M_Product_ID@: " + ddOrderLine.getM_Product_ID() + "\n @DD_OrderLine_ID@: " + ddOrderLine ); logger.warn(ex.getLocalizedMessage(), ex); } else { ddOrderLine.setPP_Plant_From_ID(plantFromId.getRepoId()); } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteDDOrderLineAlternatives(final I_DD_OrderLine ddOrderLine) { final List<I_DD_OrderLine_Alternative> ddOrderLineAlternatives = ddOrderLowLevelService.retrieveAllAlternatives(ddOrderLine); for (final I_DD_OrderLine_Alternative ddOrderLineAlt : ddOrderLineAlternatives) { InterfaceWrapperHelper.delete(ddOrderLineAlt); } }
/** * @implSpec task http://dewiki908/mediawiki/index.php/08583_Erfassung_Packvorschrift_in_DD_Order_ist_crap_%28108882381939%29 * ("UOM In manual DD_OrderLine shall always be the uom of the product ( as talked with Mark) ") */ @ModelChange( timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_DD_OrderLine.COLUMNNAME_M_Product_ID }) public void setUOMInDDOrderLine(final I_DD_OrderLine ddOrderLine) { ddOrderLowLevelService.updateUomFromProduct(ddOrderLine); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_DD_OrderLine record) { ddOrderCandidateAllocRepository.deleteByQuery(DeleteDDOrderCandidateAllocQuery.builder() .ddOrderLineId(DDOrderLineId.ofRepoId(record.getDD_OrderLine_ID())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\interceptor\DD_OrderLine.java
1
请完成以下Java代码
public int getAD_User_SortPref_Line_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Line_Product_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt.
@return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line_Product.java
1
请完成以下Java代码
public void setFunctionSuffix (String FunctionSuffix) { set_Value (COLUMNNAME_FunctionSuffix, FunctionSuffix); } /** Get Function Suffix. @return Data sent after the function */ public String getFunctionSuffix () { return (String)get_Value(COLUMNNAME_FunctionSuffix); } /** Set XY Position. @param IsXYPosition The Function is XY position */ public void setIsXYPosition (boolean IsXYPosition) { set_Value (COLUMNNAME_IsXYPosition, Boolean.valueOf(IsXYPosition)); } /** Get XY Position. @return The Function is XY position */ public boolean isXYPosition () { Object oo = get_Value(COLUMNNAME_IsXYPosition); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); }
/** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set XY Separator. @param XYSeparator The separator between the X and Y function. */ public void setXYSeparator (String XYSeparator) { set_Value (COLUMNNAME_XYSeparator, XYSeparator); } /** Get XY Separator. @return The separator between the X and Y function. */ public String getXYSeparator () { return (String)get_Value(COLUMNNAME_XYSeparator); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java
1
请在Spring Boot框架中完成以下Java代码
protected void validateMaxSumDataSizePerTenant(TenantId tenantId, TenantEntityWithDataDao dataDao, long maxSumDataSize, long currentDataSize, EntityType entityType) { if (maxSumDataSize > 0) { if (dataDao.sumDataSizeByTenantId(tenantId) + currentDataSize > maxSumDataSize) { throw new DataValidationException(String.format("%ss total size exceeds the maximum of " + FileUtils.byteCountToDisplaySize(maxSumDataSize), entityType.getNormalName())); } } } protected static void validateJsonStructure(JsonNode expectedNode, JsonNode actualNode) { Set<String> expectedFields = new HashSet<>(); Iterator<String> fieldsIterator = expectedNode.fieldNames(); while (fieldsIterator.hasNext()) { expectedFields.add(fieldsIterator.next()); } Set<String> actualFields = new HashSet<>(); fieldsIterator = actualNode.fieldNames(); while (fieldsIterator.hasNext()) { actualFields.add(fieldsIterator.next()); } if (!expectedFields.containsAll(actualFields) || !actualFields.containsAll(expectedFields)) { throw new DataValidationException("Provided json structure is different from stored one '" + actualNode + "'!"); } } protected static void validateQueueName(String name) { validateQueueNameOrTopic(name, NAME); if (DataConstants.CF_QUEUE_NAME.equals(name) || DataConstants.CF_STATES_QUEUE_NAME.equals(name)) { throw new DataValidationException(String.format("The queue name '%s' is not allowed. This name is reserved for internal use. Please choose a different name.", name));
} } protected static void validateQueueTopic(String topic) { validateQueueNameOrTopic(topic, TOPIC); } static void validateQueueNameOrTopic(String value, String fieldName) { if (StringUtils.isEmpty(value) || value.trim().length() == 0) { throw new DataValidationException(String.format("Queue %s should be specified!", fieldName)); } if (!QUEUE_PATTERN.matcher(value).matches()) { throw new DataValidationException( String.format("Queue %s contains a character other than ASCII alphanumerics, '.', '_' and '-'!", fieldName)); } } public static boolean isValidDomain(String domainName) { if (domainName == null) { return false; } if (LOCALHOST_PATTERN.matcher(domainName).matches()) { return true; } return DOMAIN_PATTERN.matcher(domainName).matches(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\DataValidator.java
2
请完成以下Java代码
public class X_MD_Available_For_Sales extends org.compiere.model.PO implements I_MD_Available_For_Sales, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1044122981L; /** Standard Constructor */ public X_MD_Available_For_Sales (final Properties ctx, final int MD_Available_For_Sales_ID, @Nullable final String trxName) { super (ctx, MD_Available_For_Sales_ID, trxName); } /** Load Constructor */ public X_MD_Available_For_Sales (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_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 setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setMD_Available_For_Sales_ID (final int MD_Available_For_Sales_ID) { if (MD_Available_For_Sales_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, MD_Available_For_Sales_ID); } @Override public int getMD_Available_For_Sales_ID() { return get_ValueAsInt(COLUMNNAME_MD_Available_For_Sales_ID); } @Override public void setQtyOnHandStock (final @Nullable BigDecimal QtyOnHandStock)
{ set_Value (COLUMNNAME_QtyOnHandStock, QtyOnHandStock); } @Override public BigDecimal getQtyOnHandStock() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandStock); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped) { set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped); } @Override public BigDecimal getQtyToBeShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setStorageAttributesKey (final java.lang.String StorageAttributesKey) { set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return get_ValueAsString(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MD_Available_For_Sales.java
1
请完成以下Java代码
public BigDecimal getMinAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set 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; } /** Set Threshold max. @param ThresholdMax Maximum gross amount for withholding calculation (0=no limit) */ public void setThresholdMax (BigDecimal ThresholdMax) { set_Value (COLUMNNAME_ThresholdMax, ThresholdMax); } /** Get Threshold max. @return Maximum gross amount for withholding calculation (0=no limit) */ public BigDecimal getThresholdMax () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ThresholdMax); if (bd == null) return Env.ZERO; return bd; } /** Set Threshold min. @param Thresholdmin Minimum gross amount for withholding calculation */ public void setThresholdmin (BigDecimal Thresholdmin) { set_Value (COLUMNNAME_Thresholdmin, Thresholdmin); } /** Get Threshold min. @return Minimum gross amount for withholding calculation */ public BigDecimal getThresholdmin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Thresholdmin); 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_C_Withholding.java
1
请完成以下Java代码
private IMaterialTrackingQuery asMaterialTrackingQuery(@NonNull final ProductAndBPartner productAndBPartner) { return materialTrackingDAO.createMaterialTrackingQuery() .setProcessed(false) // only show "open" trackings .setReturnReadOnlyRecords(true) // we are not going to alter our cached records .setM_Product_ID(productAndBPartner.getProductId().getRepoId()) .setC_BPartner_ID(productAndBPartner.getBpartnerId().getRepoId()); } private KeyNamePair createNamePair(@NonNull final I_M_Material_Tracking materialTrackingRecord) { return KeyNamePair.of( materialTrackingRecord.getM_Material_Tracking_ID(), materialTrackingRecord.getLot()); } @Nullable private static MaterialTrackingId normalizeValueKey(@Nullable final Object valueKey) { if (valueKey == null) { return null; } else if (valueKey instanceof Number) { final int valueKeyAsInt = ((Number)valueKey).intValue(); return MaterialTrackingId.ofRepoIdOrNull(valueKeyAsInt); } else { final int valueKeyAsInt = NumberUtils.asInt(valueKey.toString(), -1); return MaterialTrackingId.ofRepoIdOrNull(valueKeyAsInt); }
} @Override public AttributeValueId getAttributeValueIdOrNull(final Object valueKey) { return null; } /** * @return {@code null}. */ @Override public NamePair getNullValue() {return null;} @Override public boolean isHighVolume() {return isHighVolume;} @Override public String getCachePrefix() { return CACHE_MAIN_TABLE_NAME; } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(materialTrackingId2KeyNamePair.stats()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\attribute\MaterialTrackingAttributeValuesProvider.java
1
请完成以下Java代码
public class DeleteHistoricDecisionInstancesBatchCmd implements Command<Batch> { protected List<String> historicDecisionInstanceIds; protected HistoricDecisionInstanceQuery historicDecisionInstanceQuery; protected String deleteReason; public DeleteHistoricDecisionInstancesBatchCmd(List<String> ids, HistoricDecisionInstanceQuery query, String deleteReason) { this.historicDecisionInstanceIds = ids; this.historicDecisionInstanceQuery = query; this.deleteReason = deleteReason; } @Override public Batch execute(CommandContext commandContext) { BatchElementConfiguration elementConfiguration = collectHistoricDecisionInstanceIds(commandContext); ensureNotEmpty(BadUserRequestException.class, "historicDecisionInstanceIds", elementConfiguration.getIds()); return new BatchBuilder(commandContext) .type(Batch.TYPE_HISTORIC_DECISION_INSTANCE_DELETION) .config(getConfiguration(elementConfiguration)) .permission(BatchPermissions.CREATE_BATCH_DELETE_DECISION_INSTANCES) .operationLogHandler(this::writeUserOperationLog) .build(); } protected BatchElementConfiguration collectHistoricDecisionInstanceIds(CommandContext commandContext) { BatchElementConfiguration elementConfiguration = new BatchElementConfiguration(); if (!CollectionUtil.isEmpty(historicDecisionInstanceIds)) {
HistoricDecisionInstanceQueryImpl query = new HistoricDecisionInstanceQueryImpl(); query.decisionInstanceIdIn(historicDecisionInstanceIds.toArray(new String[0])); elementConfiguration.addDeploymentMappings( commandContext.runWithoutAuthorization(query::listDeploymentIdMappings), historicDecisionInstanceIds); } final HistoricDecisionInstanceQueryImpl decisionInstanceQuery = (HistoricDecisionInstanceQueryImpl) historicDecisionInstanceQuery; if (decisionInstanceQuery != null) { elementConfiguration.addDeploymentMappings(decisionInstanceQuery.listDeploymentIdMappings()); } return elementConfiguration; } protected void writeUserOperationLog(CommandContext commandContext, int numInstances) { List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances)); propertyChanges.add(new PropertyChange("async", null, true)); propertyChanges.add(new PropertyChange("deleteReason", null, deleteReason)); commandContext.getOperationLogManager() .logDecisionInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY, null, propertyChanges); } public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) { return new BatchConfiguration(elementConfiguration.getIds(), elementConfiguration.getMappings()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\cmd\DeleteHistoricDecisionInstancesBatchCmd.java
1
请完成以下Java代码
public class XMLWriter { public static final String NODENAME_Migrations = "Migrations"; private final transient Logger logger = LogManager.getLogger(getClass()); private final String fileName; private OutputStream outputStream = null; public XMLWriter(String fileName) { this.fileName = fileName; } public XMLWriter(OutputStream is) { this.fileName = null; this.outputStream = is; } public void write(I_AD_Migration migration) { try { write0(migration); } catch (Exception e) { throw new AdempiereException(e); } } private void write0(I_AD_Migration migration) throws ParserConfigurationException, TransformerException, IOException { if (migration == null || migration.getAD_Migration_ID() <= 0) { throw new AdempiereException("No migration to export. Migration is null or new."); } logger.debug("Creating xml document for migration: " + migration); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement(NODENAME_Migrations); document.appendChild(root); final IXMLHandlerFactory converterFactory = Services.get(IXMLHandlerFactory.class); final IXMLHandler<I_AD_Migration> converter = converterFactory.getHandler(I_AD_Migration.class); final Node migrationNode = converter.toXmlNode(document, migration); root.appendChild(migrationNode);
// set up a transformer final TransformerFactory transFactory = TransformerFactory.newInstance(); transFactory.setAttribute("indent-number", 2); final Transformer trans = transFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.STANDALONE, "yes"); logger.debug("Writing xml to file."); Writer writer = null; try { writer = getWriter(); final StreamResult result = new StreamResult(writer); final DOMSource source = new DOMSource(document); trans.transform(source, result); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } writer = null; } } } private Writer getWriter() throws IOException { if (fileName != null) { return new FileWriter(fileName); } else if (outputStream != null) { return new OutputStreamWriter(outputStream); } else { throw new AdempiereException("Cannot identify target stream"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\XMLWriter.java
1
请完成以下Spring Boot application配置
server: port: 9080 web: debug: true page-size: 15 user: home: C:/Users/app #Config 4 Security ==> Mapped to Security Object security: providers: - http-basic-auth: realm: "myRealm" principal-type: USER # Can be USER or SERVICE, default is USER users: - login: "user" password: "user" roles: ["ROLE_USER"] - login: "admin" password: "admin" roles: ["ROLE_USER", "ROLE_ADMIN"] #Config 4 Security Web Server Integration ==> Mapped to WebSecurity Object web-serve
r: securityDefaults: authenticate: true paths: - path: "/user" methods: ["get"] roles-allowed: ["ROLE_USER", "ROLE_ADMIN"] - path: "/admin" methods: ["get"] roles-allowed: ["ROLE_ADMIN"]
repos\tutorials-master\microservices-modules\helidon\helidon-se\src\main\resources\application.yaml
2
请完成以下Java代码
public class IntegerBucketSorter implements Sorter<Integer> { private final Comparator<Integer> comparator; public IntegerBucketSorter(Comparator<Integer> comparator) { this.comparator = comparator; } public IntegerBucketSorter() { comparator = Comparator.naturalOrder(); } public List<Integer> sort(List<Integer> arrayToSort) { List<List<Integer>> buckets = splitIntoUnsortedBuckets(arrayToSort); for(List<Integer> bucket : buckets){ bucket.sort(comparator); } return concatenateSortedBuckets(buckets); } private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){ List<Integer> sortedArray = new LinkedList<>(); for(List<Integer> bucket : buckets){ sortedArray.addAll(bucket); } return sortedArray; } private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){ final int max = findMax(initialList); final int numberOfBuckets = (int) Math.sqrt(initialList.size()); List<List<Integer>> buckets = new ArrayList<>(); for(int i = 0; i < numberOfBuckets; i++) buckets.add(new ArrayList<>()); //distribute the data for (int i : initialList) {
buckets.get(hash(i, max, numberOfBuckets)).add(i); } return buckets; } private int findMax(List<Integer> input){ int m = Integer.MIN_VALUE; for (int i : input){ m = Math.max(i, m); } return m; } private static int hash(int i, int max, int numberOfBuckets) { return (int) ((double) i / max * (numberOfBuckets - 1)); } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-3\src\main\java\com\baeldung\algorithms\bucketsort\IntegerBucketSorter.java
1
请在Spring Boot框架中完成以下Java代码
public int getS_ExternalProjectReference_ID() { return get_ValueAsInt(COLUMNNAME_S_ExternalProjectReference_ID); } @Override public void setS_Issue_ID (final int S_Issue_ID) { if (S_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Issue_ID, S_Issue_ID); } @Override public int getS_Issue_ID() { return get_ValueAsInt(COLUMNNAME_S_Issue_ID); } @Override public de.metas.serviceprovider.model.I_S_Milestone getS_Milestone() { return get_ValueAsPO(COLUMNNAME_S_Milestone_ID, de.metas.serviceprovider.model.I_S_Milestone.class); } @Override public void setS_Milestone(final de.metas.serviceprovider.model.I_S_Milestone S_Milestone) { set_ValueFromPO(COLUMNNAME_S_Milestone_ID, de.metas.serviceprovider.model.I_S_Milestone.class, S_Milestone); } @Override public void setS_Milestone_ID (final int S_Milestone_ID) { if (S_Milestone_ID < 1) set_Value (COLUMNNAME_S_Milestone_ID, null); else set_Value (COLUMNNAME_S_Milestone_ID, S_Milestone_ID); } @Override public int getS_Milestone_ID() { return get_ValueAsInt(COLUMNNAME_S_Milestone_ID); } @Override public de.metas.serviceprovider.model.I_S_Issue getS_Parent_Issue() { return get_ValueAsPO(COLUMNNAME_S_Parent_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class); } @Override public void setS_Parent_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Parent_Issue) { set_ValueFromPO(COLUMNNAME_S_Parent_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Parent_Issue); }
@Override public void setS_Parent_Issue_ID (final int S_Parent_Issue_ID) { if (S_Parent_Issue_ID < 1) set_Value (COLUMNNAME_S_Parent_Issue_ID, null); else set_Value (COLUMNNAME_S_Parent_Issue_ID, S_Parent_Issue_ID); } @Override public int getS_Parent_Issue_ID() { return get_ValueAsInt(COLUMNNAME_S_Parent_Issue_ID); } /** * Status AD_Reference_ID=541142 * Reference name: S_Issue_Status */ public static final int STATUS_AD_Reference_ID=541142; /** In progress = InProgress */ public static final String STATUS_InProgress = "InProgress"; /** Closed = Closed */ public static final String STATUS_Closed = "Closed"; /** Pending = Pending */ public static final String STATUS_Pending = "Pending"; /** Delivered = Delivered */ public static final String STATUS_Delivered = "Delivered"; /** New = New */ public static final String STATUS_New = "New"; /** Invoiced = Invoiced */ public static final String STATUS_Invoiced = "Invoiced"; @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 setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Issue.java
2
请完成以下Java代码
public void deleteHistoricIncidentsByBatchId(List<String> historicBatchIds) { if (isHistoryEventProduced()) { getDbEntityManager().delete(HistoricIncidentEntity.class, "deleteHistoricIncidentsByBatchIds", historicBatchIds); } } protected void configureQuery(HistoricIncidentQueryImpl query) { getAuthorizationManager().configureHistoricIncidentQuery(query); getTenantManager().configureQuery(query); } protected boolean isHistoryEventProduced() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); return historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_CREATE, null) || historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_DELETE, null) || historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, null) || historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_RESOLVE, null); } public DbOperation deleteHistoricIncidentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize);
return getDbEntityManager() .deletePreserveOrder(HistoricIncidentEntity.class, "deleteHistoricIncidentsByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } public void addRemovalTimeToHistoricIncidentsByBatchId(String batchId, Date removalTime) { Map<String, Object> parameters = new HashMap<>(); parameters.put("batchId", batchId); parameters.put("removalTime", removalTime); getDbEntityManager() .updatePreserveOrder(HistoricIncidentEntity.class, "updateHistoricIncidentsByBatchId", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricIncidentManager.java
1
请完成以下Java代码
public Class<?> verifyClassName(final I_AD_JavaClass javaClassDef) { final String className = javaClassDef.getClassname(); final Class<?> javaClass; ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = getClass().getClassLoader(); } try { javaClass = cl.loadClass(className); } catch (final ClassNotFoundException e) { throw new AdempiereException("Classname not found: " + className, e); } return javaClass; } private Class<?> getJavaTypeClassOrNull(final I_AD_JavaClass javaClassDef) { if (javaClassDef.getAD_JavaClass_Type_ID() <= 0) { return null; } final I_AD_JavaClass_Type javaClassTypeDef = javaClassDef.getAD_JavaClass_Type(); final String typeClassname = javaClassTypeDef.getClassname(); if (Check.isEmpty(typeClassname, true))
{ return null; } final Class<?> typeClass; ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = getClass().getClassLoader(); } try { typeClass = cl.loadClass(typeClassname.trim()); } catch (final ClassNotFoundException e) { throw new AdempiereException("Classname not found: " + typeClassname, e); } return typeClass; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\impl\JavaClassBL.java
1
请完成以下Java代码
public void setDataCollectionStartDate(Date dataCollectionStartDate) { this.dataCollectionStartDate = dataCollectionStartDate; } @Override public Map<String, Command> getCommands() { return commands; } public void setCommands(Map<String, Command> commands) { this.commands = commands; } public void putCommand(String commandName, int count) { if (commands == null) { commands = new HashMap<>(); } commands.put(commandName, new CommandImpl(count)); } @Override public Map<String, Metric> getMetrics() { return metrics; } public void setMetrics(Map<String, Metric> metrics) { this.metrics = metrics; } public void putMetric(String metricName, int count) { if (metrics == null) { metrics = new HashMap<>(); } metrics.put(metricName, new MetricImpl(count)); } public void mergeDynamicData(InternalsImpl other) { this.commands = other.commands; this.metrics = other.metrics; }
@Override public JdkImpl getJdk() { return jdk; } public void setJdk(JdkImpl jdk) { this.jdk = jdk; } @Override public Set<String> getCamundaIntegration() { return camundaIntegration; } public void setCamundaIntegration(Set<String> camundaIntegration) { this.camundaIntegration = camundaIntegration; } @Override public LicenseKeyDataImpl getLicenseKey() { return licenseKey; } public void setLicenseKey(LicenseKeyDataImpl licenseKey) { this.licenseKey = licenseKey; } @Override public Set<String> getWebapps() { return webapps; } public void setWebapps(Set<String> webapps) { this.webapps = webapps; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\InternalsImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static class InventoryHeaderKey { @NonNull ZonedDateTime movementDate; @Nullable String poReference; } @Value @Builder private static class InventoryLineKey { @NonNull HuId topLevelHU; @NonNull ProductId productId; @Nullable InOutLineId receiptLineId; } @Value @Builder private static class InventoryLineCandidate { @NonNull ZonedDateTime movementDate;
@NonNull HuId topLevelHUId; @NonNull ProductId productId; @NonNull Quantity qty; @Nullable I_M_InOutLine receiptLine; @Nullable String poReference; @Nullable public InOutLineId getInOutLineId() { return receiptLine != null ? InOutLineId.ofRepoId(receiptLine.getM_InOutLine_ID()) : null; } public UomId getUomId() { return qty.getUomId(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\internaluse\InventoryAllocationDestination.java
2
请完成以下Java代码
private String objectToString(final Object value, final int displayType, final boolean isMandatory) { if (value == null) { if (isMandatory) { logger.warn("Value is null even if is marked to be mandatory [Returning null]"); } return null; } // final String valueStr; if (DisplayType.isDate(displayType)) { valueStr = dateTimeFormat.format(value); } else if (DisplayType.YesNo == displayType) { if (value instanceof Boolean) {
valueStr = ((Boolean)value) ? "true" : "false"; } else { valueStr = "Y".equals(value) ? "true" : "false"; } return valueStr; } else { valueStr = value.toString(); } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\util\DefaultDataConverter.java
1
请完成以下Java代码
public List<AuthorList> getAuthors() { return authors; } public void setAuthors(List<AuthorList> authors) { this.authors = authors; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((BookList) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\entity\BookList.java
1
请完成以下Java代码
public boolean saveTxtTo(String path, Filter filter) { try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8")); Set<Map.Entry<String, Item>> entries = trie.entrySet(); for (Map.Entry<String, Item> entry : entries) { if (filter.onSave(entry.getValue())) { bw.write(entry.getValue().toString()); bw.newLine(); } } bw.close(); } catch (Exception e) { Predefine.logger.warning("保存到" + path + "失败" + e); return false; } return true; } /** * 调整频次,按排序后的次序给定频次 * * @param itemList * @return 处理后的列表 */ public static List<Item> normalizeFrequency(List<Item> itemList) { for (Item item : itemList) { ArrayList<Map.Entry<String, Integer>> entryArray = new ArrayList<Map.Entry<String, Integer>>(item.labelMap.entrySet()); Collections.sort(entryArray, new Comparator<Map.Entry<String, Integer>>()
{ @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); int index = 1; for (Map.Entry<String, Integer> pair : entryArray) { item.labelMap.put(pair.getKey(), index); ++index; } } return itemList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\DictionaryMaker.java
1
请完成以下Java代码
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) { Optional<Entry<K, V>> maxEntry = map.entrySet() .stream() .max(Comparator.comparing(Entry::getValue)); return maxEntry.get() .getValue(); } public <K, V extends Comparable<V>> K keyOfMaxUsingStream(Map<K, V> map) { return map.entrySet() .stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse(null); } public static void main(String[] args) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 3);
map.put(2, 4); map.put(3, 5); map.put(4, 6); map.put(5, 7); MapMax mapMax = new MapMax(); System.out.println(mapMax.maxUsingIteration(map)); System.out.println(mapMax.maxUsingCollectionsMax(map)); System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); System.out.println(mapMax.maxUsingStreamAndLambda(map)); System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-2\src\main\java\com\baeldung\map\mapmax\MapMax.java
1
请完成以下Java代码
public int getM_Transaction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Transaction_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Cost_Collector getPP_Cost_Collector() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class); } @Override public void setPP_Cost_Collector(org.eevolution.model.I_PP_Cost_Collector PP_Cost_Collector) { set_ValueFromPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class, PP_Cost_Collector); } /** Set Manufacturing Cost Collector. @param PP_Cost_Collector_ID Manufacturing Cost Collector */ @Override
public void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID) { if (PP_Cost_Collector_ID < 1) set_Value (COLUMNNAME_PP_Cost_Collector_ID, null); else set_Value (COLUMNNAME_PP_Cost_Collector_ID, Integer.valueOf(PP_Cost_Collector_ID)); } /** Get Manufacturing Cost Collector. @return Manufacturing Cost Collector */ @Override public int getPP_Cost_Collector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Cost_Collector_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Transaction.java
1
请在Spring Boot框架中完成以下Java代码
public class ReceivedFile implements Serializable { @Serial private static final long serialVersionUID = -420530763778423322L; @Id @JdbcTypeCode(SqlTypes.CHAR) UUID id; Instant receivedDate; String originalFileName; String storedName; @Enumerated(EnumType.STRING) FileGroup fileGroup; public ReceivedFile(FileGroup group, String originalFileName, String storedName) { this.fileGroup = group; this.originalFileName = originalFileName; this.storedName = storedName; this.id = UUID.randomUUID();
} /** * this can resemble S3 bucket */ public enum FileGroup { NOTE_ATTACHMENT("attachments"), ; //add other public final String path; FileGroup(String path) { this.path = path; } } }
repos\spring-boot-web-application-sample-master\main-app\main-orm\src\main\java\gt\app\domain\ReceivedFile.java
2
请完成以下Java代码
public java.lang.String getPriceList() { return get_ValueAsString(COLUMNNAME_PriceList); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setProductValue (final java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setProjectValue (final @Nullable java.lang.String ProjectValue) { set_Value (COLUMNNAME_ProjectValue, ProjectValue); } @Override public java.lang.String getProjectValue() { return get_ValueAsString(COLUMNNAME_ProjectValue); } @Override
public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated) { set_Value (COLUMNNAME_QtyCalculated, QtyCalculated); } @Override public BigDecimal getQtyCalculated() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUOM (final java.lang.String UOM) { set_Value (COLUMNNAME_UOM, UOM); } @Override public java.lang.String getUOM() { return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setWarehouseValue (final java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java
1
请完成以下Java代码
public class GetDeploymentProcessDiagramLayoutCmd implements Command<DiagramLayout>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; public GetDeploymentProcessDiagramLayoutCmd(String processDefinitionId) { if (processDefinitionId == null || processDefinitionId.length() < 1) { throw new ProcessEngineException("The process definition id is mandatory, but '" + processDefinitionId + "' has been provided."); } this.processDefinitionId = processDefinitionId; } public DiagramLayout execute(final CommandContext commandContext) { ProcessDefinitionEntity processDefinition = Context .getProcessEngineConfiguration() .getDeploymentCache() .findDeployedProcessDefinitionById(processDefinitionId);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadProcessDefinition(processDefinition); } InputStream processModelStream = commandContext.runWithoutAuthorization( new GetDeploymentProcessModelCmd(processDefinitionId)); InputStream processDiagramStream = commandContext.runWithoutAuthorization( new GetDeploymentProcessDiagramCmd(processDefinitionId)); return new ProcessDiagramLayoutFactory().getProcessDiagramLayout(processModelStream, processDiagramStream); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetDeploymentProcessDiagramLayoutCmd.java
1
请在Spring Boot框架中完成以下Java代码
public void setMEASUREATTR(String value) { this.measureattr = value; } /** * Gets the value of the measureunit property. * * @return * possible object is * {@link String } * */ public String getMEASUREUNIT() { return measureunit; } /** * Sets the value of the measureunit property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREUNIT(String value) { this.measureunit = value; } /** * Gets the value of the measurevalue property.
* * @return * possible object is * {@link String } * */ public String getMEASUREVALUE() { return measurevalue; } /** * Sets the value of the measurevalue property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREVALUE(String value) { this.measurevalue = 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\DMESU1.java
2
请在Spring Boot框架中完成以下Java代码
static class JsonbHttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean(JsonbHttpMessageConverter.class) JsonbHttpMessageConvertersCustomizer jsonbHttpMessageConvertersCustomizer(Jsonb jsonb) { return new JsonbHttpMessageConvertersCustomizer(jsonb); } } static class JsonbHttpMessageConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final JsonbHttpMessageConverter converter; JsonbHttpMessageConvertersCustomizer(Jsonb jsonb) { this.converter = new JsonbHttpMessageConverter(jsonb); } @Override public void customize(ClientBuilder builder) { builder.withJsonConverter(this.converter); } @Override public void customize(ServerBuilder builder) { builder.withJsonConverter(this.converter); } } private static class PreferJsonbOrMissingJacksonAndGsonCondition extends AnyNestedCondition { PreferJsonbOrMissingJacksonAndGsonCondition() { super(ConfigurationPhase.REGISTER_BEAN);
} @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } @SuppressWarnings("removal") @ConditionalOnMissingBean({ JacksonJsonHttpMessageConvertersCustomizer.class, Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class, GsonHttpConvertersCustomizer.class }) static class JacksonAndGsonMissing { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\JsonbHttpMessageConvertersConfiguration.java
2
请完成以下Java代码
public void setLastName(final String lastName) { this.lastName = lastName; this.lastNameSet = true; } public void setEmail(final String email) { this.email = email; this.emailSet = true; } public void setPhone(final String phone) { this.phone = phone; this.phoneSet = true; } public void setFax(final String fax) { this.fax = fax; this.faxSet = true; } public void setMobilePhone(final String mobilePhone) { this.mobilePhone = mobilePhone; this.mobilePhoneSet = true; } public void setDefaultContact(final Boolean defaultContact) { this.defaultContact = defaultContact; this.defaultContactSet = true; } public void setShipToDefault(final Boolean shipToDefault) { this.shipToDefault = shipToDefault; this.shipToDefaultSet = true; } public void setBillToDefault(final Boolean billToDefault) { this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setNewsletter(final Boolean newsletter) { this.newsletter = newsletter; this.newsletterSet = true; } public void setDescription(final String description) { this.description = description; this.descriptionSet = true; } public void setSales(final Boolean sales) { this.sales = sales;
this.salesSet = true; } public void setSalesDefault(final Boolean salesDefault) { this.salesDefault = salesDefault; this.salesDefaultSet = true; } public void setPurchase(final Boolean purchase) { this.purchase = purchase; this.purchaseSet = true; } public void setPurchaseDefault(final Boolean purchaseDefault) { this.purchaseDefault = purchaseDefault; this.purchaseDefaultSet = true; } public void setSubjectMatter(final Boolean subjectMatter) { this.subjectMatter = subjectMatter; this.subjectMatterSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestContact.java
1
请完成以下Java代码
default List<String> getAudience() { return this.getClaimAsStringList(LogoutTokenClaimNames.AUD); } /** * Returns the time at which the ID Token was issued {@code (iat)}. * @return the time at which the ID Token was issued */ default Instant getIssuedAt() { return this.getClaimAsInstant(LogoutTokenClaimNames.IAT); } /** * Returns a {@link Map} that identifies this token as a logout token * @return the identifying {@link Map} */ default Map<String, Object> getEvents() { return getClaimAsMap(LogoutTokenClaimNames.EVENTS); } /**
* Returns a {@code String} value {@code (sid)} representing the OIDC Provider session * @return the value representing the OIDC Provider session */ default String getSessionId() { return getClaimAsString(LogoutTokenClaimNames.SID); } /** * Returns the JWT ID {@code (jti)} claim which provides a unique identifier for the * JWT. * @return the JWT ID claim which provides a unique identifier for the JWT */ default String getId() { return this.getClaimAsString(LogoutTokenClaimNames.JTI); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\logout\LogoutTokenClaimAccessor.java
1
请完成以下Java代码
public class CustomErrorResponse { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss") private LocalDateTime timestamp; private int status; private String error; public LocalDateTime getTimestamp() { return timestamp; } public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } public int getStatus() {
return status; } public void setStatus(int status) { this.status = status; } public String getError() { return error; } public void setError(String error) { this.error = error; } }
repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\error\CustomErrorResponse.java
1
请完成以下Java代码
public Date getDatePromisedMax() { return this._datePromisedMax; } @Nullable public MRPFirmType getMRPFirmType() { return this._mrpFirmType; } public boolean isQtyNotZero() { return false; } @Nullable public Boolean getMRPAvailable() { return _mrpAvailable; } public boolean isOnlyActiveRecords() { return _onlyActiveRecords; } @Override public MRPQueryBuilder setOnlyActiveRecords(final boolean onlyActiveRecords) { this._onlyActiveRecords = onlyActiveRecords; return this; } @Override public MRPQueryBuilder setOrderType(final String orderType) { this._orderTypes.clear(); if (orderType != null) {
this._orderTypes.add(orderType); } return this; } private Set<String> getOrderTypes() { return this._orderTypes; } @Override public MRPQueryBuilder setReferencedModel(final Object referencedModel) { this._referencedModel = referencedModel; return this; } public Object getReferencedModel() { return this._referencedModel; } @Override public void setPP_Order_BOMLine_Null() { this._ppOrderBOMLine_Null = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPQueryBuilder.java
1
请完成以下Java代码
private void onTreeAction(final String action) { final Action a = tree.getActionMap().get(action); if (a != null) { a.actionPerformed(new ActionEvent(tree, ActionEvent.ACTION_PERFORMED, null)); } } /** * Clicked on Expand All */ private void expandTree() { if (treeExpand.isSelected()) { for (int row = 0; row < tree.getRowCount(); row++) { tree.expandRow(row); } } else { // patch: 1654055 +jgubo Changed direction of collapsing the tree nodes for (int row = tree.getRowCount(); row > 0; row--) { tree.collapseRow(row); } } } // expandTree private static void setMappings(final JTree tree) { final ActionMap map = tree.getActionMap(); map.put(TransferHandler.getCutAction().getValue(Action.NAME), TransferHandler.getCutAction()); map.put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction()); } public AdempiereTreeModel getTreeModel() { return treeModel; } public void filterIds(final List<Integer> ids) { if (treeModel == null) {
return; // nothing to do } Check.assumeNotNull(ids, "Param 'ids' is not null"); treeModel.filterIds(ids); if (treeExpand.isSelected()) { expandTree(); } if (ids != null && ids.size() > 0) { setTreeSelectionPath(ids.get(0), true); } } @Override public void requestFocus() { treeSearch.requestFocus(); } @Override public boolean requestFocusInWindow() { return treeSearch.requestFocusInWindow(); } } // VTreePanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreePanel.java
1
请完成以下Java代码
public class SecurityContextChangedEvent extends ApplicationEvent { public static final Supplier<SecurityContext> NO_CONTEXT = () -> null; private final Supplier<SecurityContext> oldContext; private final Supplier<SecurityContext> newContext; /** * Construct an event * @param oldContext the old security context * @param newContext the new security context, use * {@link SecurityContextChangedEvent#NO_CONTEXT} for if the context is cleared * @since 5.8 */ public SecurityContextChangedEvent(Supplier<SecurityContext> oldContext, Supplier<SecurityContext> newContext) { super(SecurityContextHolder.class); this.oldContext = oldContext; this.newContext = newContext; } /** * Construct an event * @param oldContext the old security context * @param newContext the new security context */ public SecurityContextChangedEvent(SecurityContext oldContext, SecurityContext newContext) { this(() -> oldContext, (newContext != null) ? () -> newContext : NO_CONTEXT); } /** * Get the {@link SecurityContext} set on the {@link SecurityContextHolder} * immediately previous to this event * @return the previous {@link SecurityContext} */ public SecurityContext getOldContext() { return this.oldContext.get(); } /** * Get the {@link SecurityContext} set on the {@link SecurityContextHolder} as of this * event * @return the current {@link SecurityContext}
*/ public SecurityContext getNewContext() { return this.newContext.get(); } /** * Say whether the event is a context-clearing event. * * <p> * This method is handy for avoiding looking up the new context to confirm it is a * cleared event. * @return {@code true} if the new context is * {@link SecurityContextChangedEvent#NO_CONTEXT} * @since 5.8 */ public boolean isCleared() { return this.newContext == NO_CONTEXT; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\SecurityContextChangedEvent.java
1
请在Spring Boot框架中完成以下Java代码
public void handleEvent(@NonNull final DDOrderDocStatusChangedEvent ddOrderChangedDocStatusEvent) { final List<Candidate> candidatesForDDOrderId = DDOrderUtil .retrieveCandidatesForDDOrderId( candidateRepositoryRetrieval, ddOrderChangedDocStatusEvent.getDdOrderId()); Check.errorIf(candidatesForDDOrderId.isEmpty(), "No Candidates found for PP_Order_ID={} ", ddOrderChangedDocStatusEvent.getDdOrderId()); final DocStatus newDocStatusFromEvent = ddOrderChangedDocStatusEvent.getNewDocStatus(); final List<Candidate> updatedCandidatesToPersist = new ArrayList<>(); for (final Candidate candidateForDDOrderId : candidatesForDDOrderId) { final BigDecimal newQuantity = computeNewQuantity(newDocStatusFromEvent, candidateForDDOrderId); final DistributionDetail distributionDetail = // DistributionDetail.cast(candidateForDDOrderId.getBusinessCaseDetail()); final Candidate updatedCandidateToPersist = candidateForDDOrderId.toBuilder() // .status(newCandidateStatus) .materialDescriptor(candidateForDDOrderId.getMaterialDescriptor().withQuantity(newQuantity)) .businessCaseDetail(distributionDetail.toBuilder().ddOrderDocStatus(newDocStatusFromEvent).build()) .build(); updatedCandidatesToPersist.add(updatedCandidateToPersist); } updatedCandidatesToPersist.forEach(candidateChangeService::onCandidateNewOrChange);
} private BigDecimal computeNewQuantity( @NonNull final DocStatus newDocStatusFromEvent, @NonNull final Candidate candidateForDDOrderId) { final BigDecimal newQuantity; if (newDocStatusFromEvent.isClosed()) { // Take the "actualQty" instead of max(actual, planned) newQuantity = candidateForDDOrderId.computeActualQty(); } else { // take the max(actual, planned) final BigDecimal plannedQty = candidateForDDOrderId.getBusinessCaseDetail().getQty(); newQuantity = candidateForDDOrderId.computeActualQty().max(plannedQty); } return newQuantity; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderDocStatusChangedHandler.java
2
请在Spring Boot框架中完成以下Java代码
private AlbertaCompositeProductProducer buildAlbertaCompositeProductProducer( @NonNull final AlbertaDataQuery dataQuery, @Nullable final PriceListId pharmacyPriceListId) { final Map<ProductId, I_M_ProductPrice> productId2ProductPrice = Optional.ofNullable(pharmacyPriceListId) .map(priceListId -> priceListDAO.retrievePriceListVersionOrNull(priceListId, ZonedDateTime.now(), null)) .map(priceListVersion -> PriceListVersionId.ofRepoId(priceListVersion.getM_PriceList_Version_ID())) .map(priceListVersionId -> priceListDAO.retrieveProductPrices(priceListVersionId) .filter(productPrice -> !productPrice.isAttributeDependant()) .collect(ImmutableMap.toImmutableMap( productPrice -> ProductId.ofRepoId(productPrice.getM_Product_ID()), Function.identity() ))) .orElse(ImmutableMap.of()); return AlbertaCompositeProductProducer.builder() .productId2ProductPrice(productId2ProductPrice) .product2AlbertaArticle(albertaProductDAO.getAlbertaArticles(dataQuery)) .product2BillableTherapies(albertaProductDAO.getBillableTherapies(dataQuery)) .product2Therapies(albertaProductDAO.getTherapies(dataQuery)) .product2PackagingUnits(albertaProductDAO.getPackagingUnits(dataQuery)) .getAlbertaArticleIdSupplier(this::getAlbertaArticleIdByProductId) .getProductGroupIdentifierSupplier(this::getProductGroupIdentifierByProductId) .build(); } @NonNull private Optional<String> getProductGroupIdentifierByProductId(@NonNull final ProductId productId) { final I_M_Product product = productDAO.getById(productId); final ExternalSystem externalSystem = externalSystemRepository.getByType(ExternalSystemType.Alberta); final GetExternalReferenceByRecordIdReq getExternalReferenceByRecordIdReq = GetExternalReferenceByRecordIdReq.builder() .recordId(product.getM_Product_Category_ID()) .externalSystem(externalSystem) .externalReferenceType(ProductCategoryExternalReferenceType.PRODUCT_CATEGORY) .build();
return externalReferenceRepository.getExternalReferenceByMFReference(getExternalReferenceByRecordIdReq) .map(ExternalReference::getExternalReference); } @NonNull private Optional<String> getAlbertaArticleIdByProductId(@NonNull final ProductId productId) { final ExternalSystem externalSystem = externalSystemRepository.getByType(ExternalSystemType.Alberta); final GetExternalReferenceByRecordIdReq getExternalReferenceByRecordIdReq = GetExternalReferenceByRecordIdReq.builder() .recordId(productId.getRepoId()) .externalSystem(externalSystem) .externalReferenceType(ProductExternalReferenceType.PRODUCT) .build(); return externalReferenceRepository.getExternalReferenceByMFReference(getExternalReferenceByRecordIdReq) .map(ExternalReference::getExternalReference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\service\AlbertaProductService.java
2
请完成以下Java代码
public void setAD_Message_ID (int AD_Message_ID) { if (AD_Message_ID <= 0) { super.setAD_Message_ID(retrieveAdMessageRepoIdByValue(getCtx(), "NoMessageFound")); } else { super.setAD_Message_ID(AD_Message_ID); } } // setAD_Message_ID /** * Set Client Org * @param AD_Client_ID client * @param AD_Org_ID org */ @Override public void setClientOrg(int AD_Client_ID, int AD_Org_ID) { super.setClientOrg(AD_Client_ID, AD_Org_ID); } // setClientOrg /** * Set Record * @param AD_Table_ID table * @param Record_ID record */ public void setRecord (int AD_Table_ID, int Record_ID) { setAD_Table_ID(AD_Table_ID);
setRecord_ID(Record_ID); } // setRecord public void setRecord (final TableRecordReference record) { if(record != null) { setRecord(record.getAD_Table_ID(), record.getRecord_ID()); } else { setRecord(-1, -1); } } /** * String Representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer ("MNote[") .append(get_ID()).append(",AD_Message_ID=").append(getAD_Message_ID()) .append(",").append(getReference()) .append(",Processed=").append(isProcessed()) .append("]"); return sb.toString(); } // toString } // MNote
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MNote.java
1