instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public org.compiere.model.I_AD_PrintFormat getRfQ_Win_PrintFormat() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class); } @Override public void setRfQ_Win_PrintFormat(org.compiere.model.I_AD_PrintFormat RfQ_Win_PrintFormat) { set_ValueFromPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, RfQ_Win_PrintFormat); } /** Set RfQ Won Druck - Format. @param RfQ_Win_PrintFormat_ID RfQ Won Druck - Format */ @Override public void setRfQ_Win_PrintFormat_ID (int RfQ_Win_PrintFormat_ID) { if (RfQ_Win_PrintFormat_ID < 1) set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, null); else set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, Integer.valueOf(RfQ_Win_PrintFormat_ID)); } /** Get RfQ Won Druck - Format. @return RfQ Won Druck - Format */ @Override public int getRfQ_Win_PrintFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_PrintFormat_ID); if (ii == null) return 0;
return ii.intValue(); } /** * RfQType AD_Reference_ID=540661 * Reference name: RfQType */ public static final int RFQTYPE_AD_Reference_ID=540661; /** Default = D */ public static final String RFQTYPE_Default = "D"; /** Procurement = P */ public static final String RFQTYPE_Procurement = "P"; /** Set Ausschreibung Art. @param RfQType Ausschreibung Art */ @Override public void setRfQType (java.lang.String RfQType) { set_Value (COLUMNNAME_RfQType, RfQType); } /** Get Ausschreibung Art. @return Ausschreibung Art */ @Override public java.lang.String getRfQType () { return (java.lang.String)get_Value(COLUMNNAME_RfQType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_Topic.java
1
请完成以下Java代码
public String getFoosAsJsonFromREST() { return "Get some Foos with Header New"; } // advanced - multiple mappings @RequestMapping(value = { "/advanced/bars", "/advanced/foos" }) @ResponseBody public String getFoosOrBarsByPath() { return "Advanced - Get some Foos or Bars"; } @RequestMapping(value = "*") @ResponseBody public String getFallback() { return "Fallback for GET Requests"; } @RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String allFallback() { return "Fallback for All Requests"; } @RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST }) @ResponseBody public String putAndPostFoos() { return "Advanced - PUT and POST within single method"; } // --- Ambiguous Mapping
@GetMapping(value = "foos/duplicate" ) public ResponseEntity<String> duplicate() { return new ResponseEntity<>("Duplicate", HttpStatus.OK); } // uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping // @GetMapping(value = "foos/duplicate" ) // public String duplicateEx() { // return "Duplicate"; // } @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_XML_VALUE) public ResponseEntity<String> duplicateXml() { return new ResponseEntity<>("<message>Duplicate</message>", HttpStatus.OK); } @GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> duplicateJson() { return new ResponseEntity<>("{\"message\":\"Duplicate\"}", HttpStatus.OK); } }
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requestmapping\FooMappingExamplesController.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderRequest { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne(cascade = { CascadeType.REMOVE, CascadeType.PERSIST }) private ShipmentInfo shipmentInfo; @OneToMany(orphanRemoval = true, cascade = CascadeType.PERSIST, mappedBy = "orderRequest") private List<LineItem> lineItems; public OrderRequest(ShipmentInfo shipmentInfo) { this.shipmentInfo = shipmentInfo; }
public OrderRequest(List<LineItem> lineItems) { this.lineItems = lineItems; } public void removeLineItem(LineItem lineItem) { lineItems.remove(lineItem); } public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; } protected OrderRequest() { } }
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\removal\OrderRequest.java
2
请完成以下Java代码
public void setLength(final @Nullable BigDecimal Length) { set_Value(COLUMNNAME_Length, Length); } @Override public BigDecimal getLength() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxVolume(final BigDecimal MaxVolume) { set_Value(COLUMNNAME_MaxVolume, MaxVolume); } @Override public BigDecimal getMaxVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxVolume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxWeight(final BigDecimal MaxWeight) { set_Value(COLUMNNAME_MaxWeight, MaxWeight); } @Override public BigDecimal getMaxWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_PackagingContainer_ID(final int M_PackagingContainer_ID) { if (M_PackagingContainer_ID < 1) set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, null); else set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, M_PackagingContainer_ID); } @Override public int getM_PackagingContainer_ID() { return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_ID); } @Override public void setM_Product_ID(final int M_Product_ID) { if (M_Product_ID < 1) set_Value(COLUMNNAME_M_Product_ID, null); else set_Value(COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() {
return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName(final java.lang.String Name) { set_Value(COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue(final @Nullable java.lang.String Value) { set_Value(COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWidth(final @Nullable BigDecimal Width) { set_Value(COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
1
请完成以下Java代码
private AbstractStub<?> createStub(final Class<? extends AbstractStub<?>> stubClass, final Channel channel) { final StubFactory factory = getStubFactories().stream() .filter(stubFactory -> stubFactory.isApplicable(stubClass)) .findFirst() .orElseThrow(() -> new BeanInstantiationException(stubClass, "Unsupported stub type: " + stubClass.getName() + " -> Please report this issue.")); try { return factory.createStub(stubClass, channel); } catch (final Exception exception) { throw new BeanInstantiationException(stubClass, "Failed to create gRPC stub of type " + stubClass.getName(), exception); } } /** * Lazy getter for the list of defined {@link StubFactory} beans. * * @return A list of all defined {@link StubFactory} beans. */ private List<StubFactory> getStubFactories() { if (this.stubFactories == null) { this.stubFactories = new ArrayList<>(this.applicationContext.getBeansOfType(StubFactory.class).values()); this.stubFactories.add(new FallbackStubFactory()); } return this.stubFactories; } /** * Lazy factory getter from the context for bean registration with {@link GrpcClientBean} annotations. * * @return configurable bean factory */ private ConfigurableListableBeanFactory getConfigurableBeanFactory() { if (this.configurableBeanFactory == null) { this.configurableBeanFactory = ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory(); }
return this.configurableBeanFactory; } /** * Gets the bean name from the given annotation. * * @param grpcClientBean The annotation to extract it from. * @return The extracted name. */ private String getBeanName(final GrpcClientBean grpcClientBean) { if (!grpcClientBean.beanName().isEmpty()) { return grpcClientBean.beanName(); } else { return grpcClientBean.client().value() + grpcClientBean.clazz().getSimpleName(); } } /** * Checks whether the given class is annotated with {@link Configuration}. * * @param clazz The class to check. * @return True, if the given class is annotated with {@link Configuration}. False otherwise. */ private boolean isAnnotatedWithConfiguration(final Class<?> clazz) { final Configuration configurationAnnotation = AnnotationUtils.findAnnotation(clazz, Configuration.class); return configurationAnnotation != null; } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\inject\GrpcClientBeanPostProcessor.java
1
请完成以下Java代码
void setBaseAmt(@NonNull final BigDecimal baseAmt) { this.baseAmt = baseAmt; } void setPriceAndQty( @NonNull final BigDecimal price, @NonNull final Quantity qtyEntered, @NonNull final CurrencyPrecision amountPrecision) { Check.assumeEquals(qtyEntered.getUomId(), this.uomId, "Param qtyEntered needs to have UomId={}; qtyEntered={}", this.uomId, qtyEntered); this.price = price; this.qtyEntered = qtyEntered.toBigDecimal(); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(qtyEntered, getProductId());
this.lineNetAmt = price.multiply(qtyInProductUOM.toBigDecimal()); this.lineNetAmt = amountPrecision.roundIfNeeded(this.lineNetAmt); } public boolean isGeneratedLine() { return OrderGroupCompensationUtils.isGeneratedLine(getGroupTemplateLineId()); } public boolean isManualLine() { return !isGeneratedLine(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupCompensationLine.java
1
请完成以下Java代码
public class Department extends AbstractAuditModel { /** * 部门名 */ @Column(name = "name", columnDefinition = "varchar(255) not null") private String name; /** * 上级部门id */ @ManyToOne(cascade = {CascadeType.REFRESH}, optional = true) @JoinColumn(name = "superior", referencedColumnName = "id") private Department superior; /** * 所属层级 */ @Column(name = "levels", columnDefinition = "int not null default 0") private Integer levels; /** * 排序
*/ @Column(name = "order_no", columnDefinition = "int not null default 0") private Integer orderNo; /** * 子部门集合 */ @OneToMany(cascade = {CascadeType.REFRESH, CascadeType.REMOVE}, fetch = FetchType.EAGER, mappedBy = "superior") private Collection<Department> children; /** * 部门下用户集合 */ @ManyToMany(mappedBy = "departmentList") private Collection<User> userList; }
repos\spring-boot-demo-master\demo-orm-jpa\src\main\java\com\xkcoding\orm\jpa\entity\Department.java
1
请在Spring Boot框架中完成以下Java代码
private String getGLNFromBusinessEntityType(@NonNull final BusinessEntityType businessEntityType) { if (Check.isNotBlank(businessEntityType.getGLN())) { return GLN_PREFIX + businessEntityType.getGLN(); } final String gln = businessEntityType.getFurtherIdentification() .stream() .filter(furtherIdentificationType -> furtherIdentificationType.getIdentificationType().equals("GLN")) .findFirst() .map(FurtherIdentificationType::getValue) .orElseThrow(() -> new RuntimeException("No GLN found for businessEntity!businessEntity: " + businessEntityType)); return GLN_PREFIX + gln; } private String getDocumentDate() { return document.getDocumentDate() .toGregorianCalendar() .toZonedDateTime() .withZoneSameLocal(ZoneId.of(DOCUMENT_ZONE_ID)) .toInstant() .toString(); }
private Optional<BigDecimal> asBigDecimal(@Nullable final String value) { if (Check.isBlank(value)) { return Optional.empty(); } try { final BigDecimal bigDecimalValue = new BigDecimal(value); return Optional.of(bigDecimalValue.abs()); } catch (final Exception e) { return Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\remadvimport\ecosio\JsonRemittanceAdviceProducer.java
2
请完成以下Java代码
private ScriptApplyResult apply(@NonNull final IScript script) { final IScriptsApplierListener listener = getListener(); final IScriptExecutor executor = getExecutor(script); logger.info("Applying {}", script); boolean needExecute = true; while (needExecute) { needExecute = false; final long startTS = System.currentTimeMillis(); ScriptExecutionException error = null; try { executor.execute(script); } catch (final ScriptExecutionException e) { error = e; } catch (final Exception e) { error = new ScriptExecutionException("Error running script", e) .setScript(script) .setDatabase(targetDatabase) .setExecutor(executor); } finally { final long durationMillis = System.currentTimeMillis() - startTS; if (error == null) { logger.info("... Applied in {}ms", durationMillis); script.setLastDurationMillis(durationMillis); listener.onScriptApplied(script); return ScriptApplyResult.Applied; } else { final ScriptFailedResolution scriptFailedResolution = listener.onScriptFailed(script, error); if (scriptFailedResolution == ScriptFailedResolution.Fail) { throw error; } else if (scriptFailedResolution == ScriptFailedResolution.Ignore) { logger.info("... Ignored"); return ScriptApplyResult.Ignored; } else if (scriptFailedResolution == ScriptFailedResolution.Retry) { logger.info("... Retry"); needExecute = true; } else { throw new ScriptExecutionException("Invalid ScriptFailedResolution: " + scriptFailedResolution, error); } } } } throw new IllegalStateException("Internal error: Shall never reach this point"); }
private IScriptsRegistry getScriptsRegistry() { return targetDatabase.getScriptsRegistry(); } private IScriptExecutor getExecutor(final IScript script) { try { return scriptExecutorFactory.createScriptExecutor(targetDatabase, script); } catch (final ScriptException se) { throw se.addParameter("script.fileName", script.getLocalFile()); } catch (final RuntimeException rte) { logger.error("Caught " + rte.getClass().getSimpleName() + " while getting executor for script " + script.getLocalFile() + "; -> logging here and rethrowing", rte); throw rte; } } private IScriptExecutor getSqlExecutor() { return scriptExecutorFactory.createScriptExecutor(targetDatabase); } @Override public int getCountAll() { return countAll; } @Override public int getCountApplied() { return countApplied; } @Override public int getCountIgnored() { return countIgnored; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\applier\impl\ScriptsApplier.java
1
请完成以下Java代码
public class ReceiveTaskXMLConverter extends BaseBpmnXMLConverter { @Override public Class<? extends BaseElement> getBpmnElementType() { return ReceiveTask.class; } @Override protected String getXMLElementName() { return ELEMENT_TASK_RECEIVE; } @Override @SuppressWarnings("unchecked") protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { ReceiveTask receiveTask = new ReceiveTask(); BpmnXMLUtil.addXMLLocation(receiveTask, xtr); String skipExpression = BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TASK_SCRIPT_SKIP_EXPRESSION, xtr); if (StringUtils.isNotEmpty(skipExpression)) { receiveTask.setSkipExpression(skipExpression); } BpmnXMLUtil.addCustomAttributes(xtr, receiveTask, defaultElementAttributes, defaultActivityAttributes);
parseChildElements(getXMLElementName(), receiveTask, model, xtr); return receiveTask; } @Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { ReceiveTask receiveTask = (ReceiveTask) element; writeQualifiedAttribute(ATTRIBUTE_TASK_SCRIPT_SKIP_EXPRESSION, receiveTask.getSkipExpression(), xtw); } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\ReceiveTaskXMLConverter.java
1
请完成以下Java代码
public String toString() { final I_AD_InfoColumn infoColumn = getAD_InfoColumn(); if (infoColumn != null) { return getClass().getSimpleName() + "[" + infoColumn.getName() + "]"; } else { return super.toString(); } } @Override public final String getText() { if (editor == null) { return null; } final Object value = editor.getValue(); if (value == null) { return null; } return value.toString(); } @Override public Object getParameterValue(final int index, final boolean returnValueTo) { final Object field; if (returnValueTo)
{ field = getParameterToComponent(index); } else { field = getParameterComponent(index); } if (field instanceof CEditor) { final CEditor editor = (CEditor)field; return editor.getValue(); } else { throw new AdempiereException("Component type not supported - " + field); } } /** * Method called when one of the parameter fields changed */ protected void onFieldChanged() { // parent.executeQuery(); we don't want to query each time, because we might block the search } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\AbstractInfoQueryCriteriaGeneral.java
1
请完成以下Java代码
public JSONLookupValuesList getAttributeDropdown( @PathVariable("asiDocId") final String asiDocIdStr, @PathVariable("attributeName") final String attributeName) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return forASIDocumentReadonly(asiDocId, asiDoc -> asiDoc.getFieldLookupValues(attributeName)) .transform(this::toJSONLookupValuesList); } @PostMapping(value = "/{asiDocId}/complete") public JSONLookupValue complete( @PathVariable("asiDocId") final String asiDocIdStr, @RequestBody final JSONCompleteASIRequest request) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr);
return Execution.callInNewExecution("complete", () -> completeInTrx(asiDocId, request)) .transform(this::toJSONLookupValue); } private LookupValue completeInTrx(final DocumentId asiDocId, final JSONCompleteASIRequest request) { return asiRepo.forASIDocumentWritable( asiDocId, NullDocumentChangesCollector.instance, documentsCollection, asiDoc -> { final List<JSONDocumentChangedEvent> events = request.getEvents(); if (events != null && !events.isEmpty()) { asiDoc.processValueChanges(events, REASON_ProcessASIDocumentChanges); } return asiDoc.complete(); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRestController.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutCaseInstanceParentId() { return withoutCaseInstanceParentId; } public void setWithoutCaseInstanceParentId(Boolean withoutCaseInstanceParentId) {
this.withoutCaseInstanceParentId = withoutCaseInstanceParentId; } public Boolean getWithoutCaseInstanceCallbackId() { return withoutCaseInstanceCallbackId; } public void setWithoutCaseInstanceCallbackId(Boolean withoutCaseInstanceCallbackId) { this.withoutCaseInstanceCallbackId = withoutCaseInstanceCallbackId; } public Set<String> getCaseInstanceCallbackIds() { return caseInstanceCallbackIds; } public void setCaseInstanceCallbackIds(Set<String> caseInstanceCallbackIds) { this.caseInstanceCallbackIds = caseInstanceCallbackIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceQueryRequest.java
2
请完成以下Java代码
public void propertyChange (PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); // metas: request focus (2009_0027_G131) if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS)) requestFocus(); // metas end } // propertyChange /** * Return Editor value * @return value */ @Override public Object getValue() { if (m_value == null) return null; return new Integer(m_value.getC_Location_ID()); } // getValue /** * Return Editor value * @return value */ public int getC_Location_ID() { if (m_value == null) return 0; return m_value.getC_Location_ID(); } // getC_Location_ID /** * Return Display Value * @return display value */ @Override public String getDisplay() { return m_text.getText(); } // getDisplay /** * ActionListener - Button - Start Dialog * @param e ActionEvent */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == mDelete) { m_value = null; // create new } // final VLocationDialog ld = new VLocationDialog(SwingUtils.getFrame(this), Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Location"), m_value); ld.setVisible(true); Object oldValue = getValue(); m_value = ld.getValue(); // if (e.getSource() == mDelete) ; else if (!ld.isChanged()) return; // Data Binding try { int C_Location_ID = 0; if (m_value != null)
C_Location_ID = m_value.getC_Location_ID(); Integer ii = new Integer(C_Location_ID); if (C_Location_ID > 0) fireVetoableChange(m_columnName, oldValue, ii); setValue(ii); if (ii.equals(oldValue) && m_GridTab != null && m_GridField != null) { // force Change - user does not realize that embedded object is already saved. m_GridTab.processFieldChange(m_GridField); } } catch (PropertyVetoException pve) { log.error("VLocation.actionPerformed", pve); } } // actionPerformed /** * Action Listener Interface * @param listener listener */ @Override public void addActionListener(ActionListener listener) { m_text.addActionListener(listener); } // addActionListener @Override public synchronized void addMouseListener(MouseListener l) { m_text.addMouseListener(l); } /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField Model Field */ @Override public void setField (org.compiere.model.GridField mField) { m_GridField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_GridField; } // metas @Override public boolean isAutoCommit() { return true; } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VLocation
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocation.java
1
请在Spring Boot框架中完成以下Java代码
public class EDI_Desadv_Pack_Item { private final IQueryBL queryBL = Services.get(IQueryBL.class); /** * Makes sure that the sum of all {@code EDI_Desadv_Pack_Item.MovementQty} * values is not bigger than the respective {@code EDI_DesadvLine}'s {code QtyDeliveredInStockingUOM}. * Note that the business logic first sets the desadv-line's value and the desadv-line-pack's value. * Also note that we ignore packs that have no inoutline-id, because they might be there * when a SSCC-label is created before the delivery. * However they are not yet considered in the desadv-line's value. */ @ModelChange( timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_EDI_Desadv_Pack_Item.COLUMNNAME_MovementQty, I_EDI_Desadv_Pack_Item.COLUMNNAME_M_InOutLine_ID }) public void validateMovementQtySum(final I_EDI_Desadv_Pack_Item desadvPackItem) { if (desadvPackItem.getM_InOutLine_ID() <= 0) { return; // nothing to check; this pack's qty is not yet supposed to count for the line's QtyDelivered. } final BigDecimal otherPackItemsForLineSum = queryBL.createQueryBuilder(I_EDI_Desadv_Pack_Item.class) .addOnlyActiveRecordsFilter() .addNotEqualsFilter(I_EDI_Desadv_Pack_Item.COLUMN_EDI_Desadv_Pack_Item_ID, desadvPackItem.getEDI_Desadv_Pack_Item_ID())
.addEqualsFilter(I_EDI_Desadv_Pack_Item.COLUMN_EDI_DesadvLine_ID, desadvPackItem.getEDI_DesadvLine_ID()) .addNotNull(I_EDI_Desadv_Pack_Item.COLUMNNAME_M_InOutLine_ID) .create() .aggregate(I_EDI_Desadv_Pack_Item.COLUMNNAME_MovementQty, IQuery.Aggregate.SUM, BigDecimal.class); final BigDecimal allLinePacksSum = otherPackItemsForLineSum.add(desadvPackItem.getMovementQty()); final BigDecimal lineSum = desadvPackItem.getEDI_DesadvLine().getQtyDeliveredInStockingUOM(); if (allLinePacksSum.compareTo(lineSum) > 0) { throw new AdempiereException("EDI_DesadvLine.QtyDeliveredInStockingUOM=" + lineSum + ",but the sum of all EDI_Desadv_Pack_Item.MovementQtys=" + allLinePacksSum) .appendParametersToMessage() .setParameter("EDI_Desadv_Pack_Item_ID", desadvPackItem.getEDI_Desadv_Pack_Item_ID()) .setParameter("EDI_DesadvLine_ID", desadvPackItem.getEDI_DesadvLine_ID()) .setParameter("EDI_Desadv_ID", desadvPackItem.getEDI_DesadvLine().getEDI_Desadv_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\EDI_Desadv_Pack_Item.java
2
请完成以下Java代码
public MobileApplicationId getApplicationId() {return APPLICATION_ID;} @Override public WorkflowLaunchersList provideLaunchers(final WorkflowLaunchersQuery query) {return launchersProvider.provideLaunchers(query);} @Override public WFProcess startWorkflow(final WorkflowStartRequest request) { final UserId invokerId = request.getInvokerId(); final InventoryId inventoryId = InventoryWFProcessStartParams.ofParams(request.getWfParameters()).getInventoryId(); final Inventory inventory = jobService.startJob(inventoryId, invokerId); return toWFProcess(inventory); } @Override public WFProcess continueWorkflow(final WFProcessId wfProcessId, final UserId callerId) { final InventoryId inventoryId = toInventoryId(wfProcessId); final Inventory inventory = jobService.reassignJob(inventoryId, callerId); return toWFProcess(inventory); } @Override public void abort(final WFProcessId wfProcessId, final UserId callerId) { jobService.abort(wfProcessId, callerId); } @Override public void abortAll(final UserId callerId) { jobService.abortAll(callerId); } @Override public void logout(final @NonNull UserId userId) { abortAll(userId); } @Override public WFProcess getWFProcessById(final WFProcessId wfProcessId) { final Inventory inventory = jobService.getById(toInventoryId(wfProcessId)); return toWFProcess(inventory); } @Override public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess) { final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache();
final Inventory inventory = getInventory(wfProcess); return WFProcessHeaderProperties.builder() .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("DocumentNo")) .value(inventory.getDocumentNo()) .build()) .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("MovementDate")) .value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate())) .build()) .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID")) .value(inventory.getWarehouseId() != null ? warehouses.getById(inventory.getWarehouseId()).getWarehouseName() : "") .build()) .build(); } @NonNull public static Inventory getInventory(final @NonNull WFProcess wfProcess) { return wfProcess.getDocumentAs(Inventory.class); } public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper) { final Inventory inventory = getInventory(wfProcess); final Inventory inventoryChanged = mapper.apply(inventory); return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java
1
请完成以下Java代码
public class ProprietaryDate2 { @XmlElement(name = "Tp", required = true) protected String tp; @XmlElement(name = "Dt", required = true) protected DateAndDateTimeChoice dt; /** * Gets the value of the tp property. * * @return * possible object is * {@link String } * */ public String getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link String } * */ public void setTp(String value) { this.tp = value;
} /** * Gets the value of the dt property. * * @return * possible object is * {@link DateAndDateTimeChoice } * */ public DateAndDateTimeChoice getDt() { return dt; } /** * Sets the value of the dt property. * * @param value * allowed object is * {@link DateAndDateTimeChoice } * */ public void setDt(DateAndDateTimeChoice value) { this.dt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ProprietaryDate2.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonMobileApplication { @NonNull String id; @NonNull String caption; @NonNull ImmutableSet<String> actions; int maxStartedLaunchers; boolean allowStartNextJobOnly; boolean requiresWorkstation; boolean requiresWorkplace; boolean requiresTrolley; boolean showFilterByQRCode; boolean showFilters; boolean showFilterByDocumentNo; boolean showFilterByQtyAvailableAtPickFromLocator; boolean showInMainMenu; int sortNo; @Nullable ImmutableMap<String, Object> applicationParameters; public static JsonMobileApplication of( final MobileApplicationInfo appInfo, final JsonOpts jsonOpts, final MobileApplicationPermissions mobileApplicationPermissions) { return builder() .id(appInfo.getId().getAsString()) .caption(appInfo.getCaption().translate(jsonOpts.getAdLanguage())) .actions(appInfo.getActions() .stream() .filter(action -> mobileApplicationPermissions.isAllowAction(appInfo.getRepoId(), action.getId())) .map(MobileApplicationAction::getInternalName) .collect(ImmutableSet.toImmutableSet())) .maxStartedLaunchers(appInfo.getMaxStartedLaunchers().toIntOrZero()) .allowStartNextJobOnly(appInfo.isAllowStartNextJobOnly()) .requiresWorkstation(appInfo.isRequiresWorkstation()) .requiresWorkplace(appInfo.isRequiresWorkplace()) .requiresTrolley(appInfo.isRequiresTrolley()) .showFilterByQRCode(appInfo.isShowFilterByQRCode()) .showFilters(appInfo.isShowFilters()) .showFilterByDocumentNo(appInfo.isShowFilterByDocumentNo()) .showFilterByQtyAvailableAtPickFromLocator(appInfo.isShowFilterByQtyAvailableAtPickFromLocator())
.showInMainMenu(appInfo.isShowInMainMenu()) .sortNo(appInfo.getSortNo()) .applicationParameters(toJsonApplicationParameters(appInfo.getApplicationParameters())) .build(); } @Nullable private static ImmutableMap<String, Object> toJsonApplicationParameters(@Nullable final Map<String, Object> applicationParameters) { if (applicationParameters == null || applicationParameters.isEmpty()) { return null; } return applicationParameters.entrySet() .stream() .filter(entry -> entry.getValue() != null) // filter out null values .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\json\JsonMobileApplication.java
2
请完成以下Java代码
private static @Nullable Long internalParseDate(String value, DateFormat[] formats) { Date date = null; for (int i = 0; (date == null) && (i < formats.length); i++) { try { date = formats[i].parse(value); } catch (ParseException ex) { } } if (date == null) { return null; } return date.getTime(); } /** * Tries to parse the given date as an HTTP date. If local format list is not * <code>null</code>, it's used instead. * @param value The string to parse * @param threadLocalformats Array of formats to use for parsing. If <code>null</code> * , HTTP formats are used. * @return Parsed date (or -1 if error occurred) */ public static long parseDate(String value, DateFormat[] threadLocalformats) { Long cachedDate = null; try { cachedDate = parseCache.get(value); } catch (Exception ex) { } if (cachedDate != null) { return cachedDate; } Long date;
if (threadLocalformats != null) { date = internalParseDate(value, threadLocalformats); synchronized (parseCache) { updateCache(parseCache, value, date); } } else { synchronized (parseCache) { date = internalParseDate(value, formats); updateCache(parseCache, value, date); } } return (date != null) ? date : -1L; } /** * Updates cache. * @param cache Cache to be updated * @param key Key to be updated * @param value New value */ @SuppressWarnings("unchecked") private static void updateCache(HashMap cache, Object key, @Nullable Object value) { if (value == null) { return; } if (cache.size() > 1000) { cache.clear(); } cache.put(key, value); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\FastHttpDateFormat.java
1
请完成以下Java代码
abstract class M_HU_Report_Print_Template extends JavaProcess implements IProcessPrecondition { private final HUQRCodesService huQRCodesService = SpringContextHolder.instance.getBean(HUQRCodesService.class); private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); protected abstract AdProcessId getPrintFormatProcessId(); @Override @RunOutOfTrx protected final String doIt() { final I_M_HU hu = getSelectedHU(); generateQRCode(hu); final ReportResultData labelReport = createLabelReport(hu); getResult().setReportData(labelReport); return MSG_OK; } private I_M_HU getSelectedHU()
{ final List<I_M_HU> hus = handlingUnitsBL.getBySelectionId(getPinstanceId()); return CollectionUtils.singleElement(hus); } private void generateQRCode(final I_M_HU hu) { final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); huQRCodesService.generateForExistingHU(huId); } private ReportResultData createLabelReport(@NonNull final I_M_HU hu) { final HUToReport huToReport = HUToReportWrapper.of(hu); return HUReportExecutor.newInstance() .printPreview(true) .executeNow(getPrintFormatProcessId(), ImmutableList.of(huToReport)) .getReportData(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_Report_Print_Template.java
1
请完成以下Java代码
private void setBytes(byte[] bytes) { if (id == null) { if (bytes != null) { ByteArrayEntityManager byteArrayEntityManager = CommandContextUtil.getIdmByteArrayEntityManager(); entity = byteArrayEntityManager.create(); entity.setName(name); entity.setBytes(bytes); byteArrayEntityManager.insert(entity); id = entity.getId(); } } else { ensureInitialized(); entity.setBytes(bytes); } } public IdmByteArrayEntity getEntity() { ensureInitialized(); return entity; } public void delete() { if (!deleted && id != null) { if (entity != null) { // if the entity has been loaded already, // we might as well use the safer optimistic locking delete. CommandContextUtil.getIdmByteArrayEntityManager().delete(entity); } else { CommandContextUtil.getIdmByteArrayEntityManager().deleteByteArrayById(id); } entity = null; id = null; deleted = true; } }
private void ensureInitialized() { if (id != null && entity == null) { entity = CommandContextUtil.getIdmByteArrayEntityManager().findById(id); if (entity != null) { name = entity.getName(); } } } public boolean isDeleted() { return deleted; } @Override public String toString() { return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]"); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\ByteArrayRef.java
1
请完成以下Java代码
public int getC_DunningDoc_Line_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningDoc_Line_Source_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Massenaustritt. @param IsWriteOff Massenaustritt */ @Override public void setIsWriteOff (boolean IsWriteOff) { set_Value (COLUMNNAME_IsWriteOff, Boolean.valueOf(IsWriteOff)); } /** Get Massenaustritt. @return Massenaustritt */ @Override public boolean isWriteOff () { Object oo = get_Value(COLUMNNAME_IsWriteOff); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Massenaustritt Applied. @param IsWriteOffApplied Massenaustritt Applied */ @Override public void setIsWriteOffApplied (boolean IsWriteOffApplied) { set_Value (COLUMNNAME_IsWriteOffApplied, Boolean.valueOf(IsWriteOffApplied)); } /** Get Massenaustritt Applied. @return Massenaustritt Applied */ @Override public boolean isWriteOffApplied () { Object oo = get_Value(COLUMNNAME_IsWriteOffApplied); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line_Source.java
1
请完成以下Java代码
public void receiveMessage(ReceiveMessagePayload messagePayload) { String messageName = messagePayload.getName(); String correlationKey = messagePayload.getCorrelationKey(); EventSubscriptionEntity subscription = managementService.executeCommand( new FindMessageEventSubscription(messageName, correlationKey) ); if (subscription != null && Objects.equals(correlationKey, subscription.getConfiguration())) { Map<String, Object> variables = messagePayload.getVariables(); String executionId = subscription.getExecutionId(); runtimeService.messageEventReceived(messageName, executionId, variables); } else { throw new ActivitiObjectNotFoundException( "Message subscription name '" + messageName + "' with correlation key '" + correlationKey + "' not found." ); } } static class FindMessageEventSubscription implements Command<EventSubscriptionEntity> {
private final String messageName; private final String correlationKey; public FindMessageEventSubscription(String messageName, String correlationKey) { this.messageName = messageName; this.correlationKey = correlationKey; } public EventSubscriptionEntity execute(CommandContext commandContext) { return new EventSubscriptionQueryImpl(commandContext) .eventType("message") .eventName(messageName) .configuration(correlationKey) .singleResult(); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\RuntimeReceiveMessagePayloadEventListener.java
1
请完成以下Java代码
public VPanelFormFieldBuilder setDisplayType(int displayType) { this.displayType = displayType; return this; } private String getHeader() { // null allowed return header; } /** * @param header String which is Displayed as Label. */ public VPanelFormFieldBuilder setHeader(String header) { this.header = header; return this; } private String getColumnName() { Check.assumeNotEmpty(columnName, "columnName not empty"); return columnName; } /** * @param columnName Will be the name of the GridField. */ public VPanelFormFieldBuilder setColumnName(String columnName) { this.columnName = columnName; return this; } private boolean isSameLine() { return sameLine; } /** * Default: {@link #DEFAULT_SameLine} * * @param sameLine If true, the new Field will be added in the same line. */ public VPanelFormFieldBuilder setSameLine(boolean sameLine) { this.sameLine = sameLine; return this; } private boolean isMandatory() { return mandatory; } /** * Default: {@link #DEFAULT_Mandatory} * * @param mandatory true if this field shall be marked as mandatory */ public VPanelFormFieldBuilder setMandatory(boolean mandatory) { this.mandatory = mandatory; return this; } private boolean isAutocomplete() { if (autocomplete != null) { return autocomplete; } // if Search, always auto-complete if (DisplayType.Search == displayType) { return true; } return false; } public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete)
{ this.autocomplete = autocomplete; return this; } private int getAD_Column_ID() { // not set is allowed return AD_Column_ID; } /** * @param AD_Column_ID Column for lookups. */ public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName) { return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID()); } private EventListener getEditorListener() { // null allowed return editorListener; } /** * @param listener VetoableChangeListener that gets called if the field is changed. */ public VPanelFormFieldBuilder setEditorListener(EventListener listener) { this.editorListener = listener; return this; } public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel) { this.bindEditorToModel = bindEditorToModel; return this; } public VPanelFormFieldBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
1
请完成以下Spring Boot application配置
# Database db.driver: com.mysql.jdbc.Driver db.url: jdbc:mysql://localhost:8889/netgloo_blog db.username: root db.password: root # Hibernate hibernate.dialect: org.hibernate.dialect.MySQL5Dialect hibern
ate.show_sql: true hibernate.hbm2ddl.auto: update entitymanager.packagesToScan: netgloo
repos\spring-boot-samples-master\spring-boot-mysql-jpa-hibernate\src\main\resources\application.properties
2
请完成以下Java代码
public class TemplateMessageDTO extends TemplateDTO implements Serializable { private static final long serialVersionUID = 411137565170647585L; /** * 发送人(用户登录账户) */ protected String fromUser; /** * 发送给(用户登录账户) */ protected String toUser; /** * 消息主题 */ protected String title;
public TemplateMessageDTO(){ } /** * 构造器1 发模板消息用 */ public TemplateMessageDTO(String fromUser, String toUser,String title, Map<String, String> templateParam, String templateCode){ super(templateCode, templateParam); this.fromUser = fromUser; this.toUser = toUser; this.title = title; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\dto\message\TemplateMessageDTO.java
1
请在Spring Boot框架中完成以下Java代码
class UserRepositoryImplJdbc extends JdbcDaoSupport implements UserRepositoryCustom { private static final String COMPLICATED_SQL = "SELECT * FROM User"; @Autowired public UserRepositoryImplJdbc(DataSource dataSource) { setDataSource(dataSource); } /* * (non-Javadoc) * @see example.springdata.jpa.UserRepositoryCustom#myCustomBatchOperation() */ public List<User> myCustomBatchOperation() { return getJdbcTemplate().query(COMPLICATED_SQL, new UserRowMapper()); } private static class UserRowMapper implements RowMapper<User> {
/* * (non-Javadoc) * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int) */ public User mapRow(ResultSet rs, int rowNum) throws SQLException { var user = new User(rs.getLong("id")); user.setUsername(rs.getString("username")); user.setLastname(rs.getString("lastname")); user.setFirstname(rs.getString("firstname")); return user; } } }
repos\spring-data-examples-main\jpa\example\src\main\java\example\springdata\jpa\custom\UserRepositoryImplJdbc.java
2
请完成以下Java代码
public static class RemoveAsyncEventRepositoryFunction<T, ID> extends AbstractAsyncEventOperationRepositoryFunction<T, ID> { /** * Constructs a new instance of {@link RemoveAsyncEventRepositoryFunction} initialized with the given, required * {@link RepositoryAsyncEventListener}. * * @param listener {@link RepositoryAsyncEventListener} forwarding {@link AsyncEvent AsyncEvents} for processing * by this {@link Function} * @see RepositoryAsyncEventListener */ public RemoveAsyncEventRepositoryFunction(@NonNull RepositoryAsyncEventListener<T, ID> listener) { super(listener); } /** * @inheritDoc */ @Override
public boolean canProcess(@Nullable AsyncEvent<ID, T> event) { Operation operation = event != null ? event.getOperation() : null; return Operation.REMOVE.equals(operation); } /** * @inheritDoc */ @Override protected <R> R doRepositoryOp(T entity) { getRepository().delete(entity); return null; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\RepositoryAsyncEventListener.java
1
请完成以下Java代码
public static HttpHeaders fromMessage(MessageHeaders headers, List<String> ignoredHeders) { HttpHeaders result = new HttpHeaders(); for (String name : headers.keySet()) { Object value = headers.get(name); name = name.toLowerCase(Locale.ROOT); if (!IGNORED.containsHeader(name) && !ignoredHeders.contains(name)) { Collection<?> values = multi(value); for (Object object : values) { result.set(name, object.toString()); } } } return result; } @SuppressWarnings("unchecked") public static HttpHeaders fromMessage(MessageHeaders headers) { return fromMessage(headers, Collections.EMPTY_LIST); } public static HttpHeaders sanitize(HttpHeaders request, List<String> ignoredHeders, List<String> requestOnlyHeaders) { HttpHeaders result = new HttpHeaders(); for (String name : request.headerNames()) { List<String> value = request.get(name); name = name.toLowerCase(Locale.ROOT); if (!IGNORED.containsHeader(name) && !REQUEST_ONLY.containsHeader(name) && !ignoredHeders.contains(name) && !requestOnlyHeaders.contains(name)) { result.put(name, value); }
} return result; } @SuppressWarnings("unchecked") public static HttpHeaders sanitize(HttpHeaders request) { return sanitize(request, Collections.EMPTY_LIST, Collections.EMPTY_LIST); } public static MessageHeaders fromHttp(HttpHeaders headers) { Map<String, Object> map = new LinkedHashMap<>(); for (String name : headers.headerNames()) { Collection<?> values = multi(headers.get(name)); name = name.toLowerCase(Locale.ROOT); Object value = values == null ? null : (values.size() == 1 ? values.iterator().next() : values); if (name.toLowerCase(Locale.ROOT).equals(HttpHeaders.CONTENT_TYPE.toLowerCase(Locale.ROOT))) { name = MessageHeaders.CONTENT_TYPE; } map.put(name, value); } return new MessageHeaders(map); } private static Collection<?> multi(Object value) { return value instanceof Collection ? (Collection<?>) value : Arrays.asList(value); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\MessageHeaderUtils.java
1
请完成以下Java代码
public class RunAlgorithm { public static void main(String[] args) throws InstantiationException, IllegalAccessException { Scanner in = new Scanner(System.in); System.out.println("Run algorithm:"); System.out.println("1 - Simulated Annealing"); System.out.println("2 - Simple Genetic Algorithm"); System.out.println("3 - Ant Colony"); int decision = in.nextInt(); switch (decision) { case 1: System.out.println( "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); break; case 2:
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); break; case 3: AntColonyOptimization antColony = new AntColonyOptimization(21); antColony.startAntOptimization(); break; default: System.out.println("Unknown option"); break; } in.close(); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\RunAlgorithm.java
1
请完成以下Java代码
protected String doIt() throws Exception { final I_C_Order order = getRecord(I_C_Order.class); orderCheckupBL.generateReportsIfEligible(order); return "@Success@"; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { final I_C_Order order = context.getSelectedModel(I_C_Order.class); if (order == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no order"); } // Make sure this feature is enabled (sysconfig) if (!sysConfigBL.getBooleanValue(SYSCONFIG_EnableProcessGear, false, order.getAD_Client_ID(), order.getAD_Org_ID()))
{ return ProcessPreconditionsResolution.rejectWithInternalReason("not enabled"); } // Only completed/closed orders if (!docActionBL.isDocumentCompletedOrClosed(order)) { logger.debug("{} has DocStatus={}; nothing to do", new Object[] { order, order.getDocStatus() }); return ProcessPreconditionsResolution.reject("only completed/closed orders are allowed"); } // Only eligible orders if (!orderCheckupBL.isEligibleForReporting(order)) { return ProcessPreconditionsResolution.reject("not eligible for reporting"); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\process\C_Order_MFGWarehouse_Report_Generate.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentRepositoryService implements StudentService { private StudentRepository repo; @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; } public Optional<Student> findOne(String id) { return repo.findById(id); } public List<Student> findAll() { List<Student> people = new ArrayList<>(); Iterator<Student> it = repo.findAll().iterator(); while (it.hasNext()) { people.add(it.next()); } return people; } public List<Student> findByFirstName(String firstName) { return repo.findByFirstName(firstName);
} public List<Student> findByLastName(String lastName) { return repo.findByLastName(lastName); } public void create(Student student) { student.setCreated(DateTime.now()); repo.save(student); } public void update(Student student) { student.setUpdated(DateTime.now()); repo.save(student); } public void delete(Student student) { repo.delete(student); } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\StudentRepositoryService.java
2
请在Spring Boot框架中完成以下Java代码
public class RemoteNotificationRuleProcessor implements NotificationRuleProcessor { private final NotificationDeduplicationService deduplicationService; private final TbQueueProducerProvider producerProvider; private final TopicService topicService; private final PartitionService partitionService; @Override public void process(NotificationRuleTrigger trigger) { try { if (!DeduplicationStrategy.NONE.equals(trigger.getDeduplicationStrategy()) && deduplicationService.alreadyProcessed(trigger)) { return; } log.debug("Submitting notification rule trigger: {}", trigger); TransportProtos.NotificationRuleProcessorMsg.Builder msg = TransportProtos.NotificationRuleProcessorMsg.newBuilder()
.setTrigger(ByteString.copyFrom(JavaSerDesUtil.encode(trigger))); partitionService.getAllServiceIds(ServiceType.TB_CORE).stream().findAny().ifPresent(serviceId -> { TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, serviceId); producerProvider.getTbCoreNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), TransportProtos.ToCoreNotificationMsg.newBuilder() .setNotificationRuleProcessorMsg(msg) .build()), null); }); } catch (Throwable e) { log.error("Failed to submit notification rule trigger: {}", trigger, e); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\notification\RemoteNotificationRuleProcessor.java
2
请完成以下Java代码
public class MHierarchy extends X_PA_Hierarchy { /** * */ private static final long serialVersionUID = 3278979908976853690L; /** * Get MHierarchy from Cache * @param ctx context * @param PA_Hierarchy_ID id * @return MHierarchy */ public static MHierarchy get (Properties ctx, int PA_Hierarchy_ID) { Integer key = new Integer (PA_Hierarchy_ID); MHierarchy retValue = (MHierarchy)s_cache.get (key); if (retValue != null) return retValue; retValue = new MHierarchy (ctx, PA_Hierarchy_ID, null); if (retValue.get_ID () != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MHierarchy> s_cache = new CCache<Integer, MHierarchy> ("PA_Hierarchy_ID", 20); /** * Default Constructor * @param ctx context * @param PA_Hierarchy_ID id * @param trxName trx */ public MHierarchy (Properties ctx, int PA_Hierarchy_ID, String trxName) { super (ctx, PA_Hierarchy_ID, trxName); } // MHierarchy /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MHierarchy (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MHierarchy
/** * Get AD_Tree_ID based on tree type * @param TreeType Tree Type * @return id or 0 */ public int getAD_Tree_ID (String TreeType) { if (MTree.TREETYPE_Activity.equals(TreeType)) return getAD_Tree_Activity_ID(); if (MTree.TREETYPE_BPartner.equals(TreeType)) return getAD_Tree_BPartner_ID(); if (MTree.TREETYPE_Campaign.equals(TreeType)) return getAD_Tree_Campaign_ID(); if (MTree.TREETYPE_ElementValue.equals(TreeType)) return getAD_Tree_Account_ID(); if (MTree.TREETYPE_Organization.equals(TreeType)) return getAD_Tree_Org_ID(); if (MTree.TREETYPE_Product.equals(TreeType)) return getAD_Tree_Product_ID(); if (MTree.TREETYPE_Project.equals(TreeType)) return getAD_Tree_Project_ID(); if (MTree.TREETYPE_SalesRegion.equals(TreeType)) return getAD_Tree_SalesRegion_ID(); // log.warn("Not supported: " + TreeType); return 0; } // getAD_Tree_ID } // MHierarchy
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MHierarchy.java
1
请完成以下Java代码
protected PageData<EntityView> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return entityViewDao.findEntityViewsByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, EntityView entity) { deleteEntityView(tenantId, new EntityViewId(entity.getUuidId())); } }; private final PaginatedRemover<CustomerId, EntityView> customerEntityViewsRemover = new PaginatedRemover<>() { @Override protected PageData<EntityView> findEntities(TenantId tenantId, CustomerId id, PageLink pageLink) { return entityViewDao.findEntityViewsByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, EntityView entity) { unassignEntityViewFromCustomer(tenantId, new EntityViewId(entity.getUuidId())); } }; @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findEntityViewById(tenantId, new EntityViewId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findEntityViewByIdAsync(tenantId, new EntityViewId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.ENTITY_VIEW; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\entityview\EntityViewServiceImpl.java
1
请完成以下Java代码
public class PaginateRequest { protected Integer start; protected Integer size; protected String sort; protected String order; public Integer getStart() { return start; } @ApiParam(value = "From the paginate request. Index of the first row to fetch. Defaults to 0.") public void setStart(Integer start) { this.start = start; } public Integer getSize() { return size; } @ApiParam(name = "size", type = "integer", value = "From the paginate request. Number of rows to fetch, starting from start. Defaults to 10.") public void setSize(Integer size) { this.size = size;
} public String getSort() { return sort; } @ApiParam(value = "Property to sort the results on") public void setSort(String sort) { this.sort = sort; } public String getOrder() { return order; } @ApiParam(name = "order", type = "string", value = "From the paginate request. The sort order, either 'asc' or 'desc'. Defaults to 'asc'.") public void setOrder(String order) { this.order = order; } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\PaginateRequest.java
1
请在Spring Boot框架中完成以下Java代码
public void authenticate(final String username, final String password) { contextSource.getContext("cn=" + username + ",ou=users," + env.getRequiredProperty("ldap.partitionSuffix"), password); } public List<String> search(final String username) { return ldapTemplate.search( "ou=users", "cn=" + username, (AttributesMapper<String>) attrs -> (String) attrs .get("cn") .get()); } public void create(final String username, final String password) { Name dn = LdapNameBuilder .newInstance() .add("ou", "users") .add("cn", username) .build(); DirContextAdapter context = new DirContextAdapter(dn); context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); ldapTemplate.bind(context); } public void modify(final String username, final String password) { Name dn = LdapNameBuilder .newInstance() .add("ou", "users")
.add("cn", username) .build(); DirContextOperations context = ldapTemplate.lookupContext(dn); context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); ldapTemplate.modifyAttributes(context); } private String digestSHA(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); base64 = Base64 .getEncoder() .encodeToString(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return "{SHA}" + base64; } }
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\ldap\data\service\LdapClient.java
2
请在Spring Boot框架中完成以下Java代码
public R<AuthInfo> token(@Parameter(description = "授权类型", required = true) @RequestParam(defaultValue = "password", required = false) String grantType, @Parameter(description = "刷新令牌") @RequestParam(required = false) String refreshToken, @Parameter(description = "租户ID", required = true) @RequestParam(defaultValue = "000000", required = false) String tenantId, @Parameter(description = "账号") @RequestParam(required = false) String account, @Parameter(description = "密码") @RequestParam(required = false) String password) { String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE); TokenParameter tokenParameter = new TokenParameter(); tokenParameter.getArgs().set("tenantId", tenantId) .set("account", account) .set("password", password) .set("grantType", grantType) .set("refreshToken", refreshToken) .set("userType", userType); ITokenGranter granter = TokenGranterBuilder.getGranter(grantType); UserInfo userInfo = granter.grant(tokenParameter); if (userInfo == null || userInfo.getUser() == null || userInfo.getUser().getId() == null) { return R.fail(TokenUtil.USER_NOT_FOUND); } return R.data(TokenUtil.createAuthInfo(userInfo)); }
@GetMapping("/captcha") @Operation(summary = "获取验证码") public R<Kv> captcha() { SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5); String verCode = specCaptcha.text().toLowerCase(); String key = UUID.randomUUID().toString(); // 存入redis并设置过期时间为30分钟 bladeRedis.setEx(CacheNames.CAPTCHA_KEY + key, verCode, 30L, TimeUnit.MINUTES); // 将key和base64返回给前端 return R.data(Kv.init().set("key", key).set("image", specCaptcha.toBase64())); } @PostMapping("/logout") @Operation(summary = "登出") public R<Kv> logout() { // 登出预留逻辑 return R.data(Kv.init().set("code", "200").set("msg", "操作成功")); } }
repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\controller\AuthController.java
2
请完成以下Java代码
protected static Class loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException { CommandContext commandContext = Context.getCommandContext(); boolean useClassForName = commandContext == null || commandContext.isUseClassForNameClassLoading(); return useClassForName ? Class.forName(className, true, classLoader) : classLoader.loadClass(className); } public static boolean isGetter(Method method) { String name = method.getName(); Class<?> type = method.getReturnType(); Class<?>[] params = method.getParameterTypes(); if (!GETTER_PATTERN.matcher(name).matches()) { return false; } // special for isXXX boolean if (name.startsWith("is")) { return params.length == 0 && "boolean".equalsIgnoreCase(type.getSimpleName()); } return params.length == 0 && !type.equals(Void.TYPE); } public static boolean isSetter(Method method, boolean allowBuilderPattern) { String name = method.getName(); Class<?> type = method.getReturnType(); Class<?>[] params = method.getParameterTypes(); if (!SETTER_PATTERN.matcher(name).matches()) { return false; } return params.length == 1 && (type.equals(Void.TYPE) || (allowBuilderPattern && method.getDeclaringClass().isAssignableFrom(type))); } public static boolean isSetter(Method method) { return isSetter(method, false); } public static String getGetterShorthandName(Method method) { if (!isGetter(method)) { return method.getName(); } String name = method.getName(); if (name.startsWith("get")) { name = name.substring(3); name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
} else if (name.startsWith("is")) { name = name.substring(2); name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1); } return name; } public static String getSetterShorthandName(Method method) { if (!isSetter(method)) { return method.getName(); } String name = method.getName(); if (name.startsWith("set")) { name = name.substring(3); name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1); } return name; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\util\ReflectUtil.java
1
请完成以下Spring Boot application配置
# Increased timeout to fit slower environments like TravisCI spring.couchbase.env.timeouts.view=15000 spring.couchbase.env.timeouts.query=15000 spring.couchbase.connection-string=couchbase://127.0.0.1 spring.couchbase.username=Administrator spring.couc
hbase.password=password spring.data.couchbase.bucket-name=travel-sample spring.data.couchbase.auto-index=true
repos\spring-data-examples-main\couchbase\example\src\main\resources\application.properties
2
请完成以下Java代码
public int getRfQ_SelectedWinners_Count () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_SelectedWinners_Count); if (ii == null) return 0; return ii.intValue(); } /** Set Selected winners Qty. @param RfQ_SelectedWinners_QtySum Selected winners Qty */ @Override public void setRfQ_SelectedWinners_QtySum (java.math.BigDecimal RfQ_SelectedWinners_QtySum) { throw new IllegalArgumentException ("RfQ_SelectedWinners_QtySum is virtual column"); } /** Get Selected winners Qty. @return Selected winners Qty */ @Override public java.math.BigDecimal getRfQ_SelectedWinners_QtySum () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RfQ_SelectedWinners_QtySum); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Use line quantity. @param UseLineQty Use line quantity */ @Override public void setUseLineQty (boolean UseLineQty) {
set_Value (COLUMNNAME_UseLineQty, Boolean.valueOf(UseLineQty)); } /** Get Use line quantity. @return Use line quantity */ @Override public boolean isUseLineQty () { Object oo = get_Value(COLUMNNAME_UseLineQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLine.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig { private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class); private SingleSignOutFilter singleSignOutFilter; private LogoutFilter logoutFilter; private CasAuthenticationProvider casAuthenticationProvider; private ServiceProperties serviceProperties; @Autowired public WebSecurityConfig(SingleSignOutFilter singleSignOutFilter, LogoutFilter logoutFilter, CasAuthenticationProvider casAuthenticationProvider, ServiceProperties serviceProperties) { this.logoutFilter = logoutFilter; this.singleSignOutFilter = singleSignOutFilter; this.serviceProperties = serviceProperties; this.casAuthenticationProvider = casAuthenticationProvider; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers( "/secured", "/login").authenticated() .and() .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) .and() .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class)
.addFilterBefore(logoutFilter, LogoutFilter.class) .csrf().ignoringAntMatchers("/exit/cas"); return http.build(); } @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .authenticationProvider(casAuthenticationProvider) .build(); } public AuthenticationEntryPoint authenticationEntryPoint() { CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); entryPoint.setLoginUrl("https://localhost:8443/cas/login"); entryPoint.setServiceProperties(serviceProperties); return entryPoint; } }
repos\tutorials-master\security-modules\cas\cas-secured-app\src\main\java\com\baeldung\cassecuredapp\config\WebSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class InMemoryAuditEventRepository implements AuditEventRepository { private static final int DEFAULT_CAPACITY = 1000; private final Object monitor = new Object(); /** * Circular buffer of the event with tail pointing to the last element. */ private AuditEvent[] events; private volatile int tail = -1; public InMemoryAuditEventRepository() { this(DEFAULT_CAPACITY); } public InMemoryAuditEventRepository(int capacity) { this.events = new AuditEvent[capacity]; } /** * Set the capacity of this event repository. * @param capacity the capacity */ public void setCapacity(int capacity) { synchronized (this.monitor) { this.events = new AuditEvent[capacity]; } } @Override public void add(AuditEvent event) { Assert.notNull(event, "'event' must not be null"); synchronized (this.monitor) { this.tail = (this.tail + 1) % this.events.length;
this.events[this.tail] = event; } } @Override public List<AuditEvent> find(@Nullable String principal, @Nullable Instant after, @Nullable String type) { LinkedList<AuditEvent> events = new LinkedList<>(); synchronized (this.monitor) { for (int i = 0; i < this.events.length; i++) { AuditEvent event = resolveTailEvent(i); if (event != null && isMatch(principal, after, type, event)) { events.addFirst(event); } } } return events; } private boolean isMatch(@Nullable String principal, @Nullable Instant after, @Nullable String type, AuditEvent event) { boolean match = true; match = match && (principal == null || event.getPrincipal().equals(principal)); match = match && (after == null || event.getTimestamp().isAfter(after)); match = match && (type == null || event.getType().equals(type)); return match; } private AuditEvent resolveTailEvent(int offset) { int index = ((this.tail + this.events.length - offset) % this.events.length); return this.events[index]; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\audit\InMemoryAuditEventRepository.java
2
请完成以下Java代码
public ExecutionEntity getExecution() { if(executionId != null) { ExecutionEntity execution = Context.getCommandContext() .getExecutionManager() .findExecutionById(executionId); if (execution == null) { LOG.executionNotFound(executionId); } return execution; } else { return null; } } @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("executionId", executionId); persistentState.put("processDefinitionId", processDefinitionId); persistentState.put("activityId", activityId); persistentState.put("jobDefinitionId", jobDefinitionId); persistentState.put("annotation", annotation); return persistentState; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } public String getHistoryConfiguration() { return historyConfiguration; } public void setHistoryConfiguration(String historyConfiguration) { this.historyConfiguration = historyConfiguration; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", incidentTimestamp=" + incidentTimestamp + ", incidentType=" + incidentType + ", executionId=" + executionId + ", activityId=" + activityId + ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId + ", causeIncidentId=" + causeIncidentId + ", rootCauseIncidentId=" + rootCauseIncidentId + ", configuration=" + configuration + ", tenantId=" + tenantId + ", incidentMessage=" + incidentMessage + ", jobDefinitionId=" + jobDefinitionId + ", failedActivityId=" + failedActivityId + ", annotation=" + annotation + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IncidentEntity other = (IncidentEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentEntity.java
1
请完成以下Java代码
public void run() { detail.scrollToVisible(); } }); } }); } } public VEditor getEditor(final String columnName) { return columnName2editor.get(columnName); } public final List<String> getEditorColumnNames() {
return new ArrayList<>(columnName2editor.keySet()); } public final CLabel getEditorLabel(final String columnName) { return columnName2label.get(columnName); } public final void updateVisibleFieldGroups() { for (final VPanelFieldGroup panel : fieldGroupPanels) { panel.updateVisible(); } } } // VPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanel.java
1
请完成以下Java代码
public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public Boolean getWithIncident() { return withIncident; } @CamundaQueryParam(value="withIncident", converter = BooleanConverter.class) public void setWithIncident(Boolean withIncident) { this.withIncident = withIncident; } @Override protected String getOrderByValue(String sortBy) { return ORDER_BY_VALUES.get(sortBy); } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } public String getOuterOrderBy() { String outerOrderBy = getOrderBy(); if (outerOrderBy == null || outerOrderBy.isEmpty()) { return "ID_ asc"; } else if (outerOrderBy.contains(".")) { return outerOrderBy.substring(outerOrderBy.lastIndexOf(".") + 1); } else { return outerOrderBy; } }
private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) { List<QueryVariableValue> values = new ArrayList<QueryVariableValue>(); if (variables == null) { return values; } for (VariableQueryParameterDto variable : variables) { QueryVariableValue value = new QueryVariableValue( variable.getName(), resolveVariableValue(variable.getValue()), ConditionQueryParameterDto.getQueryOperator(variable.getOperator()), false); value.initialize(variableTypes, dbType); values.add(value); } return values; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\AbstractProcessInstanceQueryDto.java
1
请完成以下Java代码
public void collect(final DocumentFieldDescriptor.Builder field) { Preconditions.checkState(allowCollecting, "allowCollecting shall be true"); final String fieldName = field.getFieldName(); if (!COLUMNNAMES.contains(fieldName)) { return; } final DocumentFieldDescriptor.Builder fieldAlreadyCollected = collectedFields.get(fieldName); if (fieldAlreadyCollected != null) { logger.warn("Skip collecting {} because we already collected {} for same field name", field, fieldAlreadyCollected); return; } collectedFields.put(fieldName, field); } public void collectFinish() { Preconditions.checkState(allowCollecting, "allowCollecting shall be true"); allowCollecting = false; // // Update DocumentNo field flags for (final String fieldName : COLUMNNAMES_DocumentNos) { final DocumentFieldDescriptor.Builder field = collectedFields.get(fieldName); if (field == null) { continue; } field.addCharacteristic(Characteristic.PublicField); field.addCharacteristic(Characteristic.SpecialField_DocumentNo); break; // only first field shall be elected as DocumentNo } } public DocumentFieldDescriptor.Builder getDocumentSummary() { for (final String fieldName : COLUMNNAMES_DocumentSummary) { final DocumentFieldDescriptor.Builder field = collectedFields.get(fieldName); if (field == null) { continue; } field.addCharacteristic(Characteristic.PublicField);
//field.addCharacteristic(Characteristic.SpecialField_DocumentSummary); return field; } return null; } public Map<Characteristic, DocumentFieldDescriptor.Builder> getDocStatusAndDocAction() { final DocumentFieldDescriptor.Builder fieldDocStatus = collectedFields.get(WindowConstants.FIELDNAME_DocStatus); final DocumentFieldDescriptor.Builder fieldDocAction = collectedFields.get(WindowConstants.FIELDNAME_DocAction); if (fieldDocStatus == null || fieldDocAction == null) { return null; } fieldDocStatus.addCharacteristic(Characteristic.PublicField); fieldDocStatus.addCharacteristic(Characteristic.SpecialField_DocStatus); fieldDocAction.addCharacteristic(Characteristic.PublicField); fieldDocAction.addCharacteristic(Characteristic.SpecialField_DocAction); return ImmutableMap.<Characteristic, DocumentFieldDescriptor.Builder> builder() .put(Characteristic.SpecialField_DocStatus, fieldDocStatus) .put(Characteristic.SpecialField_DocAction, fieldDocAction) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\SpecialDocumentFieldsCollector.java
1
请完成以下Java代码
public int getC_BPartner_Location_Value_ID() { return -1; } @Override public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID) { } @Override public int getAD_User_ID() { return delegate.getC_Dunning_Contact_ID(); } @Override public void setAD_User_ID(final int AD_User_ID) {
delegate.setC_Dunning_Contact_ID(AD_User_ID); } @Override public String getBPartnerAddress() { return delegate.getBPartnerAddress(); } @Override public void setBPartnerAddress(String address) { delegate.setBPartnerAddress(address); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningDocDocumentLocationAdapter.java
1
请在Spring Boot框架中完成以下Java代码
KotlinGradleBuildCustomizer kotlinBuildCustomizerGroovyDsl(KotlinProjectSettings kotlinProjectSettings) { return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\''); } /** * Configuration for Kotlin projects using Spring Boot 2.0 and later. */ @Configuration @ConditionalOnPlatformVersion("2.0.0.M1") static class SpringBoot2AndLaterKotlinProjectGenerationConfiguration { @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) KotlinMavenBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { return new KotlinMavenBuildCustomizer(kotlinProjectSettings); } @Bean MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor( ProjectDescription description) { return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main") .parameters(Parameter.of("args", "Array<String>")) .body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication", description.getApplicationName()))); } } /** * Kotlin source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID)
static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) { return (typeDeclaration) -> { KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure") .modifiers(KotlinModifier.OVERRIDE) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("return application.sources($L::class.java)", description.getApplicationName())); typeDeclaration.addFunctionDeclaration(configure); }; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationDefaultContributorsConfiguration.java
2
请完成以下Java代码
public DetailsBuilder maxJobsPerAcquisition(int maxJobsPerAcquisition) { this.maxJobsPerAcquisition = maxJobsPerAcquisition; return this; } public DetailsBuilder waitTimeInMillis(int waitTimeInMillis) { this.waitTimeInMillis = waitTimeInMillis; return this; } public DetailsBuilder processEngineName(String processEngineName) { if (this.processEngineNames == null) { this.processEngineNames = new HashSet<String>(); } this.processEngineNames.add(processEngineName); return this; } public DetailsBuilder processEngineNames(Set<? extends String> processEngineNames) { if (this.processEngineNames == null) { this.processEngineNames = new HashSet<String>(); } this.processEngineNames.addAll(processEngineNames); return this; } public DetailsBuilder clearProcessEngineNames(Set<? extends String> processEngineNames) { if (this.processEngineNames != null) { this.processEngineNames.clear(); } return this; } public Details build() { return new Details(this); } } public String getName() { return name; } public String getLockOwner() { return lockOwner; } public int getLockTimeInMillis() {
return lockTimeInMillis; } public int getMaxJobsPerAcquisition() { return maxJobsPerAcquisition; } public int getWaitTimeInMillis() { return waitTimeInMillis; } public Set<String> getProcessEngineNames() { return processEngineNames; } @Override public String toString() { return "Details [name=" + name + ", lockOwner=" + lockOwner + ", lockTimeInMillis=" + lockTimeInMillis + ", maxJobsPerAcquisition=" + maxJobsPerAcquisition + ", waitTimeInMillis=" + waitTimeInMillis + ", processEngineNames=" + processEngineNames + "]"; } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\actuator\JobExecutorHealthIndicator.java
1
请完成以下Java代码
public class PMM_PurchaseCandidate_TabCallout extends TabCalloutAdapter implements IStatefulTabCallout { private FacetExecutor<I_PMM_PurchaseCandidate> gridTabFacetExecutor; /** * Action: Create purchase orders */ private PMM_CreatePurchaseOrders_Action action_CreatePurchaseOrders = null; @Override public void onInit(final ICalloutRecord calloutRecord) { final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord); if(gridTab == null) { return; } final ISideActionsGroupsListModel sideActionsGroupsModel = gridTab.getSideActionsGroupsModel(); // // Add action: Create purchase orders { action_CreatePurchaseOrders = new PMM_CreatePurchaseOrders_Action(gridTab); sideActionsGroupsModel .getGroupById(GridTab.SIDEACTIONS_Actions_GroupId) .addAction(action_CreatePurchaseOrders); } // // Setup facet filtering engine { gridTabFacetExecutor = new FacetExecutor<>(I_PMM_PurchaseCandidate.class); // Current facets will be displayed in GridTab's right-side panel final IFacetsPool<I_PMM_PurchaseCandidate> facetsPool = new SideActionFacetsPool<>(sideActionsGroupsModel); gridTabFacetExecutor.setFacetsPool(facetsPool); // The datasource which will be filtered by our facets is actually THIS grid tab final IFacetFilterable<I_PMM_PurchaseCandidate> facetFilterable = new GridTabFacetFilterable<>(I_PMM_PurchaseCandidate.class, gridTab); gridTabFacetExecutor.setFacetFilterable(facetFilterable); // We will use service registered collectors to collect the facets from our rows
final IFacetCollector<I_PMM_PurchaseCandidate> facetCollectors = Services.get(IPurchaseCandidateFacetCollectorFactory.class).createFacetCollectors(); gridTabFacetExecutor.addFacetCollector(facetCollectors); } } @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { updateFacets(calloutRecord); } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { // NOTE: we are not updating the facets on refresh all because following case would fail: // Case: user is pressing the "Refresh" toolbar button to refresh THE content of the grid, // but user is not expecting to have all it's facets reset. // updateFacets(gridTab); } /** * Retrieve facets from current grid tab rows and add them to window side panel * * @param calloutRecord */ private void updateFacets(final ICalloutRecord calloutRecord) { // // If user asked to approve for invoicing some ICs, the grid will be asked to refresh all, // but in this case we don't want to reset current facets and recollect them if (action_CreatePurchaseOrders.isRunning()) { return; } // // Collect the facets from current grid tab rows and fully update the facets pool. gridTabFacetExecutor.collectFacetsAndResetPool(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\callout\PMM_PurchaseCandidate_TabCallout.java
1
请完成以下Java代码
class RunProcessCommand extends AbstractCommand { private final String[] command; private volatile @Nullable RunProcess process; RunProcessCommand(String... command) { super("", ""); this.command = command; } @Override public ExitStatus run(String... args) throws Exception { return run(Arrays.asList(args)); } protected ExitStatus run(Collection<String> args) throws IOException { RunProcess process = new RunProcess(this.command); this.process = process; int code = process.run(true, StringUtils.toStringArray(args));
if (code == 0) { return ExitStatus.OK; } else { return new ExitStatus(code, "EXTERNAL_ERROR"); } } boolean handleSigInt() { RunProcess process = this.process; Assert.state(process != null, "'process' must not be null"); return process.handleSigInt(); } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\RunProcessCommand.java
1
请完成以下Java代码
public Boolean getVariableNamesIgnoreCase() { return variableNamesIgnoreCase; } public Boolean getVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } public String getTaskOwnerLike() { return taskOwnerLike; } public String getTaskOwner() { return taskOwner; } public Integer getTaskPriority() { return taskPriority; } public String getTaskParentTaskId() { return taskParentTaskId; } public String[] getTenantIds() { return tenantIds; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore;
} public boolean isTenantIdSet() { return isTenantIdSet; } public List<HistoricTaskInstanceQueryImpl> getQueries() { return queries; } public boolean isOrQueryActive() { return isOrQueryActive; } public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) { orQuery.isOrQueryActive = true; this.queries.add(orQuery); } public void setOrQueryActive() { isOrQueryActive = true; } @Override public HistoricTaskInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public HistoricTaskInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PrintingServiceImpl implements IPrintingService { private final String printerName; private final String printerType; private final boolean isDirectPrint; PrintingServiceImpl(String printerName, String printerType, boolean isDirectPrint) { if (printerName == null) throw new AdempiereException("printerName is null"); if (printerType == null) throw new AdempiereException("printerType is null"); this.printerName = printerName; this.printerType = printerType; this.isDirectPrint = isDirectPrint; } @Override public String getPrinterName() { return printerName; } @Override public String getPrinterType() { return printerType; } @Override public boolean isDirectPrint() { return isDirectPrint; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (isDirectPrint ? 1231 : 1237); result = prime * result + ((printerName == null) ? 0 : printerName.hashCode()); result = prime * result + ((printerType == null) ? 0 : printerType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null)
return false; if (getClass() != obj.getClass()) return false; PrintingServiceImpl other = (PrintingServiceImpl)obj; if (isDirectPrint != other.isDirectPrint) return false; if (printerName == null) { if (other.printerName != null) return false; } else if (!printerName.equals(other.printerName)) return false; if (printerType == null) { if (other.printerType != null) return false; } else if (!printerType.equals(other.printerType)) return false; return true; } @Override public String toString() { return "PrintingServiceImpl [printerName=" + printerName + ", printerType=" + printerType + ", isDirectPrint=" + isDirectPrint + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\PrintingServiceImpl.java
2
请完成以下Java代码
protected I_M_HU_LUTU_Configuration createM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration template) { // Validate parameters final int M_LU_HU_PI_ID = p_M_LU_HU_PI_ID; final int M_HU_PI_Item_Product_ID = p_M_HU_PI_Item_Product_ID; final BigDecimal qtyCUsPerTU = p_QtyCUsPerTU; final BigDecimal qtyTU = p_QtyTU; final BigDecimal qtyLU = p_QtyLU; if (M_HU_PI_Item_Product_ID <= 0) { throw new FillMandatoryException(PARAM_M_HU_PI_Item_Product_ID); } if (qtyCUsPerTU == null || qtyCUsPerTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } if (qtyTU == null || qtyTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyTU); } if (M_LU_HU_PI_ID > 0 && qtyLU.signum() <= 0) {
throw new FillMandatoryException(PARAM_QtyLU); } final ILUTUConfigurationFactory.CreateLUTUConfigRequest lutuConfigRequest = ILUTUConfigurationFactory.CreateLUTUConfigRequest.builder() .baseLUTUConfiguration(template) .qtyLU(qtyLU) .qtyTU(qtyTU) .qtyCUsPerTU(qtyCUsPerTU) .tuHUPIItemProductID(M_HU_PI_Item_Product_ID) .luHUPIID(M_LU_HU_PI_ID) .build(); return lutuConfigurationFactory.createNewLUTUConfigWithParams(lutuConfigRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_UsingConfig.java
1
请完成以下Java代码
public String getTableName() { final Document document = getDocument(); return document.getEntityDescriptor().getTableName(); } @Override public int getAD_Tab_ID() { final Document document = getDocument(); return document.getEntityDescriptor().getAdTabId().getRepoId(); } @Override public <T> T getModel(final Class<T> modelClass) { final Document document = getDocument(); return DocumentInterfaceWrapper.wrap(document, modelClass); } @Override public <T> T getModelBeforeChanges(final Class<T> modelClass) { final Document document = getDocument(); return DocumentInterfaceWrapper.wrapUsingOldValues(document, modelClass); } @Override public Object getValue(final String columnName) { final Document document = getDocument(); return InterfaceWrapperHelper.getValueOrNull(document, columnName); } @Override public String setValue(final String columnName, final Object value) { final Document document = getDocument(); document.setValue(columnName, value, REASON_Value_DirectSetOnCalloutRecord); return ""; } @Override public void dataRefresh() { final Document document = getDocument(); document.refreshFromRepository(); } @Override public void dataRefreshAll() { // NOTE: there is no "All" concept here, so we are just refreshing this document
final Document document = getDocument(); document.refreshFromRepository(); } @Override public void dataRefreshRecursively() { // TODO dataRefreshRecursively: refresh document and it's children throw new UnsupportedOperationException(); } @Override public boolean dataSave(final boolean manualCmd) { // TODO dataSave: save document but also update the DocumentsCollection! throw new UnsupportedOperationException(); } @Override public boolean isLookupValuesContainingId(@NonNull final String columnName, @NonNull final RepoIdAware id) { //Querying all values because getLookupValueById doesn't take validation rul into consideration. // TODO: Implement possibility to fetch sqllookupbyid with validation rule considered. return getDocument().getFieldLookupValues(columnName).containsId(id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentAsCalloutRecord.java
1
请完成以下Java代码
public boolean isProcessed() { return false; } @Override public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return values.getViewEditorRenderModeByFieldName(); } public BPartnerId getBPartnerId() {
return bpartner.getIdAs(BPartnerId::ofRepoId); } public InvoiceRow withPreparedForAllocationSet() { return withPreparedForAllocation(true); } public InvoiceRow withPreparedForAllocationUnset() { return withPreparedForAllocation(false); } public InvoiceRow withPreparedForAllocation(final boolean isPreparedForAllocation) { return this.isPreparedForAllocation != isPreparedForAllocation ? toBuilder().isPreparedForAllocation(isPreparedForAllocation).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRow.java
1
请在Spring Boot框架中完成以下Java代码
public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) { BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver(); beetlSpringViewResolver.setContentType("text/html;charset=UTF-8"); beetlSpringViewResolver.setOrder(0); beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration); return beetlSpringViewResolver; } //配置包扫描 @Bean(name = "beetlSqlScannerConfigurer") public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() { BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer(); conf.setBasePackage("com.forezp.dao"); conf.setDaoSuffix("Dao"); conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean"); return conf; } @Bean(name = "sqlManagerFactoryBean") @Primary public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("datasource") DataSource datasource) { SqlManagerFactoryBean factory = new SqlManagerFactoryBean(); BeetlSqlDataSource source = new BeetlSqlDataSource();
source.setMasterSource(datasource); factory.setCs(source); factory.setDbStyle(new MySqlStyle()); factory.setInterceptors(new Interceptor[]{new DebugInterceptor()}); factory.setNc(new UnderlinedNameConversion());//开启驼峰 factory.setSqlLoader(new ClasspathLoader("/sql"));//sql文件路径 return factory; } //配置数据库 @Bean(name = "datasource") public DataSource getDataSource() { return DataSourceBuilder.create().url("jdbc:mysql://127.0.0.1:3306/test").username("root").password("123456").build(); } //开启事务 @Bean(name = "txManager") public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("datasource") DataSource datasource) { DataSourceTransactionManager dsm = new DataSourceTransactionManager(); dsm.setDataSource(datasource); return dsm; } }
repos\SpringBootLearning-master\springboot-beatlsql\src\main\java\com\forezp\SpringbootBeatlsqlApplication.java
2
请完成以下Java代码
public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Geschäftspartner. @return Bezeichnet einen Geschäftspartner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class); } @Override public void setC_BPartner_Location(org.compiere.model.I_C_BPartner_Location C_BPartner_Location) { set_ValueFromPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class, C_BPartner_Location); } /** Set Standort. @param C_BPartner_Location_ID Identifiziert die (Liefer-) Adresse des Geschäftspartners */ @Override public void setC_BPartner_Location_ID (int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID)); } /** Get Standort. @return Identifiziert die (Liefer-) Adresse des Geschäftspartners */ @Override public int getC_BPartner_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Body. @param LetterBody Body */ @Override public void setLetterBody (java.lang.String LetterBody) { set_Value (COLUMNNAME_LetterBody, LetterBody); } /** Get Body. @return Body */ @Override public java.lang.String getLetterBody () { return (java.lang.String)get_Value(COLUMNNAME_LetterBody); }
/** Set Subject. @param LetterSubject Subject */ @Override public void setLetterSubject (java.lang.String LetterSubject) { set_Value (COLUMNNAME_LetterSubject, LetterSubject); } /** Get Subject. @return Subject */ @Override public java.lang.String getLetterSubject () { return (java.lang.String)get_Value(COLUMNNAME_LetterSubject); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (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.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_T_Letter_Spool.java
1
请完成以下Java代码
public MQuery getDrillDown (Point relativePoint) { MQuery retValue = null; for (int i = 0; i < m_elements.size() && retValue == null; i++) { PrintElement element = m_elements.get(i); retValue = element.getDrillDown (relativePoint, m_pageNo); } return retValue; } // getDrillDown /** * Get DrillAcross value * @param relativePoint relative Point * @return if found Query or null */ public MQuery getDrillAcross (Point relativePoint) { MQuery retValue = null; for (int i = 0; i < m_elements.size() && retValue == null; i++) { PrintElement element = m_elements.get(i); retValue = element.getDrillAcross (relativePoint, m_pageNo); } return retValue; } // getDrillAcross /** * set Background Image * @param image */ public void setBackgroundImage(Image image) { m_image = image; } /** * get Background Image * @return */ public Image getBackgroundImage()
{ return m_image; } /** * String Representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("Page["); sb.append(m_pageNo).append(",Elements=").append(m_elements.size()); sb.append("]"); return sb.toString(); } // toString } // Page
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Page.java
1
请完成以下Java代码
public java.math.BigDecimal getRfQ_SelectedWinners_QtySum () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RfQ_SelectedWinners_QtySum); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Use line quantity. @param UseLineQty Use line quantity */ @Override public void setUseLineQty (boolean UseLineQty) { set_Value (COLUMNNAME_UseLineQty, Boolean.valueOf(UseLineQty)); }
/** Get Use line quantity. @return Use line quantity */ @Override public boolean isUseLineQty () { Object oo = get_Value(COLUMNNAME_UseLineQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLine.java
1
请完成以下Java代码
public class SingletonMigrationLoggerContext implements IMigrationLoggerContext { private final I_AD_Migration migration; private boolean generateComments = false; public SingletonMigrationLoggerContext(final I_AD_Migration migration) { Check.assumeNotNull(migration, "migration not null"); this.migration = migration; } /** * @return true always */ @Override public boolean isEnabled() { return true; } @Override public I_AD_Migration getMigration(String key)
{ return migration; } @Override public void putMigration(String key, I_AD_Migration migration) { throw new UnsupportedOperationException(); } @Override public boolean isGenerateComments() { return generateComments; } public void setGenerateComments(final boolean generateComments) { this.generateComments = generateComments; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\SingletonMigrationLoggerContext.java
1
请完成以下Java代码
public void setReplenish_MinQty (final BigDecimal Replenish_MinQty) { set_Value (COLUMNNAME_Replenish_MinQty, Replenish_MinQty); } @Override public BigDecimal getReplenish_MinQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Replenish_MinQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStorageAttributesKey (final java.lang.String StorageAttributesKey) { set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return get_ValueAsString(COLUMNNAME_StorageAttributesKey); } @Override public void setUserElementString1 (final @Nullable java.lang.String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public java.lang.String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } @Override public void setUserElementString2 (final @Nullable java.lang.String UserElementString2) { set_Value (COLUMNNAME_UserElementString2, UserElementString2); } @Override public java.lang.String getUserElementString2() { return get_ValueAsString(COLUMNNAME_UserElementString2); } @Override public void setUserElementString3 (final @Nullable java.lang.String UserElementString3) { set_Value (COLUMNNAME_UserElementString3, UserElementString3); } @Override public java.lang.String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override public java.lang.String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); } @Override public void setUserElementString5 (final @Nullable java.lang.String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public java.lang.String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable java.lang.String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public java.lang.String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate.java
1
请完成以下Java代码
public class Passenger { private String name; private int age; private String source; private String destination; public Passenger(String name, int age, String source, String destination) { this.name = name; this.age = age; this.source = source; this.destination = destination; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }
public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } }
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\listvsarraylist\Passenger.java
1
请完成以下Java代码
public void setOnMouseOut (String script) { addAttribute ("onmouseout", script); } /** * The onkeypress event occurs when a key is pressed and released over an * element. This attribute may be used with most elements. * * @param script script */ public void setOnKeyPress (String script) { addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements.
* * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\acronym.java
1
请完成以下Java代码
public class RateLimitsTrigger implements NotificationRuleTrigger { @Serial private static final long serialVersionUID = -4423112145409424886L; private final TenantId tenantId; private final LimitedApi api; private final EntityId limitLevel; private final String limitLevelEntityName; @Override public NotificationRuleTriggerType getType() { return NotificationRuleTriggerType.RATE_LIMITS; } @Override public EntityId getOriginatorEntityId() { return limitLevel != null ? limitLevel : tenantId; }
@Override public DeduplicationStrategy getDeduplicationStrategy() { return DeduplicationStrategy.ALL; } @Override public String getDeduplicationKey() { return String.join(":", NotificationRuleTrigger.super.getDeduplicationKey(), api.toString()); } @Override public long getDefaultDeduplicationDuration() { return TimeUnit.HOURS.toMillis(4); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\rule\trigger\RateLimitsTrigger.java
1
请完成以下Spring Boot application配置
spring.sql.init.platform=mysql spring.datasource.url=jdbc:mysql://localhost:3306/jdbc_authentication spring.datasource.username=root spring.datasource.password
=pass spring.sql.init.mode=always spring.jpa.hibernate.ddl-auto=none
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\resources\application-mysql.properties
2
请完成以下Java代码
public static List<String> getAttributeKeys(OtaPackageType firmwareType) { switch (firmwareType) { case FIRMWARE: return ALL_FW_ATTRIBUTE_KEYS; case SOFTWARE: return ALL_SW_ATTRIBUTE_KEYS; } return Collections.emptyList(); } public static String getAttributeKey(OtaPackageType type, OtaPackageKey key) { return type.getKeyPrefix() + "_" + key.getValue(); } public static String getTargetTelemetryKey(OtaPackageType type, OtaPackageKey key) { return getTelemetryKey("target_", type, key); } public static String getCurrentTelemetryKey(OtaPackageType type, OtaPackageKey key) { return getTelemetryKey("current_", type, key); } private static String getTelemetryKey(String prefix, OtaPackageType type, OtaPackageKey key) { return prefix + type.getKeyPrefix() + "_" + key.getValue(); } public static String getTelemetryKey(OtaPackageType type, OtaPackageKey key) { return type.getKeyPrefix() + "_" + key.getValue(); } public static OtaPackageId getOtaPackageId(HasOtaPackage entity, OtaPackageType type) { switch (type) {
case FIRMWARE: return entity.getFirmwareId(); case SOFTWARE: return entity.getSoftwareId(); default: log.warn("Unsupported ota package type: [{}]", type); return null; } } public static <T> T getByOtaPackageType(Supplier<T> firmwareSupplier, Supplier<T> softwareSupplier, OtaPackageType type) { switch (type) { case FIRMWARE: return firmwareSupplier.get(); case SOFTWARE: return softwareSupplier.get(); default: throw new RuntimeException("Unsupported OtaPackage type: " + type); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ota\OtaPackageUtil.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeId() { return scopeId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getMetaInfo() { return metaInfo; } @Override public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } @Override public ByteArrayRef getByteArrayRef() { return byteArrayRef; }
// common methods ////////////////////////////////////////////////////////// protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class DefaultGroupingProvider implements IOLCandGroupingProvider { /** * The method returns those candidate values such as <code>M_Product_ID</code> or <code>C_BPartner_ID</code>, that * always result in different order lines if they are different. * * @return a list of values that will be transformed into a grouping key */ @Override public List<Object> provideLineGroupingValues(final OLCand olCand) { final List<Object> groupingValues = new ArrayList<>(); // // add the values that always result in different order lines and thus need to be considered as grouping keys. // Note that these values might or might not result in different orders as well groupingValues.add(olCand.getM_Product_ID()); groupingValues.add(olCand.getC_Charge_ID()); groupingValues.add(olCand.getM_AttributeSet_ID());
groupingValues.add(olCand.getM_AttributeSetInstance_ID()); groupingValues.add(olCand.getQty().getUomId()); groupingValues.add(olCand.getWarehouseDestId()); groupingValues.add(olCand.getBPartnerInfo()); groupingValues.add(olCand.getBillBPartnerInfo()); groupingValues.add(olCand.getDateOrdered()); // task 06269 note that for now we set datepromised only in the header, so different DatePromised values result in different orders, and all ol have the same datepromised groupingValues.add(olCand.getDatePromised()); return groupingValues; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\DefaultGroupingProvider.java
2
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final ShoppingCartService shoppingCartService; public MainApplication(ShoppingCartService shoppingCartService) { this.shoppingCartService = shoppingCartService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> {
System.out.println("Fetch shopping cart ..."); List<ShoppingCartDto> sc1 = shoppingCartService.allShoppingCart(); sc1.forEach(a -> { System.out.println("\nOwner: " + a.getOwner() + " Title: " + a.getTitle() + " Price: " + a.getPrice()); }); System.out.println("\nFetch shopping cart by price ..."); List<ShoppingCartDto> sc2 = shoppingCartService.byPriceShoppingCart(); sc2.forEach(a -> { System.out.println("\nOwner: " + a.getOwner() + " Title: " + a.getTitle() + " Price: " + a.getPrice()); }); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoElementCollection\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public I_PP_Order_BOMLine retrieveOrderBOMLine(@NonNull final I_PP_Order ppOrder, @NonNull final I_M_Product product) { return queryBL.createQueryBuilder(I_PP_Order_BOMLine.class, ppOrder) .addEqualsFilter(I_PP_Order_BOMLine.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID()) .addEqualsFilter(I_PP_Order_BOMLine.COLUMNNAME_M_Product_ID, product.getM_Product_ID()) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_PP_Order_BOMLine.class); } @Override public void deleteOrderBOMLinesByOrderId(@NonNull final PPOrderId orderId) { final List<I_PP_Order_BOMLine> lines = queryBL .createQueryBuilder(I_PP_Order_BOMLine.class) .addEqualsFilter(I_PP_Order_BOMLine.COLUMN_PP_Order_ID, orderId) // .addOnlyActiveRecordsFilter() .create() .list(); for (final I_PP_Order_BOMLine line : lines) { line.setProcessed(false); InterfaceWrapperHelper.delete(line); } } @Override public int retrieveNextLineNo(@NonNull final PPOrderId orderId) { Integer maxLine = queryBL .createQueryBuilder(I_PP_Order_BOMLine.class) .addEqualsFilter(I_PP_Order_BOMLine.COLUMNNAME_PP_Order_ID, orderId) .create() .aggregate(I_PP_Order_BOMLine.COLUMNNAME_Line, Aggregate.MAX, Integer.class); if (maxLine == null) { maxLine = 0; } final int nextLine = maxLine + 10; return nextLine; } @Override public void save(@NonNull final I_PP_Order_BOM orderBOM) { saveRecord(orderBOM); } @Override public void save(@NonNull final I_PP_Order_BOMLine orderBOMLine) { saveRecord(orderBOMLine); }
@Override public void deleteByOrderId(@NonNull final PPOrderId orderId) { final I_PP_Order_BOM orderBOM = getByOrderIdOrNull(orderId); if (orderBOM != null) { InterfaceWrapperHelper.delete(orderBOM); } } @Override public void markBOMLinesAsProcessed(@NonNull final PPOrderId orderId) { for (final I_PP_Order_BOMLine orderBOMLine : retrieveOrderBOMLines(orderId)) { orderBOMLine.setProcessed(true); save(orderBOMLine); } } @Override public void markBOMLinesAsNotProcessed(@NonNull final PPOrderId orderId) { for (final I_PP_Order_BOMLine orderBOMLine : retrieveOrderBOMLines(orderId)) { orderBOMLine.setProcessed(false); save(orderBOMLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMDAO.java
1
请完成以下Spring Boot application配置
# Security configuration for Apache Geode using Spring Boot and Spring Data for Apache Geode (SDG) properties spring.boot.data.gemfire.security.ssl.keystore.name=example-trusted-keystore.jks spring.data.gemfire.security.username=test spring.data.gemfire.security.password=tes
t spring.data.gemfire.security.ssl.keystore.password=s3cr3t spring.data.gemfire.security.ssl.truststore.password=s3cr3t
repos\spring-boot-data-geode-main\spring-geode-samples\boot\configuration\src\main\resources\application-security.properties
2
请完成以下Java代码
public void postHandleSingleHistoryEventCreated(HistoryEvent event) { ((JobEntity) job).setLastFailureLogId(event.getId()); } }); } } public void fireJobSuccessfulEvent(final Job job) { if (isHistoryEventProduced(HistoryEventTypes.JOB_SUCCESS, job)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricJobLogSuccessfulEvt(job); } }); } } public void fireJobDeletedEvent(final Job job) { if (isHistoryEventProduced(HistoryEventTypes.JOB_DELETE, job)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricJobLogDeleteEvt(job); } });
} } // helper ///////////////////////////////////////////////////////// protected boolean isHistoryEventProduced(HistoryEventType eventType, Job job) { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); HistoryLevel historyLevel = configuration.getHistoryLevel(); return historyLevel.isHistoryEventProduced(eventType, job); } protected void configureQuery(HistoricJobLogQueryImpl query) { getAuthorizationManager().configureHistoricJobLogQuery(query); getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricJobLogManager.java
1
请在Spring Boot框架中完成以下Java代码
public static String getParamStr(Map<String , Object> paramMap){ SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap); StringBuffer stringBuffer = new StringBuffer(); for (Map.Entry<String, Object> m : smap.entrySet()) { Object value = m.getValue(); if (value != null && StringUtils.isNotBlank(String.valueOf(value))){ stringBuffer.append(m.getKey()).append("=").append(value).append("&"); } } stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length()); return stringBuffer.toString(); } /** * 验证商户签名 * @param paramMap 签名参数 * @param paySecret 签名私钥 * @param signStr 原始签名密文 * @return
*/ public static boolean isRightSign(Map<String , Object> paramMap , String paySecret ,String signStr){ if (StringUtils.isBlank(signStr)){ return false; } String sign = getSign(paramMap, paySecret); if(signStr.equals(sign)){ return true; }else{ return false; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\MerchantApiUtil.java
2
请在Spring Boot框架中完成以下Java代码
public class PublishTask { private static final Logger LOG = LoggerFactory.getLogger(PublishTask.class); private final List<UserData> users; private final int startIndex; private final int n; private final Subscriber<? super UserData> subscriber; private boolean stopped; public PublishTask(List<UserData> users, long startIndex, long n, Subscriber<? super UserData> subscriber) { this.users = users; this.startIndex = (int)startIndex; this.n = (int)n; this.subscriber = subscriber; this.stopped = false; } public void publish() { int si = stopIndex(users.size(), startIndex, n); LOG.info("Publishing started size={} fromIndex={} n={} stopIndex={}", users.size(), startIndex, n, si); int i = startIndex; if (startIndex < users.size()) { for (; i<si; i++) { if (stopped) { LOG.info("interrupted {}", i); return; } UserData userData = users.get(i); LOG.info(" Publishing {} {}:{}:{}", i, userData.getId(), userData.getEmail(), userData.getName()); subscriber.onNext(userData); /* try { Thread.sleep(10); } catch (InterruptedException e) { LOG.error("Error: {}", e.getMessage());
} */ } if (i == users.size()) { LOG.info("onComplete"); subscriber.onComplete(); } } else { LOG.info("onComplete"); subscriber.onComplete(); } LOG.info("Publishing done {}", i); } private int stopIndex(int size, int startIndex, int n) { if ((startIndex + n) >= size) { return size; } else { return (startIndex + n); } } public void setStopped() { LOG.info("setStopped"); this.stopped = true; } }
repos\spring-examples-java-17\spring-webflux\src\main\java\itx\examples\webflux\services\PublishTask.java
2
请完成以下Java代码
public class Party6Choice { @XmlElement(name = "OrgId") protected OrganisationIdentification4 orgId; @XmlElement(name = "PrvtId") protected PersonIdentification5 prvtId; /** * Gets the value of the orgId property. * * @return * possible object is * {@link OrganisationIdentification4 } * */ public OrganisationIdentification4 getOrgId() { return orgId; } /** * Sets the value of the orgId property. * * @param value * allowed object is * {@link OrganisationIdentification4 } * */ public void setOrgId(OrganisationIdentification4 value) { this.orgId = value; } /** * Gets the value of the prvtId property. * * @return * possible object is
* {@link PersonIdentification5 } * */ public PersonIdentification5 getPrvtId() { return prvtId; } /** * Sets the value of the prvtId property. * * @param value * allowed object is * {@link PersonIdentification5 } * */ public void setPrvtId(PersonIdentification5 value) { this.prvtId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\Party6Choice.java
1
请在Spring Boot框架中完成以下Java代码
public void setCustomerNumber(String value) { this.customerNumber = value; } /** * Gets the value of the contact property. * * @return * possible object is * {@link String } * */ public String getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link String } * */ public void setContact(String value) { this.contact = value; } /** * Gets the value of the phone property. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */ public void setPhone(String value) { this.phone = value; } /** * Gets the value of the fax property. * * @return * possible object is * {@link String } * */ public String getFax() { return fax; } /** * Sets the value of the fax property. * * @param value * allowed object is * {@link String } * */ public void setFax(String value) { this.fax = value; } /** * Gets the value of the email property. * * @return * possible object is * {@link String } * */ public String getEmail() { return email; } /**
* Sets the value of the email property. * * @param value * allowed object is * {@link String } * */ public void setEmail(String value) { this.email = value; } /** * Gets the value of the comment property. * * @return * possible object is * {@link String } * */ public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ public void setComment(String value) { this.comment = value; } /** * Gets the value of the iaccount property. * * @return * possible object is * {@link String } * */ public String getIaccount() { return iaccount; } /** * Sets the value of the iaccount property. * * @param value * allowed object is * {@link String } * */ public void setIaccount(String value) { this.iaccount = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Address.java
2
请完成以下Java代码
public void setIsEUOneStopShop (final boolean IsEUOneStopShop) { set_Value (COLUMNNAME_IsEUOneStopShop, IsEUOneStopShop); } @Override public boolean isEUOneStopShop() { return get_ValueAsBoolean(COLUMNNAME_IsEUOneStopShop); } @Override public void setIsSummary (final boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, IsSummary); } @Override public boolean isSummary() { return get_ValueAsBoolean(COLUMNNAME_IsSummary); } @Override public void setName (final java.lang.String Name) {
set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org.java
1
请完成以下Java代码
public InputStream getInputStream() { if (bytes == null) { try { bytes = getBytesFromInputStream(inputStream); } catch (IOException e) { throw new ActivitiException("Could not read from inputstream", e); } } return new BufferedInputStream(new ByteArrayInputStream(bytes)); } public String toString() { return "InputStream"; } public byte[] getBytesFromInputStream(InputStream inStream) throws IOException { long length = inStream.available();
byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = inStream.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new ActivitiException("Could not completely read inputstream "); } // Close the input stream and return bytes inStream.close(); return bytes; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\io\InputStreamSource.java
1
请在Spring Boot框架中完成以下Java代码
public Result update(@RequestBody AdminUser user, @TokenToUser AdminUser loginUser) { if (loginUser == null) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!"); } if (StringUtils.isEmpty(user.getPassword())) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "请输入密码!"); } AdminUser tempUser = adminUserService.selectById(user.getId()); if (tempUser == null) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "无此用户!"); } if ("admin".endsWith(tempUser.getUserName().trim())) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "不能修改admin用户!"); } tempUser.setPassword(user.getPassword()); if (adminUserService.updatePassword(user) > 0) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("修改失败"); } }
/** * 删除 */ @RequestMapping(value = "/delete", method = RequestMethod.DELETE) public Result delete(@RequestBody Integer[] ids, @TokenToUser AdminUser loginUser) { if (loginUser == null) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!"); } if (ids.length < 1) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!"); } if (adminUserService.deleteBatch(ids) > 0) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("删除失败"); } } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\AdminUserController.java
2
请在Spring Boot框架中完成以下Java代码
public class ListLineItemReductionType { @XmlElement(name = "ReductionAmount") protected BigDecimal reductionAmount; @XmlElement(name = "ReductionRate") protected BigDecimal reductionRate; /** * Used to denote details about the reduction amount. Must be a positive value. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getReductionAmount() { return reductionAmount; } /** * Sets the value of the reductionAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setReductionAmount(BigDecimal value) { this.reductionAmount = value; }
/** * Used to denote details about the reduction rate. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getReductionRate() { return reductionRate; } /** * Sets the value of the reductionRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setReductionRate(BigDecimal value) { this.reductionRate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ListLineItemReductionType.java
2
请完成以下Java代码
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Vertriebsbeauftragter. @param SalesRep_ID Sales Representative or Company Agent */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Vertriebsbeauftragter. @return Sales Representative or Company Agent */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RMA.java
1
请完成以下Java代码
public static HalUser fromUser(User user) { HalUser halUser = new HalUser(); halUser.id = user.getId(); halUser.firstName = user.getFirstName(); halUser.lastName = user.getLastName(); halUser.email = user.getEmail(); halUser.linker.createLink(REL_SELF, user.getId()); return halUser; } public String getId() {
return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\user\HalUser.java
1
请完成以下Java代码
public class SysDepartRole { /**id*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "id") private java.lang.String id; /**部门id*/ @Excel(name = "部门id", width = 15) @Schema(description = "部门id") @Dict(dictTable ="sys_depart",dicText = "depart_name",dicCode = "id") private java.lang.String departId; /**部门角色名称*/ @Excel(name = "部门角色名称", width = 15) @Schema(description = "部门角色名称") private java.lang.String roleName; /**部门角色编码*/ @Excel(name = "部门角色编码", width = 15) @Schema(description = "部门角色编码") private java.lang.String roleCode; /**描述*/ @Excel(name = "描述", width = 15) @Schema(description = "描述") private java.lang.String description;
/**创建人*/ @Excel(name = "创建人", width = 15) @Schema(description = "创建人") private java.lang.String createBy; /**创建时间*/ @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @Schema(description = "创建时间") private java.util.Date createTime; /**更新人*/ @Excel(name = "更新人", width = 15) @Schema(description = "更新人") private java.lang.String updateBy; /**更新时间*/ @Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @Schema(description = "更新时间") private java.util.Date updateTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysDepartRole.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @ContactInfo @NotNull private String contactInfo; public Customer() { } public Customer(final long id, final String contactInfo) { this.id = id; this.contactInfo = contactInfo; } public String getContactInfo() { return contactInfo;
} public void setContactInfo(final String contactInfo) { this.contactInfo = contactInfo; } public long getId() { return id; } public void setId(final long id) { this.id = id; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\dynamicvalidation\model\Customer.java
2
请完成以下Java代码
public void onFreightCostRuleChanged(final I_C_Order order) { updateFreightAmtIfNeeded(order); } @CalloutMethod(columnNames = I_C_Order.COLUMNNAME_DeliveryViaRule) public void onDeliveryViaRuleChanged(final I_C_Order order) { updateFreightAmtIfNeeded(order); } @CalloutMethod(columnNames = I_C_Order.COLUMNNAME_M_Shipper_ID) public void onShipperChanged(final I_C_Order order) { updateFreightAmtIfNeeded(order); } private void updateFreightAmtIfNeeded(final I_C_Order order) {
// Apply on Sales Orders only if (!order.isSOTrx()) { return; } // Don't overwrite a fix price final FreightCostRule freightCostRule = FreightCostRule.ofNullableCode(order.getFreightCostRule()); if (freightCostRule.isFixPrice()) { return; } orderFreightCostService.updateFreightAmt(order); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\callout\C_Order.java
1
请完成以下Java代码
public Iterator<Document> iterator() { try { out.close(); final DataInputStream in = new DataInputStream(new FileInputStream(cache)); return new Iterator<Document>() { @Override public void remove() { throw new RuntimeException("不支持的操作"); } @Override public boolean hasNext() { try { boolean next = in.available() > 0; if (!next) in.close(); return next; } catch (IOException e) { throw new RuntimeException(e);
} } @Override public Document next() { try { return new Document(in); } catch (IOException e) { throw new RuntimeException(e); } } }; } catch (IOException e) { throw new RuntimeException(e); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\FileDataSet.java
1
请在Spring Boot框架中完成以下Java代码
public static class Controlconnection { /** * Timeout to use for control queries. */ private @Nullable Duration timeout; public @Nullable Duration getTimeout() { return this.timeout; } public void setTimeout(@Nullable Duration timeout) { this.timeout = timeout; } } public static class Throttler { /** * Request throttling type. */ private @Nullable ThrottlerType type; /** * Maximum number of requests that can be enqueued when the throttling threshold * is exceeded. */ private @Nullable Integer maxQueueSize; /** * Maximum number of requests that are allowed to execute in parallel. */ private @Nullable Integer maxConcurrentRequests; /** * Maximum allowed request rate. */ private @Nullable Integer maxRequestsPerSecond; /** * How often the throttler attempts to dequeue requests. Set this high enough that * each attempt will process multiple entries in the queue, but not delay requests * too much. */ private @Nullable Duration drainInterval; public @Nullable ThrottlerType getType() { return this.type; } public void setType(@Nullable ThrottlerType type) { this.type = type; } public @Nullable Integer getMaxQueueSize() { return this.maxQueueSize; } public void setMaxQueueSize(@Nullable Integer maxQueueSize) { this.maxQueueSize = maxQueueSize; } public @Nullable Integer getMaxConcurrentRequests() { return this.maxConcurrentRequests; } public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) { this.maxConcurrentRequests = maxConcurrentRequests; } public @Nullable Integer getMaxRequestsPerSecond() { return this.maxRequestsPerSecond; } public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) { this.maxRequestsPerSecond = maxRequestsPerSecond; }
public @Nullable Duration getDrainInterval() { return this.drainInterval; } public void setDrainInterval(@Nullable Duration drainInterval) { this.drainInterval = drainInterval; } } /** * Name of the algorithm used to compress protocol frames. */ public enum Compression { /** * Requires 'net.jpountz.lz4:lz4'. */ LZ4, /** * Requires org.xerial.snappy:snappy-java. */ SNAPPY, /** * No compression. */ NONE } public enum ThrottlerType { /** * Limit the number of requests that can be executed in parallel. */ CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"), /** * Limits the request rate per second. */ RATE_LIMITING("RateLimitingRequestThrottler"), /** * No request throttling. */ NONE("PassThroughRequestThrottler"); private final String type; ThrottlerType(String type) { this.type = type; } public String type() { return this.type; } } }
repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java
2
请完成以下Java代码
public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoginDto login = (LoginDto) o; return Objects.equals(this.user, login.user) && Objects.equals(this.pass, login.pass); } @Override public int hashCode() { return Objects.hash(user, pass); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LoginDto {\n"); sb.append(" user: ") .append(toIndentedString(user)) .append("\n");
sb.append(" pass: ") .append(toIndentedString(pass)) .append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString() .replace("\n", "\n "); } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\LoginDto.java
1
请完成以下Java代码
public Integer getInviteFriendCount() { return inviteFriendCount; } public void setInviteFriendCount(Integer inviteFriendCount) { this.inviteFriendCount = inviteFriendCount; } public Date getRecentOrderTime() { return recentOrderTime; } public void setRecentOrderTime(Date recentOrderTime) { this.recentOrderTime = recentOrderTime; } @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(", memberId=").append(memberId); sb.append(", consumeAmount=").append(consumeAmount);
sb.append(", orderCount=").append(orderCount); sb.append(", couponCount=").append(couponCount); sb.append(", commentCount=").append(commentCount); sb.append(", returnOrderCount=").append(returnOrderCount); sb.append(", loginCount=").append(loginCount); sb.append(", attendCount=").append(attendCount); sb.append(", fansCount=").append(fansCount); sb.append(", collectProductCount=").append(collectProductCount); sb.append(", collectSubjectCount=").append(collectSubjectCount); sb.append(", collectTopicCount=").append(collectTopicCount); sb.append(", collectCommentCount=").append(collectCommentCount); sb.append(", inviteFriendCount=").append(inviteFriendCount); sb.append(", recentOrderTime=").append(recentOrderTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberStatisticsInfo.java
1
请完成以下Java代码
public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } @Override public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ProcessDefinitionImpl that = (ProcessDefinitionImpl) o; return ( version == that.version && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(key, that.key) && Objects.equals(formKey, that.formKey) ); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, name, description, version, key, formKey); } @Override public String toString() { return (
"ProcessDefinition{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", key='" + key + '\'' + ", description='" + description + '\'' + ", formKey='" + formKey + '\'' + ", version=" + version + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessDefinitionImpl.java
1
请完成以下Java代码
public void setAD_RelationType_ID (int AD_RelationType_ID) { if (AD_RelationType_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_RelationType_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_RelationType_ID, Integer.valueOf(AD_RelationType_ID)); } /** Get Relation Type. @return Relation Type */ public int getAD_RelationType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_RelationType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Quell-Datensatz-ID. @param Record_Source_ID Quell-Datensatz-ID */ public void setRecord_Source_ID (int Record_Source_ID) { if (Record_Source_ID < 1) set_Value (COLUMNNAME_Record_Source_ID, null); else set_Value (COLUMNNAME_Record_Source_ID, Integer.valueOf(Record_Source_ID)); } /** Get Quell-Datensatz-ID. @return Quell-Datensatz-ID */ public int getRecord_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_Source_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ziel-Datensatz-ID. @param Record_Target_ID Ziel-Datensatz-ID */ public void setRecord_Target_ID (int Record_Target_ID)
{ if (Record_Target_ID < 1) set_Value (COLUMNNAME_Record_Target_ID, null); else set_Value (COLUMNNAME_Record_Target_ID, Integer.valueOf(Record_Target_ID)); } /** Get Ziel-Datensatz-ID. @return Ziel-Datensatz-ID */ public int getRecord_Target_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_Target_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ 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 */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Relation.java
1
请完成以下Java代码
public void executeTask() { if (!DB.isConnected()) { throw new DBException("No database connection"); } final String lastBuildInfo = Adempiere.getImplementationVersion(); if (lastBuildInfo!= null && lastBuildInfo.endsWith(Adempiere.CLIENT_VERSION_LOCAL_BUILD)) { Loggables.withLogger(logger, Level.WARN).addLog("Not signing the database build with our version={}, because it makes no sense", lastBuildInfo); return; } try {
final String sql = "UPDATE AD_System SET LastBuildInfo = ?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { lastBuildInfo }, ITrx.TRXNAME_None); CacheMgt.get().reset("AD_System"); logger.info("Set AD_System.LastBuildInfo={}", lastBuildInfo); } catch (final Exception ex) { Loggables.withLogger(logger, Level.ERROR).addLog("Failed updating the LastBuildInfo", ex); } Loggables.withLogger(logger, Level.INFO).addLog("Signed the database build with version: {}", lastBuildInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\housekeep\SignDatabaseBuildHouseKeepingTask.java
1
请完成以下Java代码
public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getNamespacePrefix() { return namespacePrefix; } public void setNamespacePrefix(String namespacePrefix) { this.namespacePrefix = namespacePrefix; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (namespacePrefix != null) { sb.append(namespacePrefix);
if (name != null) { sb.append(":").append(name); } } else { sb.append(name); } if (value != null) { sb.append("=").append(value); } return sb.toString(); } @Override public DmnExtensionAttribute clone() { DmnExtensionAttribute clone = new DmnExtensionAttribute(); clone.setValues(this); return clone; } public void setValues(DmnExtensionAttribute otherAttribute) { setName(otherAttribute.getName()); setValue(otherAttribute.getValue()); setNamespacePrefix(otherAttribute.getNamespacePrefix()); setNamespace(otherAttribute.getNamespace()); } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionAttribute.java
1
请在Spring Boot框架中完成以下Java代码
class OrderConfig { @Bean PlatformTransactionManager orderTransactionManager() { return new JpaTransactionManager(orderEntityManagerFactory().getObject()); } @Bean LocalContainerEntityManagerFactoryBean orderEntityManagerFactory() { var vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); var factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(orderDataSource()); factoryBean.setJpaVendorAdapter(vendorAdapter); factoryBean.setPackagesToScan(OrderConfig.class.getPackage().getName()); return factoryBean; } @Bean DataSource orderDataSource() { return new EmbeddedDatabaseBuilder().// setType(EmbeddedDatabaseType.HSQL).// setName("orders").// build(); } }
repos\spring-data-examples-main\jpa\multiple-datasources\src\main\java\example\springdata\jpa\multipleds\order\OrderConfig.java
2
请完成以下Java代码
static String format(String template, Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; }
builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Preconditions.java
1
请完成以下Java代码
public void addDataLoaderRegistrar(DataLoaderRegistrar registrar) { this.dataLoaderRegistrars.add(registrar); } @Override public final Mono<ExecutionGraphQlResponse> execute(ExecutionGraphQlRequest request) { return Mono.deferContextual((contextView) -> { if (!this.isDefaultExecutionIdProvider && request.getExecutionId() == null) { request.configureExecutionInput(RESET_EXECUTION_ID_CONFIGURER); } ExecutionInput executionInput = request.toExecutionInput(); ContextSnapshotFactory factory = ContextPropagationHelper.getInstance(contextView); GraphQLContext graphQLContext = executionInput.getGraphQLContext(); ContextPropagationHelper.saveInstance(factory, graphQLContext); factory.captureFrom(contextView).updateContext(graphQLContext); ExecutionInput executionInputToUse = registerDataLoaders(executionInput); return Mono.fromFuture(this.graphQlSource.graphQl().executeAsync(executionInputToUse)) .onErrorResume((ex) -> ex instanceof GraphQLError, (ex) -> Mono.just(ExecutionResult.newExecutionResult().addError((GraphQLError) ex).build())) .map((result) -> new DefaultExecutionGraphQlResponse(executionInputToUse, result)) .doOnCancel(executionInputToUse::cancel); }); } private ExecutionInput registerDataLoaders(ExecutionInput executionInput) { if (this.hasDataLoaderRegistrations == null) { this.hasDataLoaderRegistrations = initHasDataLoaderRegistrations(); } if (this.hasDataLoaderRegistrations) { GraphQLContext graphQLContext = executionInput.getGraphQLContext(); DataLoaderRegistry existingRegistry = executionInput.getDataLoaderRegistry(); if (existingRegistry == EmptyDataLoaderRegistryInstance.EMPTY_DATALOADER_REGISTRY) { DataLoaderRegistry newRegistry = DataLoaderRegistry.newRegistry().build(); applyDataLoaderRegistrars(newRegistry, graphQLContext); executionInput = executionInput.transform((builder) -> builder.dataLoaderRegistry(newRegistry)); } else { applyDataLoaderRegistrars(existingRegistry, graphQLContext);
} } return executionInput; } private boolean initHasDataLoaderRegistrations() { for (DataLoaderRegistrar registrar : this.dataLoaderRegistrars) { if (registrar.hasRegistrations()) { return true; } } return false; } private void applyDataLoaderRegistrars(DataLoaderRegistry registry, GraphQLContext graphQLContext) { this.dataLoaderRegistrars.forEach((registrar) -> registrar.registerDataLoaders(registry, graphQLContext)); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\DefaultExecutionGraphQlService.java
1
请完成以下Java代码
public IView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = request.getViewId(); viewId.assertWindowId(WINDOWID); final OrderLineDescriptor orderLineDescriptor = request.getParameterAs(VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR, OrderLineDescriptor.class); Check.assumeNotNull(orderLineDescriptor, VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR + " is mandatory!"); final ProductionSimulationRows rows = rowsRepo.getByOrderLineDescriptor(orderLineDescriptor); return ProductionSimulationView.builder() .viewId(viewId) .rows(rows) .build(); } @Override public ViewLayout getViewLayout(final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId)
{ final ITranslatableString caption = adProcessDAO.retrieveProcessNameByClassIfUnique(C_Order_ProductionSimulationView_Launcher.class) .orElse(null); return ViewLayout.builder() .setWindowId(WINDOWID) .setCaption(caption) .allowViewCloseAction(ViewCloseAction.DONE) .setAllowOpeningRowDetails(false) .setTreeCollapsible(true) .setHasTreeSupport(true) .addElementsFromViewRowClass(ProductionSimulationRow.class, viewDataType) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationViewFactory.java
1
请完成以下Java代码
private Payload createFloatPayload(Long index) { float velocity = data.get(index.intValue()); ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity); buffer.rewind(); return DefaultPayload.create(buffer); } /** * Generate sample data * * @return List of random floats */ private List<Float> generateData() { List<Float> dataList = new ArrayList<>(DATA_LENGTH); float velocity = 0; for (int i = 0; i < DATA_LENGTH; i++) { velocity += Math.random(); dataList.add(velocity);
} return dataList; } /** * Get the data used for this client. * * @return list of data values */ public List<Float> getData() { return data; } public void dispose() { this.socket.dispose(); } }
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\FireNForgetClient.java
1