instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void addLabel(E label) { Integer frequency = labelMap.get(label); if (frequency == null) { frequency = 1; } else { ++frequency; } labelMap.put(label, frequency); } public void addLabel(E label, Integer frequency) { Integer innerFrequency = labelMap.get(label); if (innerFrequency == null) { innerFrequency = frequency; } else { innerFrequency += frequency; } labelMap.put(label, innerFrequency); } public boolean containsLabel(E label) { return labelMap.containsKey(label); } public int getFrequency(E label) { Integer frequency = labelMap.get(label); if (frequency == null) return 0; return frequency; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); ArrayList<Map.Entry<E, Integer>> entries = new ArrayList<Map.Entry<E, Integer>>(labelMap.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<E, Integer>>() { @Override public int compare(Map.Entry<E, Integer> o1, Map.Entry<E, Integer> o2) { return -o1.getValue().compareTo(o2.getValue()); } });
for (Map.Entry<E, Integer> entry : entries) { sb.append(entry.getKey()); sb.append(' '); sb.append(entry.getValue()); sb.append(' '); } return sb.toString(); } public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param) { if (param == null) return null; String[] array = param.split(" "); return create(array); } @SuppressWarnings("unchecked") public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param[]) { if (param.length % 2 == 0) return null; int natureCount = (param.length - 1) / 2; Map.Entry<String, Integer>[] entries = (Map.Entry<String, Integer>[]) Array.newInstance(Map.Entry.class, natureCount); for (int i = 0; i < natureCount; ++i) { entries[i] = new AbstractMap.SimpleEntry<String, Integer>(param[1 + 2 * i], Integer.parseInt(param[2 + 2 * i])); } return new AbstractMap.SimpleEntry<String, Map.Entry<String, Integer>[]>(param[0], entries); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\EnumItem.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getKaptchaOpen() { return kaptchaOpen; } public void setKaptchaOpen(Boolean kaptchaOpen) { this.kaptchaOpen = kaptchaOpen; } public Boolean getSwaggerOpen() { return swaggerOpen; } public void setSwaggerOpen(Boolean swaggerOpen) { this.swaggerOpen = swaggerOpen; } public Integer getSessionInvalidateTime() { return sessionInvalidateTime; } public void setSessionInvalidateTime(Integer sessionInvalidateTime) { this.sessionInvalidateTime = sessionInvalidateTime; } public Integer getSessionValidationInterval() { return sessionValidationInterval; } public void setSessionValidationInterval(Integer sessionValidationInterval) { this.sessionValidationInterval = sessionValidationInterval; } public String getFilesUrlPrefix() { return filesUrlPrefix; } public void setFilesUrlPrefix(String filesUrlPrefix) { this.filesUrlPrefix = filesUrlPrefix; } public String getFilesPath() { return filesPath; } public void setFilesPath(String filesPath) { this.filesPath = filesPath;
} public Integer getHeartbeatTimeout() { return heartbeatTimeout; } public void setHeartbeatTimeout(Integer heartbeatTimeout) { this.heartbeatTimeout = heartbeatTimeout; } public String getPicsPath() { return picsPath; } public void setPicsPath(String picsPath) { this.picsPath = picsPath; } public String getPosapiUrlPrefix() { return posapiUrlPrefix; } public void setPosapiUrlPrefix(String posapiUrlPrefix) { this.posapiUrlPrefix = posapiUrlPrefix; } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\properties\MyProperties.java
2
请完成以下Java代码
private Quantity getQtyToPick() { if (qtyToPick != null) { return qtyToPick; } else { return getQtyFromHU(); } } private Quantity getQtyFromHU() { final I_M_HU pickFromHU = handlingUnitsDAO.getById(pickFrom.getHuId()); final ProductId productId = getProductId(); final IHUProductStorage productStorage = huContextFactory .createMutableHUContext() .getHUStorageFactory() .getStorage(pickFromHU) .getProductStorageOrNull(productId); // Allow empty storage. That's the case when we are adding a newly created HU if (productStorage == null) { final I_C_UOM uom = getShipmentScheduleUOM(); return Quantity.zero(uom); } return productStorage.getQty(); } private I_M_ShipmentSchedule getShipmentSchedule() { if (_shipmentSchedule == null) { _shipmentSchedule = shipmentSchedulesRepo.getById(shipmentScheduleId, I_M_ShipmentSchedule.class); } return _shipmentSchedule; }
private I_C_UOM getShipmentScheduleUOM() { return shipmentScheduleBL.getUomOfProduct(getShipmentSchedule()); } private void allocatePickingSlotIfPossible() { if (pickingSlotId == null) { return; } final I_M_ShipmentSchedule shipmentSchedule = getShipmentSchedule(); final BPartnerLocationId bpartnerAndLocationId = shipmentScheduleEffectiveBL.getBPartnerLocationId(shipmentSchedule); huPickingSlotBL.allocatePickingSlotIfPossible(PickingSlotAllocateRequest.builder() .pickingSlotId(pickingSlotId) .bpartnerAndLocationId(bpartnerAndLocationId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PickHUCommand.java
1
请完成以下Java代码
private boolean isInvalidType(MethodParameter parameter, @Nullable Object principal) { if (principal == null) { return false; } Class<?> typeToCheck = parameter.getParameterType(); boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType()); if (isParameterPublisher) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); Class<?> genericType = resolvableType.resolveGeneric(0); if (genericType == null) { return false; } typeToCheck = genericType; } return !ClassUtils.isAssignable(typeToCheck, principal.getClass()); } /** * Configure AuthenticationPrincipal template resolution * <p> * By default, this value is <code>null</code>, which indicates that templates should * not be resolved. * @param templateDefaults - whether to resolve AuthenticationPrincipal templates * parameters * @since 6.4 */ public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) { this.useAnnotationTemplate = templateDefaults != null;
this.scanner = SecurityAnnotationScanners.requireUnique(AuthenticationPrincipal.class, templateDefaults); } /** * Obtains the specified {@link Annotation} on the specified {@link MethodParameter}. * {@link MethodParameter} * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */ private @Nullable AuthenticationPrincipal findMethodAnnotation(MethodParameter parameter) { if (this.useAnnotationTemplate) { return this.scanner.scan(parameter.getParameter()); } AuthenticationPrincipal annotation = parameter.getParameterAnnotation(this.annotationType); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType); if (annotation != null) { return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize(); } } return null; } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\handler\invocation\reactive\AuthenticationPrincipalArgumentResolver.java
1
请完成以下Java代码
public T get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index out of bounds"); } Node<T> current = head; for (int i = 0; i < index; i++) { current = current.next; } return current.value; } public void removeHead() { if (head == null) return; head = head.next; if (head == null) { tail = null; } size--; } public void removeTail() { if (head == null) { return; } if (head.next == null) { head = null; tail = null; } else { Node<T> current = head; while (current.next != tail) { current = current.next; } current.next = null; tail = current; } size--; } public void removeAtIndex(int index) {
if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index out of bounds"); } if (index == 0) { removeHead(); return; } Node<T> current = head; for (int i = 0; i < index - 1; i++) { current = current.next; } if (current.next == tail) { tail = current; } current.next = current.next.next; size--; } public int size() { return size; } @Override public String toString() { StringBuilder builder = new StringBuilder(); Node<T> temp = head; while (temp != null) { builder.append(temp.value) .append("->"); if (temp == tail) builder.append("End"); temp = temp.next; } return builder.toString(); } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\customlinkedlist\CustomLinkedList.java
1
请在Spring Boot框架中完成以下Java代码
public class Address { private @Id @GeneratedValue Long id; private String name; private String city; private String postalCode; Address() { } public Address(String name, String city, String postalCode) { this.name = name; this.city = city; this.postalCode = postalCode; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; }
public void setCity(String city) { this.city = city; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "Address [id=" + id + ", name=" + name + ", city=" + city + ", postalCode=" + postalCode + "]"; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\putvspost\Address.java
2
请完成以下Java代码
@Override public void run(String... args) throws Exception { buildReport(); } private void buildReport() throws IOException, BirtException { final DesignConfig config = new DesignConfig(); final IDesignEngine engine; try { Platform.startup(config); IDesignEngineFactory factory = (IDesignEngineFactory) Platform .createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY); engine = factory.createDesignEngine(config); } catch (Exception ex) { log.error("Exception during creation of DesignEngine", ex); throw ex; } SessionHandle session = engine.newSessionHandle(ULocale.ENGLISH); ReportDesignHandle design = session.createDesign(); design.setTitle("Sample Report"); // The element factory creates instances of the various BIRT elements. ElementFactory factory = design.getElementFactory(); // Create a simple master page that describes how the report will // appear when printed. // // Note: The report will fail to load in the BIRT designer // unless you create a master page. DesignElementHandle element = factory.newSimpleMasterPage("Page Master"); //$NON-NLS-1$ design.getMasterPages().add(element); // Create a grid GridHandle grid = factory.newGridItem(null, 2 /* cols */, 1 /* row */); design.getBody().add(grid); grid.setWidth("100%");
RowHandle row0 = (RowHandle) grid.getRows().get(0); // Create an image and add it to the first cell. ImageHandle image = factory.newImage(null); CellHandle cell = (CellHandle) row0.getCells().get(0); cell.getContent().add(image); image.setURL("\"https://www.baeldung.com/wp-content/themes/baeldung/favicon/favicon-96x96.png\""); // Create a label and add it to the second cell. LabelHandle label = factory.newLabel(null); cell = (CellHandle) row0.getCells().get(1); cell.getContent().add(label); label.setText("Hello, Baeldung world!"); // Save the design and close it. File report = new File(REPORTS_FOLDER); report.mkdirs(); design.saveAs(new File(report, "static_report.rptdesign").getAbsolutePath()); design.close(); log.info("Report generated"); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-birt\src\main\java\com\baeldung\birt\designer\ReportDesignApplication.java
1
请完成以下Java代码
public String getLanguage() { return language; } public void setLanguage(final String language) { this.language = language; } @Override public String toString() { return "News{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + ", language=" + language + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Article article = (Article) o;
if (!Objects.equals(id, article.id)) { return false; } if (!Objects.equals(title, article.title)) { return false; } if (!Objects.equals(content, article.content)) { return false; } return Objects.equals(language, article.language); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (content != null ? content.hashCode() : 0); result = 31 * result + (language != null ? language.hashCode() : 0); return result; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-3\src\main\java\com\baeldung\spring\data\jpa\spel\entity\Article.java
1
请完成以下Java代码
public class AuthenticationFilter implements Filter { private OnIntercept callback; public AuthenticationFilter(OnIntercept callback) { this.callback = callback; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession(false); if (session == null || session.getAttribute("username") == null) { callback.intercept(); FrontCommand command = new LoginCommand(); command.init(httpServletRequest, httpServletResponse); command.process(); } else { chain.doFilter(request, response); } } @Override public void destroy() { } }
repos\tutorials-master\patterns-modules\intercepting-filter\src\main\java\com\baeldung\patterns\intercepting\filter\filters\AuthenticationFilter.java
1
请在Spring Boot框架中完成以下Java代码
public String getCategory() { return category; } @Override public String getParentTaskId() { return parentTaskId; } @Override public String getTenantId() { return tenantId; } @Override public String getFormKey() { return formKey; } @Override
public Set<? extends IdentityLinkInfo> getIdentityLinks() { return identityLinks; } @Override public String getScopeId() { return this.scopeId; } @Override public String getScopeType() { return this.scopeType; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java
2
请完成以下Java代码
public int getM_ProductOperation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Setup Time. @param SetupTime Setup time before starting Production */ public void setSetupTime (BigDecimal SetupTime) { set_Value (COLUMNNAME_SetupTime, SetupTime); } /** Get Setup Time. @return Setup time before starting Production */ public BigDecimal getSetupTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SetupTime); if (bd == null) return Env.ZERO; return bd; } /** Set Teardown Time. @param TeardownTime Time at the end of the operation */ public void setTeardownTime (BigDecimal TeardownTime) { set_Value (COLUMNNAME_TeardownTime, TeardownTime); } /** Get Teardown Time.
@return Time at the end of the operation */ public BigDecimal getTeardownTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TeardownTime); if (bd == null) return Env.ZERO; return bd; } /** Set Runtime per Unit. @param UnitRuntime Time to produce one unit */ public void setUnitRuntime (BigDecimal UnitRuntime) { set_Value (COLUMNNAME_UnitRuntime, UnitRuntime); } /** Get Runtime per Unit. @return Time to produce one unit */ public BigDecimal getUnitRuntime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitRuntime); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_OperationResource.java
1
请在Spring Boot框架中完成以下Java代码
public final String getRecord() { return record; } public final void setRecord(final String record) { this.record = record; } public final String getPartner() { return partner; } public final void setPartner(final String partner) { this.partner = partner; } public final String getMessageNo() { return messageNo; } public final void setMessageNo(final String messageNo) { this.messageNo = messageNo; } public final String getContractValue() { return contractValue; } public final void setContractValue(final String contractValue) { this.contractValue = contractValue; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (contractValue == null ? 0 : contractValue.hashCode()); result = prime * result + (messageNo == null ? 0 : messageNo.hashCode()); result = prime * result + (partner == null ? 0 : partner.hashCode()); result = prime * result + (record == null ? 0 : record.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final T100 other = (T100)obj; if (contractValue == null) { if (other.contractValue != null) { return false; } } else if (!contractValue.equals(other.contractValue)) {
return false; } if (messageNo == null) { if (other.messageNo != null) { return false; } } else if (!messageNo.equals(other.messageNo)) { return false; } if (partner == null) { if (other.partner != null) { return false; } } else if (!partner.equals(other.partner)) { return false; } if (record == null) { if (other.record != null) { return false; } } else if (!record.equals(other.record)) { return false; } return true; } @Override public String toString() { return "T100 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", contractValue=" + contractValue + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\T100.java
2
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bestellte Menge. @param QtyOrdered Bestellte Menge */ @Override public void setQtyOrdered (java.math.BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } /** Get Bestellte Menge. @return Bestellte Menge
*/ @Override public java.math.BigDecimal getQtyOrdered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered); if (bd == null) return Env.ZERO; return bd; } /** Set Zusagbar. @param QtyPromised Zusagbar */ @Override public void setQtyPromised (java.math.BigDecimal QtyPromised) { set_Value (COLUMNNAME_QtyPromised, QtyPromised); } /** Get Zusagbar. @return Zusagbar */ @Override public java.math.BigDecimal getQtyPromised () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_Weekly.java
1
请完成以下Java代码
public class M_InOutLine { /** * Makes sure that <b>if</b> the given <code>iol</code> has an ASI with a <code>M_Material_Tracking_ID</code> attribute, then that attribute-instance's value is also referenced from the iol's * {@link I_M_InOutLine#COLUMNNAME_M_Material_Tracking_ID M_Material_Tracking_ID} column. Note that if the AIS has a nuln tracking, than this method sets the column to null. * * @param iol */ @ModelChange( timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_InOutLine.COLUMNNAME_M_AttributeSetInstance_ID }) public void updateMaterialTrackingIDfromASI(final I_M_InOutLine iol) { final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class); final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(iol.getM_AttributeSetInstance_ID());
if (!materialTrackingAttributeBL.hasMaterialTrackingAttribute(asiId)) { return; // nothing to sync, the line's asi has no M_Material_Tracking attrib } final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId); final int m_Material_Tracking_ID = materialTracking == null ? 0 : materialTracking.getM_Material_Tracking_ID(); if (iol.getM_Material_Tracking_ID() != m_Material_Tracking_ID) { iol.setM_Material_Tracking(materialTracking); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\M_InOutLine.java
1
请完成以下Java代码
EdgeEventType getAlarmEventType() { return EdgeEventType.ALARM; } @Override String getIgnoredMessageSource() { return DataConstants.EDGE_MSG_SOURCE; } @Override protected Class<TbMsgPushToEdgeNodeConfiguration> getConfigClazz() { return TbMsgPushToEdgeNodeConfiguration.class; } @Override protected void processMsg(TbContext ctx, TbMsg msg) { try { if (EntityType.EDGE.equals(msg.getOriginator().getEntityType())) { EdgeEvent edgeEvent = buildEvent(msg, ctx); EdgeId edgeId = new EdgeId(msg.getOriginator().getId()); ListenableFuture<Void> future = notifyEdge(ctx, edgeEvent, edgeId); FutureCallback<Void> futureCallback = new FutureCallback<>() { @Override public void onSuccess(@Nullable Void result) { ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }; Futures.addCallback(future, futureCallback, ctx.getDbCallbackExecutor()); } else { List<ListenableFuture<Void>> futures = new ArrayList<>(); PageDataIterableByTenantIdEntityId<EdgeId> edgeIds = new PageDataIterableByTenantIdEntityId<>( ctx.getEdgeService()::findRelatedEdgeIdsByEntityId, ctx.getTenantId(), msg.getOriginator(), RELATED_EDGES_CACHE_ITEMS); for (EdgeId edgeId : edgeIds) { EdgeEvent edgeEvent = buildEvent(msg, ctx); futures.add(notifyEdge(ctx, edgeEvent, edgeId)); } if (futures.isEmpty()) { // ack in case no edges are related to provided entity ctx.ack(msg); } else { Futures.addCallback(Futures.allAsList(futures), new FutureCallback<>() { @Override public void onSuccess(@Nullable List<Void> voids) {
ctx.tellSuccess(msg); } @Override public void onFailure(Throwable t) { ctx.tellFailure(msg, t); } }, ctx.getDbCallbackExecutor()); } } } catch (Exception e) { log.error("Failed to build edge event", e); ctx.tellFailure(msg, e); } } private ListenableFuture<Void> notifyEdge(TbContext ctx, EdgeEvent edgeEvent, EdgeId edgeId) { edgeEvent.setEdgeId(edgeId); return ctx.getEdgeEventService().saveAsync(edgeEvent); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\edge\TbMsgPushToEdgeNode.java
1
请完成以下Java代码
public PageData<NotificationRuleInfo> findNotificationRulesInfosByTenantId(TenantId tenantId, PageLink pageLink) { return notificationRuleDao.findInfosByTenantIdAndPageLink(tenantId, pageLink); } @Override public PageData<NotificationRule> findNotificationRulesByTenantId(TenantId tenantId, PageLink pageLink) { return notificationRuleDao.findByTenantIdAndPageLink(tenantId, pageLink); } @Override public List<NotificationRule> findEnabledNotificationRulesByTenantIdAndTriggerType(TenantId tenantId, NotificationRuleTriggerType triggerType) { return notificationRuleDao.findByTenantIdAndTriggerTypeAndEnabled(tenantId, triggerType, true); } @Override public void deleteNotificationRuleById(TenantId tenantId, NotificationRuleId id) { notificationRuleDao.removeById(tenantId, id.getId()); eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build()); } @Override public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteNotificationRuleById(tenantId, (NotificationRuleId) id); } @Override public void deleteNotificationRulesByTenantId(TenantId tenantId) { notificationRuleDao.removeByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) { deleteNotificationRulesByTenantId(tenantId); }
@Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findNotificationRuleById(tenantId, new NotificationRuleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(notificationRuleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_RULE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationRuleService.java
1
请完成以下Java代码
public CallOrderSummary create(@NonNull final CallOrderSummaryData summaryData) { final I_C_CallOrderSummary record = InterfaceWrapperHelper.newInstance(I_C_CallOrderSummary.class); setSummaryDataToRecord(record, summaryData); save(record); return ofRecord(record); } @NonNull public CallOrderSummary update(@NonNull final CallOrderSummary callOrderSummary) { final I_C_CallOrderSummary record = InterfaceWrapperHelper.load(callOrderSummary.getSummaryId(), I_C_CallOrderSummary.class); setSummaryDataToRecord(record, callOrderSummary.getSummaryData()); save(record); return ofRecord(record); } private static void setSummaryDataToRecord(@NonNull final I_C_CallOrderSummary record, @NonNull final CallOrderSummaryData callOrderSummaryData) { record.setC_Order_ID(callOrderSummaryData.getOrderId().getRepoId()); record.setC_OrderLine_ID(callOrderSummaryData.getOrderLineId().getRepoId()); record.setC_Flatrate_Term_ID(callOrderSummaryData.getFlatrateTermId().getRepoId()); record.setM_Product_ID(callOrderSummaryData.getProductId().getRepoId()); record.setC_UOM_ID(callOrderSummaryData.getUomId().getRepoId()); record.setQtyEntered(callOrderSummaryData.getQtyEntered()); record.setQtyDeliveredInUOM(callOrderSummaryData.getQtyDelivered()); record.setQtyInvoicedInUOM(callOrderSummaryData.getQtyInvoiced()); record.setPOReference(callOrderSummaryData.getPoReference()); record.setIsSOTrx(callOrderSummaryData.getSoTrx().toBoolean()); if (callOrderSummaryData.getAttributeSetInstanceId() != null) { record.setM_AttributeSetInstance_ID(callOrderSummaryData.getAttributeSetInstanceId().getRepoId()); } }
@NonNull private static CallOrderSummary ofRecord(@NonNull final I_C_CallOrderSummary record) { return CallOrderSummary.builder() .summaryId(CallOrderSummaryId.ofRepoId(record.getC_CallOrderSummary_ID())) .summaryData(ofRecordData(record)) .build(); } @NonNull private static CallOrderSummaryData ofRecordData(@NonNull final I_C_CallOrderSummary record) { return CallOrderSummaryData.builder() .orderId(OrderId.ofRepoId(record.getC_Order_ID())) .orderLineId(OrderLineId.ofRepoId(record.getC_OrderLine_ID())) .flatrateTermId(FlatrateTermId.ofRepoId(record.getC_Flatrate_Term_ID())) .productId(ProductId.ofRepoId(record.getM_Product_ID())) .uomId(UomId.ofRepoId(record.getC_UOM_ID())) .qtyEntered(record.getQtyEntered()) .attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNull(record.getM_AttributeSetInstance_ID())) .qtyDelivered(record.getQtyDeliveredInUOM()) .qtyInvoiced(record.getQtyInvoicedInUOM()) .poReference(record.getPOReference()) .isActive(record.isActive()) .soTrx(SOTrx.ofBoolean(record.isSOTrx())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\summary\CallOrderSummaryRepo.java
1
请在Spring Boot框架中完成以下Java代码
public class RpSettRecordAnnex extends BaseEntity implements Serializable { /** 是否删除 **/ private String isDelete = PublicEnum.NO.name(); /** 附件名称 **/ private String annexName; /** 附件地址 **/ private String annexAddress; /** 结算id **/ private String settlementId; private static final long serialVersionUID = 1L; public RpSettRecordAnnex() { super(); } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete == null ? null : isDelete.trim(); }
public String getAnnexName() { return annexName; } public void setAnnexName(String annexName) { this.annexName = annexName == null ? null : annexName.trim(); } public String getAnnexAddress() { return annexAddress; } public void setAnnexAddress(String annexAddress) { this.annexAddress = annexAddress == null ? null : annexAddress.trim(); } public String getSettlementId() { return settlementId; } public void setSettlementId(String settlementId) { this.settlementId = settlementId; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettRecordAnnex.java
2
请完成以下Spring Boot application配置
logging: level: com.zaxxer.hikari.HikariConfig: DEBUG security: key: private: classpath:app.key public: classpath:app.pub spring: thread
s: virtual: enabled: true jpa: open-in-view: false
repos\realworld-java21-springboot3-main\server\api\src\main\resources\application.yaml
2
请完成以下Java代码
public Collection<? extends GrantedAuthority> getAuthorities() { return AuthorityUtils.createAuthorityList("ROLE_USER"); } @Override public String getUsername() { return getEmail(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true;
} @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } private static final long serialVersionUID = 5639683223516504866L; } }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\security\UserRepositoryUserDetailsService.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Note. @param Note Optional additional user defined information */ public void setNote (String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Note. @return Optional additional user defined information */ public String getNote () { return (String)get_Value(COLUMNNAME_Note); }
/** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Registration.java
1
请完成以下Java代码
class ConfigurationPropertySourcesPropertySource extends PropertySource<Iterable<ConfigurationPropertySource>> implements OriginLookup<String> { ConfigurationPropertySourcesPropertySource(String name, Iterable<ConfigurationPropertySource> source) { super(name, source); } @Override public boolean containsProperty(String name) { return findConfigurationProperty(name) != null; } @Override public @Nullable Object getProperty(String name) { ConfigurationProperty configurationProperty = findConfigurationProperty(name); return (configurationProperty != null) ? configurationProperty.getValue() : null; } @Override public @Nullable Origin getOrigin(String name) { return Origin.from(findConfigurationProperty(name)); } private @Nullable ConfigurationProperty findConfigurationProperty(String name) { try { return findConfigurationProperty(ConfigurationPropertyName.of(name, true)); }
catch (Exception ex) { return null; } } @Nullable ConfigurationProperty findConfigurationProperty(@Nullable ConfigurationPropertyName name) { if (name == null) { return null; } for (ConfigurationPropertySource configurationPropertySource : getSource()) { ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name); if (configurationProperty != null) { return configurationProperty; } } return null; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertySourcesPropertySource.java
1
请完成以下Spring Boot application配置
rocketmq.name-server=127.0.0.1:9876 rocketmq.producer.group=my-group rocketmq.producer.send-message-timeout=300000 rocketmq.producer.compress-message-body-threshold=4096 rocketmq.producer.max-message-size=4194304 rocketmq.producer.retry-times-when-s
end-async-failed=0 rocketmq.producer.retry-next-server=true rocketmq.producer.retry-times-when-send-failed=2
repos\tutorials-master\messaging-modules\apache-rocketmq\src\main\resources\application.properties
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public AggregateReference<PasskeyUser, Long> getUser() { return AggregateReference.to(userId); } public void setUser(AggregateReference<PasskeyUser, Long> userId) { this.userId = userId.getId(); } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getCredentialType() { return credentialType; } public void setCredentialType(String credentialType) { this.credentialType = credentialType; } public String getCredentialId() { return credentialId; } public void setCredentialId(String credentialId) { this.credentialId = credentialId; } public String getPublicKeyCose() { return publicKeyCose; } public void setPublicKeyCose(String publicKeyCose) { this.publicKeyCose = publicKeyCose; } public Long getSignatureCount() { return signatureCount; } public void setSignatureCount(Long signatureCount) { this.signatureCount = signatureCount; } public Boolean getUvInitialized() { return uvInitialized;
} public void setUvInitialized(Boolean uvInitialized) { this.uvInitialized = uvInitialized; } public String getTransports() { return transports; } public void setTransports(String transports) { this.transports = transports; } public Boolean getBackupEligible() { return backupEligible; } public void setBackupEligible(Boolean backupEligible) { this.backupEligible = backupEligible; } public Boolean getBackupState() { return backupState; } public void setBackupState(Boolean backupState) { this.backupState = backupState; } public String getAttestationObject() { return attestationObject; } public void setAttestationObject(String attestationObject) { this.attestationObject = attestationObject; } public Instant getLastUsed() { return lastUsed; } public void setLastUsed(Instant lastUsed) { this.lastUsed = lastUsed; } public Instant getCreated() { return created; } public void setCreated(Instant created) { this.created = created; } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyCredential.java
1
请完成以下Java代码
public String findFirst() { return getList() .stream() .findFirst() .orElse(DEFAULT_VALUE); } public Optional<String> findOptionalFirst() { return getList() .stream() .findFirst(); } private List<String> getList() { return emptyList(); } public Optional<String> optionalListFirst() { return getOptionalList()
.flatMap(list -> list.stream().findFirst()); } private Optional<List<String>> getOptionalList() { return Optional.of(getList()); } private String doSomething(boolean processed) { if (processed) { return "passed"; } else { return null; } } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral\src\main\java\com\baeldung\nulls\UsingOptional.java
1
请在Spring Boot框架中完成以下Java代码
public Result comment(HttpServletRequest request, HttpSession session, @RequestParam Long newsId, @RequestParam String verifyCode, @RequestParam String commentator, @RequestParam String commentBody) { if (!StringUtils.hasText(verifyCode)) { return ResultGenerator.genFailResult("验证码不能为空"); } ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute("verifyCode"); if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) { return ResultGenerator.genFailResult("验证码错误"); } String ref = request.getHeader("Referer"); if (!StringUtils.hasText(ref)) { return ResultGenerator.genFailResult("非法请求"); } if (null == newsId || newsId < 0) { return ResultGenerator.genFailResult("非法请求");
} if (!StringUtils.hasText(commentator)) { return ResultGenerator.genFailResult("请输入称呼"); } if (!StringUtils.hasText(commentBody)) { return ResultGenerator.genFailResult("请输入评论内容"); } if (commentBody.trim().length() > 200) { return ResultGenerator.genFailResult("评论内容过长"); } NewsComment comment = new NewsComment(); comment.setNewsId(newsId); comment.setCommentator(AntiXssUtils.cleanString(commentator)); comment.setCommentBody(AntiXssUtils.cleanString(commentBody)); session.removeAttribute("verifyCode");//留言成功后删除session中的验证码信息 return ResultGenerator.genSuccessResult(commentService.addComment(comment)); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\index\IndexController.java
2
请完成以下Java代码
public class Message extends BaseElement { protected String name; protected String itemRef; public Message() { } public Message(String id, String name, String itemRef) { this.id = id; this.name = name; this.itemRef = itemRef; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getItemRef() { return itemRef; } public void setItemRef(String itemRef) { this.itemRef = itemRef; } @Override public Message clone() { Message clone = new Message(); clone.setValues(this); return clone; } public void setValues(Message otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setItemRef(otherElement.getItemRef()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\Message.java
1
请完成以下Java代码
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDateTime getCreationDate() { return creationDate; } public void setCreationDate(LocalDateTime creationDate) { this.creationDate = creationDate; } public LocalDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(LocalDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate;
} public Integer getDeleted() { return deleted; } public void setDeleted(Integer deleted) { this.deleted = deleted; } @Override public String toString() { return id + ":" +lastName + "," + firstName; } }
repos\tutorials-master\mybatis-plus\src\main\java\com\baeldung\mybatisplus\entity\Client.java
1
请在Spring Boot框架中完成以下Java代码
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { String userProperties = element.getAttribute(ATT_PROPERTIES); List<Element> userElts = DomUtils.getChildElementsByTagName(element, ELT_USER); if (StringUtils.hasText(userProperties)) { if (!CollectionUtils.isEmpty(userElts)) { throw new BeanDefinitionStoreException( "Use of a properties file and user elements are mutually exclusive"); } BeanDefinition bd = new RootBeanDefinition(PropertiesFactoryBean.class); bd.getPropertyValues().addPropertyValue("location", userProperties); builder.addConstructorArgValue(bd); return; } if (CollectionUtils.isEmpty(userElts)) { throw new BeanDefinitionStoreException("You must supply user definitions, either with <" + ELT_USER + "> child elements or a " + "properties file (using the '" + ATT_PROPERTIES + "' attribute)"); } ManagedList<BeanDefinition> users = new ManagedList<>(); for (Object elt : userElts) { Element userElt = (Element) elt; String userName = userElt.getAttribute(ATT_NAME); String password = userElt.getAttribute(ATT_PASSWORD); if (!StringUtils.hasLength(password)) { password = generateRandomPassword(); } boolean locked = "true".equals(userElt.getAttribute(ATT_LOCKED)); boolean disabled = "true".equals(userElt.getAttribute(ATT_DISABLED)); BeanDefinitionBuilder authorities = BeanDefinitionBuilder.rootBeanDefinition(AuthorityUtils.class); authorities.addConstructorArgValue(userElt.getAttribute(ATT_AUTHORITIES)); authorities.setFactoryMethod("commaSeparatedStringToAuthorityList"); BeanDefinitionBuilder user = BeanDefinitionBuilder.rootBeanDefinition(User.class); user.addConstructorArgValue(userName); user.addConstructorArgValue(password);
user.addConstructorArgValue(!disabled); user.addConstructorArgValue(true); user.addConstructorArgValue(true); user.addConstructorArgValue(!locked); user.addConstructorArgValue(authorities.getBeanDefinition()); users.add(user.getBeanDefinition()); } builder.addConstructorArgValue(users); } private String generateRandomPassword() { if (this.random == null) { try { this.random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException ex) { // Shouldn't happen... throw new RuntimeException("Failed find SHA1PRNG algorithm!"); } } return Long.toString(this.random.nextLong()); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\authentication\UserServiceBeanDefinitionParser.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\smartdoc\Book.java
1
请在Spring Boot框架中完成以下Java代码
public class HierarchyLevel implements Comparable<HierarchyLevel> { public static final HierarchyLevel ZERO = of(0); @JsonCreator public static HierarchyLevel of(int level) { return new HierarchyLevel(level); } @Getter(AccessLevel.NONE) int level; @JsonValue public int toInt() { return level; }
private HierarchyLevel(final int level) { this.level = assumeGreaterOrEqualToZero(level, "level"); } public HierarchyLevel incByOne() { return of(this.toInt() + 1); } @Override public int compareTo(@NonNull final HierarchyLevel other) { return Integer.compare(this.level, other.level); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\hierarchy\HierarchyLevel.java
2
请在Spring Boot框架中完成以下Java代码
public class Author { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String authorId; private String authorName; @ManyToOne private Editor editor; @OneToMany(mappedBy = "author", cascade = CascadeType.PERSIST) private Set<Article> authoredArticles = new HashSet<>(); // constructors, getters and setters... Author() { } public Author(String authorName) { this.authorName = authorName; } public String getAuthorId() { return authorId; } public void setAuthorId(String authorId) { this.authorId = authorId; } public String getAuthorName() { return authorName; }
public void setAuthorName(String authorName) { this.authorName = authorName; } public Editor getEditor() { return editor; } public void setEditor(Editor editor) { this.editor = editor; } public Set<Article> getAuthoredArticles() { return authoredArticles; } public void setAuthoredArticles(Set<Article> authoredArticles) { this.authoredArticles = authoredArticles; } }
repos\tutorials-master\persistence-modules\hibernate-ogm\src\main\java\com\baeldung\hibernate\ogm\Author.java
2
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_TaxPostal[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Tax getC_Tax() throws RuntimeException { return (I_C_Tax)MTable.get(getCtx(), I_C_Tax.Table_Name) .getPO(getC_Tax_ID(), get_TrxName()); } /** Set Tax. @param C_Tax_ID Tax identifier */ public void setC_Tax_ID (int C_Tax_ID) { if (C_Tax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Tax_ID, Integer.valueOf(C_Tax_ID)); } /** Get Tax. @return Tax identifier */ public int getC_Tax_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Tax_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Tax ZIP. @param C_TaxPostal_ID Tax Postal/ZIP */ public void setC_TaxPostal_ID (int C_TaxPostal_ID) { if (C_TaxPostal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, Integer.valueOf(C_TaxPostal_ID)); } /** Get Tax ZIP. @return Tax Postal/ZIP */
public int getC_TaxPostal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxPostal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZIP. @param Postal Postal code */ public void setPostal (String Postal) { set_Value (COLUMNNAME_Postal, Postal); } /** Get ZIP. @return Postal code */ public String getPostal () { return (String)get_Value(COLUMNNAME_Postal); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getPostal()); } /** Set ZIP To. @param Postal_To Postal code to */ public void setPostal_To (String Postal_To) { set_Value (COLUMNNAME_Postal_To, Postal_To); } /** Get ZIP To. @return Postal code to */ public String getPostal_To () { return (String)get_Value(COLUMNNAME_Postal_To); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxPostal.java
1
请在Spring Boot框架中完成以下Java代码
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages"); ConditionOutcome outcome = cache.get(basename); if (outcome == null) { outcome = getMatchOutcomeForBasename(context, basename); cache.put(basename, outcome); } return outcome; } private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) { ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle"); for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) { for (Resource resource : getResources(context.getClassLoader(), name)) { if (resource.exists()) { return ConditionOutcome.match(message.found("bundle").items(resource)); } } } return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll()); } private Resource[] getResources(@Nullable ClassLoader classLoader, String name) { String target = name.replace('.', '/'); try { return new PathMatchingResourcePatternResolver(classLoader) .getResources("classpath*:" + target + ".properties"); } catch (Exception ex) {
return NO_RESOURCES; } } } static class MessageSourceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("messages.properties").registerPattern("messages_*.properties"); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceAutoConfiguration.java
2
请完成以下Java代码
public ViewActionDescriptorsList mergeWith(ViewActionDescriptorsList actionsToAdd) { if (actionsToAdd == null || actionsToAdd.viewActionsByActionId.isEmpty()) { return this; } if (this.viewActionsByActionId.isEmpty()) { return actionsToAdd; } final Map<String, ViewActionDescriptor> newViewActionsByActionId = new HashMap<>(this.viewActionsByActionId); newViewActionsByActionId.putAll(actionsToAdd.viewActionsByActionId); return new ViewActionDescriptorsList(ImmutableMap.copyOf(newViewActionsByActionId)); } public ViewActionDescriptor getAction(final String actionId)
{ final ViewActionDescriptor action = viewActionsByActionId.get(actionId); if (action == null) { throw new EntityNotFoundException("No view action found for id: " + actionId); } return action; } public Stream<WebuiRelatedProcessDescriptor> streamDocumentRelatedProcesses(final ViewAsPreconditionsContext viewContext) { return viewActionsByActionId.values().stream() .map(viewActionDescriptor -> viewActionDescriptor.toWebuiRelatedProcessDescriptor(viewContext)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionDescriptorsList.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set IP Address. @param IP_Address Defines the IP address to transfer data to */ public void setIP_Address (String IP_Address) { set_Value (COLUMNNAME_IP_Address, IP_Address); } /** Get IP Address. @return Defines the IP address to transfer data to */ public String getIP_Address () { return (String)get_Value(COLUMNNAME_IP_Address); } /** Set Last Synchronized. @param LastSynchronized Date when last synchronized */ public void setLastSynchronized (Timestamp LastSynchronized) { set_Value (COLUMNNAME_LastSynchronized, LastSynchronized); } /** Get Last Synchronized. @return Date when last synchronized */ public Timestamp getLastSynchronized () {
return (Timestamp)get_Value(COLUMNNAME_LastSynchronized); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_BroadcastServer.java
1
请在Spring Boot框架中完成以下Java代码
final class FileExtensionHint { private static final Pattern PATTERN = Pattern.compile("^(.*)\\[(\\.\\w+)](?!\\[)$"); private static final FileExtensionHint NONE = new FileExtensionHint(null); private final @Nullable Matcher matcher; private FileExtensionHint(@Nullable Matcher matcher) { this.matcher = matcher; } /** * Return {@code true} if the hint is present. * @return if the hint is present */ boolean isPresent() { return this.matcher != null; } /** * Return the extension from the hint or return the parameter if the hint is not * {@link #isPresent() present}. * @param extension the fallback extension * @return the extension either from the hint or fallback */ String orElse(String extension) { return (this.matcher != null) ? toString() : extension; } @Override public String toString() { return (this.matcher != null) ? this.matcher.group(2) : ""; }
/** * Return the {@link FileExtensionHint} from the given value. * @param value the source value * @return the {@link FileExtensionHint} (never {@code null}) */ static FileExtensionHint from(String value) { Matcher matcher = PATTERN.matcher(value); return (matcher.matches()) ? new FileExtensionHint(matcher) : NONE; } /** * Remove any hint from the given value. * @param value the source value * @return the value without any hint */ static String removeFrom(String value) { Matcher matcher = PATTERN.matcher(value); return (matcher.matches()) ? matcher.group(1) : value; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\FileExtensionHint.java
2
请完成以下Java代码
public void setNetDay (final @Nullable java.lang.String NetDay) { set_Value (COLUMNNAME_NetDay, NetDay); } @Override public java.lang.String getNetDay() { return get_ValueAsString(COLUMNNAME_NetDay); } @Override public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() {
return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setPercentage (final BigDecimal Percentage) { set_Value (COLUMNNAME_Percentage, Percentage); } @Override public BigDecimal getPercentage() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage); 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_C_PaySchedule.java
1
请完成以下Java代码
public void setHref(String href) { this.href = href; } public void resolve() { if (this.rel == null) { throw new InvalidInitializrMetadataException("Invalid link " + this + ": rel attribute is mandatory"); } if (this.href == null) { throw new InvalidInitializrMetadataException("Invalid link " + this + ": href attribute is mandatory"); } Matcher matcher = VARIABLE_REGEX.matcher(this.href); while (matcher.find()) { String variable = matcher.group(1); this.templateVariables.add(variable); } this.templated = !this.templateVariables.isEmpty(); } /** * Expand the link using the specified parameters. * @param parameters the parameters value * @return an URI where all variables have been expanded */ public URI expand(Map<String, String> parameters) { AtomicReference<String> result = new AtomicReference<>(this.href); this.templateVariables.forEach((var) -> { Object value = parameters.get(var); if (value == null) { throw new IllegalArgumentException( "Could not expand " + this.href + ", missing value for '" + var + "'"); } result.set(result.get().replace("{" + var + "}", value.toString())); }); try { return new URI(result.get()); } catch (URISyntaxException ex) {
throw new IllegalStateException("Invalid URL", ex); } } public static Link create(String rel, String href) { return new Link(rel, href); } public static Link create(String rel, String href, String description) { return new Link(rel, href, description); } public static Link create(String rel, String href, boolean templated) { return new Link(rel, href, templated); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Link.java
1
请完成以下Java代码
public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; } public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public ActivitiEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); } public ActivitiEngineAgenda getAgenda() { return agenda;
} public Object getResult() { return resultStack.pollLast(); } public void setResult(Object result) { resultStack.add(result); } public boolean isReused() { return reused; } public void setReused(boolean reused) { this.reused = reused; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserDTO other = (UserDTO) obj; if (emailAddress == null) { if (other.emailAddress != null) return false; } else if (!emailAddress.equals(other.emailAddress)) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false;
} else if (!lastName.equals(other.lastName)) return false; if (userName == null) { if (other.userName != null) return false; } else if (!userName.equals(other.userName)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "UserDTO [firstName=" + firstName + ", lastName=" + lastName + ", userName=" + userName + ", emailAddress=" + emailAddress + "]"; } }
repos\spring-boot-microservices-master\user-webservice\src\main\java\com\rohitghatol\microservices\user\dto\UserDTO.java
2
请完成以下Java代码
public String getF_START() { return F_START; } public void setF_START(String f_START) { F_START = f_START; } public String getF_END() { return F_END; } public void setF_END(String f_END) { F_END = f_END; }
public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_VERSION() { return F_VERSION; } public void setF_VERSION(String f_VERSION) { F_VERSION = f_VERSION; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscOfficeExeItem.java
1
请在Spring Boot框架中完成以下Java代码
public void loadResourceDefine(){ map = new HashMap<>(); Collection<ConfigAttribute> array; ConfigAttribute cfg; List<Permission> permissions = permissionDao.findAll(); for(Permission permission : permissions) { array = new ArrayList<>(); cfg = new SecurityConfig(permission.getName()); array.add(cfg); map.put(permission.getUrl(), array); } } @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { if(map ==null) loadResourceDefine(); HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); AntPathRequestMatcher matcher; String resUrl; for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
resUrl = iter.next(); matcher = new AntPathRequestMatcher(resUrl); if(matcher.matches(request)) { return map.get(resUrl); } } return null; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> clazz) { return true; } }
repos\springBoot-master\springboot-SpringSecurity1\src\main\java\com\us\example\service\MyInvocationSecurityMetadataSourceService.java
2
请完成以下Java代码
public ValueMapperException valueMapperExceptionDueToSerializerNotFoundForTypedValueField(Object value) { return new ValueMapperException(exceptionMessage( "024", "Cannot find serializer for value '{}'", value)); } public ValueMapperException cannotSerializeVariable(String variableName, Throwable e) { return new ValueMapperException(exceptionMessage("025", "Cannot serialize variable '{}'", variableName), e); } public void logDataFormats(Collection<DataFormat> formats) { if (isInfoEnabled()) { for (DataFormat format : formats) { logDataFormat(format); } } } protected void logDataFormat(DataFormat dataFormat) { logInfo("025", "Discovered data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName()); } public void logDataFormatProvider(DataFormatProvider provider) { if (isInfoEnabled()) { logInfo("026", "Discovered data format provider: {}[name = {}]", provider.getClass().getName(), provider.getDataFormatName()); } } @SuppressWarnings("rawtypes") public void logDataFormatConfigurator(DataFormatConfigurator configurator) {
if (isInfoEnabled()) { logInfo("027", "Discovered data format configurator: {}[dataformat = {}]", configurator.getClass(), configurator.getDataFormatClass().getName()); } } public ExternalTaskClientException multipleProvidersForDataformat(String dataFormatName) { return new ExternalTaskClientException(exceptionMessage("028", "Multiple providers found for dataformat '{}'", dataFormatName)); } public ExternalTaskClientException passNullValueParameter(String parameterName) { return new ExternalTaskClientException(exceptionMessage( "030", "Null value is not allowed as '{}'", parameterName)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientLogger.java
1
请完成以下Java代码
public boolean isExpanded() { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); return !findPanelCollapsible.isCollapsed(); } @Override public void setExpanded(final boolean expanded) { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); findPanelCollapsible.setCollapsed(!expanded); } @Override public final void requestFocus() { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); if (findPanelCollapsible.isCollapsed()) { return; } findPanel.requestFocus(); } @Override public final boolean requestFocusInWindow() { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); if (findPanelCollapsible.isCollapsed()) { return false; } return findPanel.requestFocusInWindow(); } /** * @return true if it's expanded and the underlying {@link FindPanel} allows focus. */ @Override public boolean isFocusable() { if (!isExpanded()) { return false; } return findPanel.isFocusable(); }
/** * Adds a runnable to be executed when the this panel is collapsed or expanded. * * @param runnable */ @Override public void runOnExpandedStateChange(final Runnable runnable) { Check.assumeNotNull(runnable, "runnable not null"); final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); findPanelCollapsible.addPropertyChangeListener("collapsed", new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { runnable.run(); } }); } private static final class CollapsiblePanel extends JXTaskPane implements IUISubClassIDAware { private static final long serialVersionUID = 1L; public CollapsiblePanel() { super(); } @Override public String getUISubClassID() { return AdempiereTaskPaneUI.UISUBCLASSID_VPanel_FindPanel; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_Collapsible.java
1
请完成以下Java代码
public class ReceiptScheduleUpdatedEvent extends AbstractReceiptScheduleEvent { public static ReceiptScheduleUpdatedEvent cast(@NonNull final AbstractReceiptScheduleEvent event) { return (ReceiptScheduleUpdatedEvent)event; } public static final String TYPE = "ReceiptScheduleUpdatedEvent"; private final BigDecimal orderedQuantityDelta; private final BigDecimal reservedQuantityDelta; @JsonCreator @Builder public ReceiptScheduleUpdatedEvent( @JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor, @JsonProperty("materialDescriptor") final MaterialDescriptor materialDescriptor, @JsonProperty("oldReceiptScheduleData") final OldReceiptScheduleData oldReceiptScheduleData, @JsonProperty("minMaxDescriptor") @Nullable final MinMaxDescriptor minMaxDescriptor, @JsonProperty("orderedQuantityDelta") final BigDecimal orderedQuantityDelta, @JsonProperty("reservedQuantity") final BigDecimal reservedQuantity, @JsonProperty("reservedQuantityDelta") final BigDecimal reservedQuantityDelta, @JsonProperty("receiptScheduleId") final int receiptScheduleId) { super(eventDescriptor, materialDescriptor,
oldReceiptScheduleData, minMaxDescriptor, reservedQuantity, receiptScheduleId); this.orderedQuantityDelta = orderedQuantityDelta; this.reservedQuantityDelta = reservedQuantityDelta; } @Override public ReceiptScheduleUpdatedEvent validate() { super.validate(); Check.errorIf(reservedQuantityDelta == null, "reservedQuantityDelta may not be null"); Check.errorIf(orderedQuantityDelta == null, "orderedQuantityDelta may not be null"); return this; } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\receiptschedule\ReceiptScheduleUpdatedEvent.java
1
请完成以下Java代码
private void log(final String summary, final String text, final String reference, final Throwable error) { final I_IMP_Processor impProcessor = replicationProcessor.getMImportProcessor(); Services.get(IIMPProcessorBL.class).createLog(impProcessor, summary, text, reference, error); } @Override public void onMessage(@NonNull final Message message) { String text = null; final String messageReference = "onMessage-startAt-millis-" + SystemTime.millis(); try (final IAutoCloseable ignored = setupLoggable(messageReference)) { text = extractMessageBodyAsString(message); Loggables.withLogger(logger, Level.TRACE) .addLog("Received message(text): \n{}", text); importXMLDocument(text); log("Imported Document", text, null, null); // loggable can't store the message-text for us // not sending reply if (StringUtils.isNotEmpty(message.getMessageProperties().getReplyTo())) { Loggables.withLogger(logger, Level.WARN) .addLog("Sending reply currently not supported with RabbitMQ"); } } catch (final RuntimeException e) { logException(e, text); } } private String extractMessageBodyAsString(@NonNull final Message message)
{ final String encoding = message.getMessageProperties().getContentEncoding(); if (Check.isEmpty(encoding)) { Loggables.withLogger(logger, Level.WARN) .addLog("Incoming RabbitMQ message lacks content encoding info; assuming UTF-8; messageId={}", message.getMessageProperties().getMessageId()); return new String(message.getBody(), StandardCharsets.UTF_8); } try { return new String(message.getBody(), encoding); } catch (final UnsupportedEncodingException e) { throw new AdempiereException("Incoming RabbitMQ message has unsupportred encoding='" + encoding + "'; messageId=" + message.getMessageProperties().getMessageId(), e); } } private IAutoCloseable setupLoggable(@NonNull final String reference) { final IIMPProcessorBL impProcessorBL = Services.get(IIMPProcessorBL.class); final I_IMP_Processor importProcessor = replicationProcessor.getMImportProcessor(); return impProcessorBL.setupTemporaryLoggable(importProcessor, reference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\imp\RabbitMqListener.java
1
请完成以下Java代码
public class Product { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) long id; String name = null; Double price = 0.0; public Product() { this.name = null; this.price = 0.0; } public Product(String name, Double price) { this.name = name; this.price = price; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\Product.java
1
请在Spring Boot框架中完成以下Java代码
public String getHeader(@NonNull final String name) { if (headerMap.containsKey(name)) { return headerMap.get(name); } return super.getHeader(name); } @Override public Enumeration<String> getHeaderNames() { final HashSet<String> names = new HashSet<>(Collections.list(super.getHeaderNames())); names.addAll(headerMap.keySet()); return Collections.enumeration(names); }
@Override public Enumeration<String> getHeaders(@NonNull final String name) { final ArrayList<String> values = Collections.list(super.getHeaders(name)); if (headerMap.containsKey(name)) { values.add(headerMap.get(name)); } return Collections.enumeration(values); } public void setHeader(@NonNull final String name, @NonNull final String value) { headerMap.put(name, value); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\request\RequestWrapper.java
2
请完成以下Java代码
public Filter insertOrUpdateFilter(Filter filter) { AbstractQuery<?, ?> query = filter.getQuery(); query.validate(StoredQueryValidator.get()); if (filter.getId() == null) { checkAuthorization(CREATE, FILTER, ANY); getDbEntityManager().insert((FilterEntity) filter); createDefaultAuthorizations(filter); } else { checkAuthorization(UPDATE, FILTER, filter.getId()); getDbEntityManager().merge((FilterEntity) filter); } return filter; } public void deleteFilter(String filterId) { checkAuthorization(DELETE, FILTER, filterId); FilterEntity filter = findFilterByIdInternal(filterId); ensureNotNull("No filter found for filter id '" + filterId + "'", "filter", filter); // delete all authorizations for this filter id deleteAuthorizations(FILTER, filterId); // delete the filter itself getDbEntityManager().delete(filter); } public FilterEntity findFilterById(String filterId) { ensureNotNull("Invalid filter id", "filterId", filterId); checkAuthorization(READ, FILTER, filterId); return findFilterByIdInternal(filterId); } protected FilterEntity findFilterByIdInternal(String filterId) { return getDbEntityManager().selectById(FilterEntity.class, filterId); }
@SuppressWarnings("unchecked") public List<Filter> findFiltersByQueryCriteria(FilterQueryImpl filterQuery) { configureQuery(filterQuery, FILTER); return getDbEntityManager().selectList("selectFilterByQueryCriteria", filterQuery); } public long findFilterCountByQueryCriteria(FilterQueryImpl filterQuery) { configureQuery(filterQuery, FILTER); return (Long) getDbEntityManager().selectOne("selectFilterCountByQueryCriteria", filterQuery); } // authorization utils ///////////////////////////////// protected void createDefaultAuthorizations(Filter filter) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().newFilter(filter)); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\FilterManager.java
1
请完成以下Java代码
public void setIsAutoSendCustomers (final boolean IsAutoSendCustomers) { set_Value (COLUMNNAME_IsAutoSendCustomers, IsAutoSendCustomers); } @Override public boolean isAutoSendCustomers() { return get_ValueAsBoolean(COLUMNNAME_IsAutoSendCustomers); } @Override public void setIsAutoSendVendors (final boolean IsAutoSendVendors) { set_Value (COLUMNNAME_IsAutoSendVendors, IsAutoSendVendors); } @Override public boolean isAutoSendVendors() { return get_ValueAsBoolean(COLUMNNAME_IsAutoSendVendors); } @Override public void setIsCreateBPartnerFolders (final boolean IsCreateBPartnerFolders) { set_Value (COLUMNNAME_IsCreateBPartnerFolders, IsCreateBPartnerFolders); } @Override public boolean isCreateBPartnerFolders() { return get_ValueAsBoolean(COLUMNNAME_IsCreateBPartnerFolders); } @Override public void setIsSyncBPartnersToRestEndpoint (final boolean IsSyncBPartnersToRestEndpoint) { set_Value (COLUMNNAME_IsSyncBPartnersToRestEndpoint, IsSyncBPartnersToRestEndpoint); } @Override public boolean isSyncBPartnersToRestEndpoint() { return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRestEndpoint); } @Override public void setIsSyncHUsOnMaterialReceipt (final boolean IsSyncHUsOnMaterialReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnMaterialReceipt, IsSyncHUsOnMaterialReceipt);
} @Override public boolean isSyncHUsOnMaterialReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnMaterialReceipt); } @Override public void setIsSyncHUsOnProductionReceipt (final boolean IsSyncHUsOnProductionReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnProductionReceipt, IsSyncHUsOnProductionReceipt); } @Override public boolean isSyncHUsOnProductionReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnProductionReceipt); } /** * TenantId AD_Reference_ID=276 * Reference name: AD_Org (all) */ public static final int TENANTID_AD_Reference_ID=276; @Override public void setTenantId (final java.lang.String TenantId) { set_Value (COLUMNNAME_TenantId, TenantId); } @Override public java.lang.String getTenantId() { return get_ValueAsString(COLUMNNAME_TenantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_GRSSignum.java
1
请完成以下Java代码
public void serviceActivator(String payload) { jdbcTemplate.update("insert into STUDENT values(?)", payload); if (payload.toLowerCase().startsWith("fail")) { log.error("Service failure. Test result: {} ", payload); throw new RuntimeException("Service failure."); } log.info("Service success. Test result: {}", payload); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath:table.sql") .build(); }
@Bean public DataSourceTransactionManager txManager() { return new DataSourceTransactionManager(dataSource); } public static void main(final String... args) { final AbstractApplicationContext context = new AnnotationConfigApplicationContext(TxIntegrationConfig.class); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); System.out.print("Integration flow is running. Type q + <enter> to quit "); while (true) { final String input = scanner.nextLine(); if ("q".equals(input.trim())) { context.close(); scanner.close(); break; } } System.exit(0); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\tx\TxIntegrationConfig.java
1
请在Spring Boot框架中完成以下Java代码
private AbstractRememberMeServices createPersistentRememberMeServices(H http, String key) { UserDetailsService userDetailsService = getUserDetailsService(http); return new PersistentTokenBasedRememberMeServices(key, userDetailsService, this.tokenRepository); } /** * Gets the {@link UserDetailsService} to use. Either the explicitly configured * {@link UserDetailsService} from {@link #userDetailsService(UserDetailsService)}, a * shared object from {@link HttpSecurity#getSharedObject(Class)} or the * {@link UserDetailsService} bean. * @param http {@link HttpSecurity} to get the shared {@link UserDetailsService} * @return the {@link UserDetailsService} to use */ private UserDetailsService getUserDetailsService(H http) { if (this.userDetailsService == null) { this.userDetailsService = getSharedOrBean(http, UserDetailsService.class); } Assert.state(this.userDetailsService != null, () -> "userDetailsService cannot be null. Invoke " + RememberMeConfigurer.class.getSimpleName() + "#userDetailsService(UserDetailsService) or see its javadoc for alternative approaches."); return this.userDetailsService; } /** * Gets the key to use for validating remember me tokens. If a value was passed into * {@link #key(String)}, then that is returned. Alternatively, if a key was specified * in the {@link #rememberMeServices(RememberMeServices)}}, then that is returned. If * no key was specified in either of those cases, then a secure random string is * generated. * @return the remember me key to use */
private String getKey() { if (this.key == null) { if (this.rememberMeServices instanceof AbstractRememberMeServices) { this.key = ((AbstractRememberMeServices) this.rememberMeServices).getKey(); } else { this.key = UUID.randomUUID().toString(); } } return this.key; } private <C> C getSharedOrBean(H http, Class<C> type) { C shared = http.getSharedObject(type); if (shared != null) { return shared; } ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return null; } return context.getBeanProvider(type).getIfUnique(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\RememberMeConfigurer.java
2
请完成以下Java代码
private static DDOrderCandidateId getDDOrderCandidateIdOrNull(@NonNull final Candidate candidate) { final DistributionDetail distributionDetail = DistributionDetail.castOrNull(candidate.getBusinessCaseDetail()); if (distributionDetail == null) { return null; } final DDOrderRef ddOrderRef = distributionDetail.getDdOrderRef(); if (ddOrderRef == null) { return null; } return DDOrderCandidateId.ofRepoId(ddOrderRef.getDdOrderCandidateId()); } private Quantity doDecreaseQty(final DDOrderCandidate ddOrderCandidate, final Quantity remainingQtyToDistribute)
{ if (isCandidateEligibleForBeingDecreased(ddOrderCandidate)) { final Quantity qtyToDecrease = remainingQtyToDistribute.min(ddOrderCandidate.getQtyToProcess()); ddOrderCandidate.setQtyEntered(ddOrderCandidate.getQtyEntered().subtract(qtyToDecrease)); ddOrderCandidateService.save(ddOrderCandidate); return remainingQtyToDistribute.subtract(qtyToDecrease); } return remainingQtyToDistribute; } private static boolean isCandidateEligibleForBeingDecreased(final DDOrderCandidate ddOrderCandidate) { return !ddOrderCandidate.isProcessed() && ddOrderCandidate.getQtyToProcess().signum() > 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\DDOrderCandidateAdvisedEventCreator.java
1
请完成以下Java代码
private Money extractNetAmount(final FactLine line) { return netAmtPostingSign.isDebit() ? line.getAmtSourceDrAsMoney() : line.getAmtSourceCrAsMoney(); } public void updateDocTaxes(final DocTaxesList taxes) { final HashMap<TaxId, TaxAmounts> allTaxAmountsToPropagate = new HashMap<>(this.taxAmountsByTaxId); taxes.mapEach(docTax -> { final TaxAmounts taxAmounts = allTaxAmountsToPropagate.remove(docTax.getTaxId()); if (taxAmounts == null) { return null; // remove it } else { taxAmounts.updateDocTax(docTax); return docTax; } }); for (final TaxAmounts taxAmounts : allTaxAmountsToPropagate.values()) { taxes.add(toDocTax(taxAmounts)); } } private DocTax toDocTax(@NonNull TaxAmounts taxAmounts) { return DocTax.builderFrom(taxAmounts.getTax()) .accountProvider(accountProvider) .taxBaseAmt(taxAmounts.getTaxBaseAmt().toBigDecimal()) .taxAmt(taxAmounts.getTaxAmt().toBigDecimal()) .reverseChargeTaxAmt(taxAmounts.getReverseChargeAmt().toBigDecimal()) .build(); } // // // // // private static class TaxAmounts { @NonNull @Getter private final Tax tax; @NonNull private final CurrencyPrecision precision; @NonNull @Getter private Money taxBaseAmt; private boolean isTaxCalculated = false; private Money _taxAmt; private Money _reverseChargeAmt; public TaxAmounts(@NonNull final Tax tax, @NonNull final CurrencyId currencyId, @NonNull final CurrencyPrecision precision) { this.tax = tax; this.precision = precision; this.taxBaseAmt = this._taxAmt = this._reverseChargeAmt = Money.zero(currencyId); } public void addTaxBaseAmt(@NonNull final Money taxBaseAmtToAdd) { if (taxBaseAmtToAdd.isZero()) {
return; } this.taxBaseAmt = this.taxBaseAmt.add(taxBaseAmtToAdd); this.isTaxCalculated = false; } public Money getTaxAmt() { updateTaxAmtsIfNeeded(); return _taxAmt; } public Money getReverseChargeAmt() { updateTaxAmtsIfNeeded(); return _reverseChargeAmt; } private void updateTaxAmtsIfNeeded() { if (!isTaxCalculated) { final CalculateTaxResult result = tax.calculateTax(taxBaseAmt.toBigDecimal(), false, precision.toInt()); this._taxAmt = Money.of(result.getTaxAmount(), taxBaseAmt.getCurrencyId()); this._reverseChargeAmt = Money.of(result.getReverseChargeAmt(), taxBaseAmt.getCurrencyId()); this.isTaxCalculated = true; } } public void updateDocTax(@NonNull final DocTax docTax) { if (!TaxId.equals(tax.getTaxId(), docTax.getTaxId())) { throw new AdempiereException("TaxId not matching: " + this + ", " + docTax); } docTax.setTaxBaseAmt(getTaxBaseAmt().toBigDecimal()); docTax.setTaxAmt(getTaxAmt().toBigDecimal()); docTax.setReverseChargeTaxAmt(getReverseChargeAmt().toBigDecimal()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxUpdater.java
1
请完成以下Java代码
public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRoot_AD_Table_ID (final int Root_AD_Table_ID) { if (Root_AD_Table_ID < 1) set_Value (COLUMNNAME_Root_AD_Table_ID, null); else set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID); } @Override public int getRoot_AD_Table_ID() { return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID); } @Override public void setRoot_Record_ID (final int Root_Record_ID) { if (Root_Record_ID < 1) set_Value (COLUMNNAME_Root_Record_ID, null); else set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID); } @Override public int getRoot_Record_ID()
{ return get_ValueAsInt(COLUMNNAME_Root_Record_ID); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity) { set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
1
请完成以下Java代码
public class CookieUtil { // 默认缓存时间,单位/秒, 2H private static final int COOKIE_MAX_AGE = Integer.MAX_VALUE; // 保存路径,根路径 private static final String COOKIE_PATH = "/"; /** * 保存 * * @param response * @param key * @param value * @param ifRemember */ public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) { int age = ifRemember?COOKIE_MAX_AGE:-1; set(response, key, value, null, COOKIE_PATH, age, true); } /** * 保存 * * @param response * @param key * @param value * @param maxAge */ private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) { Cookie cookie = new Cookie(key, value); if (domain != null) { cookie.setDomain(domain); } cookie.setPath(path); cookie.setMaxAge(maxAge); cookie.setHttpOnly(isHttpOnly); response.addCookie(cookie); } /** * 查询value * * @param request * @param key * @return */ public static String getValue(HttpServletRequest request, String key) { Cookie cookie = get(request, key); if (cookie != null) { return cookie.getValue(); } return null;
} /** * 查询Cookie * * @param request * @param key */ private static Cookie get(HttpServletRequest request, String key) { Cookie[] arr_cookie = request.getCookies(); if (arr_cookie != null && arr_cookie.length > 0) { for (Cookie cookie : arr_cookie) { if (cookie.getName().equals(key)) { return cookie; } } } return null; } /** * 删除Cookie * * @param request * @param response * @param key */ public static void remove(HttpServletRequest request, HttpServletResponse response, String key) { Cookie cookie = get(request, key); if (cookie != null) { set(response, key, "", null, COOKIE_PATH, 0, true); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\CookieUtil.java
1
请完成以下Java代码
public class AddEmployeeResponse { @XmlElement(name = "return") protected Employee _return; /** * Gets the value of the return property. * * @return * possible object is * {@link Employee } * */ public Employee getReturn() { return _return;
} /** * Sets the value of the return property. * * @param value * allowed object is * {@link Employee } * */ public void setReturn(Employee value) { this._return = value; } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\AddEmployeeResponse.java
1
请完成以下Java代码
public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } @Override public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID) { if (PickFrom_Warehouse_ID < 1) set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null); else set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID); } @Override public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setQtyRejectedToPick (final @Nullable BigDecimal QtyRejectedToPick) { set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick); } @Override public BigDecimal getQtyRejectedToPick() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_HUAlternative.java
1
请完成以下Java代码
private static class ImmutableFactoryGroupBuilder { private final HashSet<String> tableNamesToEnableRemoveCacheInvalidation = new HashSet<>(); private final HashMultimap<String, ModelCacheInvalidateRequestFactory> factoriesByTableName = HashMultimap.create(); public ImmutableModelCacheInvalidateRequestFactoriesList build() { return ImmutableModelCacheInvalidateRequestFactoriesList.builder() .factoriesByTableName(factoriesByTableName) .tableNamesToEnableRemoveCacheInvalidation(TableNamesGroup.builder() .groupId(TABLENAMES_GROUP_FACTORY_TABLES) .tableNames(tableNamesToEnableRemoveCacheInvalidation) .build()) .build(); } public ImmutableFactoryGroupBuilder addAll(final Collection<ColumnSqlSourceDescriptor> descriptors) { for (final ColumnSqlSourceDescriptor descriptor : descriptors) { add(descriptor); }
return this; } public ImmutableFactoryGroupBuilder add(final ColumnSqlSourceDescriptor descriptor) { tableNamesToEnableRemoveCacheInvalidation.add(descriptor.getSourceTableName()); tableNamesToEnableRemoveCacheInvalidation.add(descriptor.getTargetTableName()); final ModelCacheInvalidateRequestFactory modelCacheInvalidateRequestFactory = ColumnSqlCacheInvalidateRequestFactories.ofDescriptorOrNull(descriptor); if (modelCacheInvalidateRequestFactory != null) { factoriesByTableName.put(descriptor.getSourceTableName(), modelCacheInvalidateRequestFactory); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ColumnSqlCacheInvalidateRequestFactoryGroup.java
1
请在Spring Boot框架中完成以下Java代码
public User getJsonUserInfo(@PathVariable("userId") @Size(min = 5, max = 8) String userId) { User user = new User("Java技术栈", 18); user.setId(Long.valueOf(userId)); log.info("user info: {}", user); return user; } @GetMapping(value = "/user/xml/{userId}", produces = MediaType.APPLICATION_XML_VALUE) public UserXml getXmlUserInfo(@PathVariable("userId") String userId) { UserXml user = new UserXml(); user.setName("栈长"); user.setId(userId); List<OrderInfo> orderList = new ArrayList<>(); OrderInfo orderInfo1 = new OrderInfo("123456001", 999, new Date()); OrderInfo orderInfo2 = new OrderInfo("123456002", 777, new Date()); OrderInfo orderInfo3 = new OrderInfo("123456003", 666, new Date()); orderList.add(orderInfo1);
orderList.add(orderInfo2); orderList.add(orderInfo3); user.setOrderList(orderList); return user; } @PostMapping(value = "/user/save") public ResponseEntity saveUser(@RequestBody @Validated User user) { user.setId(RandomUtils.nextLong()); return new ResponseEntity(user, HttpStatus.OK); } @GetMapping("/") public String index() { return "index page."; } }
repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\controller\ResponseBodyController.java
2
请完成以下Java代码
public class Stock { private Integer id; private String name; private BigDecimal price; LocalDateTime dateTime; public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) { this.id = id; this.name = name; this.price = price; this.dateTime = dateTime; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public LocalDateTime getDateTime() { return dateTime; } public void setDateTime(LocalDateTime dateTime) { this.dateTime = dateTime; } }
repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-server\src\main\java\com\baeldung\sse\jaxrs\Stock.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<User> getUsers() { return users; } public void setUsers(Collection<User> users) { this.users = users; } public Collection<Privilege> getPrivileges() { return privileges; } public void setPrivileges(Collection<Privilege> privileges) { this.privileges = privileges; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.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; } Role role = (Role) obj; if (!role.equals(role.name)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\model\Role.java
1
请在Spring Boot框架中完成以下Java代码
private void handleNotificationRequestUpdate(NotificationsCountSubscription subscription, NotificationRequestUpdate update) { log.trace("[{}, subId: {}] Handling notification request update for count sub: {}", subscription.getSessionId(), subscription.getSubscriptionId(), update); fetchUnreadNotificationsCount(subscription); sendUpdate(subscription.getSessionId(), subscription.createUpdate()); } @Override public void handleMarkAsReadCmd(WebSocketSessionRef sessionRef, MarkNotificationsAsReadCmd cmd) { SecurityUser securityCtx = sessionRef.getSecurityCtx(); cmd.getNotifications().stream() .map(NotificationId::new) .forEach(notificationId -> { notificationCenter.markNotificationAsRead(securityCtx.getTenantId(), securityCtx.getId(), notificationId); }); } @Override
public void handleMarkAllAsReadCmd(WebSocketSessionRef sessionRef, MarkAllNotificationsAsReadCmd cmd) { SecurityUser securityCtx = sessionRef.getSecurityCtx(); notificationCenter.markAllNotificationsAsRead(securityCtx.getTenantId(), WEB, securityCtx.getId()); } @Override public void handleUnsubCmd(WebSocketSessionRef sessionRef, UnsubscribeCmd cmd) { localSubscriptionService.cancelSubscription(sessionRef.getTenantId(), sessionRef.getSessionId(), cmd.getCmdId()); } private void sendUpdate(String sessionId, CmdUpdate update) { log.trace("[{}, cmdId: {}] Sending WS update: {}", sessionId, update.getCmdId(), update); wsService.sendUpdate(sessionId, update); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\notification\DefaultNotificationCommandsHandler.java
2
请完成以下Java代码
public static boolean judge(char c){ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'); } public static String specialSymbols(String str) { //去除压缩包文件字符串中特殊符号 Pattern p = Pattern.compile("\\s|\t|\r|\n|\\+|#|&|=|�|\\p{P}"); // Pattern p = Pattern.compile("\\s|\\+|#|&|=|\\p{P}"); Matcher m = p.matcher(str); return m.replaceAll(""); } public static boolean isMessyCode(String strName) { //去除字符串中的空格 制表符 换行 回车 strName = specialSymbols(strName); //处理之后转换成字符数组 char[] ch = strName.trim().toCharArray(); for (char c : ch) { //判断是否是数字或者英文字符 if (!judge(c)) { //判断是否是中日韩文 if (!isChinese(c)) { //如果不是数字或者英文字符也不是中日韩文则表示是乱码返回true return true; } } } //表示不是乱码 返回false return false; }
/** * 读取文件目录树 */ public static List<ZtreeNodeVo> getTree(String rootPath) { List<ZtreeNodeVo> nodes = new ArrayList<>(); File file = new File(fileDir+rootPath); ZtreeNodeVo node = traverse(file); nodes.add(node); return nodes; } private static ZtreeNodeVo traverse(File file) { ZtreeNodeVo pathNodeVo = new ZtreeNodeVo(); pathNodeVo.setId(file.getAbsolutePath().replace(fileDir, "").replace("\\", "/")); pathNodeVo.setName(file.getName()); pathNodeVo.setPid(file.getParent().replace(fileDir, "").replace("\\", "/")); if (file.isDirectory()) { List<ZtreeNodeVo> subNodeVos = new ArrayList<>(); File[] subFiles = file.listFiles(); if (subFiles == null) { return pathNodeVo; } for (File subFile : subFiles) { ZtreeNodeVo subNodeVo = traverse(subFile); subNodeVos.add(subNodeVo); } pathNodeVo.setChildren(subNodeVos); } return pathNodeVo; } }
repos\kkFileView-master\server\src\main\java\cn\keking\utils\RarUtils.java
1
请在Spring Boot框架中完成以下Java代码
public Product getProduct(Long productId){ LOGGER.info("Getting Product from Product Repo With Product Id {}", productId); if(!productMap.containsKey(productId)){ LOGGER.error("Product Not Found for Product Id {}", productId); throw new ProductNotFoundException("Product Not Found"); } return productMap.get(productId); } @PostConstruct private void setupRepo() { Product product1 = getProduct(100001, "apple"); productMap.put(100001L, product1); Product product2 = getProduct(100002, "pears"); productMap.put(100002L, product2); Product product3 = getProduct(100003, "banana");
productMap.put(100003L, product3); Product product4 = getProduct(100004, "mango"); productMap.put(100004L, product4); Product product5 = getProduct(100005, "test"); productMap.put(100005L, product5); } private static Product getProduct(int id, String name) { Product product = new Product(); product.setId(id); product.setName(name); return product; } }
repos\tutorials-master\spring-boot-modules\spring-boot-open-telemetry\spring-boot-open-telemetry1\src\main\java\com\baeldung\opentelemetry\repository\ProductRepository.java
2
请完成以下Spring Boot application配置
#mybatis-plus配置 mybatis-plus: mapper-locations: classpath:com/example/**/mapper/*Mapper.xml #实体扫描,多个package用逗号或者分号分隔 typeAliasesPackage: com.example.**.entity #swagg
er扫描路径配置 swagger: base-packages: - org.springbalde - com.example
repos\SpringBlade-master\blade-service\blade-demo\src\main\resources\application.yml
2
请完成以下Java代码
protected byte[] getSerializedBytesValue(String serializedStringValue) { if(serializedStringValue != null) { byte[] serializedByteValue = StringUtil.toByteArray(serializedStringValue); if (!isSerializationTextBased()) { serializedByteValue = Base64.decodeBase64(serializedByteValue); } return serializedByteValue; } else { return null; } } protected boolean canWriteValue(TypedValue typedValue) { if (!(typedValue instanceof SerializableValue) && !(typedValue instanceof UntypedValueImpl)) { return false; } if (typedValue instanceof SerializableValue) { SerializableValue serializableValue = (SerializableValue) typedValue; String requestedDataFormat = serializableValue.getSerializationDataFormat(); if (!serializableValue.isDeserialized()) { // serialized object => dataformat must match return serializationDataFormat.equals(requestedDataFormat); } else { final boolean canSerialize = typedValue.getValue() == null || canSerializeValue(typedValue.getValue()); return canSerialize && (requestedDataFormat == null || serializationDataFormat.equals(requestedDataFormat)); } } else { return typedValue.getValue() == null || canSerializeValue(typedValue.getValue()); } } /** * return true if this serializer is able to serialize the provided object. * * @param value the object to test (guaranteed to be a non-null value) * @return true if the serializer can handle the object. */ protected abstract boolean canSerializeValue(Object value); // methods to be implemented by subclasses ////////////
/** * Implementations must return a byte[] representation of the provided object. * The object is guaranteed not to be null. * * @param deserializedObject the object to serialize * @return the byte array value of the object * @throws exception in case the object cannot be serialized */ protected abstract byte[] serializeToByteArray(Object deserializedObject) throws Exception; /** * Deserialize the object from a byte array. * * @param object the object to deserialize * @param valueFields the value fields * @return the deserialized object * @throws exception in case the object cannot be deserialized */ protected abstract Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception; /** * Return true if the serialization is text based. Return false otherwise * */ protected abstract boolean isSerializationTextBased(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\AbstractSerializableValueSerializer.java
1
请完成以下Java代码
private void takeSnapshotAndDestroyHU(@NonNull final I_M_HU sourceHU) { final SourceHUsService sourceHuService = SourceHUsService.get(); sourceHuService.snapshotHuIfMarkedAsSourceHu(sourceHU); handlingUnitsBL.destroyIfEmptyStorage(sourceHU); Check.errorUnless(handlingUnitsBL.isDestroyed(sourceHU), "We invoked IHandlingUnitsBL.destroyIfEmptyStorage on an HU with empty storage, but its not destroyed; hu={}", sourceHU); logger.info("Source M_HU with M_HU_ID={} is now destroyed", sourceHU.getM_HU_ID()); } private ImmutableList<PickingCandidate> changeStatusToProcessedAndSave() { final ImmutableList<PickingCandidate> pickingCandidates = getPickingCandidates(); pickingCandidates.forEach(pc -> pc.changeStatusToProcessed(getPickedHUId(pc))); pickingCandidateRepository.saveAll(pickingCandidates); return pickingCandidates; } @Nullable private PickedHuAndQty getPickedHuAndQty(@NonNull final PickingCandidate pc) { final HuId initialHuId = pc.getPickFrom().getHuId(); return initialHuId != null ? transactionedHus.get(initialHuId) : null; } @Nullable private HuId getPickedHUId(@NonNull final PickingCandidate pc) { final PickedHuAndQty item = getPickedHuAndQty(pc); final HuId initialHuId = pc.getPickFrom().getHuId(); // allow fallback on picking candidate HU as picked HU return item != null ? item.getPickedHUId() : initialHuId;
} private void validateClearedHUs(@NonNull final List<PickingCandidate> pickingCandidates, @NonNull final Set<HuId> additionalPickFromHuIds) { final ImmutableSet.Builder<HuId> huIdCollector = ImmutableSet.builder(); pickingCandidates .stream() .map(PickingCandidate::getPickFrom) .map(PickFrom::getHuId) .filter(Objects::nonNull) .forEach(huIdCollector::add); final ImmutableSet<HuId> husToValidate = huIdCollector.addAll(additionalPickFromHuIds).build(); final boolean anyNotClearedHUs = husToValidate.stream() .anyMatch(huId -> !handlingUnitsBL.isHUHierarchyCleared(huId)); if (anyNotClearedHUs) { throw new AdempiereException(MSG_ONLY_CLEARED_HUs_CAN_BE_PICKED); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ProcessHUsAndPickingCandidateCommand.java
1
请完成以下Java代码
public void validateDatePromised(final I_C_RfQResponseLineQty rfqResponseLineQty) { final Timestamp datePromised = rfqResponseLineQty.getDatePromised(); if (datePromised == null) { throw new FillMandatoryException(I_C_RfQResponseLineQty.COLUMNNAME_DatePromised); } final I_C_RfQResponseLine rfqResponseLine = rfqResponseLineQty.getC_RfQResponseLine(); final Timestamp dateWorkStart = TimeUtil.truncToDay(rfqResponseLine.getDateWorkStart()); final Timestamp dateWorkComplete = TimeUtil.truncToDay(rfqResponseLine.getDateWorkComplete()); if (!TimeUtil.isBetween(datePromised, dateWorkStart, dateWorkComplete)) { throw new AdempiereException("@Invalid@ @DatePromised@: " + datePromised + " (" + dateWorkStart + " - " + dateWorkComplete + ")"); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE } // , ifColumnsChanged = I_C_RfQResponseLineQty.COLUMNNAME_QtyPromised) public void updateC_RfQResponseLine_QtyPromised(final I_C_RfQResponseLineQty rfqResponseLineQty) {
if (isAllowResponseLineUpdate(rfqResponseLineQty)) { final I_C_RfQResponseLine rfqResponseLine = rfqResponseLineQty.getC_RfQResponseLine(); Services.get(IRfqBL.class).updateQtyPromisedAndSave(rfqResponseLine); } } public static void disableResponseLineUpdate(final I_C_RfQResponseLineQty rfqResponseLineQty) { DYNATTR_DisableResponseLineUpdate.setValue(rfqResponseLineQty, Boolean.TRUE); } private static boolean isAllowResponseLineUpdate(final I_C_RfQResponseLineQty rfqResponseLineQty) { return !DYNATTR_DisableResponseLineUpdate.isSet(rfqResponseLineQty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\model\interceptor\C_RfQResponseLineQty.java
1
请在Spring Boot框架中完成以下Java代码
public class Validation { @NonNull ValidationType type; @Nullable IStringExpression sql; @Nullable AdValRuleId adValRuleId; private Validation( @NonNull final ValidationType type, @Nullable final IStringExpression sql, @Nullable final AdValRuleId adValRuleId) { this.type = type; if (type == ValidationType.SQL) { this.sql = Check.assumeNotNull(sql, "sql is not null"); this.adValRuleId = null; } else if (type == ValidationType.ValidationRule) { this.sql = null; this.adValRuleId = Check.assumeNotNull(adValRuleId, "adValRuleId is not null"); } else
{ throw new AdempiereException("Unknown type: " + type); } } public static Validation sql(@NonNull final String sql) { final String sqlNorm = StringUtils.trimBlankToNull(sql); if (sqlNorm == null) { throw new AdempiereException("SQL validation rule shall not be empty"); } return new Validation(ValidationType.SQL, IStringExpression.compile(sqlNorm), null); } public static Validation adValRule(@NonNull final AdValRuleId adValRuleId) { return new Validation(ValidationType.ValidationRule, null, adValRuleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\model\Validation.java
2
请完成以下Java代码
private static FTSSearchResultItem extractFTSSearchResultItem( @NonNull final SearchHit hit, @NonNull final FTSSearchRequest request, @NonNull final FTSConfig ftsConfig) { return FTSSearchResultItem.builder() .key(extractKey(hit, request.getFilterDescriptor(), ftsConfig)) .json(toJson(hit)) .build(); } private static FTSSearchResultItem.KeyValueMap extractKey( @NonNull final SearchHit hit, @NonNull final FTSFilterDescriptor filterDescriptor, @NonNull final FTSConfig ftsConfig) { final FTSJoinColumnList joinColumns = filterDescriptor.getJoinColumns(); final ArrayList<FTSSearchResultItem.KeyValue> keyValues = new ArrayList<>(joinColumns.size()); for (final FTSJoinColumn joinColumn : joinColumns) { final ESFieldName esFieldName = ftsConfig.getEsFieldNameById(joinColumn.getEsFieldId()); final Object value = extractValue(hit, esFieldName, joinColumn.getValueType()); keyValues.add(FTSSearchResultItem.KeyValue.ofJoinColumnAndValue(joinColumn, value)); } return new FTSSearchResultItem.KeyValueMap(keyValues); } @Nullable private static Object extractValue( @NonNull final SearchHit hit, @NonNull final ESFieldName esFieldName, @NonNull final FTSJoinColumn.ValueType valueType) { if (ESFieldName.ID.equals(esFieldName)) { final String esDocumentId = hit.getId(); return convertValueToType(esDocumentId, valueType); } else { final Object value = hit.getSourceAsMap().get(esFieldName.getAsString());
return convertValueToType(value, valueType); } } @Nullable private static Object convertValueToType(@Nullable final Object valueObj, @NonNull final FTSJoinColumn.ValueType valueType) { if (valueObj == null) { return null; } if (valueType == FTSJoinColumn.ValueType.INTEGER) { return NumberUtils.asIntegerOrNull(valueObj); } else if (valueType == FTSJoinColumn.ValueType.STRING) { return valueObj.toString(); } else { throw new AdempiereException("Cannot convert `" + valueObj + "` (" + valueObj.getClass() + ") to " + valueType); } } private static String toJson(@NonNull final SearchHit hit) { return Strings.toString(hit, true, true); } public FTSConfig getConfigById(@NonNull final FTSConfigId ftsConfigId) { return ftsConfigService.getConfigById(ftsConfigId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchService.java
1
请在Spring Boot框架中完成以下Java代码
protected Boolean getKeepAlive() { return this.keepAlive != null ? this.keepAlive : DEFAULT_KEEP_ALIVE; } protected Boolean getReadyForEvents() { return this.readyForEvents != null ? this.readyForEvents : DEFAULT_READY_FOR_EVENTS; } protected Logger getLogger() { return this.logger; } @Bean ClientCacheConfigurer clientCacheDurableClientConfigurer() { return (beanName, clientCacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { clientCacheFactoryBean.setDurableClientId(durableClientId); clientCacheFactoryBean.setDurableClientTimeout(getDurableClientTimeout()); clientCacheFactoryBean.setKeepAlive(getKeepAlive());
clientCacheFactoryBean.setReadyForEvents(getReadyForEvents()); }); } @Bean PeerCacheConfigurer peerCacheDurableClientConfigurer() { return (beanName, cacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Durable Client ID [{}] was set on a peer Cache instance, which will not have any effect", durableClientId); } }); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DurableClientConfiguration.java
2
请完成以下Java代码
public int getM_HU_Trx_Hdr_ID() { return M_HU_Trx_Hdr_ID; } @Override public void setM_HU_Trx_Hdr_ID(final int m_HU_Trx_Hdr_ID) { M_HU_Trx_Hdr_ID = m_HU_Trx_Hdr_ID; } @Override public int getExclude_M_HU_Trx_Line_ID() { return Exclude_M_HU_Trx_Line_ID; } @Override public void setExclude_M_HU_Trx_Line_ID(final int exclude_M_HU_Trx_Line_ID) { Exclude_M_HU_Trx_Line_ID = exclude_M_HU_Trx_Line_ID; } @Override public int getParent_M_HU_Trx_Line_ID() { return Parent_M_HU_Trx_Line_ID; } @Override public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID) { Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID; } @Override public void setM_HU_Item_ID(final int Ref_HU_Item_ID) { this.Ref_HU_Item_ID = Ref_HU_Item_ID; } @Override public int getM_HU_Item_ID() { return Ref_HU_Item_ID; } @Override public int getAD_Table_ID() { return AD_Table_ID; } @Override public void setAD_Table_ID(final int aD_Table_ID) {
AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } @Override public void setRecord_ID(final int record_ID) { Record_ID = record_ID; } @Override public void setM_HU_ID(int m_hu_ID) { M_HU_ID = m_hu_ID; } @Override public int getM_HU_ID() { return M_HU_ID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java
1
请在Spring Boot框架中完成以下Java代码
public Elasticsearch getElasticsearch() { return elasticsearch; } public void setElasticsearch(Elasticsearch elasticsearch) { this.elasticsearch = elasticsearch; } public Firewall getFirewall() { return firewall; } public void setFirewall(Firewall firewall) { this.firewall = firewall; } public String getSignatureSecret() { return signatureSecret; } public void setSignatureSecret(String signatureSecret) { this.signatureSecret = signatureSecret; } public Shiro getShiro() { return shiro; } public void setShiro(Shiro shiro) { this.shiro = shiro; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public DomainUrl getDomainUrl() { return domainUrl; } public void setDomainUrl(DomainUrl domainUrl) {
this.domainUrl = domainUrl; } public String getSignUrls() { return signUrls; } public void setSignUrls(String signUrls) { this.signUrls = signUrls; } public String getFileViewDomain() { return fileViewDomain; } public void setFileViewDomain(String fileViewDomain) { this.fileViewDomain = fileViewDomain; } public String getUploadType() { return uploadType; } public void setUploadType(String uploadType) { this.uploadType = uploadType; } public WeiXinPay getWeiXinPay() { return weiXinPay; } public void setWeiXinPay(WeiXinPay weiXinPay) { this.weiXinPay = weiXinPay; } public BaiduApi getBaiduApi() { return baiduApi; } public void setBaiduApi(BaiduApi baiduApi) { this.baiduApi = baiduApi; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\JeecgBaseConfig.java
2
请完成以下Java代码
public static ReservedHUsPolicy onlyNotReservedExceptVhuIds(@NonNull final Collection<HuId> vhuIdsToConsiderEvenIfReserved) { return vhuIdsToConsiderEvenIfReserved.isEmpty() ? CONSIDER_ONLY_NOT_RESERVED : builder().vhuReservedStatus(OptionalBoolean.FALSE).alwaysConsiderVhuIds(vhuIdsToConsiderEvenIfReserved).build(); } public static ReservedHUsPolicy onlyVHUIds(@NonNull final Collection<HuId> onlyVHUIds) { Check.assumeNotEmpty(onlyVHUIds, "onlyVHUIds shall not be empty"); return builder().vhuReservedStatus(OptionalBoolean.UNKNOWN).onlyConsiderVhuIds(onlyVHUIds).build(); } private final OptionalBoolean vhuReservedStatus; private final ImmutableSet<HuId> alwaysConsiderVhuIds; private final ImmutableSet<HuId> onlyConsiderVhuIds; @Builder private ReservedHUsPolicy( final OptionalBoolean vhuReservedStatus, @Nullable final Collection<HuId> alwaysConsiderVhuIds, @Nullable final Collection<HuId> onlyConsiderVhuIds) { this.vhuReservedStatus = vhuReservedStatus; this.alwaysConsiderVhuIds = alwaysConsiderVhuIds != null ? ImmutableSet.copyOf(alwaysConsiderVhuIds) : ImmutableSet.of(); this.onlyConsiderVhuIds = onlyConsiderVhuIds != null ? ImmutableSet.copyOf(onlyConsiderVhuIds) : ImmutableSet.of(); } public boolean isConsiderVHU(@NonNull final I_M_HU vhu) { final HuId vhuId = HuId.ofRepoId(vhu.getM_HU_ID()); if (!onlyConsiderVhuIds.isEmpty() && !onlyConsiderVhuIds.contains(vhuId))
{ return false; } if (alwaysConsiderVhuIds.contains(vhuId)) { return true; } return isHUReservedStatusMatches(vhu); } private boolean isHUReservedStatusMatches(@NonNull final I_M_HU vhu) { return vhuReservedStatus.isUnknown() || vhuReservedStatus.isTrue() == vhu.isReserved(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\ReservedHUsPolicy.java
1
请完成以下Java代码
public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Exclude Attribute Set. @param M_AttributeSetExclude_ID Exclude the ability to enter Attribute Sets */ public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID) { if (M_AttributeSetExclude_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID)); } /** Get Exclude Attribute Set. @return Exclude the ability to enter Attribute Sets */ public int getM_AttributeSetExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_AttributeSet getM_AttributeSet() throws RuntimeException { return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name) .getPO(getM_AttributeSet_ID(), get_TrxName()); } /** Set Attribute Set. @param M_AttributeSet_ID Product Attribute Set
*/ public void setM_AttributeSet_ID (int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID)); } /** Get Attribute Set. @return Product Attribute Set */ public int getM_AttributeSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_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_AttributeSetExclude.java
1
请完成以下Java代码
private LocalDateInterval getSearchingDateInterval(@NonNull final LocalDate createdDate) { final int daysOffset = sysConfigBL.getIntValue(AD_SYS_CONFIG_NR_OF_LINES_WITH_SAME_PO_REFERENCE_DAYS_OFFSET, -1); if (daysOffset < 0) { return null; } return LocalDateInterval.builder() .startDate(createdDate.minusDays(daysOffset)) .endDate(createdDate.plusDays(daysOffset)) .build(); } private boolean isExtraSyncNeededForOldShipmentSchedule( @NonNull final I_M_ShipmentSchedule currentShipmentScheduleRecord, @NonNull final I_M_ShipmentSchedule oldShipmentScheduleRecord) { final WarehouseId oldRecordWarehouseId = shipmentScheduleEffectiveBL.getWarehouseId(oldShipmentScheduleRecord); final WarehouseId currentRecordWarehouseId = shipmentScheduleEffectiveBL.getWarehouseId(currentShipmentScheduleRecord); return oldShipmentScheduleRecord.getM_Product_ID() != currentShipmentScheduleRecord.getM_Product_ID() || !oldRecordWarehouseId.equals(currentRecordWarehouseId) || oldShipmentScheduleRecord.getM_Warehouse_ID() != currentShipmentScheduleRecord.getM_Warehouse_ID() || oldShipmentScheduleRecord.getM_AttributeSetInstance_ID() != currentShipmentScheduleRecord.getM_AttributeSetInstance_ID() || oldShipmentScheduleRecord.getAD_Org_ID() != currentShipmentScheduleRecord.getAD_Org_ID(); }
private void syncAvailableForSalesForShipmentSchedule( @NonNull final I_M_ShipmentSchedule shipmentScheduleRecord, @NonNull final AvailableForSalesConfig config) { final Properties ctx = Env.copyCtx(InterfaceWrapperHelper.getCtx(shipmentScheduleRecord)); final ProductId productId = ProductId.ofRepoId(shipmentScheduleRecord.getM_Product_ID()); final OrgId orgId = OrgId.ofRepoId(shipmentScheduleRecord.getAD_Org_ID()); final AttributesKey storageAttributesKey = AttributesKeys .createAttributesKeyFromASIStorageAttributes(AttributeSetInstanceId.ofRepoIdOrNone(shipmentScheduleRecord.getM_AttributeSetInstance_ID())) .orElse(AttributesKey.NONE); final WarehouseId warehouseId = shipmentScheduleEffectiveBL.getWarehouseId(shipmentScheduleRecord); final EnqueueAvailableForSalesRequest enqueueAvailableForSalesRequest = availableForSalesUtil. createRequestWithPreparationDateNow(ctx, config, productId, orgId, storageAttributesKey, warehouseId); trxManager.runAfterCommit(() -> availableForSalesService.enqueueAvailableForSalesRequest(enqueueAvailableForSalesRequest)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\modelvalidator\M_ShipmentSchedule.java
1
请完成以下Java代码
public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException { Object cellValue = new Object(); FileInputStream inputStream = new FileInputStream(new File(fileLocation)); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); FormulaEvaluator evaluator = workbook.getCreationHelper() .createFormulaEvaluator(); CellAddress cellAddress = new CellAddress(cellLocation); Row row = sheet.getRow(cellAddress.getRow()); Cell cell = row.getCell(cellAddress.getColumn()); if (cell.getCellType() == CellType.FORMULA) { switch (evaluator.evaluateFormulaCell(cell)) { case BOOLEAN: cellValue = cell.getBooleanCellValue();
break; case NUMERIC: cellValue = cell.getNumericCellValue(); break; case STRING: cellValue = cell.getStringCellValue(); break; default: cellValue = null; } } workbook.close(); return cellValue; } }
repos\tutorials-master\apache-poi-4\src\main\java\com\baeldung\poi\excel\read\cellvalueandnotformula\CellValueAndNotFormulaHelper.java
1
请完成以下Java代码
public ArticleRecord value4(Integer value) { setAuthorId(value); return this; } @Override public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // -------------------------------------------------------------------------
/** * Create a detached ArticleRecord */ public ArticleRecord() { super(Article.ARTICLE); } /** * Create a detached, initialised ArticleRecord */ public ArticleRecord(Integer id, String title, String description, Integer authorId) { super(Article.ARTICLE); set(0, id); set(1, title); set(2, description); set(3, authorId); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java
1
请在Spring Boot框架中完成以下Java代码
public Security getSecurity() { return this.security; } // @fold:off public static class Security { // @fold:on // fields... private final String username; private final String password; private final List<String> roles; // @fold:off public Security(String username, String password, @DefaultValue("USER") List<String> roles) { this.username = username; this.password = password; this.roles = roles; } // @fold:on // getters... public String getUsername() {
return this.username; } public String getPassword() { return this.password; } public List<String> getRoles() { return this.roles; } // @fold:off } }
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\features\externalconfig\typesafeconfigurationproperties\constructorbinding\MyProperties.java
2
请完成以下Java代码
public boolean isEnabled(Feature feature) { return features.contains(feature); } /** * Parse expression. */ public Tree build(String expression) throws TreeBuilderException { try { return createParser(expression).tree(); } catch (Scanner.ScanException e) { throw new TreeBuilderException(expression, e.position, e.encountered, e.expected, e.getMessage()); } catch (ParseException e) { throw new TreeBuilderException(expression, e.position, e.encountered, e.expected, e.getMessage()); } } protected Parser createParser(String expression) { return new Parser(this, expression); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } return features.equals(((Builder) obj).features); } @Override public int hashCode() { return getClass().hashCode(); } /** * Dump out abstract syntax tree for a given expression * * @param args array with one element, containing the expression string */ public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java " + Builder.class.getName() + " <expression string>"); System.exit(1); } PrintWriter out = new PrintWriter(System.out); Tree tree = null; try { tree = new Builder(Feature.METHOD_INVOCATIONS).build(args[0]);
} catch (TreeBuilderException e) { System.out.println(e.getMessage()); System.exit(0); } NodePrinter.dump(out, tree.getRoot()); if (!tree.getFunctionNodes().iterator().hasNext() && !tree.getIdentifierNodes().iterator().hasNext()) { ELContext context = new ELContext() { @Override public VariableMapper getVariableMapper() { return null; } @Override public FunctionMapper getFunctionMapper() { return null; } @Override public ELResolver getELResolver() { return null; } }; out.print(">> "); try { out.println(tree.getRoot().getValue(new Bindings(null, null), context, null)); } catch (ELException e) { out.println(e.getMessage()); } } out.flush(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Builder.java
1
请完成以下Java代码
protected String doIt() { final Stream<HUEditorRow> selectedTopLevelHuRows = streamSelectedRows(HUEditorRowFilter.select(Select.ONLY_TOPLEVEL)); final List<I_M_HU> hus = retrieveEligibleHUEditorRows(selectedTopLevelHuRows) .map(HUEditorRow::getM_HU) .collect(ImmutableList.toImmutableList()); if (hus.isEmpty()) { throw new AdempiereException("@NoSelection@"); } final PPOrderLinesView ppOrderView = getPPOrderView().orElseThrow(() -> new AdempiereException("No Issue/Receipt view")); final PPOrderId ppOrderId = ppOrderView.getPpOrderId(); final HUPPOrderIssueProducer issueProducer = huPPOrderBL.createIssueProducer(ppOrderId) .considerIssueMethodForQtyToIssueCalculation(false); // issue exactly the HUs selected by user
final PPOrderBOMLineId selectedOrderBOMLineId = getSelectedOrderBOMLineId(); if (selectedOrderBOMLineId != null) { issueProducer.targetOrderBOMLine(selectedOrderBOMLineId); } issueProducer.createIssues(hus); final HUEditorView huEditorView = getView(); huEditorView.removeHUsAndInvalidate(hus); ppOrderView.invalidateAll(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_HUEditor_IssueTopLevelHUs.java
1
请完成以下Java代码
private static DecodedJWT verifyJWT(String jwtToken) { try { DecodedJWT decodedJWT = verifier.verify(jwtToken); return decodedJWT; } catch (JWTVerificationException e) { System.out.println(e.getMessage()); } return null; } private static DecodedJWT decodedJWT(String jwtToken) { try { DecodedJWT decodedJWT = JWT.decode(jwtToken); return decodedJWT; } catch (JWTDecodeException e) { System.out.println(e.getMessage()); } return null; } private static boolean isJWTExpired(DecodedJWT decodedJWT) { Date expiresAt = decodedJWT.getExpiresAt(); return expiresAt.before(new Date()); }
public static void main(String args[]) throws InterruptedException { initialize(); String jwtToken = createJWT(); System.out.println("Created JWT : " + jwtToken); Thread.sleep(1000L); DecodedJWT decodedJWT = verifyJWT(jwtToken); if (decodedJWT == null) { System.out.println("JWT Verification Failed"); } decodedJWT = decodedJWT(jwtToken); if (decodedJWT != null) { System.out.println("Token Issued At : " + decodedJWT.getIssuedAt()); System.out.println("Token Expires At : " + decodedJWT.getExpiresAt()); Boolean isExpired = isJWTExpired(decodedJWT); System.out.println("Is Expired : " + isExpired); } } }
repos\tutorials-master\security-modules\jwt\src\main\java\com\baeldung\jwt\auth0\JWTDecode.java
1
请完成以下Java代码
public void setService_BPartner_ID (final int Service_BPartner_ID) { if (Service_BPartner_ID < 1) set_Value (COLUMNNAME_Service_BPartner_ID, null); else set_Value (COLUMNNAME_Service_BPartner_ID, Service_BPartner_ID); } @Override public int getService_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Service_BPartner_ID); } @Override public void setServiceFeeAmount (final @Nullable BigDecimal ServiceFeeAmount) { set_Value (COLUMNNAME_ServiceFeeAmount, ServiceFeeAmount); } @Override public BigDecimal getServiceFeeAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public org.compiere.model.I_C_Invoice getService_Fee_Invoice() { return get_ValueAsPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setService_Fee_Invoice(final org.compiere.model.I_C_Invoice Service_Fee_Invoice) { set_ValueFromPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class, Service_Fee_Invoice); } @Override public void setService_Fee_Invoice_ID (final int Service_Fee_Invoice_ID) { if (Service_Fee_Invoice_ID < 1) set_Value (COLUMNNAME_Service_Fee_Invoice_ID, null); else set_Value (COLUMNNAME_Service_Fee_Invoice_ID, Service_Fee_Invoice_ID); } @Override public int getService_Fee_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID); } @Override public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate)
{ set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate); } @Override public BigDecimal getServiceFeeVatRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setService_Product_ID (final int Service_Product_ID) { if (Service_Product_ID < 1) set_Value (COLUMNNAME_Service_Product_ID, null); else set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID); } @Override public int getService_Product_ID() { return get_ValueAsInt(COLUMNNAME_Service_Product_ID); } @Override public void setService_Tax_ID (final int Service_Tax_ID) { if (Service_Tax_ID < 1) set_Value (COLUMNNAME_Service_Tax_ID, null); else set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID); } @Override public int getService_Tax_ID() { return get_ValueAsInt(COLUMNNAME_Service_Tax_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java
1
请完成以下Java代码
public Optional<BPartnerContact> extractContactByHandle(@NonNull final String handle) { final Predicate<BPartnerContact> predicate = c -> c.getHandles().contains(handle); return extractContact(predicate); } public Optional<BPartnerContact> extractContact(@NonNull final Predicate<BPartnerContact> filter) { return createFilteredContactStream(filter) .findAny(); } private Stream<BPartnerContact> createFilteredContactStream(@NonNull final Predicate<BPartnerContact> filter) { return getContacts() .stream() .filter(filter); } /** * Changes this instance by removing all contacts whose IDs are not in the given set */ public void retainContacts(@NonNull final Set<BPartnerContactId> contactIdsToRetain) { contacts.removeIf(contact -> !contactIdsToRetain.contains(contact.getId())); } public Optional<BPartnerLocation> extractLocation(@NonNull final BPartnerLocationId bPartnerLocationId) { final Predicate<BPartnerLocation> predicate = l -> bPartnerLocationId.equals(l.getId()); return createFilteredLocationStream(predicate).findAny(); } public Optional<BPartnerLocation> extractBillToLocation() { final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsBillToOr(false); return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsBillToDefaultOr(false))); } public Optional<BPartnerLocation> extractShipToLocation() { final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsShipToOr(false); return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsShipToDefaultOr(false))); } public Optional<BPartnerLocation> extractLocationByHandle(@NonNull final String handle) { return extractLocation(bpLocation -> bpLocation.containsHandle(handle)); } public Optional<BPartnerLocation> extractLocation(@NonNull final Predicate<BPartnerLocation> filter) { return createFilteredLocationStream(filter).findAny();
} private Stream<BPartnerLocation> createFilteredLocationStream(@NonNull final Predicate<BPartnerLocation> filter) { return getLocations() .stream() .filter(filter); } public void addBankAccount(@NonNull final BPartnerBankAccount bankAccount) { bankAccounts.add(bankAccount); } public Optional<BPartnerBankAccount> getBankAccountByIBAN(@NonNull final String iban) { Check.assumeNotEmpty(iban, "iban is not empty"); return bankAccounts.stream() .filter(bankAccount -> iban.equals(bankAccount.getIban())) .findFirst(); } public void addCreditLimit(@NonNull final BPartnerCreditLimit creditLimit) { creditLimits.add(creditLimit); } @NonNull public Stream<BPartnerContactId> streamContactIds() { return this.getContacts().stream().map(BPartnerContact::getId); } @NonNull public Stream<BPartnerLocationId> streamBPartnerLocationIds() { return this.getLocations().stream().map(BPartnerLocation::getId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerComposite.java
1
请在Spring Boot框架中完成以下Java代码
public class Task { public static Random random =new Random(); @Async public Future<String> doTaskOne() throws Exception { System.out.println("开始做任务一"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"); return new AsyncResult<>("任务一完成"); } @Async public Future<String> doTaskTwo() throws Exception { System.out.println("开始做任务二"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis(); System.out.println("完成任务二,耗时:" + (end - start) + "毫秒"); return new AsyncResult<>("任务二完成"); } @Async public Future<String> doTaskThree() throws Exception { System.out.println("开始做任务三"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务三,耗时:" + (end - start) + "毫秒"); return new AsyncResult<>("任务三完成"); } }
repos\SpringBoot-Learning-master\1.x\Chapter4-1-2\src\main\java\com\didispace\async\Task.java
2
请完成以下Spring Boot application配置
########################################################## ################## 所有profile共有的配置 ################# ########################################################## ################### 自定义配置 ################### xncoding: muti-datasource-open: true #是否开启多数据源(true/false) ################### spring配置 ################### spring: profiles: active: dev ################### mybatis-plus配置 ################### mybatis-plus: mapper-locations: classpath*:com/xncoding/pos/common/dao/repository/mapping/*.xml typeAliasesPackage: > com.xncoding.pos.common.dao.entity global-config: id-type: 0 # 0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid) db-column-underline: false refresh-mapper: true configuration: map-underscore-to-camel-case: true cache-enabled: true #配置的缓存的全局开关 lazyLoadingEnabled: true #延时加载的开关 multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性 logging: level: org.springframework.web.servlet: ERROR --- ##################################################################### ######################## 开发环境profile ########################## ##################################################################### spring:
profiles: dev datasource: url: jdbc:mysql://127.0.0.1:3306/pos?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 username: root password: 123456 #多数据源 biz: datasource: url: jdbc:mysql://127.0.0.1:3306/biz?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 username: root password: 123456 logging: level: ROOT: INFO com: xncoding: DEBUG file: D:/logs/app.log
repos\SpringBootBucket-master\springboot-multisource\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
private void processLogMessageRequest(@NonNull final Exchange exchange) { final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class); final JsonMetasfreshId adPInstanceId = context.getJsonExternalSystemRequest().getAdPInstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId cannot be null at this stage!"); final JsonPluFileAudit jsonPluFileAudit = context.getJsonPluFileAuditNonNull(); final String jsonPluFileAuditMessage = JSONUtil.writeValueAsString(jsonPluFileAudit); final LogMessageRequest logMessageRequest = LogMessageRequest.builder() .logMessage(jsonPluFileAuditMessage) .pInstanceId(adPInstanceId) .build(); exchange.getIn().setBody(logMessageRequest); } private void processJsonAttachmentRequest(@NonNull final Exchange exchange) { final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class); final JsonExternalSystemRequest request = context.getJsonExternalSystemRequest(); final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId cannot be null at this stage!"); final String fileContent = context.getUpdatedPLUFileContent(); final byte[] fileData = fileContent.getBytes(); final String base64FileData = Base64.getEncoder().encodeToString(fileData); final JsonAttachment attachment = JsonAttachment.builder() .fileName(context.getPLUTemplateFilename()) .data(base64FileData)
.type(JsonAttachmentSourceType.Data) .build(); final JsonTableRecordReference jsonTableRecordReference = JsonTableRecordReference.builder() .tableName(LeichMehlConstants.AD_PINSTANCE_TABLE_NAME) .recordId(adPInstanceId) .build(); final JsonAttachmentRequest jsonAttachmentRequest = JsonAttachmentRequest.builder() .attachment(attachment) .orgCode(request.getOrgCode()) .reference(jsonTableRecordReference) .build(); exchange.getIn().setBody(jsonAttachmentRequest); } private void addXMLDeclarationIfNeeded(@NonNull final Exchange exchange) { final DispatchMessageRequest request = exchange.getIn().getBody(DispatchMessageRequest.class); final DispatchMessageRequest modifiedRequest = request.withPayload(XMLUtil.addXMLDeclarationIfNeeded(request.getPayload())); exchange.getIn().setBody(modifiedRequest); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\LeichUndMehlExportPPOrderRouteBuilder.java
2
请完成以下Java代码
public ServletContext getServletContext() { return this.servletContext; } @Override public void setMaxInactiveInterval(int interval) { this.session.setMaxInactiveInterval(Duration.ofSeconds(interval)); } @Override public int getMaxInactiveInterval() { return (int) this.session.getMaxInactiveInterval().getSeconds(); } @Override public Object getAttribute(String name) { checkState(); return this.session.getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { checkState(); return Collections.enumeration(this.session.getAttributeNames()); } @Override public void setAttribute(String name, Object value) { checkState(); Object oldValue = this.session.getAttribute(name); this.session.setAttribute(name, value); if (value != oldValue) { if (oldValue instanceof HttpSessionBindingListener) { try { ((HttpSessionBindingListener) oldValue) .valueUnbound(new HttpSessionBindingEvent(this, name, oldValue)); } catch (Throwable th) { logger.error("Error invoking session binding event listener", th); } } if (value instanceof HttpSessionBindingListener) { try { ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value)); } catch (Throwable th) { logger.error("Error invoking session binding event listener", th); } } } } @Override public void removeAttribute(String name) { checkState(); Object oldValue = this.session.getAttribute(name); this.session.removeAttribute(name); if (oldValue instanceof HttpSessionBindingListener) { try { ((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue)); }
catch (Throwable th) { logger.error("Error invoking session binding event listener", th); } } } @Override public void invalidate() { checkState(); this.invalidated = true; } @Override public boolean isNew() { checkState(); return !this.old; } void markNotNew() { this.old = true; } private void checkState() { if (this.invalidated) { throw new IllegalStateException("The HttpSession has already be invalidated."); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HttpSessionAdapter.java
1
请完成以下Java代码
void delete() { repository.delete(customer); changeHandler.onChange(); } void save() { repository.save(customer); changeHandler.onChange(); } public interface ChangeHandler { void onChange(); } public final void editCustomer(Customer c) { if (c == null) { setVisible(false); return; } final boolean persisted = c.getId() != null; if (persisted) { // Find fresh entity for editing // In a more complex app, you might want to load // the entity/DTO with lazy loaded relations for editing customer = repository.findById(c.getId()).get(); } else {
customer = c; } cancel.setVisible(persisted); // Bind customer properties to similarly named fields // Could also use annotation or "manual binding" or programmatically // moving values from fields to entities before saving binder.setBean(customer); setVisible(true); // Focus first name initially firstName.focus(); } public void setChangeHandler(ChangeHandler h) { // ChangeHandler is notified when either save or delete // is clicked changeHandler = h; } }
repos\springboot-demo-master\vaadin\src\main\java\com\et\vaadin\view\CustomerEditor.java
1
请完成以下Java代码
public class JeecgSystemCloudApplication extends SpringBootServletInitializer implements CommandLineRunner { @Autowired private RedisTemplate<String, Object> redisTemplate; @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(JeecgSystemCloudApplication.class); } public static void main(String[] args) throws UnknownHostException { ConfigurableApplicationContext application = SpringApplication.run(JeecgSystemCloudApplication.class, args); Environment env = application.getEnvironment(); String ip = InetAddress.getLocalHost().getHostAddress(); String port = env.getProperty("server.port"); String path = oConvertUtils.getString(env.getProperty("server.servlet.context-path")); log.info("\n----------------------------------------------------------\n\t" + "Application Jeecg-Boot is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:" + port + path + "/doc.html\n" + "External: \thttp://" + ip + ":" + port + path + "/doc.html\n" + "Swagger文档: \thttp://" + ip + ":" + port + path + "/doc.html\n" + "----------------------------------------------------------");
} /** * 启动的时候,触发下gateway网关刷新 * * 解决: 先启动gateway后启动服务,Swagger接口文档访问不通的问题 * @param args */ @Override public void run(String... args) { BaseMap params = new BaseMap(); params.put(GlobalConstants.HANDLER_NAME, GlobalConstants.LODER_ROUDER_HANDLER); //刷新网关 redisTemplate.convertAndSend(GlobalConstants.REDIS_TOPIC_NAME, params); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-system-cloud-start\src\main\java\org\jeecg\JeecgSystemCloudApplication.java
1
请完成以下Java代码
public DbOperationType getOperationType() { return operationType; } public void setOperationType(DbOperationType operationType) { this.operationType = operationType; } public int getRowsAffected() { return rowsAffected; } public void setRowsAffected(int rowsAffected) { this.rowsAffected = rowsAffected; } public boolean isFailed() { return state == State.FAILED_CONCURRENT_MODIFICATION || state == State.FAILED_CONCURRENT_MODIFICATION_EXCEPTION || state == State.FAILED_ERROR; } public State getState() { return state; } public void setState(State state) { this.state = state; } public Exception getFailure() { return failure; }
public void setFailure(Exception failure) { this.failure = failure; } public enum State { NOT_APPLIED, APPLIED, /** * Indicates that the operation was not performed for any reason except * concurrent modifications. */ FAILED_ERROR, /** * Indicates that the operation was not performed and that the reason * was a concurrent modification to the data to be updated. * Applies to databases with isolation level READ_COMMITTED. */ FAILED_CONCURRENT_MODIFICATION, /** * Indicates that the operation was not performed and was a concurrency * conflict with a SQL exception. Applies to PostgreSQL. */ FAILED_CONCURRENT_MODIFICATION_EXCEPTION } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbOperation.java
1
请完成以下Java代码
private static void treeSetByValue() { SortedSet<Employee> values = new TreeSet<>(map.values()); System.out.println(values); } private static void treeSetByKey() { SortedSet<String> keysSet = new TreeSet<>(map.keySet()); System.out.println(keysSet); } private static void treeMapSortByKey() { TreeMap<String, Employee> sorted = new TreeMap<>(map); sorted.putAll(map); sorted.entrySet().forEach(System.out::println); } private static void arrayListSortByValue() { List<Employee> employeeById = new ArrayList<>(map.values()); Collections.sort(employeeById); System.out.println(employeeById); } private static void arrayListSortByKey() { List<String> employeeByKey = new ArrayList<>(map.keySet()); Collections.sort(employeeByKey); System.out.println(employeeByKey); }
private static void initialize() { Employee employee1 = new Employee(1L, "Mher"); map.put(employee1.getName(), employee1); Employee employee2 = new Employee(22L, "Annie"); map.put(employee2.getName(), employee2); Employee employee3 = new Employee(8L, "John"); map.put(employee3.getName(), employee3); Employee employee4 = new Employee(2L, "George"); map.put(employee4.getName(), employee4); } private static void addDuplicates() { Employee employee5 = new Employee(1L, "Mher"); map.put(employee5.getName(), employee5); Employee employee6 = new Employee(22L, "Annie"); map.put(employee6.getName(), employee6); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\sort\SortHashMap.java
1
请完成以下Java代码
public void setHR_ListVersion_ID (int HR_ListVersion_ID) { if (HR_ListVersion_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, Integer.valueOf(HR_ListVersion_ID)); } /** Get Payroll List Version. @return Payroll List Version */ public int getHR_ListVersion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Max Value. @param MaxValue Max Value */ public void setMaxValue (BigDecimal MaxValue) { set_Value (COLUMNNAME_MaxValue, MaxValue); } /** Get Max Value. @return Max Value */ public BigDecimal getMaxValue () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxValue); if (bd == null) return Env.ZERO; return bd; } /** Set Min Value. @param MinValue Min Value */ public void setMinValue (BigDecimal MinValue) { set_Value (COLUMNNAME_MinValue, MinValue); } /** Get Min Value.
@return Min Value */ public BigDecimal getMinValue () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinValue); if (bd == null) return Env.ZERO; return bd; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListLine.java
1
请在Spring Boot框架中完成以下Java代码
public class BookController { @Autowired private BookRepository repository; // Find @GetMapping("/books") List<Book> findAll() { return repository.findAll(); } // Save @PostMapping("/books") Book newBook(@Valid @RequestBody Book newBook) { return repository.save(newBook); } // Find @GetMapping("/books/{id}") Book findOne(@PathVariable @Min(1) Long id) { return repository.findById(id) .orElseThrow(() -> new BookNotFoundException(id)); } // Save or update @PutMapping("/books/{id}") Book saveOrUpdate(@RequestBody Book newBook, @PathVariable Long id) { return repository.findById(id) .map(x -> { x.setName(newBook.getName()); x.setAuthor(newBook.getAuthor()); x.setPrice(newBook.getPrice()); return repository.save(x); }) .orElseGet(() -> { newBook.setId(id); return repository.save(newBook);
}); } // update author only @PatchMapping("/books/{id}") Book patch(@RequestBody Map<String, String> update, @PathVariable Long id) { return repository.findById(id) .map(x -> { String author = update.get("author"); if (!StringUtils.isEmpty(author)) { x.setAuthor(author); // better create a custom method to update a value = :newValue where id = :id return repository.save(x); } else { throw new BookUnSupportedFieldPatchException(update.keySet()); } }) .orElseGet(() -> { throw new BookNotFoundException(id); }); } @DeleteMapping("/books/{id}") void deleteBook(@PathVariable Long id) { repository.deleteById(id); } }
repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\BookController.java
2
请完成以下Java代码
public ResponseEntity<?> storeLogs(@RequestBody @NonNull final CreatePInstanceLogRequest request, @PathVariable final Integer adPInstanceId) { externalSystemService.storeExternalPinstanceLog(request, PInstanceId.ofRepoId(adPInstanceId)); return ResponseEntity.ok().build(); } @ApiOperation("Create an AD_Issue. Note: it's not necessary that the process in question was started by the `invoke` endpoint.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully created issue"), @ApiResponse(code = 401, message = "You are not authorized to create new issue"), @ApiResponse(code = 403, message = "Accessing a related resource is forbidden"), @ApiResponse(code = 422, message = "The request body could not be processed") }) @PostMapping(path = "{AD_PInstance_ID}/externalstatus/error", consumes = "application/json", produces = "application/json") public ResponseEntity<JsonCreateIssueResponse> handleError(@RequestBody @NonNull final JsonError request, @PathVariable final Integer AD_PInstance_ID) { final JsonCreateIssueResponse issueResponse = externalSystemService.createIssue(request, PInstanceId.ofRepoId(AD_PInstance_ID)); return ResponseEntity.ok(issueResponse); } private ResponseEntity<?> getResponse(@NonNull final ProcessExecutionResult processExecutionResult) {
final RunProcessResponse runProcessResponse; runProcessResponse = RunProcessResponse.builder() .pInstanceID(String.valueOf(processExecutionResult.getPinstanceId().getRepoId())) .errors(processExecutionResult.getThrowable() != null ? JsonError.ofSingleItem(JsonErrors.ofThrowable(processExecutionResult.getThrowable(), Env.getADLanguageOrBaseLanguage())) : null) .build(); return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(runProcessResponse); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\externlasystem\ExternalSystemRestController.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-application # 应用名 nacos: # Nacos 配置中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:18848 # Nacos 服务器地址 auto-register: true # 是否自动注册到 Nacos 中。默认为 false。 namespace: # 使用的 Nacos 的命名空间,默认为 null。 register: service-name: ${spring
.application.name} # 注册到 Nacos 的服务名 group-name: DEFAULT_GROUP # 使用的 Nacos 服务分组,默认为 DEFAULT_GROUP。 cluster-name: # 集群名,默认为空。
repos\SpringBoot-Labs-master\lab-44\lab-44-nacos-discovery-demo\src\main\resources\application.yaml
2
请完成以下Java代码
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("MessageEventPayload [id="); builder.append(id); builder.append(", messageName="); builder.append(name); builder.append(", correlationKey="); builder.append(correlationKey); builder.append(", businessKey="); builder.append(businessKey); builder.append(", variables="); builder.append(variables); builder.append("]"); return builder.toString(); } @Override public int hashCode() { return Objects.hash(businessKey, correlationKey, id, name, variables); }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageEventPayload other = (MessageEventPayload) obj; return ( Objects.equals(businessKey, other.businessKey) && Objects.equals(correlationKey, other.correlationKey) && Objects.equals(id, other.id) && Objects.equals(name, other.name) && Objects.equals(variables, other.variables) ); } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\MessageEventPayload.java
1
请完成以下Java代码
public void updateHistoricActivityInstance(ActivityInstance activityInstance) { for (HistoryManager historyManager : historyManagers) { historyManager.updateHistoricActivityInstance(activityInstance); } } @Override public void createHistoricActivityInstance(ActivityInstance activityInstance) { for (HistoryManager historyManager : historyManagers) { historyManager.createHistoricActivityInstance(activityInstance); } } @Override public void recordHistoricUserTaskLogEntry(HistoricTaskLogEntryBuilder taskLogEntryBuilder) {
for (HistoryManager historyManager : historyManagers) { historyManager.recordHistoricUserTaskLogEntry(taskLogEntryBuilder); } } @Override public void deleteHistoryUserTaskLog(long logNumber) { for (HistoryManager historyManager : historyManagers) { historyManager.deleteHistoryUserTaskLog(logNumber); } } public void addHistoryManager(HistoryManager historyManager) { historyManagers.add(historyManager); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\CompositeHistoryManager.java
1