instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected String doIt() throws Exception { final I_C_InvoiceSchedule invoiceScheduleRecord; if (getProcessInfo().getRecord_ID() <= 0) { invoiceScheduleRecord = InterfaceWrapperHelper.newInstance(I_C_InvoiceSchedule.class); isNewRecord = true; } else { invoiceScheduleRecord = getProcessInfo().getRecord(I_C_InvoiceSchedule.class); } if (Check.isNotBlank(name)) { invoiceScheduleRecord.setName(StringUtils.trim(name)); } invoiceScheduleRecord.setInvoiceDistance(invoiceDistance.intValue()); invoiceScheduleRecord.setInvoiceFrequency(invoiceFrequency); invoiceScheduleRecord.setInvoiceDay(Math.min(31, Math.max(1, invoiceDay.intValue()))); // enforce a value between 1 and 31 invoiceScheduleRecord.setInvoiceWeekDay(invoiceWeekDay); invoiceScheduleRecord.setIsAmount(isAmount); invoiceScheduleRecord.setAmt(amt); InterfaceWrapperHelper.saveRecord(invoiceScheduleRecord); return MSG_OK; } /** * I also defined the values in AD_ProcessParam.DefaultLogic, but the expressions weren't used. */ @Nullable @Override public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter) { if (getProcessInfo().getRecord_ID() <= 0) { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } final I_C_InvoiceSchedule invoiceScheduleRecord = getProcessInfo().getRecord(I_C_InvoiceSchedule.class); if (I_C_InvoiceSchedule.COLUMNNAME_Name.equals(parameter.getColumnName())) { return invoiceScheduleRecord.getName(); } else if (I_C_InvoiceSchedule.COLUMNNAME_InvoiceDistance.equals(parameter.getColumnName())) { return invoiceScheduleRecord.getInvoiceDistance(); } else if (I_C_InvoiceSchedule.COLUMNNAME_InvoiceFrequency.equals(parameter.getColumnName())) { return invoiceScheduleRecord.getInvoiceFrequency(); } else if (I_C_InvoiceSchedule.COLUMNNAME_InvoiceDay.equals(parameter.getColumnName())) {
return invoiceScheduleRecord.getInvoiceDay(); } else if (I_C_InvoiceSchedule.COLUMNNAME_InvoiceWeekDay.equals(parameter.getColumnName())) { return invoiceScheduleRecord.getInvoiceWeekDay(); } else if (I_C_InvoiceSchedule.COLUMNNAME_IsAmount.equals(parameter.getColumnName())) { return invoiceScheduleRecord.isAmount(); } else if (I_C_InvoiceSchedule.COLUMNNAME_Amt.equals(parameter.getColumnName())) { return invoiceScheduleRecord.getAmt(); } return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } /** * Needed because otherwise we need a cache-reset in case a new record was added. */ @Override protected final void postProcess(final boolean success) { if (success && isNewRecord) { getView().invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\process\C_InvoiceSchedule_CreateOrUpdate.java
1
请完成以下Java代码
public static void create(final JsonNodeTrx wtx) { wtx.insertObjectAsFirstChild(); wtx.insertObjectRecordAsFirstChild("foo", new ArrayValue()) .insertStringValueAsFirstChild("bar") .insertNullValueAsRightSibling() .insertNumberValueAsRightSibling(2.33); wtx.moveToParent().trx().moveToParent(); wtx.insertObjectRecordAsRightSibling("bar", new ObjectValue()) .insertObjectRecordAsFirstChild("hello", new StringValue("world")) .moveToParent(); wtx.insertObjectRecordAsRightSibling("helloo", new BooleanValue(true)) .moveToParent().trx().moveToParent().trx().moveToParent(); wtx.insertObjectRecordAsRightSibling("baz", new StringValue("hello")) .moveToParent(); wtx.insertObjectRecordAsRightSibling("tada", new ArrayValue()) .insertObjectAsFirstChild() .insertObjectRecordAsFirstChild("foo", new StringValue("bar")) .moveToParent().trx().moveToParent(); wtx.insertObjectAsRightSibling() .insertObjectRecordAsFirstChild("baz", new BooleanValue(false)) .moveToParent().trx().moveToParent(); wtx.insertStringValueAsRightSibling("boo") .insertObjectAsRightSibling() .insertArrayAsRightSibling(); wtx.moveToDocumentRoot(); }
public static void createVersioned(final JsonNodeTrx wtx) { // Create sample document. JsonDocumentCreator.create(wtx); wtx.commit(); // Add changes and commit a second revision. wtx.moveToDocumentRoot().trx().moveToFirstChild(); wtx.insertObjectRecordAsFirstChild("revision2", new StringValue("yes")); wtx.commit(); // Add changes and commit a third revision. wtx.moveToDocumentRoot().trx().moveToFirstChild().trx().moveToFirstChild(); wtx.insertObjectRecordAsRightSibling("revision3", new StringValue("yes")); wtx.commit(); } }
repos\tutorials-master\persistence-modules\sirix\src\main\java\io\sirix\tutorial\json\JsonDocumentCreator.java
1
请完成以下Java代码
private void createArchive( final I_C_Print_Package printPackage, final byte[] data, final I_C_Async_Batch asyncBatch, final int current) { final TableRecordReference printPackageRef = TableRecordReference.of(printPackage); final Properties ctx = InterfaceWrapperHelper.getCtx(asyncBatch); final org.adempiere.archive.api.IArchiveBL archiveService = Services.get(org.adempiere.archive.api.IArchiveBL.class); final ArchiveResult archiveResult = archiveService.archive(ArchiveRequest.builder() .flavor(DocumentReportFlavor.PRINT) .data(new ByteArrayResource(data)) .trxName(ITrx.TRXNAME_ThreadInherited) .archiveName(printPackage.getTransactionID() + "_" + printPackage.getBinaryFormat()) .recordRef(printPackageRef) .build()); final I_AD_Archive archive = Check.assumeNotNull(archiveResult.getArchiveRecord(), "archiveResult.getArchiveRecord()!=null for archiveResult={}", archiveResult); final de.metas.printing.model.I_AD_Archive directArchive = InterfaceWrapperHelper.create(archive, de.metas.printing.model.I_AD_Archive.class); directArchive.setIsDirectEnqueue(true); final Timestamp today = SystemTime.asDayTimestamp(); final SimpleDateFormat dt = new SimpleDateFormat("dd-MM-yyyy"); final String name = Services.get(IMsgBL.class).getMsg(ctx, PDFArchiveName) + "_" + dt.format(today) + "_PDF_" + current + "_von_" + asyncBatch.getCountExpected() + "_" + asyncBatch.getC_Async_Batch_ID(); directArchive.setName(name); // // set async batch
AsyncHelper.setAsyncBatchId(archive, AsyncBatchId.ofRepoId(asyncBatch.getC_Async_Batch_ID())); InterfaceWrapperHelper.save(directArchive); } private void createPrintPackage(final I_C_Print_Job_Instructions printjobInstructions) { final IPrintPackageBL printPackageBL = Services.get(IPrintPackageBL.class); final Properties ctx = InterfaceWrapperHelper.getCtx(printjobInstructions); final I_C_Print_Package printPackage = InterfaceWrapperHelper.create(ctx, I_C_Print_Package.class, ITrx.TRXNAME_ThreadInherited); // Creating the Print Package template (request): final String transactionId = UUID.randomUUID().toString(); printPackage.setTransactionID(transactionId); InterfaceWrapperHelper.save(printPackage, ITrx.TRXNAME_ThreadInherited); final PrintPackageCtx printCtx = (PrintPackageCtx)printPackageBL.createEmptyInitialCtx(); printCtx.setHostKey(printjobInstructions.getHostKey()); printCtx.setTransactionId(printPackage.getTransactionID()); printPackageBL.addPrintingDataToPrintPackage(printPackage, printjobInstructions, printCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\async\spi\impl\PDFDocPrintingWorkpackageProcessor.java
1
请完成以下Java代码
public Mono<Authentication> authenticate(Authentication authentication) { // @formatter:off return Mono.justOrEmpty(authentication) .filter((a) -> a instanceof BearerTokenAuthenticationToken) .cast(BearerTokenAuthenticationToken.class) .map(BearerTokenAuthenticationToken::getToken) .flatMap(this.jwtDecoder::decode) .flatMap(this.jwtAuthenticationConverter::convert) .cast(Authentication.class) .onErrorMap(JwtException.class, this::onError); // @formatter:on } /** * Use the given {@link Converter} for converting a {@link Jwt} into an * {@link AbstractAuthenticationToken}. * @param jwtAuthenticationConverter the {@link Converter} to use
*/ public void setJwtAuthenticationConverter( Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter) { Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null"); this.jwtAuthenticationConverter = jwtAuthenticationConverter; } private AuthenticationException onError(JwtException ex) { if (ex instanceof BadJwtException) { return new InvalidBearerTokenException(ex.getMessage(), ex); } return new AuthenticationServiceException(ex.getMessage(), ex); } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtReactiveAuthenticationManager.java
1
请完成以下Java代码
private static final class MessagePanel extends JScrollPane { private static final long serialVersionUID = 1L; private final StringBuffer messageBuf = new StringBuffer(); private final JEditorPane message = new JEditorPane() { private static final long serialVersionUID = 1L; @Override public Dimension getPreferredSize() { final Dimension d = super.getPreferredSize(); final Dimension m = getMaximumSize(); if (d.height > m.height || d.width > m.width) { final Dimension d1 = new Dimension(); d1.height = Math.min(d.height, m.height); d1.width = Math.min(d.width, m.width); return d1; } else { return d; } } }; public MessagePanel() { super(); setBorder(null); setViewportView(message); message.setContentType("text/html"); message.setEditable(false); message.setBackground(Color.white); message.setFocusable(true); } public void moveCaretToEnd() { message.setCaretPosition(message.getDocument().getLength()); // scroll down } public void setText(final String text)
{ messageBuf.setLength(0); appendText(text); } public void appendText(final String text) { messageBuf.append(text); message.setText(messageBuf.toString()); } @Override public Dimension getPreferredSize() { final Dimension d = super.getPreferredSize(); final Dimension m = getMaximumSize(); if (d.height > m.height || d.width > m.width) { final Dimension d1 = new Dimension(); d1.height = Math.min(d.height, m.height); d1.width = Math.min(d.width, m.width); return d1; } else { return d; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessPanel.java
1
请完成以下Java代码
private @Nullable List<GraphQLError> resolveInternal(Throwable exception, DataFetchingEnvironment env) { try { return (this.threadLocalContextAware) ? ContextPropagationHelper.captureFrom(env.getGraphQlContext()) .wrap(() -> resolveToMultipleErrors(exception, env)) .call() : resolveToMultipleErrors(exception, env); } catch (Exception ex2) { this.logger.warn("Failure while resolving " + exception.getMessage(), ex2); return null; } } /** * Override this method to resolve an Exception to multiple GraphQL errors. * @param ex the exception to resolve * @param env the environment for the invoked {@code DataFetcher} * @return the resolved errors or {@code null} if unresolved */ protected @Nullable List<GraphQLError> resolveToMultipleErrors(Throwable ex, DataFetchingEnvironment env) {
GraphQLError error = resolveToSingleError(ex, env); return (error != null) ? Collections.singletonList(error) : null; } /** * Override this method to resolve an Exception to a single GraphQL error. * @param ex the exception to resolve * @param env the environment for the invoked {@code DataFetcher} * @return the resolved error or {@code null} if unresolved */ protected @Nullable GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) { return null; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\DataFetcherExceptionResolverAdapter.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer("X_M_PackagingTreeItemSched[") .append(get_ID()).append("]"); return sb.toString(); } /** * Set Packaging Tree Item Schedule. * * @param M_PackagingTreeItemSched_ID * Packaging Tree Item Schedule */ public void setM_PackagingTreeItemSched_ID(int M_PackagingTreeItemSched_ID) { if (M_PackagingTreeItemSched_ID < 1) set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, null); else set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, Integer.valueOf(M_PackagingTreeItemSched_ID)); } /** * Get Packaging Tree Item Schedule. * * @return Packaging Tree Item Schedule */ public int getM_PackagingTreeItemSched_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItemSched_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_PackagingTreeItem getM_PackagingTreeItem() throws RuntimeException { return (I_M_PackagingTreeItem)MTable.get(getCtx(), I_M_PackagingTreeItem.Table_Name) .getPO(getM_PackagingTreeItem_ID(), get_TrxName()); } /** * Set Packaging Tree Item. * * @param M_PackagingTreeItem_ID * Packaging Tree Item */ public void setM_PackagingTreeItem_ID(int M_PackagingTreeItem_ID) { if (M_PackagingTreeItem_ID < 1) set_Value(COLUMNNAME_M_PackagingTreeItem_ID, null); else set_Value(COLUMNNAME_M_PackagingTreeItem_ID, Integer.valueOf(M_PackagingTreeItem_ID)); } /** * Get Packaging Tree Item. * * @return Packaging Tree Item */ public int getM_PackagingTreeItem_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItem_ID);
if (ii == null) return 0; return ii.intValue(); } @Override public I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException { return (I_M_ShipmentSchedule)MTable.get(getCtx(), I_M_ShipmentSchedule.Table_Name) .getPO(getM_ShipmentSchedule_ID(), get_TrxName()); } @Override public int getM_ShipmentSchedule_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID); if (ii == null) return 0; return ii.intValue(); } @Override public void setM_ShipmentSchedule_ID(int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value(COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value(COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID)); } /** * Set Menge. * * @param Qty * Menge */ public void setQty(BigDecimal Qty) { set_Value(COLUMNNAME_Qty, Qty); } /** * Get Menge. * * @return Menge */ public BigDecimal getQty() { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTreeItemSched.java
1
请在Spring Boot框架中完成以下Java代码
class GitHubBasicService { private GitHubBasicApi gitHubApi; GitHubBasicService() { Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build(); gitHubApi = retrofit.create(GitHubBasicApi.class); } List<String> getTopContributors(String userName) throws IOException { List<Repository> repos = gitHubApi.listRepos(userName).execute().body(); repos = repos != null ? repos : Collections.emptyList(); return repos.stream().flatMap(repo -> getContributors(userName, repo)).sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct().sorted().collect(Collectors.toList());
} private Stream<Contributor> getContributors(String userName, Repository repo) { List<Contributor> contributors = null; try { contributors = gitHubApi.listRepoContributors(userName, repo.getName()).execute().body(); } catch (IOException e) { e.printStackTrace(); } contributors = contributors != null ? contributors : Collections.emptyList(); return contributors.stream().filter(c -> c.getContributions() > 100); } }
repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\retrofit\basic\GitHubBasicService.java
2
请完成以下Java代码
public Long call() { try { List<Worker> workers = new ArrayList<>(); CountDownLatch counter = new CountDownLatch(workerCount); for (int i = 0; i < workerCount; i++) { Connection conn = factory.newConnection(); workers.add(new Worker("queue_" + i, conn, iterations, counter, payloadSize)); } ExecutorService executor = new ThreadPoolExecutor(workerCount, workerCount, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workerCount, true)); long start = System.currentTimeMillis(); log.info("[I61] Starting {} workers...", workers.size()); executor.invokeAll(workers); if (counter.await(5, TimeUnit.MINUTES)) { long elapsed = System.currentTimeMillis() - start;
log.info("[I59] Tasks completed: #workers={}, #iterations={}, elapsed={}ms, stats={}", workerCount, iterations, elapsed); return throughput(workerCount, iterations, elapsed); } else { throw new RuntimeException("[E61] Timeout waiting workers to complete"); } } catch (Exception ex) { throw new RuntimeException(ex); } } private static long throughput(int workerCount, int iterations, long elapsed) { return (iterations * workerCount * 1000) / elapsed; } }
repos\tutorials-master\messaging-modules\rabbitmq\src\main\java\com\baeldung\benchmark\ConnectionPerChannelPublisher.java
1
请完成以下Java代码
public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public Integer getRecommendStatus() { return recommendStatus; } public void setRecommendStatus(Integer recommendStatus) { this.recommendStatus = recommendStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) {
this.sort = sort; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", subjectId=").append(subjectId); sb.append(", subjectName=").append(subjectName); sb.append(", recommendStatus=").append(recommendStatus); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeRecommendSubject.java
1
请完成以下Java代码
private static final class ElementValuesMap { private final ImmutableMap<ElementValueId, ElementValue> byId; private ImmutableSet<ElementValueId> _openItemIds; private ElementValuesMap(final List<ElementValue> list) { byId = Maps.uniqueIndex(list, ElementValue::getId); } public ElementValue getById(final ElementValueId id) { final ElementValue elementValue = byId.get(id); if (elementValue == null) { throw new AdempiereException("No Element Value found for " + id); } return elementValue; }
public ImmutableSet<ElementValueId> getOpenItemIds() { ImmutableSet<ElementValueId> openItemIds = this._openItemIds; if (openItemIds == null) { openItemIds = this._openItemIds = byId.values() .stream() .filter(ElementValue::isOpenItem) .map(ElementValue::getId) .collect(ImmutableSet.toImmutableSet()); } return openItemIds; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ElementValueRepository.java
1
请完成以下Java代码
public void onC_Order_ID(final I_DD_Order ddOrder) { final I_C_Order order = ddOrder.getC_Order(); if (order == null || order.getC_Order_ID() <= 0) { return; } // Get Details ddOrder.setDateOrdered(order.getDateOrdered()); ddOrder.setPOReference(order.getPOReference()); ddOrder.setAD_Org_ID(order.getAD_Org_ID()); ddOrder.setAD_OrgTrx_ID(order.getAD_OrgTrx_ID()); ddOrder.setC_Activity_ID(order.getC_Activity_ID()); ddOrder.setC_Campaign_ID(order.getC_Campaign_ID()); ddOrder.setC_Project_ID(order.getC_Project_ID()); ddOrder.setUser1_ID(order.getUser1_ID()); ddOrder.setUser2_ID(order.getUser2_ID());
// Warehouse (05251 begin: we need to use the advisor) final WarehouseId warehouseId = Services.get(IWarehouseAdvisor.class).evaluateOrderWarehouse(order); Check.assumeNotNull(warehouseId, "IWarehouseAdvisor finds a ware house for {}", order); ddOrder.setM_Warehouse_ID(warehouseId.getRepoId()); // ddOrder.setDeliveryRule(order.getDeliveryRule()); ddOrder.setDeliveryViaRule(order.getDeliveryViaRule()); ddOrder.setM_Shipper_ID(order.getM_Shipper_ID()); ddOrder.setFreightCostRule(order.getFreightCostRule()); ddOrder.setFreightAmt(order.getFreightAmt()); ddOrder.setC_BPartner_ID(order.getC_BPartner_ID()); ddOrder.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID()); ddOrder.setAD_User_ID(order.getAD_User_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\callout\DD_Order.java
1
请完成以下Java代码
public ExpenseCategory getCategory() { return category == null ? null : ExpenseCategory.fromId(category); } public void setCategory(ExpenseCategory category) { this.category = category == null ? null : category.getId(); } public String getName() { return name; } public void setName(String name) { this.name = name; }
public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\Expense.java
1
请完成以下Java代码
public void setCamundaClass(String camundaClass) { camundaClassAttribute.setValue(this, camundaClass); } public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaDelegateExpression() { return camundaDelegateExpressionAttribute.getValue(this); } public void setCamundaDelegateExpression(String camundaDelegateExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaDelegateExpression); } public Collection<CamundaField> getCamundaFields() { return camundaFieldCollection.get(this); } public CamundaScript getCamundaScript() { return camundaScriptChild.getChild(this); } public void setCamundaScript(CamundaScript camundaScript) { camundaScriptChild.setChild(this, camundaScript); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaExecutionListenerImpl.java
1
请完成以下Java代码
public boolean isSomethingReported(@NonNull final I_PP_Order ppOrder) { if (getQuantities(ppOrder).isSomethingReported()) { return true; } final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); return orderBOMsRepo.retrieveOrderBOMLines(ppOrderId) .stream() .map(this::getQuantities) .anyMatch(OrderBOMLineQuantities::isSomethingReported); } @Override public Optional<DocSequenceId> getSerialNoSequenceId(@NonNull final PPOrderId ppOrderId) { final I_PP_Order_BOM orderBOM = orderBOMsRepo.getByOrderIdOrNull(ppOrderId); if (orderBOM == null) { throw new AdempiereException("@NotFound@ @PP_Order_BOM_ID@: " + ppOrderId); } return DocSequenceId.optionalOfRepoId(orderBOM.getSerialNo_Sequence_ID()); } @Override public QtyCalculationsBOM getQtyCalculationsBOM(@NonNull final I_PP_Order order) { final ImmutableList<QtyCalculationsBOMLine> lines = orderBOMsRepo.retrieveOrderBOMLines(order) .stream() .map(orderBOMLineRecord -> toQtyCalculationsBOMLine(order, orderBOMLineRecord)) .collect(ImmutableList.toImmutableList()); return QtyCalculationsBOM.builder() .lines(lines) .orderId(PPOrderId.ofRepoIdOrNull(order.getPP_Order_ID())) .build(); } @Override public void save(final I_PP_Order_BOMLine orderBOMLine) { orderBOMsRepo.save(orderBOMLine); }
@Override public Set<ProductId> getProductIdsToIssue(final PPOrderId ppOrderId) { return getOrderBOMLines(ppOrderId, I_PP_Order_BOMLine.class) .stream() .filter(bomLine -> BOMComponentType.ofNullableCodeOrComponent(bomLine.getComponentType()).isIssue()) .map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(@NonNull final I_PP_Order ppOrder) { final WarehouseId warehouseId = WarehouseId.ofRepoId(ppOrder.getM_Warehouse_ID()); return getIssueFromWarehouseIds(warehouseId); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(final WarehouseId ppOrderWarehouseId) { return warehouseDAO.getWarehouseIdsOfSameGroup(ppOrderWarehouseId, WarehouseGroupAssignmentType.MANUFACTURING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMBL.java
1
请完成以下Java代码
public class GeoIP { private String ipAddress; private String city; private String latitude; private String longitude; public GeoIP() { } public GeoIP(String ipAddress) { this.ipAddress = ipAddress; } public GeoIP(String ipAddress, String city, String latitude, String longitude) { this.ipAddress = ipAddress; this.city = city; this.latitude = latitude; this.longitude = longitude; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } }
repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\form\GeoIP.java
1
请完成以下Java代码
public void setC_ElementValue_ID (int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ElementValue_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ElementValue_ID, Integer.valueOf(C_ElementValue_ID)); } /** Get Account Element. @return Account Element */ public int getC_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sub Account. @param C_SubAcct_ID Sub account for Element Value */ public void setC_SubAcct_ID (int C_SubAcct_ID) { if (C_SubAcct_ID < 1) set_ValueNoCheck (COLUMNNAME_C_SubAcct_ID, null); else set_ValueNoCheck (COLUMNNAME_C_SubAcct_ID, Integer.valueOf(C_SubAcct_ID)); } /** Get Sub Account. @return Sub account for Element Value */ public int getC_SubAcct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_SubAcct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); }
/** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set 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); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SubAcct.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserOneMapper userOneMapper; @Autowired private UserTwoMapper userTwoMapper; @RequestMapping("/getUsers") public List<UserEntity> getUsers() { List<UserEntity> usersOne=userOneMapper.getAll(); List<UserEntity> usersTwo=userTwoMapper.getAll(); usersOne.addAll(usersTwo); return usersOne; } @RequestMapping("/getList") public Page<UserEntity> getList(UserParam userParam) { List<UserEntity> users=userOneMapper.getList(userParam); long count=userOneMapper.getCount(userParam); Page page = new Page(userParam,count,users); return page; } @RequestMapping("/getUser") public UserEntity getUser(Long id) { UserEntity user=userTwoMapper.getOne(id); return user; }
@RequestMapping("/add") public void save(UserEntity user) { userOneMapper.insert(user); } @RequestMapping(value="update") public void update(UserEntity user) { userOneMapper.update(user); } @RequestMapping(value="/delete/{id}") public void delete(@PathVariable("id") Long id) { userTwoMapper.delete(id); } }
repos\spring-boot-leaning-master\1.x\第08课:Mybatis Druid 多数据源\spring-boot-multi-mybatis-druid\src\main\java\com\neo\web\UserController.java
2
请完成以下Java代码
private ImmutableMultimap<Path, PrintingSegment> extractAndAssignPaths( @NonNull final String baseDirectory, @NonNull final PrintingData printingData) { final ImmutableMultimap.Builder<Path, PrintingSegment> path2Segments = new ImmutableMultimap.Builder<>(); for (final PrintingSegment segment : printingData.getSegments()) { final HardwarePrinter printer = segment.getPrinter(); if (!OutputType.Store.equals(printer.getOutputType())) { logger.debug("Printer with id={} has outputType={}; -> skipping it", printer.getId().getRepoId(), printer.getOutputType()); continue; } final Path path; if (segment.getTrayId() != null) { final HardwareTray tray = printer.getTray(segment.getTrayId());
path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName()), FileUtil.stripIllegalCharacters(tray.getTrayNumber() + "-" + tray.getName())); } else { path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName())); } path2Segments.put(path, segment); } return path2Segments.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFFileStorer.java
1
请完成以下Java代码
public class InvokePCMAction extends AlterExternalSystemServiceStatusAction { private final InvokePCMService invokePCMService = SpringContextHolder.instance.getBean(InvokePCMService.class); public final ExternalSystemConfigRepo externalSystemConfigDAO = SpringContextHolder.instance.getBean(ExternalSystemConfigRepo.class); @Override protected IExternalSystemChildConfigId getExternalChildConfigId() { final int id; if (this.childConfigId > 0) { id = this.childConfigId; } else { final IExternalSystemChildConfig childConfig = externalSystemConfigDAO.getChildByParentIdAndType(ExternalSystemParentConfigId.ofRepoId(getRecord_ID()), getExternalSystemType()) .orElseThrow(() -> new AdempiereException("No childConfig found for type Pro Care Management and parent config") .appendParametersToMessage() .setParameter("externalSystemParentConfigId", getRecord_ID())); id = childConfig.getId().getRepoId(); } return ExternalSystemPCMConfigId.ofRepoId(id); } @Override protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final ExternalSystemPCMConfig pcmConfig = ExternalSystemPCMConfig.cast(externalSystemParentConfig.getChildConfig()); final OrgId orgId = pcmConfig.getOrgId(); final BPartnerLocationId orgBPartnerLocationId = orgDAO.getOrgInfoById(orgId).getOrgBPartnerLocationId(); Check.assumeNotNull(orgBPartnerLocationId, "AD_Org_ID={} needs to have an Organisation Business Partner Location ID", OrgId.toRepoId(orgId));
return invokePCMService.getParameters(pcmConfig, externalRequest, orgBPartnerLocationId.getBpartnerId()); } @Override protected String getTabName() { return getExternalSystemType().getValue(); } @Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.ProCareManagement; } @Override protected long getSelectedRecordCount(final IProcessPreconditionsContext context) { return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_ExternalSystem_Config_ProCareManagement.Table_Name.equals(recordRef.getTableName())) .count(); } @Override protected String getOrgCode(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final ExternalSystemPCMConfig pcmConfig = ExternalSystemPCMConfig.cast(externalSystemParentConfig.getChildConfig()); final OrgId orgId = pcmConfig.getOrgId(); return orgDAO.getById(orgId).getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokePCMAction.java
1
请完成以下Java代码
private Properties copy(Properties properties) { Properties copy = new Properties(); copy.putAll(properties); return copy; } private static final class PropertiesIterator implements Iterator<Entry> { private final Iterator<Map.Entry<Object, Object>> iterator; private PropertiesIterator(Properties properties) { this.iterator = properties.entrySet().iterator(); } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public Entry next() { Map.Entry<Object, Object> entry = this.iterator.next(); return new Entry((String) entry.getKey(), (String) entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException("InfoProperties are immutable."); } } /** * Property entry. */
public static final class Entry { private final String key; private final String value; private Entry(String key, String value) { this.key = key; this.value = value; } public String getKey() { return this.key; } public String getValue() { return this.value; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\InfoProperties.java
1
请完成以下Java代码
public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); } /** Set Summary. @param Summary Textual summary of this request */ @Override public void setSummary (java.lang.String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ @Override public java.lang.String getSummary () { return (java.lang.String)get_Value(COLUMNNAME_Summary); }
/** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Request.java
1
请完成以下Java代码
protected ObjectNode mapType(Type type) { ObjectNode result = mapValue(type); result.put("action", type.getAction()); ObjectNode tags = nodeFactory.objectNode(); type.getTags().forEach(tags::put); result.set("tags", tags); return result; } private ObjectNode mapVersionMetadata(MetadataElement value) { ObjectNode result = nodeFactory.objectNode(); result.put("id", formatVersion(value.getId())); result.put("name", value.getName()); return result; }
protected String formatVersion(String versionId) { Version version = VersionParser.DEFAULT.safeParse(versionId); return (version != null) ? version.format(Format.V1).toString() : versionId; } protected ObjectNode mapValue(MetadataElement value) { ObjectNode result = nodeFactory.objectNode(); result.put("id", value.getId()); result.put("name", value.getName()); if ((value instanceof Describable) && ((Describable) value).getDescription() != null) { result.put("description", ((Describable) value).getDescription()); } return result; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\InitializrMetadataV2JsonMapper.java
1
请在Spring Boot框架中完成以下Java代码
JerseyAdditionalHealthEndpointPathsResourcesRegistrar jerseyAdditionalHealthEndpointPathsResourcesRegistrar( WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups healthEndpointGroups) { ExposableWebEndpoint health = getHealthEndpoint(webEndpointsSupplier); return new JerseyAdditionalHealthEndpointPathsResourcesRegistrar(health, healthEndpointGroups); } private static @Nullable ExposableWebEndpoint getHealthEndpoint(WebEndpointsSupplier webEndpointsSupplier) { Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints(); return webEndpoints.stream() .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) .findFirst() .orElse(null); } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(ResourceConfig.class) @EnableConfigurationProperties(JerseyProperties.class) static class JerseyInfrastructureConfiguration { @Bean @ConditionalOnMissingBean JerseyApplicationPath jerseyApplicationPath(JerseyProperties properties, ResourceConfig config) { return new DefaultJerseyApplicationPath(properties.getApplicationPath(), config); } @Bean ResourceConfig resourceConfig(ObjectProvider<ResourceConfigCustomizer> resourceConfigCustomizers) { ResourceConfig resourceConfig = new ResourceConfig(); resourceConfigCustomizers.orderedStream().forEach((customizer) -> customizer.customize(resourceConfig)); return resourceConfig; } @Bean ServletRegistrationBean<ServletContainer> jerseyServletRegistration(JerseyApplicationPath jerseyApplicationPath, ResourceConfig resourceConfig) { return new ServletRegistrationBean<>(new ServletContainer(resourceConfig), jerseyApplicationPath.getUrlMapping()); } } static class JerseyAdditionalHealthEndpointPathsResourcesRegistrar implements ResourceConfigCustomizer { private final @Nullable ExposableWebEndpoint endpoint;
private final HealthEndpointGroups groups; JerseyAdditionalHealthEndpointPathsResourcesRegistrar(@Nullable ExposableWebEndpoint endpoint, HealthEndpointGroups groups) { this.endpoint = endpoint; this.groups = groups; } @Override public void customize(ResourceConfig config) { register(config); } private void register(ResourceConfig config) { EndpointMapping mapping = new EndpointMapping(""); JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.SERVER, this.groups); Collection<Resource> endpointResources = resourceFactory .createEndpointResources(mapping, (this.endpoint != null) ? Collections.singletonList(this.endpoint) : Collections.emptyList()) .stream() .filter(Objects::nonNull) .toList(); register(endpointResources, config); } private void register(Collection<Resource> resources, ResourceConfig config) { config.registerResources(new HashSet<>(resources)); } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\actuate\endpoint\web\HealthEndpointJerseyExtensionAutoConfiguration.java
2
请完成以下Java代码
public Map<Class< ? >, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class< ? >, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class< ? >, String> getSelectStatements() { return selectStatements; } public void setSelectStatements(Map<Class< ? >, String> selectStatements) { this.selectStatements = selectStatements; } public boolean isDbIdentityUsed() { return isDbIdentityUsed; } public void setDbIdentityUsed(boolean isDbIdentityUsed) { this.isDbIdentityUsed = isDbIdentityUsed; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public boolean isCmmnEnabled() { return cmmnEnabled; } public void setCmmnEnabled(boolean cmmnEnabled) { this.cmmnEnabled = cmmnEnabled;
} public boolean isDmnEnabled() { return dmnEnabled; } public void setDmnEnabled(boolean dmnEnabled) { this.dmnEnabled = dmnEnabled; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSessionFactory.java
1
请完成以下Java代码
public TenantEntity findTenantById(String tenantId) { checkAuthorization(Permissions.READ, Resources.TENANT, tenantId); return getDbEntityManager().selectById(TenantEntity.class, tenantId); } public TenantQuery createTenantQuery() { return new DbTenantQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutorTxRequired()); } public TenantQuery createTenantQuery(CommandContext commandContext) { return new DbTenantQueryImpl(); } public long findTenantCountByQueryCriteria(DbTenantQueryImpl query) { configureQuery(query, Resources.TENANT); return (Long) getDbEntityManager().selectOne("selectTenantCountByQueryCriteria", query); } public List<Tenant> findTenantByQueryCriteria(DbTenantQueryImpl query) { configureQuery(query, Resources.TENANT); return getDbEntityManager().selectList("selectTenantByQueryCriteria", query); } //memberships ////////////////////////////////////////// protected boolean existsMembership(String userId, String groupId) { Map<String, String> key = new HashMap<>(); key.put("userId", userId); key.put("groupId", groupId); return ((Long) getDbEntityManager().selectOne("selectMembershipCount", key)) > 0; } protected boolean existsTenantMembership(String tenantId, String userId, String groupId) { Map<String, String> key = new HashMap<>(); key.put("tenantId", tenantId); if (userId != null) {
key.put("userId", userId); } if (groupId != null) { key.put("groupId", groupId); } return ((Long) getDbEntityManager().selectOne("selectTenantMembershipCount", key)) > 0; } //authorizations //////////////////////////////////////////////////// @Override protected void configureQuery(@SuppressWarnings("rawtypes") AbstractQuery query, Resource resource) { Context.getCommandContext() .getAuthorizationManager() .configureQuery(query, resource); } @Override protected void checkAuthorization(Permission permission, Resource resource, String resourceId) { Context.getCommandContext() .getAuthorizationManager() .checkAuthorization(permission, resource, resourceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbReadOnlyIdentityServiceProvider.java
1
请完成以下Java代码
public class Example { private String name; private Integer n; private Boolean real; public Example() { } public Example(String name, Integer n, Boolean real) { this.name = name; this.n = n; this.real = real; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public Integer getN() { return n; } public void setN(Integer n) { this.n = n; } public Boolean getReal() { return real; } public void setReal(Boolean real) { this.real = real; } }
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\jsonurlreader\data\Example.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hilo") @GenericGenerator(name = "hilo", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "hilo_sequence"), @Parameter(name = "initial_value", value = "1"), @Parameter(name = "increment_size", value = "100"), @Parameter(name = "optimizer", value = "hilo") } ) private Long id; private String name;
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootHiLo\src\main\java\com\bookstore\entity\Author.java
2
请完成以下Java代码
public int getC_PricingRule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_PricingRule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java-Klasse. @param Classname Java-Klasse */ @Override public void setClassname (java.lang.String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitäts-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\pricing\model\X_C_PricingRule.java
1
请在Spring Boot框架中完成以下Java代码
class TransitionService { final ProcessRepository repository; final MongoTemplate template; final AtomicInteger counter = new AtomicInteger(0); public Process newProcess() { return repository.save(new Process(counter.incrementAndGet(), State.CREATED, 0)); } @Transactional public void run(Integer id) { var process = lookup(id); if (!State.CREATED.equals(process.state())) { return; } start(process); verify(process); finish(process);
} private void finish(Process process) { template.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id()))) .apply(Update.update("state", State.DONE).inc("transitionCount", 1)).first(); } void start(Process process) { template.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id()))) .apply(Update.update("state", State.ACTIVE).inc("transitionCount", 1)).first(); } Process lookup(Integer id) { return repository.findById(id).get(); } void verify(Process process) { Assert.state(process.id() % 3 != 0, "We're sorry but we needed to drop that one"); } }
repos\spring-data-examples-main\mongodb\transactions\src\main\java\example\springdata\mongodb\imperative\TransitionService.java
2
请在Spring Boot框架中完成以下Java代码
public PageData<TenantProfile> getTenantProfiles( @Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @Parameter(description = TENANT_PROFILE_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @Parameter(description = SORT_PROPERTY_DESCRIPTION, schema = @Schema(allowableValues = {"createdTime", "name", "description", "isDefault"})) @RequestParam(required = false) String sortProperty, @Parameter(description = SORT_ORDER_DESCRIPTION, schema = @Schema(allowableValues = {"ASC", "DESC"})) @RequestParam(required = false) String sortOrder) throws ThingsboardException { PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); return checkNotNull(tenantProfileService.findTenantProfiles(getTenantId(), pageLink)); } @ApiOperation(value = "Get Tenant Profiles Info (getTenantProfileInfos)", notes = "Returns a page of tenant profile info objects registered in the platform. " + TENANT_PROFILE_INFO_DESCRIPTION + PAGE_DATA_PARAMETERS + SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('SYS_ADMIN')") @GetMapping(value = "/tenantProfileInfos", params = {"pageSize", "page"}) public PageData<EntityInfo> getTenantProfileInfos( @Parameter(description = PAGE_SIZE_DESCRIPTION, required = true)
@RequestParam int pageSize, @Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @Parameter(description = TENANT_PROFILE_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @Parameter(description = SORT_PROPERTY_DESCRIPTION, schema = @Schema(allowableValues = {"id", "name"})) @RequestParam(required = false) String sortProperty, @Parameter(description = SORT_ORDER_DESCRIPTION, schema = @Schema(allowableValues = {"ASC", "DESC"})) @RequestParam(required = false) String sortOrder) throws ThingsboardException { PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); return checkNotNull(tenantProfileService.findTenantProfileInfos(getTenantId(), pageLink)); } @GetMapping(value = "/tenantProfiles", params = {"ids"}) @PreAuthorize("hasAuthority('SYS_ADMIN')") public List<TenantProfile> getTenantProfilesByIds(@Parameter(description = "Comma-separated list of tenant profile ids", array = @ArraySchema(schema = @Schema(type = "string"))) @RequestParam("ids") UUID[] ids) { return tenantProfileService.findTenantProfilesByIds(TenantId.SYS_TENANT_ID, ids); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\TenantProfileController.java
2
请完成以下Java代码
public void setTitle(String title) { this.title = title; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } @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(((Chapter) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseTriggers\src\main\java\com\bookstore\entity\Chapter.java
1
请完成以下Java代码
public User getUserProfile() { try { return facebookClient.fetchObject("me", User.class, Parameter.with("fields", "id,name,email")); } catch (FacebookOAuthException e) { // Handle expired/invalid token logger.log(Level.SEVERE,"Authentication failed: " + e.getMessage()); return null; } catch (FacebookResponseContentException e) { // General API errors logger.log(Level.SEVERE,"API error: " + e.getMessage()); return null; } } public List<User> getFriendList() { try { Connection<User> friendsConnection = facebookClient.fetchConnection("me/friends", User.class); return friendsConnection.getData(); } catch (Exception e) { logger.log(Level.SEVERE,"Error fetching friends list: " + e.getMessage()); return null; } } public String postStatusUpdate(String message) { try { FacebookType response = facebookClient.publish("me/feed", FacebookType.class, Parameter.with("message", message)); return "Post ID: " + response.getId(); } catch (Exception e) { logger.log(Level.SEVERE,"Failed to post status: " + e.getMessage()); return null; } } public void uploadPhotoToFeed() { try (InputStream imageStream = getClass().getResourceAsStream("/static/image.jpg")) { FacebookType response = facebookClient.publish("me/photos", FacebookType.class, BinaryAttachment.with("image.jpg", imageStream), Parameter.with("message", "Uploaded with RestFB"));
logger.log(Level.INFO,"Photo uploaded. ID: " + response.getId()); } catch (IOException e) { logger.log(Level.SEVERE,"Failed to read image file: " + e.getMessage()); } } public String postToPage(String pageId, String message) { try { Page page = facebookClient.fetchObject(pageId, Page.class, Parameter.with("fields", "access_token")); FacebookClient pageClient = new DefaultFacebookClient(page.getAccessToken(), appSecret, Version.LATEST); FacebookType response = pageClient.publish(pageId + "/feed", FacebookType.class, Parameter.with("message", message)); return "Page Post ID: " + response.getId(); } catch (Exception e) { logger.log(Level.SEVERE,"Failed to post to page: " + e.getMessage()); return null; } } }
repos\tutorials-master\libraries-http-3\src\main\java\com\baeldung\facebook\FacebookService.java
1
请完成以下Java代码
public void deBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 System.out.println("URL : " + request.getRequestURL().toString()); System.out.println("HTTP_METHOD : " + request.getMethod()); System.out.println("IP : " + request.getRemoteAddr()); System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 处理完请求,返回内容 System.out.println("方法的返回值 : " + ret); } //后置异常通知 @AfterThrowing("webLog()") public void throwss(JoinPoint jp){ System.out.println("方法异常时执行....."); }
//后置最终通知,final增强,不管是抛出异常或者正常退出都会执行 @After("webLog()") public void after(JoinPoint jp){ System.out.println("方法最后执行....."); } //环绕通知,环绕增强,相当于MethodInterceptor @Around("webLog()") public Object arround(ProceedingJoinPoint pjp) { System.out.println("方法环绕start....."); try { Object o = pjp.proceed(); System.out.println("方法环绕proceed,结果是 :" + o); return o; } catch (Throwable e) { e.printStackTrace(); return null; } } }
repos\SpringBootBucket-master\springboot-aop\src\main\java\com\xncoding\aop\aspect\LogAspect.java
1
请完成以下Java代码
public static String getDecisionRequirementsDiagramResourceName(String dmnFileResource, String decisionKey, String diagramSuffix) { String dmnFileResourceBase = stripDmnFileSuffix(dmnFileResource); return dmnFileResourceBase + decisionKey + "." + diagramSuffix; } /** * Finds the name of a resource for the diagram for a decision definition. Assumes that the decision definition's key and (DMN) resource name are already set. * * @return name of an existing resource, or null if no matching image resource is found in the resources. */ public static String getDecisionRequirementsDiagramResourceNameFromDeployment( DecisionEntity decisionDefinition, Map<String, EngineResource> resources) { if (StringUtils.isEmpty(decisionDefinition.getResourceName())) { throw new IllegalStateException("Provided decision definition must have its resource name set."); } String dmnResourceBase = stripDmnFileSuffix(decisionDefinition.getResourceName()); String key = decisionDefinition.getKey();
for (String diagramSuffix : DIAGRAM_SUFFIXES) { String possibleName = dmnResourceBase + key + "." + diagramSuffix; if (resources.containsKey(possibleName)) { return possibleName; } possibleName = dmnResourceBase + diagramSuffix; if (resources.containsKey(possibleName)) { return possibleName; } } return null; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\ResourceNameUtil.java
1
请完成以下Java代码
private PO load(final Properties ctx, final int id, final String trxName) { if (id < 0) { return null; } // NOTE: we call MTable.getPO because we want to hit the ModelCacheService. // If we are using Query directly then cache won't be asked to retrieve (but it will just be asked to put to cache) if (id == 0) { // FIXME: this is a special case because the system will consider we want a new record. Fix this workaround return new Query(ctx, tableName, loadWhereClause, trxName) .setParameters(id) .firstOnly(PO.class); } else { return TableModelLoader.instance.getPO(ctx, tableName, id, trxName); } } protected abstract int getId(); protected abstract boolean setId(int id); public final String getTableName() { return tableName;
} protected final String getParentColumnName() { return parentColumnName; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("parentColumnName", parentColumnName) .add("tableName", tableName) .add("idColumnName", idColumnName) .add("loadWhereClause", loadWhereClause) .add("po", poRef) .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\AbstractPOCacheLocal.java
1
请完成以下Java代码
public void setOneMinuteException(Long oneMinuteException) { this.oneMinuteException = oneMinuteException; } public Long getOneMinutePass() { return oneMinutePass; } public void setOneMinutePass(Long oneMinutePass) { this.oneMinutePass = oneMinutePass; } public Long getOneMinuteBlock() { return oneMinuteBlock; } public void setOneMinuteBlock(Long oneMinuteBlock) { this.oneMinuteBlock = oneMinuteBlock; }
public Long getOneMinuteTotal() { return oneMinuteTotal; } public void setOneMinuteTotal(Long oneMinuteTotal) { this.oneMinuteTotal = oneMinuteTotal; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\ResourceVo.java
1
请完成以下Java代码
public class GridTabValidationContext implements IValidationContext { private static final transient Logger logger = LogManager.getLogger(GridTabValidationContext.class); private final Properties ctx; private final int windowNo; private final int tabNo; private final String contextTableName; private final String tableName; public GridTabValidationContext(final Properties ctx, final int windowNo, final int tabNo, final String tableName) { Check.assume(ctx != null, "context not null"); // any windowNo, even Env.WINDOW_None is allowed Check.assume(tableName != null, "tableName not null"); if (windowNo == Env.WINDOW_MAIN && tabNo <= 0) { final AdempiereException ex = new AdempiereException("Possible invalid definition of GridTabValidationContext: windowNo=" + windowNo + ", tabNo=" + tabNo + ", tableName=" + tableName); logger.warn(ex.getLocalizedMessage(), ex); } this.ctx = ctx; this.windowNo = windowNo; this.tabNo = tabNo; this.tableName = tableName; final int contextTableId = Env.getContextAsInt(ctx, windowNo, tabNo, GridTab.CTX_AD_Table_ID, true); if (contextTableId <= 0) { this.contextTableName = null; // accept even if there is no tableId found, because maybe we are using the field in custom interfaces // throw new AdempiereException("No AD_Table_ID found for WindowNo=" + windowNo + ", TabNo=" + tabNo); } else { this.contextTableName = Services.get(IADTableDAO.class).retrieveTableName(contextTableId); if (Check.isEmpty(contextTableName, true)) { throw new AdempiereException("No TableName found for AD_Table_ID=" + contextTableId); } }
} @Override public String getTableName() { return tableName; } /** * Gets the context value for the given {@code variableName} by calling {@link Env#getContext(Properties, int, int, String, Scope)} with {@link Scope#Window}. */ @Override public String get_ValueAsString(final String variableName) { Check.assumeNotNull(variableName, "variableName not null"); if(PARAMETER_ContextTableName.equals(variableName)) { return contextTableName; } // only checking the window scope; global scope might contain default values (e.g. #C_DocTypeTarget_ID) that might confuse a validation rule final String value = Env.getContext(ctx, windowNo, tabNo, variableName, Scope.Window); if (Env.isNumericPropertyName(variableName) && Env.isPropertyValueNull(variableName, value)) { // Because empty fields are not exported in context, even if they are present in Tab // is better to return "-1" as default value, to make this explicit // and also to not make Env.parseContext log a WARNING message return "-1"; } return value; } @Override public String toString() { return "GridTabValidationContext [windowNo=" + windowNo + ", tabNo=" + tabNo + ", contextTableName=" + contextTableName + ", tableName=" + tableName + ", ctx=" + ctx + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\GridTabValidationContext.java
1
请完成以下Java代码
public void addVariableData(String variableName, String changeType, String scopeId, String scopeType, String scopeDefinitionId) { if (variableData == null) { variableData = new LinkedHashMap<>(); } if (!variableData.containsKey(variableName)) { variableData.put(variableName, new ArrayList<>()); } VariableListenerSessionData sessionData = new VariableListenerSessionData(changeType, scopeId, scopeType, scopeDefinitionId); variableData.get(variableName).add(sessionData); } @Override public void flush() {
} @Override public void close() { } public Map<String, List<VariableListenerSessionData>> getVariableData() { return variableData; } public void setVariableData(Map<String, List<VariableListenerSessionData>> variableData) { this.variableData = variableData; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variablelistener\VariableListenerSession.java
1
请完成以下Java代码
private void executeAfterFinishSql(@NonNull final I_C_Queue_WorkPackage workPackage) { final String afterFinishSqlRaw = getParameters().getParameterAsString(PARAM_AFTER_FINISH_SQL); if (Check.isEmpty(afterFinishSqlRaw, true)) { return; } final String afterFinishSql = parseSql(afterFinishSqlRaw, workPackage); Loggables.addLog("SQL to execute: {0}", afterFinishSql); final int updateCount = executeSql(afterFinishSql); Loggables.addLog("Updated {0} records", updateCount); } @VisibleForTesting int executeSql(final String sql) { return DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); } private static String parseSql(final String sqlRaw, final I_C_Queue_WorkPackage workpackage)
{ // // Normalize String sql = sqlRaw.trim() .replaceAll("--.*[\r\n\t]", "") // remove one-line-comments (comments within /* and */ are OK) .replaceAll("[\r\n\t]", " "); // replace line-breaks with spaces // // Parse context variables { final IStringExpression sqlExpression = Services.get(IExpressionFactory.class).compile(sql, IStringExpression.class); final Evaluatee evalCtx = Evaluatees.compose(InterfaceWrapperHelper.getEvaluatee(workpackage)); sql = sqlExpression.evaluate(evalCtx, OnVariableNotFound.Fail); } return sql; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\migration\async\ExecuteSQLWorkpackageProcessor.java
1
请完成以下Java代码
private void out(String t) { l.info(t); } private String calcNetHashRate(Block block) { String response = "Net hash rate not available"; if (block.getNumber() > thou) { long timeDelta = 0; for (int i = 0; i < thou; ++i) { Block parent = ethereum .getBlockchain() .getBlockByHash(block.getParentHash()); timeDelta += Math.abs(block.getTimestamp() - parent.getTimestamp()); } response = String.valueOf(block .getDifficultyBI() .divide(BIUtil.toBI(timeDelta / thou)) .divide(new BigInteger("1000000000")) .doubleValue()) + " GH/s"; } return response; } public EthListener(Ethereum ethereum) { this.ethereum = ethereum;
} @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { if (syncDone) { out("Net hash rate: " + calcNetHashRate(block)); out("Block difficulty: " + block.getDifficultyBI().toString()); out("Block transactions: " + block.getTransactionsList().toString()); out("Best block (last block): " + ethereum .getBlockchain() .getBestBlock().toString()); out("Total difficulty: " + ethereum .getBlockchain() .getTotalDifficulty().toString()); } } @Override public void onSyncDone(SyncState state) { out("onSyncDone " + state); if (!syncDone) { out(" ** SYNC DONE ** "); syncDone = true; } } }
repos\tutorials-master\ethereum\src\main\java\com\baeldung\ethereumj\listeners\EthListener.java
1
请完成以下Java代码
public class LoginFilter extends AbstractAuthenticationProcessingFilter { public LoginFilter(String url, AuthenticationManager authManager) { super(new AntPathRequestMatcher(url)); setAuthenticationManager(authManager); } @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException { AccountCredentials creds = new ObjectMapper(). readValue(req.getInputStream(), AccountCredentials.class); return getAuthenticationManager().authenticate( new UsernamePasswordAuthenticationToken(creds.getUsername(),
creds.getPassword(), Collections.emptyList())); } @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException { Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); String tenant = ""; for (GrantedAuthority gauth : authorities) { tenant = gauth.getAuthority(); } AuthenticationService.addToken(res, auth.getName(), tenant.substring(5)); } }
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\multitenant\security\LoginFilter.java
1
请完成以下Java代码
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_TASK_BUSINESS_RULE, BusinessRuleTaskJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { convertersToJsonMap.put(BusinessRuleTask.class, BusinessRuleTaskJsonConverter.class); } protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_BUSINESS_RULE; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { BusinessRuleTask ruleTask = (BusinessRuleTask) baseElement; propertiesNode.put(PROPERTY_RULETASK_CLASS, ruleTask.getClassName()); propertiesNode.put( PROPERTY_RULETASK_VARIABLES_INPUT, convertListToCommaSeparatedString(ruleTask.getInputVariables()) ); propertiesNode.put(PROPERTY_RULETASK_RESULT, ruleTask.getResultVariableName()); propertiesNode.put(PROPERTY_RULETASK_RULES, convertListToCommaSeparatedString(ruleTask.getRuleNames())); if (ruleTask.isExclude()) { propertiesNode.put(PROPERTY_RULETASK_EXCLUDE, PROPERTY_VALUE_YES); } }
protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { BusinessRuleTask task = new BusinessRuleTask(); task.setClassName(getPropertyValueAsString(PROPERTY_RULETASK_CLASS, elementNode)); task.setInputVariables(getPropertyValueAsList(PROPERTY_RULETASK_VARIABLES_INPUT, elementNode)); task.setResultVariableName(getPropertyValueAsString(PROPERTY_RULETASK_RESULT, elementNode)); task.setRuleNames(getPropertyValueAsList(PROPERTY_RULETASK_RULES, elementNode)); task.setExclude(getPropertyValueAsBoolean(PROPERTY_RULETASK_EXCLUDE, elementNode)); return task; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BusinessRuleTaskJsonConverter.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(SubProcess.class, BPMN_ELEMENT_SUB_PROCESS) .namespaceUri(BPMN20_NS) .extendsType(Activity.class) .instanceProvider(new ModelTypeInstanceProvider<SubProcess>() { public SubProcess newInstance(ModelTypeInstanceContext instanceContext) { return new SubProcessImpl(instanceContext); } }); triggeredByEventAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_TRIGGERED_BY_EVENT) .defaultValue(false) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); laneSetCollection = sequenceBuilder.elementCollection(LaneSet.class) .build(); flowElementCollection = sequenceBuilder.elementCollection(FlowElement.class) .build(); artifactCollection = sequenceBuilder.elementCollection(Artifact.class) .build(); /** camunda extensions */ camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC) .namespace(CAMUNDA_NS) .defaultValue(false) .build(); typeBuilder.build(); } public SubProcessImpl(ModelTypeInstanceContext context) { super(context); } public SubProcessBuilder builder() { return new SubProcessBuilder((BpmnModelInstance) modelInstance, this); } public boolean triggeredByEvent() { return triggeredByEventAttribute.getValue(this); }
public void setTriggeredByEvent(boolean triggeredByEvent) { triggeredByEventAttribute.setValue(this, triggeredByEvent); } public Collection<LaneSet> getLaneSets() { return laneSetCollection.get(this); } public Collection<FlowElement> getFlowElements() { return flowElementCollection.get(this); } public Collection<Artifact> getArtifacts() { return artifactCollection.get(this); } /** camunda extensions */ /** * @deprecated use isCamundaAsyncBefore() instead. */ @Deprecated public boolean isCamundaAsync() { return camundaAsyncAttribute.getValue(this); } /** * @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead. */ @Deprecated public void setCamundaAsync(boolean isCamundaAsync) { camundaAsyncAttribute.setValue(this, isCamundaAsync); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SubProcessImpl.java
1
请完成以下Java代码
public String getSkuCode() { return skuCode; } public void setSkuCode(String skuCode) { this.skuCode = skuCode; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public Integer getLowStock() { return lowStock; } public void setLowStock(Integer lowStock) { this.lowStock = lowStock; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Integer getSale() { return sale; } public void setSale(Integer sale) { this.sale = sale; } public BigDecimal getPromotionPrice() { return promotionPrice;
} public void setPromotionPrice(BigDecimal promotionPrice) { this.promotionPrice = promotionPrice; } public Integer getLockStock() { return lockStock; } public void setLockStock(Integer lockStock) { this.lockStock = lockStock; } public String getSpData() { return spData; } public void setSpData(String spData) { this.spData = spData; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", skuCode=").append(skuCode); sb.append(", price=").append(price); sb.append(", stock=").append(stock); sb.append(", lowStock=").append(lowStock); sb.append(", pic=").append(pic); sb.append(", sale=").append(sale); sb.append(", promotionPrice=").append(promotionPrice); sb.append(", lockStock=").append(lockStock); sb.append(", spData=").append(spData); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsSkuStock.java
1
请在Spring Boot框架中完成以下Java代码
public String getMHUPackagingCodeTUText() { return mhuPackagingCodeTUText; } /** * Sets the value of the mhuPackagingCodeTUText property. * * @param value * allowed object is * {@link String } * */ public void setMHUPackagingCodeTUText(String value) { this.mhuPackagingCodeTUText = value; } /** * Gets the value of the line property. * * @return * possible object is * {@link BigInteger }
* */ public BigInteger getLine() { return line; } /** * Sets the value of the line property. * * @param value * allowed object is * {@link BigInteger } * */ public void setLine(BigInteger value) { this.line = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvPackItemType.java
2
请完成以下Java代码
public Set<Map.Entry<String, TriaFrequency>> getTriGram() { return trieTria.entrySet(); } // public static void main(String[] args) // { // Occurrence occurrence = new Occurrence(); // occurrence.addAll("算法工程师\n" + // "算法(Algorithm)是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时间内获得所要求的输出。如果一个算法有缺陷,或不适合于某个问题,执行这个算法将不会解决这个问题。不同的算法可能用不同的时间、空间或效率来完成同样的任务。一个算法的优劣可以用空间复杂度与时间复杂度来衡量。算法工程师就是利用算法处理事物的人。\n" + // "\n" + // "1职位简介\n" + // "算法工程师是一个非常高端的职位;\n" + // "专业要求:计算机、电子、通信、数学等相关专业;\n" + // "学历要求:本科及其以上的学历,大多数是硕士学历及其以上;\n" +
// "语言要求:英语要求是熟练,基本上能阅读国外专业书刊;\n" + // "必须掌握计算机相关知识,熟练使用仿真工具MATLAB等,必须会一门编程语言。\n" + // "\n" + // "2研究方向\n" + // "视频算法工程师、图像处理算法工程师、音频算法工程师 通信基带算法工程师\n" + // "\n" + // "3目前国内外状况\n" + // "目前国内从事算法研究的工程师不少,但是高级算法工程师却很少,是一个非常紧缺的专业工程师。算法工程师根据研究领域来分主要有音频/视频算法处理、图像技术方面的二维信息算法处理和通信物理层、雷达信号处理、生物医学信号处理等领域的一维信息算法处理。\n" + // "在计算机音视频和图形图形图像技术等二维信息算法处理方面目前比较先进的视频处理算法:机器视觉成为此类算法研究的核心;另外还有2D转3D算法(2D-to-3D conversion),去隔行算法(de-interlacing),运动估计运动补偿算法(Motion estimation/Motion Compensation),去噪算法(Noise Reduction),缩放算法(scaling),锐化处理算法(Sharpness),超分辨率算法(Super Resolution),手势识别(gesture recognition),人脸识别(face recognition)。\n" + // "在通信物理层等一维信息领域目前常用的算法:无线领域的RRM、RTT,传送领域的调制解调、信道均衡、信号检测、网络优化、信号分解等。\n" + // "另外数据挖掘、互联网搜索算法也成为当今的热门方向。\n" + // "算法工程师逐渐往人工智能方向发展。"); // occurrence.compute(); // System.out.println(occurrence); // System.out.println(occurrence.getPhraseByScore()); // } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\occurrence\Occurrence.java
1
请完成以下Java代码
public Publisher getPublisher() { return publisher; } public String getName() { return name; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.publisher); hash = 97 * hash + Objects.hashCode(this.name); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) {
return false; } final AuthorId other = (AuthorId) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.publisher, other.publisher)) { return false; } return true; } @Override public String toString() { return "AuthorId{ " + "publisher=" + publisher + ", name=" + name + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddableMapRel\src\main\java\com\bookstore\entity\AuthorId.java
1
请完成以下Java代码
public List<ExecutionListener> getExecutionListeners(String eventName) { List<ExecutionListener> executionListenerList = getExecutionListeners().get(eventName); if (executionListenerList != null) { return executionListenerList; } return Collections.EMPTY_LIST; } public void addExecutionListener(String eventName, ExecutionListener executionListener) { addExecutionListener(eventName, executionListener, -1); } public void addExecutionListener(String eventName, ExecutionListener executionListener, int index) { List<ExecutionListener> listeners = executionListeners.get(eventName); if (listeners == null) { listeners = new ArrayList<>(); executionListeners.put(eventName, listeners); } if (index < 0) { listeners.add(executionListener); } else { listeners.add(index, executionListener);
} } public Map<String, List<ExecutionListener>> getExecutionListeners() { return executionListeners; } // getters and setters ////////////////////////////////////////////////////// @Override public List<ActivityImpl> getActivities() { return activities; } public IOSpecification getIoSpecification() { return ioSpecification; } public void setIoSpecification(IOSpecification ioSpecification) { this.ioSpecification = ioSpecification; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ScopeImpl.java
1
请完成以下Java代码
public boolean isScheduledToMove(@NonNull final HuId huId) { // TODO: only not processed ones return queryBL.createQueryBuilder(I_DD_OrderLine_HU_Candidate.class) .addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_M_HU_ID, huId) .create() .anyMatch(); } public ImmutableList<DDOrderMoveSchedule> getByDDOrderId(final DDOrderId ddOrderId) { return newLoaderAndSaver().loadByDDOrderId(ddOrderId); } public ImmutableList<DDOrderMoveSchedule> getByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds) { return newLoaderAndSaver().loadByDDOrderLineIds(ddOrderLineIds); } public boolean hasInProgressSchedules(@NonNull final DDOrderLineId ddOrderLineId) { return queryBL.createQueryBuilder(I_DD_Order_MoveSchedule.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_DD_OrderLine_ID, ddOrderLineId) .addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_Status, DDOrderMoveScheduleStatus.IN_PROGRESS) .create() .anyMatch(); } public boolean hasInProgressSchedules(final DDOrderId ddOrderId)
{ return queryBL.createQueryBuilder(I_DD_Order_MoveSchedule.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_DD_Order_ID, ddOrderId) .addEqualsFilter(I_DD_Order_MoveSchedule.COLUMNNAME_Status, DDOrderMoveScheduleStatus.IN_PROGRESS) .create() .anyMatch(); } public Set<DDOrderId> retrieveDDOrderIdsInTransit(@NonNull final LocatorId inTransitLocatorId) { return queryInTransitSchedules(inTransitLocatorId) .create() .listDistinctAsImmutableSet(I_DD_OrderLine_HU_Candidate.COLUMNNAME_DD_Order_ID, DDOrderId.class); } public IQueryBuilder<I_DD_OrderLine_HU_Candidate> queryInTransitSchedules(final @NotNull LocatorId inTransitLocatorId) { return queryBL.createQueryBuilder(I_DD_OrderLine_HU_Candidate.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_Status, DDOrderMoveScheduleStatus.IN_PROGRESS) .addEqualsFilter(I_DD_OrderLine_HU_Candidate.COLUMNNAME_InTransit_Locator_ID, inTransitLocatorId) .addNotNull(I_DD_OrderLine_HU_Candidate.COLUMNNAME_M_HU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleRepository.java
1
请完成以下Java代码
public DocTypeSequenceMap retrieveDocTypeSequenceMap(final I_C_DocType docType) { final Properties ctx = InterfaceWrapperHelper.getCtx(docType); final int docTypeId = docType.getC_DocType_ID(); return retrieveDocTypeSequenceMap(ctx, docTypeId); } @Cached(cacheName = I_C_DocType_Sequence.Table_Name + "#by#" + I_C_DocType_Sequence.COLUMNNAME_C_DocType_ID) public DocTypeSequenceMap retrieveDocTypeSequenceMap(@CacheCtx final Properties ctx, final int docTypeId) { final DocTypeSequenceMap.Builder docTypeSequenceMapBuilder = DocTypeSequenceMap.builder(); final I_C_DocType docType = InterfaceWrapperHelper.create(ctx, docTypeId, I_C_DocType.class, ITrx.TRXNAME_None); final DocSequenceId docNoSequenceId = DocSequenceId.ofRepoIdOrNull(docType.getDocNoSequence_ID()); docTypeSequenceMapBuilder.defaultDocNoSequenceId(docNoSequenceId); final List<I_C_DocType_Sequence> docTypeSequenceDefs = Services.get(IQueryBL.class) .createQueryBuilder(I_C_DocType_Sequence.class, ctx, ITrx.TRXNAME_None)
.addEqualsFilter(I_C_DocType_Sequence.COLUMNNAME_C_DocType_ID, docTypeId) .addOnlyActiveRecordsFilter() .create() .list(I_C_DocType_Sequence.class); for (final I_C_DocType_Sequence docTypeSequenceDef : docTypeSequenceDefs) { final ClientId adClientId = ClientId.ofRepoId(docTypeSequenceDef.getAD_Client_ID()); final OrgId adOrgId = OrgId.ofRepoId(docTypeSequenceDef.getAD_Org_ID()); final DocSequenceId docSequenceId = DocSequenceId.ofRepoId(docTypeSequenceDef.getDocNoSequence_ID()); docTypeSequenceMapBuilder.addDocSequenceId(adClientId, adOrgId, docSequenceId); } return docTypeSequenceMapBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocumentSequenceDAO.java
1
请完成以下Java代码
public long getHitCount() { return hitCount.longValue(); } @Override public void incrementHitCount() { hitCount.incrementAndGet(); } @Override public long getHitInTrxCount() { return hitInTrxCount.longValue(); } @Override public void incrementHitInTrxCount() { hitInTrxCount.incrementAndGet(); } @Override public long getMissCount() { return missCount.longValue(); } @Override public void incrementMissCount() { missCount.incrementAndGet(); } @Override public long getMissInTrxCount() {
return missInTrxCount.longValue(); } @Override public void incrementMissInTrxCount() { missInTrxCount.incrementAndGet(); } @Override public boolean isCacheEnabled() { if (cacheConfig != null) { return cacheConfig.isEnabled(); } // if no caching config is provided, it means we are dealing with an overall statistics // so we consider caching as Enabled return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheStatistics.java
1
请在Spring Boot框架中完成以下Java代码
public class UserResponse { protected String id; protected String firstName; protected String lastName; protected String displayName; protected String passWord; protected String url; protected String email; protected String tenantId; protected String pictureUrl; @ApiModelProperty(example = "no-reply@flowable.org") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @ApiModelProperty(example = "http://localhost:8182/identity/users/testuser") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "testuser") public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "Fred") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @ApiModelProperty(example = "Smith") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @ApiModelProperty(example = "Fred Smith") public String getDisplayName() {
return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getPassword() { return passWord; } public void setPassword(String passWord) { this.passWord = passWord; } @JsonInclude(JsonInclude.Include.NON_NULL) @ApiModelProperty(example = "companyTenantId") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "http://localhost:8182/identity/users/testuser/picture") public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserResponse.java
2
请完成以下Java代码
public int getAD_WorkflowProcessorLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_WorkflowProcessorLog_ID); if (ii == null) return 0; return ii.intValue(); } /** Set BinaryData. @param BinaryData Binary Data */ public void setBinaryData (byte[] BinaryData) { set_Value (COLUMNNAME_BinaryData, BinaryData); } /** Get BinaryData. @return Binary Data */ public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Error. @param IsError An Error occured in the execution */ public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Error. @return An Error occured in the execution */ public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Reference. @param Reference Reference for this record */ public void setReference (String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference); } /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WorkflowProcessorLog.java
1
请在Spring Boot框架中完成以下Java代码
public String getTypeName() { return TYPE_NAME; } @Override public void setValue(Object value, ValueFields valueFields) { if (value == null) { valueFields.setCachedValue(null); valueFields.setBytes(null); return; } String textValue = (String) value; lengthVerifier.verifyLength(textValue.length(), valueFields, this); byte[] serializedValue = serialize(textValue, valueFields); valueFields.setBytes(serializedValue);
valueFields.setCachedValue(textValue); } @Override public boolean isAbleToStore(Object value) { if (value == null) { return false; } if (String.class.isAssignableFrom(value.getClass())) { String stringValue = (String) value; return stringValue.length() >= minLength; } return false; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\LongStringType.java
2
请完成以下Java代码
public class StreamRoutingFilter implements GlobalFilter, Ordered { private final StreamBridge streamBridge; private final List<HttpMessageReader<?>> messageReaders; private final SetStatusGatewayFilterFactory setStatusFilter; public StreamRoutingFilter(StreamBridge streamBridge, List<HttpMessageReader<?>> messageReaders) { this.streamBridge = streamBridge; this.messageReaders = messageReaders; // TODO: is this the right place for this? this.streamBridge.setAsync(true); setStatusFilter = new SetStatusGatewayFilterFactory(); } @Override public int getOrder() { return RouteToRequestUrlFilter.ROUTE_TO_URL_FILTER_ORDER + 10; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR); String scheme = requestUrl.getScheme(); if (isAlreadyRouted(exchange) || !"stream".equals(scheme)) { return chain.filter(exchange); } setAlreadyRouted(exchange); ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
return serverRequest.bodyToMono(byte[].class).flatMap(requestBody -> { ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); Message<?> inputMessage = null; MessageBuilder<?> builder = MessageBuilder.withPayload(requestBody); if (!CollectionUtils.isEmpty(request.getQueryParams())) { // TODO: move HeaderUtils builder = builder.setHeader(MessageHeaderUtils.HTTP_REQUEST_PARAM, request.getQueryParams().toSingleValueMap()); // TODO: sanitize? } inputMessage = builder.copyHeaders(headers.toSingleValueMap()).build(); // TODO: output content type boolean send = streamBridge.send(requestUrl.getHost(), inputMessage); HttpStatus responseStatus = (send) ? HttpStatus.OK : HttpStatus.BAD_REQUEST; SetStatusGatewayFilterFactory.Config config = new SetStatusGatewayFilterFactory.Config(); config.setStatus(responseStatus.name()); return setStatusFilter.apply(config).filter(exchange, chain); }); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\StreamRoutingFilter.java
1
请完成以下Java代码
public IEventBus getEventBus(final Topic topic) { assertJUnitTestMode(); return eventBuses.computeIfAbsent(topic, this::createEventBus); } private EventBus createEventBus(final Topic topic) { final MicrometerEventBusStatsCollector micrometerEventBusStatsCollector = EventBusFactory.createMicrometerEventBusStatsCollector(topic, new SimpleMeterRegistry()); final EventBusMonitoringService eventBusMonitoringService = new EventBusMonitoringService(new MicrometerPerformanceMonitoringService(new SimpleMeterRegistry())); final ExecutorService executor = null; return new EventBus(topic, executor, micrometerEventBusStatsCollector, new PlainEventEnqueuer(), eventBusMonitoringService, new EventLogService(new EventLogsRepository())); } @Override public IEventBus getEventBusIfExists(final Topic topic) { assertJUnitTestMode(); return eventBuses.get(topic); } @Override public List<IEventBus> getAllEventBusInstances() { assertJUnitTestMode(); return ImmutableList.copyOf(eventBuses.values()); } @Override public void initEventBussesWithGlobalListeners() { assertJUnitTestMode(); // as of now, no unit test needs an implementation. }
@Override public void destroyAllEventBusses() { assertJUnitTestMode(); // as of now, no unit test needs an implementation. } @Override public void registerGlobalEventListener(final Topic topic, final IEventListener listener) { assertJUnitTestMode(); // as of now, no unit test needs an implementation. } @Override public void addAvailableUserNotificationsTopic(final Topic topic) { assertJUnitTestMode(); // as of now, no unit test needs an implementation. } @Override public void registerUserNotificationsListener(final IEventListener listener) { assertJUnitTestMode(); // as of now, no unit test needs an implementation. } @Override public void unregisterUserNotificationsListener(final IEventListener listener) { assertJUnitTestMode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\PlainEventBusFactory.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Sentry getSentry() { return sentryRefAttribute.getReferenceTargetElement(this); } public void setSentry(Sentry sentry) { sentryRefAttribute.setReferenceTargetElement(this, sentry); }
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Criterion.class, CMMN_ELEMENT_CRITERION) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .abstractType(); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); sentryRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SENTRY_REF) .idAttributeReference(Sentry.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CriterionImpl.java
1
请完成以下Java代码
public List<ObjectNode> getWidgetsConfig() { return getChildObjects("widgets"); } @JsonIgnore private List<ObjectNode> getChildObjects(String propertyName) { return Optional.ofNullable(configuration) .map(config -> config.get(propertyName)) .filter(node -> !node.isEmpty() && (node.isObject() || node.isArray())) .map(node -> Streams.stream(node.elements()) .filter(JsonNode::isObject) .map(jsonNode -> (ObjectNode) jsonNode) .collect(Collectors.toList())) .orElse(Collections.emptyList()); }
@Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Dashboard [tenantId="); builder.append(getTenantId()); builder.append(", title="); builder.append(getTitle()); builder.append(", configuration="); builder.append(configuration); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Dashboard.java
1
请完成以下Java代码
public class MarketDataUtil { public static int encodeAndWrite(ByteBuffer buffer, MarketData marketData) { final int pos = buffer.position(); final UnsafeBuffer directBuffer = new UnsafeBuffer(buffer); final MessageHeaderEncoder headerEncoder = new MessageHeaderEncoder(); final TradeDataEncoder dataEncoder = new TradeDataEncoder(); final BigDecimal priceDecimal = BigDecimal.valueOf(marketData.getPrice()); final int priceMantis = priceDecimal.scaleByPowerOfTen(priceDecimal.scale()) .intValue(); final int priceExponent = priceDecimal.scale() * -1; final TradeDataEncoder encoder = dataEncoder.wrapAndApplyHeader(directBuffer, pos, headerEncoder); encoder.amount(marketData.getAmount()); encoder.quote() .market(marketData.getMarket()) .currency(marketData.getCurrency()) .symbol(marketData.getSymbol()) .price() .mantissa(priceMantis) .exponent((byte) priceExponent); // set position final int encodedLength = headerEncoder.encodedLength() + encoder.encodedLength(); buffer.position(pos + encodedLength); return encodedLength; } public static MarketData readAndDecode(ByteBuffer buffer) { final int pos = buffer.position();
final UnsafeBuffer directBuffer = new UnsafeBuffer(buffer); final MessageHeaderDecoder headerDecoder = new MessageHeaderDecoder(); final TradeDataDecoder dataDecoder = new TradeDataDecoder(); dataDecoder.wrapAndApplyHeader(directBuffer, pos, headerDecoder); // set position final int encodedLength = headerDecoder.encodedLength() + dataDecoder.encodedLength(); buffer.position(pos + encodedLength); final double price = BigDecimal.valueOf(dataDecoder.quote() .price() .mantissa()) .scaleByPowerOfTen(dataDecoder.quote() .price() .exponent()) .doubleValue(); return MarketData.builder() .amount(dataDecoder.amount()) .symbol(dataDecoder.quote() .symbol()) .market(dataDecoder.quote() .market()) .currency(dataDecoder.quote() .currency()) .price(price) .build(); } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketDataUtil.java
1
请完成以下Java代码
public class Main { private static final transient Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { Realm realm = new MyCustomRealm(); SecurityManager securityManager = new DefaultSecurityManager(realm); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("user", "password"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.error("Username Not Found!", uae); } catch (IncorrectCredentialsException ice) { log.error("Invalid Credentials!", ice); } catch (LockedAccountException lae) { log.error("Your Account is Locked!", lae); } catch (AuthenticationException ae) { log.error("Unexpected Error!", ae); } } log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); if (currentUser.hasRole("admin")) { log.info("Welcome Admin"); } else if(currentUser.hasRole("editor")) { log.info("Welcome, Editor!"); } else if(currentUser.hasRole("author")) {
log.info("Welcome, Author"); } else { log.info("Welcome, Guest"); } if(currentUser.isPermitted("articles:compose")) { log.info("You can compose an article"); } else { log.info("You are not permitted to compose an article!"); } if(currentUser.isPermitted("articles:save")) { log.info("You can save articles"); } else { log.info("You can not save articles"); } if(currentUser.isPermitted("articles:publish")) { log.info("You can publish articles"); } else { log.info("You can not publish articles"); } Session session = currentUser.getSession(); session.setAttribute("key", "value"); String value = (String) session.getAttribute("key"); if (value.equals("value")) { log.info("Retrieved the correct value! [" + value + "]"); } currentUser.logout(); System.exit(0); } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\intro\Main.java
1
请完成以下Java代码
public String getCanton() { return canton; } /** * Sets the value of the canton property. * * @param value * allowed object is * {@link String } * */ public void setCanton(String value) { this.canton = value; } /** * Gets the value of the treatment property. * * @return * possible object is * {@link String } * */ public String getTreatment() { if (treatment == null) { return "ambulatory"; } else { return treatment; } } /** * Sets the value of the treatment property. * * @param value * allowed object is * {@link String } * */ public void setTreatment(String value) { this.treatment = value; } /** * Gets the value of the reason property. * * @return * possible object is * {@link String } * */ public String getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link String } * */ public void setReason(String value) { this.reason = value; } /** * Gets the value of the apid property. * * @return * possible object is * {@link String } * */ public String getApid() { return apid; } /**
* Sets the value of the apid property. * * @param value * allowed object is * {@link String } * */ public void setApid(String value) { this.apid = value; } /** * Gets the value of the acid property. * * @return * possible object is * {@link String } * */ public String getAcid() { return acid; } /** * Sets the value of the acid property. * * @param value * allowed object is * {@link String } * */ public void setAcid(String value) { this.acid = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\TreatmentType.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_PO_OrderLine_Alloc_ID (final int C_PO_OrderLine_Alloc_ID) { if (C_PO_OrderLine_Alloc_ID < 1) set_ValueNoCheck (COLUMNNAME_C_PO_OrderLine_Alloc_ID, null); else set_ValueNoCheck (COLUMNNAME_C_PO_OrderLine_Alloc_ID, C_PO_OrderLine_Alloc_ID); } @Override public int getC_PO_OrderLine_Alloc_ID() { return get_ValueAsInt(COLUMNNAME_C_PO_OrderLine_Alloc_ID); } @Override public org.compiere.model.I_C_OrderLine getC_PO_OrderLine() { return get_ValueAsPO(COLUMNNAME_C_PO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_PO_OrderLine(final org.compiere.model.I_C_OrderLine C_PO_OrderLine) { set_ValueFromPO(COLUMNNAME_C_PO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_PO_OrderLine); } @Override public void setC_PO_OrderLine_ID (final int C_PO_OrderLine_ID) { if (C_PO_OrderLine_ID < 1) set_Value (COLUMNNAME_C_PO_OrderLine_ID, null); else set_Value (COLUMNNAME_C_PO_OrderLine_ID, C_PO_OrderLine_ID); } @Override public int getC_PO_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_PO_OrderLine_ID); } @Override public org.compiere.model.I_C_OrderLine getC_SO_OrderLine() {
return get_ValueAsPO(COLUMNNAME_C_SO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_SO_OrderLine(final org.compiere.model.I_C_OrderLine C_SO_OrderLine) { set_ValueFromPO(COLUMNNAME_C_SO_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_SO_OrderLine); } @Override public void setC_SO_OrderLine_ID (final int C_SO_OrderLine_ID) { if (C_SO_OrderLine_ID < 1) set_Value (COLUMNNAME_C_SO_OrderLine_ID, null); else set_Value (COLUMNNAME_C_SO_OrderLine_ID, C_SO_OrderLine_ID); } @Override public int getC_SO_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_SO_OrderLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PO_OrderLine_Alloc.java
1
请完成以下Java代码
public class CollectCountHitPolicyHandler extends AbstractCollectNumberHitPolicyHandler { protected static final HitPolicyEntry HIT_POLICY = new HitPolicyEntry(HitPolicy.COLLECT, BuiltinAggregator.COUNT); @Override public HitPolicyEntry getHitPolicyEntry() { return HIT_POLICY; } @Override protected BuiltinAggregator getAggregator() { return BuiltinAggregator.COUNT; } @Override protected TypedValue aggregateValues(List<TypedValue> values) { return Variables.integerValue(values.size()); } @Override protected Integer aggregateIntegerValues(List<Integer> intValues) {
// not used return 0; } @Override protected Long aggregateLongValues(List<Long> longValues) { // not used return 0L; } @Override protected Double aggregateDoubleValues(List<Double> doubleValues) { // not used return 0.0; } @Override public String toString() { return "CollectCountHitPolicyHandler{}"; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\CollectCountHitPolicyHandler.java
1
请完成以下Java代码
public static boolean lacksRole(String roleName) { return !hasRole(roleName); } /** * 验证当前用户是否属于以下任意一个角色。 * * @param roleNames 角色列表 * @return 属于:true,否则false */ public static boolean hasAnyRoles(String roleNames) { boolean hasAnyRole = false; Subject subject = getSubject(); if (subject != null && roleNames != null && roleNames.length() > 0) { for (String role : roleNames.split(NAMES_DELIMETER)) { if (subject.hasRole(role.trim())) { hasAnyRole = true; break; } } } return hasAnyRole; } /** * 验证当前用户是否拥有指定权限,使用时与lacksPermission 搭配使用 * * @param permission 权限名 * @return 拥有权限:true,否则false */ public static boolean hasPermission(String permission) { return getSubject() != null && permission != null && permission.length() > 0 && getSubject().isPermitted(permission); } /** * 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。 * * @param permission 权限名 * @return 拥有权限:true,否则false */ public static boolean lacksPermission(String permission) { return !hasPermission(permission); } /** * 已认证通过的用户,不包含已记住的用户,这是与user标签的区别所在。与notAuthenticated搭配使用 * * @return 通过身份验证:true,否则false */ public static boolean isAuthenticated() { return getSubject() != null && getSubject().isAuthenticated(); }
/** * 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。。 * * @return 没有通过身份验证:true,否则false */ public static boolean notAuthenticated() { return !isAuthenticated(); } /** * 认证通过或已记住的用户。与guset搭配使用。 * * @return 用户:true,否则 false */ public static boolean isUser() { return getSubject() != null && getSubject().getPrincipal() != null; } /** * 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用 * * @return 访客:true,否则false */ public static boolean isGuest() { return !isUser(); } /** * 输出当前用户信息,通常为登录帐号信息。 * * @return 当前用户信息 */ public static String principal() { if (getSubject() != null) { Object principal = getSubject().getPrincipal(); return principal.toString(); } return ""; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\shiro\ShiroKit.java
1
请在Spring Boot框架中完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() /*.antMatchers("/admin/**").hasRole("ADMIN")//Indicates that the user accessing the URL in the "/admin/**" mode must have the role of ADMIN .antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .anyRequest().authenticated()//Indicates that in addition to the URL pattern defined previously, users must access other URLs after authentication (access after logging in) */ .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O object) { object.setSecurityMetadataSource(cfisms()); object.setAccessDecisionManager(cadm()); return object; } }) .and()
.formLogin() .loginProcessingUrl("/login").permitAll() .and() .csrf().disable(); } @Bean CustomFilterInvocationSecurityMetadataSource cfisms() { return new CustomFilterInvocationSecurityMetadataSource(); } @Bean CustomAccessDecisionManager cadm() { return new CustomAccessDecisionManager(); } }
repos\springboot-demo-master\security\src\main\java\com\et\security\config\WebSecurityConfig.java
2
请完成以下Java代码
public final class JSONDocumentLayoutColumn { static List<JSONDocumentLayoutColumn> ofList(final List<DocumentLayoutColumnDescriptor> columns, final JSONDocumentLayoutOptions jsonOpts) { return columns.stream() .map(column -> of(column, jsonOpts)) .collect(GuavaCollectors.toImmutableList()); } private static JSONDocumentLayoutColumn of(final DocumentLayoutColumnDescriptor column, final JSONDocumentLayoutOptions jsonOpts) { return new JSONDocumentLayoutColumn(column, jsonOpts); } @JsonProperty("elementGroups") @JsonInclude(Include.NON_EMPTY) @Getter private final List<JSONDocumentLayoutElementGroup> elementGroups;
@JsonCreator private JSONDocumentLayoutColumn( @JsonProperty("elementGroups") @Nullable final List<JSONDocumentLayoutElementGroup> elementGroups) { this.elementGroups = elementGroups == null ? ImmutableList.of() : ImmutableList.copyOf(elementGroups); } private JSONDocumentLayoutColumn(final DocumentLayoutColumnDescriptor column, final JSONDocumentLayoutOptions jsonOpts) { elementGroups = JSONDocumentLayoutElementGroup.ofList(column.getElementGroups(), jsonOpts); } Stream<JSONDocumentLayoutElement> streamInlineTabElements() { return getElementGroups().stream().flatMap(JSONDocumentLayoutElementGroup::streamInlineTabElements); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutColumn.java
1
请完成以下Java代码
private I_C_BPartner createNewBPartner(@NonNull final I_I_Pharma_BPartner importRecord) { final I_C_BPartner bpartner = InterfaceWrapperHelper.newInstance(I_C_BPartner.class); bpartner.setAD_Org_ID(importRecord.getAD_Org_ID()); bpartner.setCompanyName(extractCompanyName(importRecord)); bpartner.setIsCompany(true); bpartner.setName(extractCompanyName(importRecord)); bpartner.setName2(importRecord.getb00name2()); bpartner.setName3(importRecord.getb00name3()); bpartner.setIFA_Manufacturer(importRecord.getb00adrnr()); bpartner.setDescription("IFA " + importRecord.getb00adrnr()); bpartner.setIsManufacturer(true); bpartner.setURL(importRecord.getb00homepag()); return bpartner; } private String extractCompanyName(@NonNull final I_I_Pharma_BPartner importRecord) { if (!Check.isEmpty(importRecord.getb00name1(), true)) { return importRecord.getb00name1(); } if (!Check.isEmpty(importRecord.getb00email(), true)) { return importRecord.getb00email(); } if (!Check.isEmpty(importRecord.getb00email2(), true)) { return importRecord.getb00email2(); } return importRecord.getb00adrnr(); } private I_C_BPartner updateExistingBPartner(@NonNull final I_I_Pharma_BPartner importRecord) {
final I_C_BPartner bpartner; bpartner = InterfaceWrapperHelper.create(importRecord.getC_BPartner(), I_C_BPartner.class); if (!Check.isEmpty(importRecord.getb00name1(), true)) { bpartner.setIsCompany(true); bpartner.setCompanyName(importRecord.getb00name1()); bpartner.setName(importRecord.getb00name1()); } if (!Check.isEmpty(importRecord.getb00name2())) { bpartner.setName2(importRecord.getb00name2()); } if (!Check.isEmpty(importRecord.getb00name3())) { bpartner.setName3(importRecord.getb00name3()); } if (!Check.isEmpty(importRecord.getb00adrnr())) { bpartner.setIFA_Manufacturer(importRecord.getb00adrnr()); bpartner.setDescription("IFA " + importRecord.getb00adrnr()); } bpartner.setIsManufacturer(true); if (!Check.isEmpty(importRecord.getb00homepag())) { bpartner.setURL(importRecord.getb00homepag()); } return bpartner; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerImportHelper.java
1
请完成以下Java代码
public boolean isUnconditional() { return !isStdUserWorkflow() && getConditions().isEmpty(); } // isUnconditional public BooleanWithReason checkAllowGoingAwayFrom(final WFActivity fromActivity) { if (isStdUserWorkflow()) { final IDocument document = fromActivity.getDocumentOrNull(); if (document != null) { final String docStatus = document.getDocStatus(); final String docAction = document.getDocAction(); if (!IDocument.ACTION_Complete.equals(docAction) || IDocument.STATUS_Completed.equals(docStatus) || IDocument.STATUS_WaitingConfirmation.equals(docStatus) || IDocument.STATUS_WaitingPayment.equals(docStatus) || IDocument.STATUS_Voided.equals(docStatus) || IDocument.STATUS_Closed.equals(docStatus) || IDocument.STATUS_Reversed.equals(docStatus)) { return BooleanWithReason.falseBecause("document state is not valid for a standard workflow transition (docStatus=" + docStatus + ", docAction=" + docAction + ")"); } } } // No Conditions final ImmutableList<WFNodeTransitionCondition> conditions = getConditions(); if (conditions.isEmpty()) { return BooleanWithReason.trueBecause("no conditions"); } // First condition always AND
boolean ok = conditions.get(0).evaluate(fromActivity); for (int i = 1; i < conditions.size(); i++) { final WFNodeTransitionCondition condition = conditions.get(i); if (condition.isOr()) { ok = ok || condition.evaluate(fromActivity); } else { ok = ok && condition.evaluate(fromActivity); } } // for all conditions return ok ? BooleanWithReason.trueBecause("transition conditions matched") : BooleanWithReason.falseBecause("transition conditions NOT matched"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFNodeTransition.java
1
请在Spring Boot框架中完成以下Java代码
public class Database { String url; String username; String password; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() {
return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\configurationproperties\Database.java
2
请完成以下Java代码
public static <T> Appender<T> compose(Appender<T> one, Appender<T> two) { return one == null ? two : two == null ? one : new CompositeAppender<>(one, two); } /** * Composes an array of {@link Appender Appenders} into a {@link CompositeAppender}. * * This operation is null-safe. * * @param <T> {@link Class type} of the logging events processed by the {@link Appender Appenders}. * @param appenders array of {@link Appender Appenders} to compose; may be {@literal null}. * @return a composition of the array of {@link Appender Appenders}; returns {@literal null} if the array is empty. * @see #compose(Iterable) */ @SuppressWarnings("unchecked") public static <T> Appender<T> compose(Appender<T>... appenders) { List<Appender<T>> resolvedAppenders = appenders != null ? Arrays.asList(appenders) : Collections.emptyList(); return compose(resolvedAppenders); } /** * Composes the {@link Iterable} of {@link Appender Appenders} into a {@link CompositeAppender}. * * This operation is null-safe. * * @param <T> {@link Class type} of the logging events processed by the {@link Appender Appenders}. * @param appenders {@link Iterable} of {@link Appender Appenders} to compose; may be {@literal null}. * @return a composition of the {@link Iterable} of {@link Appender Appenders}; returns {@literal null} * if the {@link Iterable} is {@literal null} or empty. * @see #compose(Appender, Appender) * @see java.lang.Iterable */ public static <T> Appender<T> compose(Iterable<Appender<T>> appenders) { Appender<T> currentAppender = null; appenders = appenders != null ? appenders : Collections::emptyIterator; for (Appender<T> appender : appenders) { currentAppender = compose(currentAppender, appender); } return currentAppender; } /** * Constructs a new instance of {@link CompositeAppender} composed of {@link Appender} one and {@link Appender} two. * * @param one first {@link Appender} in the composite. * @param two second {@link Appender} in the composite. * @see ch.qos.logback.core.Appender */ private CompositeAppender(Appender<T> one, Appender<T> two) { this.one = one; this.two = two; this.name = DEFAULT_NAME; this.started = true; }
protected Appender<T> getAppenderOne() { return this.one; } protected Appender<T> getAppenderTwo() { return this.two; } @Override public void setContext(Context context) { super.setContext(context); getAppenderOne().setContext(context); getAppenderTwo().setContext(context); } @Override public Context getContext() { Context context = super.getContext(); context = context != null ? context : getAppenderOne().getContext(); context = context != null ? context : getAppenderTwo().getContext(); return context; } @Override protected void append(T eventObject) { getAppenderOne().doAppend(eventObject); getAppenderTwo().doAppend(eventObject); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\CompositeAppender.java
1
请完成以下Java代码
final class WarehouseRoutingsIndex { public static final WarehouseRoutingsIndex of(final List<WarehouseRouting> warehouseRoutings) { return new WarehouseRoutingsIndex(warehouseRoutings); } private final ImmutableListMultimap<WarehouseId, String> docBaseTypesByWarehouseId; private WarehouseRoutingsIndex(final List<WarehouseRouting> warehouseRoutings) { docBaseTypesByWarehouseId = warehouseRoutings.stream() .collect(ImmutableListMultimap.toImmutableListMultimap( WarehouseRouting::getWarehouseId, WarehouseRouting::getDocBaseType)); } public boolean isAllowAnyDocType(@NonNull final WarehouseId warehouseId) { // allow any docType if there were no routings defined for given warehouse return getDocBaseTypesForWarehouse(warehouseId).isEmpty(); } private List<String> getDocBaseTypesForWarehouse(final WarehouseId warehouseId) { return docBaseTypesByWarehouseId.get(warehouseId);
} public boolean isDocTypeAllowed(@NonNull final WarehouseId warehouseId, @NonNull final String docBaseType) { if (isAllowAnyDocType(warehouseId)) { return true; } return getDocBaseTypesForWarehouse(warehouseId).contains(docBaseType); } public Set<WarehouseId> getWarehouseIdsAllowedForDocType(final Set<WarehouseId> warehouseIds, final String docBaseType) { return warehouseIds .stream() .filter(warehouseId -> isDocTypeAllowed(warehouseId, docBaseType)) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseRoutingsIndex.java
1
请完成以下Java代码
private static LocalTime parseLocalTime(final String timeStr) { return !Check.isEmpty(timeStr, true) ? LocalTime.parse(timeStr, timeFormatter) : null; } private List<PackageLabels> createDeliveryPackageLabels(final Label goLabels) { return goLabels.getSendung() .stream() .map(goPackageLabels -> createPackageLabels(goPackageLabels)) .collect(ImmutableList.toImmutableList()); } private PackageLabels createPackageLabels(final Label.Sendung goPackageLabels) { final Label.Sendung.PDFs pdfs = goPackageLabels.getPDFs(); return PackageLabels.builder() .orderId(GOUtils.createOrderId(goPackageLabels.getSendungsnummerAX4())) .defaultLabelType(GOPackageLabelType.DIN_A6_ROUTER_LABEL) .label(PackageLabel.builder() .type(GOPackageLabelType.DIN_A4_HWB) .fileName(GOPackageLabelType.DIN_A4_HWB.toString()) .contentType(PackageLabel.CONTENTTYPE_PDF) .labelData(pdfs.getFrachtbrief()) .build()) .label(PackageLabel.builder()
.type(GOPackageLabelType.DIN_A6_ROUTER_LABEL) .fileName(GOPackageLabelType.DIN_A6_ROUTER_LABEL.toString()) .contentType(PackageLabel.CONTENTTYPE_PDF) .labelData(pdfs.getRouterlabel()) .build()) .label(PackageLabel.builder() .type(GOPackageLabelType.DIN_A6_ROUTER_LABEL_ZEBRA) .fileName(GOPackageLabelType.DIN_A6_ROUTER_LABEL_ZEBRA.toString()) .contentType(PackageLabel.CONTENTTYPE_PDF) .labelData(pdfs.getRouterlabelZebra()) .build()) .build(); } @Override public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request) { return JsonDeliveryAdvisorResponse.builder() .requestId(request.getId()) .shipperProduct(JsonShipperProduct.builder() .code(GOShipperProduct.Overnight.getCode()) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GOClient.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean convert(BitSet bitSet) { return bitSet.get(0); } } @ReadingConverter public enum ZonedDateTimeReadConverter implements Converter<LocalDateTime, ZonedDateTime> { INSTANCE; @Override public ZonedDateTime convert(LocalDateTime localDateTime) { // Be aware - we are using the UTC timezone return ZonedDateTime.of(localDateTime, ZoneOffset.UTC); } } @WritingConverter public enum ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, LocalDateTime> { INSTANCE; @Override public LocalDateTime convert(ZonedDateTime zonedDateTime) { return zonedDateTime.toLocalDateTime(); } } @WritingConverter public enum DurationWriteConverter implements Converter<Duration, Long> {
INSTANCE; @Override public Long convert(Duration source) { return source != null ? source.toMillis() : null; } } @ReadingConverter public enum DurationReadConverter implements Converter<Long, Duration> { INSTANCE; @Override public Duration convert(Long source) { return source != null ? Duration.ofMillis(source) : null; } } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\DatabaseConfiguration.java
2
请完成以下Java代码
public void parseIntermediateTimerEventDefinition(Element timerEventDefinition, ActivityImpl timerActivity) { // start and end event listener are set by parseIntermediateCatchEvent() } @Override public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition, ActivityImpl signalActivity) { // start and end event listener are set by parseIntermediateCatchEvent() } @Override public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) { // start and end event listener are set by parseBoundaryEvent() } @Override public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) { } @Override public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); }
@Override public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) { } @Override public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) { } @Override public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) { } @Override public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) { } @Override public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) { } public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) { } @Override public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) { } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventParseListener.java
1
请完成以下Java代码
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) { if (isExportedFromAdonis50(bpmnModel)) { Map<String, DiagramNode> mapOfFixedBounds = new HashMap<String, DiagramNode>(); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); xPath.setNamespaceContext(new Bpmn20NamespaceContext()); for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) { String elementId = entry.getKey(); DiagramNode elementBounds = entry.getValue(); String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])"; try { XPathExpression xPathExpression = xPath.compile(expression); String elementLocalName = xPathExpression.evaluate(bpmnModel); if (!"participant".equals(elementLocalName) && !"lane".equals(elementLocalName) && !"textAnnotation".equals(elementLocalName) && !"group".equals(elementLocalName)) { elementBounds.setX(elementBounds.getX() - elementBounds.getWidth()/2); elementBounds.setY(elementBounds.getY() - elementBounds.getHeight()/2); } } catch (XPathExpressionException e) { throw new ProcessEngineException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e); } mapOfFixedBounds.put(elementId, elementBounds); } return mapOfFixedBounds; } else { return elementBoundsFromBpmnDi; } } protected boolean isExportedFromAdonis50(Document bpmnModel) {
return "ADONIS".equals(bpmnModel.getDocumentElement().getAttribute("exporter")) && "5.0".equals(bpmnModel.getDocumentElement().getAttribute("exporterVersion")); } protected DocumentBuilderFactory getConfiguredDocumentBuilderFactory() { boolean isXxeParsingEnabled = Context.getProcessEngineConfiguration().isEnableXxeProcessing(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Configure XXE Processing try { for (Map.Entry<String, Boolean> feature : XXE_FEATURES.entrySet()) { factory.setFeature(feature.getKey(), isXxeParsingEnabled ^ feature.getValue()); } } catch (Exception e) { throw new ProcessEngineException("Error while configuring BPMN parser.", e); } factory.setXIncludeAware(isXxeParsingEnabled); factory.setExpandEntityReferences(isXxeParsingEnabled); // Get a factory that understands namespaces factory.setNamespaceAware(true); return factory; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\diagram\ProcessDiagramLayoutFactory.java
1
请完成以下Java代码
public void setRequiredInputs(List<InformationRequirement> requiredInputs) { this.requiredInputs = requiredInputs; } public void addRequiredInput(InformationRequirement requiredInput) { this.requiredInputs.add(requiredInput); } public List<AuthorityRequirement> getAuthorityRequirements() { return authorityRequirements; } public void setAuthorityRequirements(List<AuthorityRequirement> authorityRequirements) { this.authorityRequirements = authorityRequirements; } public void addAuthorityRequirement(AuthorityRequirement authorityRequirement) { this.authorityRequirements.add(authorityRequirement); } public Expression getExpression() { return expression; } public void setExpression(Expression expression) { this.expression = expression; }
public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } @JsonIgnore public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\Decision.java
1
请在Spring Boot框架中完成以下Java代码
private void forwardToEventService(ErrorEventProto eventProto, TbCallback callback) { Event event = ErrorEvent.builder() .tenantId(toTenantId(eventProto.getTenantIdMSB(), eventProto.getTenantIdLSB())) .entityId(new UUID(eventProto.getEntityIdMSB(), eventProto.getEntityIdLSB())) .serviceId(eventProto.getServiceId()) .ts(System.currentTimeMillis()) .method(eventProto.getMethod()) .error(eventProto.getError()) .build(); forwardToEventService(event, callback); } private void forwardToEventService(LifecycleEventProto eventProto, TbCallback callback) { Event event = LifecycleEvent.builder() .tenantId(toTenantId(eventProto.getTenantIdMSB(), eventProto.getTenantIdLSB())) .entityId(new UUID(eventProto.getEntityIdMSB(), eventProto.getEntityIdLSB())) .serviceId(eventProto.getServiceId()) .ts(System.currentTimeMillis()) .lcEventType(eventProto.getLcEventType()) .success(eventProto.getSuccess()) .error(StringUtils.isNotEmpty(eventProto.getError()) ? eventProto.getError() : null) .build(); forwardToEventService(event, callback); } private void forwardToEventService(Event event, TbCallback callback) { DonAsynchron.withCallback(actorContext.getEventService().saveAsync(event), result -> callback.onSuccess(), callback::onFailure, actorContext.getDbCallbackExecutor()); } void forwardToRuleEngineCallService(TransportProtos.RestApiCallResponseMsgProto restApiCallResponseMsg, TbCallback callback) { ruleEngineCallService.onQueueMsg(restApiCallResponseMsg, callback); } private void throwNotHandled(Object msg, TbCallback callback) { log.warn("Message not handled: {}", msg);
callback.onFailure(new RuntimeException("Message not handled!")); } private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) { return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB)); } @Override protected void stopConsumers() { super.stopConsumers(); mainConsumer.stop(); mainConsumer.awaitStop(); usageStatsConsumer.stop(); firmwareStatesConsumer.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCoreConsumerService.java
2
请在Spring Boot框架中完成以下Java代码
public String getDeliveryRequirements() { return deliveryRequirements; } /** * Sets the value of the deliveryRequirements property. * * @param value * allowed object is * {@link String } * */ public void setDeliveryRequirements(String value) { this.deliveryRequirements = value; } /** * Gets the value of the despatchPattern property. * * @return * possible object is * {@link String } * */ public String getDespatchPattern() { return despatchPattern; } /** * Sets the value of the despatchPattern property. * * @param value * allowed object is * {@link String } * */ public void setDespatchPattern(String value) { this.despatchPattern = value; } /** * Gets the value of the cumulativeQuantity property. * * @return * possible object is * {@link ConditionalUnitType } * */ public ConditionalUnitType getCumulativeQuantity() { return cumulativeQuantity; } /** * Sets the value of the cumulativeQuantity property. * * @param value * allowed object is * {@link ConditionalUnitType } *
*/ public void setCumulativeQuantity(ConditionalUnitType value) { this.cumulativeQuantity = value; } /** * Gets the value of the planningQuantityExtension property. * * @return * possible object is * {@link PlanningQuantityExtensionType } * */ public PlanningQuantityExtensionType getPlanningQuantityExtension() { return planningQuantityExtension; } /** * Sets the value of the planningQuantityExtension property. * * @param value * allowed object is * {@link PlanningQuantityExtensionType } * */ public void setPlanningQuantityExtension(PlanningQuantityExtensionType value) { this.planningQuantityExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PlanningQuantityType.java
2
请完成以下Java代码
public class SinglyLinkedList<S> { private int size; private Node<S> head = null; private Node<S> tail = null; public boolean isEmpty() { return size() == 0; } public int size() { return size; } public void add(S element) { Node<S> newTail = new Node<>(element); if (head == null) { tail = newTail; head = tail; } else { tail.next = newTail; tail = newTail; } ++size; } public void remove(S element) { if (isEmpty()) { return; } Node<S> previous = null; Node<S> current = head; while (current != null) { if (Objects.equals(element, current.element)) { Node<S> next = current.next; if (isFistNode(current)) { head = next; } else if (isLastNode(current)) { previous.next = null; } else { Node<S> next1 = current.next; previous.next = next1; } --size; break; } previous = current; current = current.next; } } public void removeLast() { if (isEmpty()) { return; } else if (size() == 1) { tail = null; head = null; } else { Node<S> secondToLast = null; Node<S> last = head; while (last.next != null) { secondToLast = last; last = last.next;
} secondToLast.next = null; } --size; } public boolean contains(S element) { if (isEmpty()) { return false; } Node<S> current = head; while (current != null) { if (Objects.equals(element, current.element)) return true; current = current.next; } return false; } private boolean isLastNode(Node<S> node) { return tail == node; } private boolean isFistNode(Node<S> node) { return head == node; } public static class Node<T> { private T element; private Node<T> next; public Node(T element) { this.element = element; } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\linkedlistremove\SinglyLinkedList.java
1
请完成以下Java代码
private boolean validateAllocationLineAmounts(@Nullable final List<JsonPaymentAllocationLine> lines) { return !Check.isEmpty(lines) && lines.stream().anyMatch(line -> Check.isEmpty(line.getAmount())); } private OrgId retrieveOrg(@Nullable final String orgCode) { final Optional<OrgId> orgId; if (Check.isNotBlank(orgCode)) { final OrgQuery query = OrgQuery.builder() .orgValue(orgCode) .build(); orgId = orgDAO.retrieveOrgIdBy(query); } else { orgId = Optional.empty(); } return orgId.orElse(Env.getOrgId()); } private Optional<BPartnerId> retrieveBPartnerId(final IdentifierString bPartnerIdentifierString, final OrgId orgId) { return bpartnerPriceListServicesFacade.getBPartnerId(bPartnerIdentifierString, orgId); } private Optional<InvoiceId> retrieveInvoice(final IdentifierString invoiceIdentifier, final OrgId orgId, final DocBaseAndSubType docType) { final InvoiceQuery invoiceQuery = createInvoiceQuery(invoiceIdentifier).docType(docType).orgId(orgId).build(); return invoiceDAO.retrieveIdByInvoiceQuery(invoiceQuery); } private static InvoiceQuery.InvoiceQueryBuilder createInvoiceQuery(@NonNull final IdentifierString identifierString) { final IdentifierString.Type type = identifierString.getType(); if (IdentifierString.Type.METASFRESH_ID.equals(type)) { return InvoiceQuery.builder().invoiceId(MetasfreshId.toValue(identifierString.asMetasfreshId())); } else if (IdentifierString.Type.EXTERNAL_ID.equals(type)) { return InvoiceQuery.builder().externalId(identifierString.asExternalId()); } else if (IdentifierString.Type.DOC.equals(type)) { return InvoiceQuery.builder().documentNo(identifierString.asDoc()); } else { throw new AdempiereException("Invalid identifierString: " + identifierString); } } private Optional<I_C_Order> getOrderIdFromIdentifier(final IdentifierString orderIdentifier, final OrgId orgId) { return orderDAO.retrieveByOrderCriteria(createOrderQuery(orderIdentifier, orgId));
} private OrderQuery createOrderQuery(final IdentifierString identifierString, final OrgId orgId) { final IdentifierString.Type type = identifierString.getType(); final OrderQuery.OrderQueryBuilder builder = OrderQuery.builder().orgId(orgId); if (IdentifierString.Type.METASFRESH_ID.equals(type)) { return builder .orderId(MetasfreshId.toValue(identifierString.asMetasfreshId())) .build(); } else if (IdentifierString.Type.EXTERNAL_ID.equals(type)) { return builder .externalId(identifierString.asExternalId()) .build(); } else if (IdentifierString.Type.DOC.equals(type)) { return builder .documentNo(identifierString.asDoc()) .build(); } else { throw new AdempiereException("Invalid identifierString: " + identifierString); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\payment\JsonPaymentService.java
1
请完成以下Java代码
public final class DocActionOptionsContext { @NonNull private final UserRolePermissionsKey userRolePermissionsKey; @NonNull private final String tableName; @NonNull private final String docStatus; // NOTE: we are tolerating null/not set C_DocType_ID because not all of our documents have this column. @Nullable private final DocTypeId docTypeId; private final boolean processing; private final String orderType; @NonNull private final SOTrx soTrx;
private String docActionToUse; @NonNull @Default private ImmutableSet<String> docActions = ImmutableSet.of(); @Getter(AccessLevel.NONE) @NonNull private final IValidationContext validationContext; public ClientId getAdClientId() { return getUserRolePermissionsKey().getClientId(); } public String getParameterValue(final String parameterName) { return validationContext.get_ValueAsString(parameterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocActionOptionsContext.java
1
请完成以下Java代码
public String getType() { String structureRef = itemSubjectRef.getStructureRef(); return structureRef.substring(structureRef.indexOf(':') + 1); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ValuedDataObject otherObject = (ValuedDataObject) o; if (!otherObject.getItemSubjectRef().getStructureRef().equals(this.itemSubjectRef.getStructureRef())) {
return false; } if (!otherObject.getId().equals(this.id)) { return false; } if (!otherObject.getName().equals(this.name)) { return false; } if (!otherObject.getValue().equals(this.value.toString())) { return false; } return true; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ValuedDataObject.java
1
请完成以下Java代码
public void warn(int WindowNo, String AD_Message) { logger.warn(AD_Message); } @Override public void warn(int WindowNo, String AD_Message, String message) { logger.warn("" + AD_Message + ": " + message); } @Override public void error(int WIndowNo, String AD_Message) { logger.warn("" + AD_Message); } @Override public void error(int WIndowNo, String AD_Message, String message) { logger.error("" + AD_Message + ": " + message); } @Override public void download(byte[] data, String contentType, String filename) { throw new UnsupportedOperationException("not implemented"); } @Override public void downloadNow(InputStream content, String contentType, String filename) { throw new UnsupportedOperationException("not implemented"); } @Override public String getClientInfo() { // implementation basically copied from SwingClientUI final String javaVersion = System.getProperty("java.version"); return new StringBuilder("!! NO UI REGISTERED YET !!, java.version=").append(javaVersion).toString(); } @Override
public void showWindow(Object model) { throw new UnsupportedOperationException("Not implemented: ClientUI.showWindow()"); } @Override public IClientUIInvoker invoke() { throw new UnsupportedOperationException("not implemented"); } @Override public IClientUIAsyncInvoker invokeAsync() { throw new UnsupportedOperationException("not implemented"); } @Override public void showURL(String url) { System.err.println("Showing URL is not supported on server side: " + url); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\impl\ClientUI.java
1
请完成以下Java代码
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); } public I_M_Product getRelatedProduct() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getRelatedProduct_ID(), get_TrxName()); } /** Set Related Product. @param RelatedProduct_ID Related Product */ public void setRelatedProduct_ID (int RelatedProduct_ID) { if (RelatedProduct_ID < 1) set_ValueNoCheck (COLUMNNAME_RelatedProduct_ID, null); else set_ValueNoCheck (COLUMNNAME_RelatedProduct_ID, Integer.valueOf(RelatedProduct_ID)); } /** Get Related Product. @return Related Product */ public int getRelatedProduct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RelatedProduct_ID); if (ii == null) return 0; return ii.intValue();
} /** RelatedProductType AD_Reference_ID=313 */ public static final int RELATEDPRODUCTTYPE_AD_Reference_ID=313; /** Web Promotion = P */ public static final String RELATEDPRODUCTTYPE_WebPromotion = "P"; /** Alternative = A */ public static final String RELATEDPRODUCTTYPE_Alternative = "A"; /** Supplemental = S */ public static final String RELATEDPRODUCTTYPE_Supplemental = "S"; /** Set Related Product Type. @param RelatedProductType Related Product Type */ public void setRelatedProductType (String RelatedProductType) { set_ValueNoCheck (COLUMNNAME_RelatedProductType, RelatedProductType); } /** Get Related Product Type. @return Related Product Type */ public String getRelatedProductType () { return (String)get_Value(COLUMNNAME_RelatedProductType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RelatedProduct.java
1
请完成以下Java代码
public Image getImage() { //return smile image //java.awt.Toolkit.getDefaultToolkit().getImage(getImageURL()).flush(); //if (smileImage == null) { String src = (String)elem.getAttributes(). getAttribute(HTML.Attribute.SRC); //System.out.println("img load: " + src.substring(4)); URL url = getClass().getClassLoader(). getResource(src.substring(4)); //getResource("at/freecom/apps/images/freecom.gif"); //getResource("javax/swing/text/html/icons/image-delayed.gif"); if (url == null) return null; smileImage = Toolkit.getDefaultToolkit().getImage(url); if (smileImage==null) return null; //forcing image to load synchronously ImageIcon ii = new ImageIcon(); ii.setImage(smileImage); //} return smileImage; } public URL getImageURL() { // here we return url to some image. It might be any // existing image. we need to move ImageView to the // state where it thinks that image was loaded. // ImageView is calling getImage to get image for // measurement and painting when image was loaded
if (false) { return getClass().getClassLoader(). getResource("javax/swing/text/html/icons/image-delayed.gif"); } else { String src = (String)elem.getAttributes(). getAttribute(HTML.Attribute.SRC); //System.out.println("img load: " + src.substring(4)); URL url = getClass().getClassLoader(). getResource(src.substring(4)); if (url != null) { // System.out.println("load image: " + url); return url; } } return null; } private static Image smileImage = null; } private ViewFactory oldFactory; } private static ViewFactory defaultFactory = null; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\FCHtmlEditorKit.java
1
请完成以下Java代码
public boolean isDebugTrxCreateStacktrace() { return getTrxManager().isDebugTrxCreateStacktrace(); } @Override public void setDebugClosedTransactions(boolean enabled) { getTrxManager().setDebugClosedTransactions(enabled); } @Override public boolean isDebugClosedTransactions() { return getTrxManager().isDebugClosedTransactions(); } @Override public String[] getActiveTransactionInfos() { final List<ITrx> trxs = getTrxManager().getActiveTransactionsList(); return toStringArray(trxs); } @Override public String[] getDebugClosedTransactionInfos() { final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions(); return toStringArray(trxs); } private final String[] toStringArray(final List<ITrx> trxs) { if (trxs == null || trxs.isEmpty()) { return new String[] {}; } final String[] arr = new String[trxs.size()]; for (int i = 0; i < trxs.size(); i++) { final ITrx trx = trxs.get(0); if (trx == null) { arr[i] = "null"; } else { arr[i] = trx.toString(); } } return arr; } @Override public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName); } final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx))
{ // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try { rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); } if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
protected void applyFilters(GroupQuery query) { if (id != null) { query.groupId(id); } if (ids != null) { query.groupIdIn(ids); } if (name != null) { query.groupName(name); } if (nameLike != null) { query.groupNameLike(nameLike); } if (type != null) { query.groupType(type); } if (member != null) { query.groupMember(member); } if (tenantId != null) { query.memberOfTenant(tenantId);
} } @Override protected void applySortBy(GroupQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) { query.orderByGroupId(); } else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) { query.orderByGroupName(); } else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) { query.orderByGroupType(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupQueryDto.java
1
请完成以下Java代码
protected <T> HttpClientResponseHandler<T> handleResponse(final Class<T> responseClass) { return new AbstractHttpClientResponseHandler<>() { public T handleEntity(HttpEntity responseEntity) throws IOException { T response = null; if (responseClass.isAssignableFrom(byte[].class)) { InputStream inputStream = null; try { inputStream = responseEntity.getContent(); response = (T) IoUtil.inputStreamAsByteArray(inputStream); } finally { IoUtil.closeSilently(inputStream); } } else if (!responseClass.isAssignableFrom(Void.class)) { response = deserializeResponse(responseEntity, responseClass); } try { EntityUtils.consume(responseEntity); } catch (IOException e) { LOG.exceptionWhileClosingResourceStream(response, e); } return response; } @Override public T handleResponse(ClassicHttpResponse response) throws IOException { final StatusLine statusLine = new StatusLine(response); final HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { try { RestException engineException = deserializeResponse(entity, EngineRestExceptionDto.class).toRestException(); int statusCode = statusLine.getStatusCode(); engineException.setHttpStatusCode(statusCode); throw engineException; } finally { EntityUtils.consume(entity); } }
return entity == null ? null : handleEntity(entity); } }; } protected <T> T deserializeResponse(HttpEntity httpEntity, Class<T> responseClass) { InputStream inputStream = null; try { inputStream = httpEntity.getContent(); return objectMapper.readValue(inputStream, responseClass); } catch (JsonParseException e) { throw LOG.exceptionWhileParsingJsonObject(responseClass, e); } catch (JsonMappingException e) { throw LOG.exceptionWhileMappingJsonObject(responseClass, e); } catch (IOException e) { throw LOG.exceptionWhileDeserializingJsonObject(responseClass, e); } finally { IoUtil.closeSilently(inputStream); } } protected ByteArrayEntity serializeRequest(RequestDto dto) { byte[] serializedRequest; try { serializedRequest = objectMapper.writeValueAsBytes(dto); } catch (JsonProcessingException e) { throw LOG.exceptionWhileSerializingJsonObject(dto, e); } ByteArrayEntity byteArrayEntity = null; if (serializedRequest != null) { byteArrayEntity = new ByteArrayEntity(serializedRequest, ContentType.APPLICATION_JSON); } return byteArrayEntity; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\RequestExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class PageDescriptor { PageIdentifier pageIdentifier; int offset; int pageSize; int totalSize; Instant selectionTime; public static PageDescriptor createNew( @NonNull final String querySelectionUUID, final int pageSize, final int totalSize, @NonNull final Instant selectionTime) { return new PageDescriptor( querySelectionUUID, UIDStringUtil.createNext(), 0, pageSize, totalSize, selectionTime); } /** Create another page descriptor for the next page. */ public PageDescriptor createNext() { return PageDescriptor.builder() .selectionUid(pageIdentifier.getSelectionUid()) .pageUid(UIDStringUtil.createNext()) .offset(offset + pageSize) .pageSize(pageSize) .totalSize(totalSize) .selectionTime(selectionTime) .build(); } @Builder private PageDescriptor( @NonNull final String selectionUid,
@NonNull final String pageUid, final int offset, final int pageSize, final int totalSize, @NonNull final Instant selectionTime) { assumeNotEmpty(selectionUid, "Param selectionUid may not be empty"); assumeNotEmpty(pageUid, "Param selectionUid may not be empty"); this.pageIdentifier = PageIdentifier.builder() .selectionUid(selectionUid) .pageUid(pageUid) .build(); this.offset = offset; this.pageSize = pageSize; this.totalSize = totalSize; this.selectionTime = selectionTime; } public PageDescriptor withSize(final int adjustedSize) { if (pageSize == adjustedSize) { return this; } return PageDescriptor.builder() .selectionUid(pageIdentifier.getSelectionUid()) .pageUid(pageIdentifier.getPageUid()) .offset(offset) .pageSize(adjustedSize) .totalSize(totalSize) .selectionTime(selectionTime) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\PageDescriptor.java
2
请完成以下Java代码
public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { return ImmutableList.of(); } @Override public Stream<PickingSlotRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public ViewId getIncludedViewId(final IViewRow row) { final PackingHUsViewKey key = extractPackingHUsViewKey(PickingSlotRow.cast(row)); return key.getPackingHUsViewId(); } private PackingHUsViewKey extractPackingHUsViewKey(final PickingSlotRow row) { final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(row.getPickingSlotRowId()); return PackingHUsViewKey.builder() .pickingSlotsClearingViewIdPart(getViewId().getViewIdPart()) .bpartnerId(rootRow.getBPartnerId()) .bpartnerLocationId(rootRow.getBPartnerLocationId()) .build(); } public Optional<HUEditorView> getPackingHUsViewIfExists(final ViewId packingHUsViewId) { final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId); return packingHUsViewsCollection.getByKeyIfExists(key);
} public Optional<HUEditorView> getPackingHUsViewIfExists(final PickingSlotRowId rowId) { final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(rowId); final PackingHUsViewKey key = extractPackingHUsViewKey(rootRow); return packingHUsViewsCollection.getByKeyIfExists(key); } public HUEditorView computePackingHUsViewIfAbsent(@NonNull final ViewId packingHUsViewId, @NonNull final PackingHUsViewSupplier packingHUsViewFactory) { return packingHUsViewsCollection.computeIfAbsent(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsViewFactory); } public void setPackingHUsView(@NonNull final HUEditorView packingHUsView) { final ViewId packingHUsViewId = packingHUsView.getViewId(); packingHUsViewsCollection.put(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsView); } void closePackingHUsView(final ViewId packingHUsViewId, final ViewCloseAction closeAction) { final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId); packingHUsViewsCollection.removeIfExists(key) .ifPresent(packingHUsView -> packingHUsView.close(closeAction)); } public void handleEvent(final HUExtractedFromPickingSlotEvent event) { packingHUsViewsCollection.handleEvent(event); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PickingSlotsClearingView.java
1
请完成以下Java代码
public void setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID) { if (WEBUI_Board_CardField_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID); } @Override public int getWEBUI_Board_CardField_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); }
@Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java
1
请在Spring Boot框架中完成以下Java代码
private void applyKafkaConnectionDetailsForAdmin(Map<String, Object> properties, KafkaConnectionDetails connectionDetails) { Configuration admin = connectionDetails.getAdmin(); properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, admin.getBootstrapServers()); applySecurityProtocol(properties, admin.getSecurityProtocol()); applySslBundle(properties, admin.getSslBundle()); } static BackOff getBackOff(Backoff retryTopicBackoff) { PropertyMapper map = PropertyMapper.get(); RetryPolicy.Builder builder = RetryPolicy.builder().maxRetries(Long.MAX_VALUE); map.from(retryTopicBackoff.getDelay()).to(builder::delay); map.from(retryTopicBackoff.getMaxDelay()).when(Predicate.not(Duration::isZero)).to(builder::maxDelay); map.from(retryTopicBackoff.getMultiplier()).to(builder::multiplier); map.from(retryTopicBackoff.getJitter()).when((Predicate.not(Duration::isZero))).to(builder::jitter); return builder.build().getBackOff(); } static void applySslBundle(Map<String, Object> properties, @Nullable SslBundle sslBundle) { if (sslBundle != null) { properties.put(SslConfigs.SSL_ENGINE_FACTORY_CLASS_CONFIG, SslBundleSslEngineFactory.class); properties.put(SslBundle.class.getName(), sslBundle); } } static void applySecurityProtocol(Map<String, Object> properties, @Nullable String securityProtocol) {
if (StringUtils.hasLength(securityProtocol)) { properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol); } } static class KafkaRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection().registerType(SslBundleSslEngineFactory.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaAutoConfiguration.java
2
请完成以下Java代码
public void failedAcquisitionLocks(String processEngine, AcquiredJobs acquiredJobs) { logDebug("033", "Jobs failed to Lock during Acquisition of jobs for the process engine '{}' : {}", processEngine, acquiredJobs.getNumberOfJobsFailedToLock()); } public void jobsToAcquire(String processEngine, int numJobsToAcquire) { logDebug("034", "Attempting to acquire {} jobs for the process engine '{}'", numJobsToAcquire, processEngine); } public void rejectedJobExecutions(String processEngine, int numJobsRejected) { logDebug("035", "Jobs execution rejections for the process engine '{}' : {}", processEngine, numJobsRejected); } public void availableJobExecutionThreads(String processEngine, int numAvailableThreads) { logDebug("036", "Available job execution threads for the process engine '{}' : {}", processEngine, numAvailableThreads); } public void currentJobExecutions(String processEngine, int numExecutions) { logDebug("037", "Jobs currently in execution for the process engine '{}' : {}", processEngine, numExecutions); }
public void numJobsInQueue(String processEngine, int numJobsInQueue, int maxQueueSize) { logDebug("038", "Jobs currently in queue to be executed for the process engine '{}' : {} (out of the max queue size : {})", processEngine, numJobsInQueue, maxQueueSize); } public void availableThreadsCalculationError() { logDebug("039", "Arithmetic exception occurred while computing remaining available thread count for logging."); } public void totalQueueCapacityCalculationError() { logDebug("040", "Arithmetic exception occurred while computing total queue capacity for logging."); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutorLogger.java
1
请完成以下Java代码
public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Use Ad. @param IsUseAd Whether or not this templates uses Ad's */ public void setIsUseAd (boolean IsUseAd) { set_Value (COLUMNNAME_IsUseAd, Boolean.valueOf(IsUseAd)); } /** Get Use Ad. @return Whether or not this templates uses Ad's */ public boolean isUseAd () { Object oo = get_Value(COLUMNNAME_IsUseAd); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Valid. @param IsValid Element is valid */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Valid. @return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now.
@param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set TemplateXST. @param TemplateXST Contains the template code itself */ public void setTemplateXST (String TemplateXST) { set_Value (COLUMNNAME_TemplateXST, TemplateXST); } /** Get TemplateXST. @return Contains the template code itself */ public String getTemplateXST () { return (String)get_Value(COLUMNNAME_TemplateXST); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template.java
1
请在Spring Boot框架中完成以下Java代码
public class ActiveMqListenerConfig { @Value("${tradeQueueName.notify}") private String tradeQueueDestinationName; /** * 队列目的地 * * @return 队列目的地 */ @Bean(name = "tradeQueueDestination") public ActiveMQQueue tradeQueueDestination() { return new ActiveMQQueue(tradeQueueDestinationName); } /**
* 消息监听容器 * * @param singleConnectionFactory 连接工厂 * @param tradeQueueDestination 消息目的地 * @param consumerSessionAwareMessageListener 监听器实现 * @return 消息监听容器 */ @Bean(name = "tradeQueueMessageListenerContainer") public DefaultMessageListenerContainer tradeQueueMessageListenerContainer(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory, @Qualifier("tradeQueueDestination") ActiveMQQueue tradeQueueDestination, @Qualifier("consumerSessionAwareMessageListener") ConsumerSessionAwareMessageListener consumerSessionAwareMessageListener) { DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(); messageListenerContainer.setConnectionFactory(singleConnectionFactory); messageListenerContainer.setMessageListener(consumerSessionAwareMessageListener); messageListenerContainer.setDestination(tradeQueueDestination); return messageListenerContainer; } }
repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\config\ActiveMqListenerConfig.java
2
请完成以下Java代码
public class MigrationExecutorContext implements IMigrationExecutorContext { private final Properties ctx; private final IMigrationExecutorProvider factory; private boolean failOnFirstError = true; private MigrationOperation migrationOperation = MigrationOperation.BOTH; private final List<IPostponedExecutable> postponedExecutables = new ArrayList<IPostponedExecutable>(); public MigrationExecutorContext(final Properties ctx, final IMigrationExecutorProvider factory) { this.ctx = ctx; this.factory = factory; } @Override public Properties getCtx() { return ctx; } @Override public boolean isFailOnFirstError() { return failOnFirstError; } @Override public void setFailOnFirstError(final boolean failOnFirstError) { this.failOnFirstError = failOnFirstError; } @Override public IMigrationExecutorProvider getMigrationExecutorProvider() { return factory; } @Override public void setMigrationOperation(MigrationOperation operation) { Check.assumeNotNull(operation, "operation not null"); this.migrationOperation = operation;
} @Override public boolean isApplyDML() { return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DML; } @Override public boolean isApplyDDL() { return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DDL; } @Override public boolean isSkipMissingColumns() { // TODO configuration to be implemented return true; } @Override public boolean isSkipMissingTables() { // TODO configuration to be implemented return true; } @Override public void addPostponedExecutable(IPostponedExecutable executable) { Check.assumeNotNull(executable, "executable not null"); postponedExecutables.add(executable); } @Override public List<IPostponedExecutable> popPostponedExecutables() { final List<IPostponedExecutable> result = new ArrayList<IPostponedExecutable>(postponedExecutables); postponedExecutables.clear(); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutorContext.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, Boolean> getEnable() { return this.enable; } public void setEnable(Map<String, Boolean> enable) { this.enable = enable; } public Http getHttp() { return this.http; } public Map<String, String> getKeyValues() { return this.keyValues; } public void setKeyValues(Map<String, String> keyValues) { this.keyValues = keyValues; } public static class Http { private final Client client = new Client(); private final Server server = new Server(); public Client getClient() { return this.client; } public Server getServer() { return this.server; } public static class Client { private final ClientRequests requests = new ClientRequests(); public ClientRequests getRequests() { return this.requests; } public static class ClientRequests { /** * Name of the observation for client requests. */ private String name = "http.client.requests"; public String getName() { return this.name; } public void setName(String name) { this.name = name; } } } public static class Server {
private final ServerRequests requests = new ServerRequests(); public ServerRequests getRequests() { return this.requests; } public static class ServerRequests { /** * Name of the observation for server requests. */ private String name = "http.server.requests"; public String getName() { return this.name; } public void setName(String name) { this.name = name; } } } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public List<Object> getList() { return list; } public void setList(List<Object> list) { this.list = list; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } @Override public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Person\":{" ); sb.append( "\"lastName\":\"" ) .append( lastName ).append( '\"' ); sb.append( ",\"age\":" ) .append( age ); sb.append( ",\"boss\":" ) .append( boss ); sb.append( ",\"birth\":\"" ) .append( birth ).append( '\"' ); sb.append( ",\"map\":" ) .append( map ); sb.append( ",\"list\":" ) .append( list ); sb.append( ",\"dog\":" ) .append( dog ); sb.append( "}}" ); return sb.toString(); } }
repos\SpringBootLearning-master (1)\springboot-config\src\main\java\com\gf\entity\Person.java
2
请完成以下Java代码
public DocumentEntityDataBindingDescriptor getOrBuild() { return dataBinding; } } public static final class ASIAttributeFieldBinding implements DocumentFieldDataBindingDescriptor { private final AttributeId attributeId; private final String attributeName; private final boolean mandatory; private final Function<I_M_AttributeInstance, Object> readMethod; private final BiConsumer<I_M_AttributeInstance, IDocumentFieldView> writeMethod; private ASIAttributeFieldBinding( @NonNull final AttributeId attributeId, final String attributeName, final boolean mandatory, final Function<I_M_AttributeInstance, Object> readMethod, final BiConsumer<I_M_AttributeInstance, IDocumentFieldView> writeMethod) { this.attributeId = attributeId; Check.assumeNotEmpty(attributeName, "attributeName is not empty"); this.attributeName = attributeName; this.mandatory = mandatory; Check.assumeNotNull(readMethod, "Parameter readMethod is not null"); this.readMethod = readMethod; Check.assumeNotNull(writeMethod, "Parameter writeMethod is not null"); this.writeMethod = writeMethod; } @Override public String getColumnName() { return attributeName; } @Override public boolean isMandatory() { return mandatory; } public Object readValue(final I_M_AttributeInstance ai) { return readMethod.apply(ai); }
private void writeValue(final I_M_AttributeInstance ai, final IDocumentFieldView field) { writeMethod.accept(ai, field); } private static void writeValueFromLookup(final I_M_AttributeInstance ai, final IDocumentFieldView field, boolean isNumericKey) { final LookupValue lookupValue = isNumericKey ? field.getValueAs(IntegerLookupValue.class) : field.getValueAs(StringLookupValue.class); final AttributeValueId attributeValueId = field.getDescriptor().getLookupDescriptor() .orElseThrow(() -> new AdempiereException("No lookup defined for " + field)) .cast(ASILookupDescriptor.class) .getAttributeValueId(lookupValue); ai.setValueNumber(lookupValue != null && isNumericKey ? BigDecimal.valueOf(lookupValue.getIdAsInt()) : null); // IMPORTANT: always setValueNumber before setValue because setValueNumber is overriden and set the Value string too. wtf?! ai.setValue(lookupValue == null ? null : lookupValue.getIdAsString()); ai.setM_AttributeValue_ID(AttributeValueId.toRepoId(attributeValueId)); } public I_M_AttributeInstance createAndSaveM_AttributeInstance(final I_M_AttributeSetInstance asiRecord, final IDocumentFieldView asiField) { final I_M_AttributeInstance aiRecord = InterfaceWrapperHelper.newInstance(I_M_AttributeInstance.class, asiRecord); aiRecord.setM_AttributeSetInstance(asiRecord); aiRecord.setM_Attribute_ID(attributeId.getRepoId()); writeValue(aiRecord, asiField); InterfaceWrapperHelper.save(aiRecord); return aiRecord; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIDescriptorFactory.java
1