instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setIsAdditionalCustomQuery (final boolean IsAdditionalCustomQuery) { set_Value (COLUMNNAME_IsAdditionalCustomQuery, IsAdditionalCustomQuery); } @Override public boolean isAdditionalCustomQuery() { return get_ValueAsBoolean(COLUMNNAME_IsAdditionalCustomQuery); } @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); }
@Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_ConfigGroup.java
1
请在Spring Boot框架中完成以下Java代码
public String logout(HttpServletRequest request, Model model) { request.getSession().removeAttribute(ConstantClass.USER); return "system/login"; } /** * 函数功能说明 :首页 * * @return String * @throws * @参数: @return */ @RequestMapping(value = "/index", method = {RequestMethod.POST, RequestMethod.GET}) public String index(HttpServletRequest request, Model model) { // 获取登录的用户 RpUserInfo rpUserInfo = (RpUserInfo) request.getSession().getAttribute(ConstantClass.USER); if (rpUserInfo != null) { return "system/index"; } String mobile = request.getParameter("mobile"); String password = request.getParameter("password"); String msg = ""; if (StringUtil.isEmpty(mobile)) { msg = "请输入手机号/密码"; model.addAttribute("msg", msg); return "system/login"; } if (StringUtil.isEmpty(password)) {
msg = "请输入手机号/密码"; model.addAttribute("msg", msg); return "system/login"; } rpUserInfo = rpUserInfoService.getDataByMobile(mobile); if (rpUserInfo == null) { msg = "用户名/密码错误"; } else if (!EncryptUtil.encodeMD5String(password).equals(rpUserInfo.getPassword())) { msg = "用户名/密码错误"; } model.addAttribute("mobile", mobile); model.addAttribute("password", password); request.getSession().setAttribute(ConstantClass.USER, rpUserInfo); if (!StringUtil.isEmpty(msg)) { model.addAttribute("msg", msg); return "system/login"; } return "system/index"; } }
repos\roncoo-pay-master\roncoo-pay-web-merchant\src\main\java\com\roncoo\pay\controller\login\LoginController.java
2
请完成以下Java代码
public org.compiere.model.I_M_Attribute getM_Attribute() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class); } @Override public void setM_Attribute(org.compiere.model.I_M_Attribute M_Attribute) { set_ValueFromPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class, M_Attribute); } /** Set Merkmal. @param M_Attribute_ID Product Attribute */ @Override public void setM_Attribute_ID (int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID)); } /** Get Merkmal. @return Product Attribute */ @Override public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name)
{ set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue.java
1
请完成以下Java代码
public Mono<URI> getRedirectUri(ServerWebExchange exchange) { MultiValueMap<String, HttpCookie> cookieMap = exchange.getRequest().getCookies(); return Mono.justOrEmpty(cookieMap.getFirst(REDIRECT_URI_COOKIE_NAME)) .map(HttpCookie::getValue) .map(CookieServerRequestCache::decodeCookie) .onErrorResume(IllegalArgumentException.class, (ex) -> Mono.empty()) .map(URI::create); } @Override public Mono<ServerHttpRequest> removeMatchingRequest(ServerWebExchange exchange) { return Mono.just(exchange.getResponse()) .map(ServerHttpResponse::getCookies) .doOnNext((cookies) -> cookies.add(REDIRECT_URI_COOKIE_NAME, invalidateRedirectUriCookie(exchange.getRequest()))) .thenReturn(exchange.getRequest()); } /** * Sets the {@link Consumer}, allowing customization of cookie. * @param cookieCustomizer customize for cookie * @since 6.4 */ public void setCookieCustomizer(Consumer<ResponseCookie.ResponseCookieBuilder> cookieCustomizer) { Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null"); this.cookieCustomizer = cookieCustomizer; } private static ResponseCookie.ResponseCookieBuilder createRedirectUriCookieBuilder(ServerHttpRequest request) { String path = request.getPath().pathWithinApplication().value(); String query = request.getURI().getRawQuery(); String redirectUri = path + ((query != null) ? "?" + query : ""); return createResponseCookieBuilder(request, encodeCookie(redirectUri), COOKIE_MAX_AGE); } private static ResponseCookie invalidateRedirectUriCookie(ServerHttpRequest request) { return createResponseCookieBuilder(request, null, Duration.ZERO).build();
} private static ResponseCookie.ResponseCookieBuilder createResponseCookieBuilder(ServerHttpRequest request, @Nullable String cookieValue, Duration age) { return ResponseCookie.from(REDIRECT_URI_COOKIE_NAME) .value(cookieValue) .path(request.getPath().contextPath().value() + "/") .maxAge(age) .httpOnly(true) .secure("https".equalsIgnoreCase(request.getURI().getScheme())) .sameSite("Lax"); } private static String encodeCookie(String cookieValue) { return new String(Base64.getEncoder().encode(cookieValue.getBytes())); } private static String decodeCookie(String encodedCookieValue) { return new String(Base64.getDecoder().decode(encodedCookieValue.getBytes())); } private static ServerWebExchangeMatcher createDefaultRequestMatcher() { ServerWebExchangeMatcher get = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/**"); ServerWebExchangeMatcher notFavicon = new NegatedServerWebExchangeMatcher( ServerWebExchangeMatchers.pathMatchers("/favicon.*")); MediaTypeServerWebExchangeMatcher html = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML); html.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); return new AndServerWebExchangeMatcher(get, notFavicon, html); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\savedrequest\CookieServerRequestCache.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Duration getReceiveTimeout() { return this.receiveTimeout; } public void setReceiveTimeout(@Nullable Duration receiveTimeout) { this.receiveTimeout = receiveTimeout; } public Session getSession() { return this.session; } public static class Session { /** * Acknowledge mode used when creating sessions. */ private AcknowledgeMode acknowledgeMode = AcknowledgeMode.AUTO; /** * Whether to use transacted sessions. */ private boolean transacted; public AcknowledgeMode getAcknowledgeMode() { return this.acknowledgeMode; } public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) { this.acknowledgeMode = acknowledgeMode; } public boolean isTransacted() { return this.transacted; } public void setTransacted(boolean transacted) { this.transacted = transacted; } } } public enum DeliveryMode {
/** * Does not require that the message be logged to stable storage. This is the * lowest-overhead delivery mode but can lead to lost of message if the broker * goes down. */ NON_PERSISTENT(1), /* * Instructs the JMS provider to log the message to stable storage as part of the * client's send operation. */ PERSISTENT(2); private final int value; DeliveryMode(int value) { this.value = value; } public int getValue() { return this.value; } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsProperties.java
2
请完成以下Java代码
public List<Rating> findCachedRatingsByBookId(Long bookId) { return setOps.members("book-" + bookId) .stream() .map(rtId -> { try { return jsonMapper.readValue(valueOps.get(rtId), Rating.class); } catch (IOException ex) { return null; } }) .collect(Collectors.toList()); } public Rating findCachedRatingById(Long ratingId) { try { return jsonMapper.readValue(valueOps.get("rating-" + ratingId), Rating.class); } catch (IOException e) { return null; } } public List<Rating> findAllCachedRatings() { List<Rating> ratings = null; ratings = redisTemplate.keys("rating*") .stream() .map(rtId -> { try { return jsonMapper.readValue(valueOps.get(rtId), Rating.class); } catch (IOException e) { return null; } }) .collect(Collectors.toList()); return ratings; } public boolean createRating(Rating persisted) { try { valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted)); setOps.add("book-" + persisted.getBookId(), "rating-" + persisted.getId()); return true; } catch (JsonProcessingException ex) { return false; } }
public boolean updateRating(Rating persisted) { try { valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted)); return true; } catch (JsonProcessingException e) { e.printStackTrace(); } return false; } public boolean deleteRating(Long ratingId) { Rating toDel; try { toDel = jsonMapper.readValue(valueOps.get("rating-" + ratingId), Rating.class); setOps.remove("book-" + toDel.getBookId(), "rating-" + ratingId); redisTemplate.delete("rating-" + ratingId); return true; } catch (IOException e) { e.printStackTrace(); } return false; } @Override public void afterPropertiesSet() throws Exception { this.redisTemplate = new StringRedisTemplate(cacheConnectionFactory); this.valueOps = redisTemplate.opsForValue(); this.setOps = redisTemplate.opsForSet(); jsonMapper = new ObjectMapper(); jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingCacheRepository.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((id == null) ? 0 : id.hashCode()); 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; } final Organization other = (Organization) obj; if (id == null) { if (other.id != null) { return false;
} } else if (!id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\Organization.java
1
请完成以下Java代码
public StockQtyAndUOMQty getQtysWithIssues(@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn) { Quantity deliveredInUom; switch (invoicableQtyBasedOn) { case CatchWeight: deliveredInUom = coalesce(getQtyWithIssuesCatch(), getQtyWithIssuesNominal()); break; case NominalWeight: deliveredInUom = getQtyWithIssuesNominal(); break; default: throw new AdempiereException("Unexpected InvoicableQtyBasedOn=" + invoicableQtyBasedOn); } return StockQtyAndUOMQty.builder() .productId(productId) .stockQty(qtyWithIssuesInStockUom) .uomQty(deliveredInUom).build(); } public StockQtyAndUOMQty computeQtysWithIssuesEffective( @Nullable final Percent qualityDiscountOverride, @NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn) { if (qualityDiscountOverride == null) { return getQtysWithIssues(invoicableQtyBasedOn); } final Quantity qtyTotal = getQtysTotal(invoicableQtyBasedOn).getUOMQtyNotNull(); final Quantity qtyTotalInStockUom = getQtysTotal(invoicableQtyBasedOn).getStockQty(); final BigDecimal qtyWithIssuesEffective = qualityDiscountOverride.computePercentageOf( qtyTotal.toBigDecimal(), qtyTotal.getUOM().getStdPrecision()); final BigDecimal qtyWithIssuesInStockUomEffective = qualityDiscountOverride.computePercentageOf( qtyTotalInStockUom.toBigDecimal(), qtyTotalInStockUom.getUOM().getStdPrecision()); return StockQtyAndUOMQtys.create( qtyWithIssuesInStockUomEffective, productId,
qtyWithIssuesEffective, qtyTotal.getUomId()); } public StockQtyAndUOMQty computeInvoicableQtyDelivered( @Nullable final Percent qualityDiscountOverride, @NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn) { final StockQtyAndUOMQty qtysWithIssuesEffective = computeQtysWithIssuesEffective(qualityDiscountOverride, invoicableQtyBasedOn); return getQtysTotal(invoicableQtyBasedOn).subtract(qtysWithIssuesEffective); } public Percent computeQualityDiscount(@NonNull final InvoicableQtyBasedOn invoicableQtyBasedOn) { return Percent.of( getQtysWithIssues(invoicableQtyBasedOn).getUOMQtyNotNull().toBigDecimal(), getQtysTotal(invoicableQtyBasedOn).getUOMQtyNotNull().toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\ReceiptData.java
1
请完成以下Java代码
protected void rollbackOperation() { // first, rollback all successful steps for (DeploymentOperationStep step : successfulSteps) { try { step.cancelOperationStep(this); } catch(Exception e) { LOG.exceptionWhileRollingBackOperation(e); } } // second, remove services for (String serviceName : installedServices) { try { serviceContainer.stopService(serviceName); } catch(Exception e) { LOG.exceptionWhileStopping("service", serviceName, e); } } } public List<String> getInstalledServices() { return installedServices; } // builder ///////////////////////////// public static class DeploymentOperationBuilder { protected PlatformServiceContainer container; protected String name; protected boolean isUndeploymentOperation = false; protected List<DeploymentOperationStep> steps = new ArrayList<DeploymentOperationStep>(); protected Map<String, Object> initialAttachments = new HashMap<String, Object>(); public DeploymentOperationBuilder(PlatformServiceContainer container, String name) { this.container = container; this.name = name;
} public DeploymentOperationBuilder addStep(DeploymentOperationStep step) { steps.add(step); return this; } public DeploymentOperationBuilder addSteps(Collection<DeploymentOperationStep> steps) { for (DeploymentOperationStep step: steps) { addStep(step); } return this; } public DeploymentOperationBuilder addAttachment(String name, Object value) { initialAttachments.put(name, value); return this; } public DeploymentOperationBuilder setUndeploymentOperation() { isUndeploymentOperation = true; return this; } public void execute() { DeploymentOperation operation = new DeploymentOperation(name, container, steps); operation.isRollbackOnFailure = !isUndeploymentOperation; operation.attachments.putAll(initialAttachments); container.executeDeploymentOperation(operation); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\spi\DeploymentOperation.java
1
请完成以下Java代码
public AmountRangeBoundary1 getToAmt() { return toAmt; } /** * Sets the value of the toAmt property. * * @param value * allowed object is * {@link AmountRangeBoundary1 } * */ public void setToAmt(AmountRangeBoundary1 value) { this.toAmt = value; } /** * Gets the value of the frToAmt property. * * @return * possible object is * {@link FromToAmountRange } * */ public FromToAmountRange getFrToAmt() { return frToAmt; } /** * Sets the value of the frToAmt property. * * @param value * allowed object is * {@link FromToAmountRange } * */ public void setFrToAmt(FromToAmountRange value) { this.frToAmt = value; } /** * Gets the value of the eqAmt property. * * @return * possible object is * {@link BigDecimal } * */
public BigDecimal getEQAmt() { return eqAmt; } /** * Sets the value of the eqAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setEQAmt(BigDecimal value) { this.eqAmt = value; } /** * Gets the value of the neqAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getNEQAmt() { return neqAmt; } /** * Sets the value of the neqAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setNEQAmt(BigDecimal value) { this.neqAmt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ImpliedCurrencyAmountRangeChoice.java
1
请在Spring Boot框架中完成以下Java代码
public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) { if (event.getEntityId().getEntityType() == EntityType.TENANT) { if (event.getEvent() == ComponentLifecycleEvent.DELETED) { Set<TopicPartitionInfo> partitions = stateService.getPartitions(); if (CollectionUtils.isEmpty(partitions)) { return; } stateService.delete(partitions.stream() .filter(tpi -> tpi.getTenantId().isPresent() && tpi.getTenantId().get().equals(event.getTenantId())) .collect(Collectors.toSet())); } } } private void forwardToActorSystem(CalculatedFieldTelemetryMsgProto msg, TbCallback callback) { var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB()); var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB())); actorContext.tell(new CalculatedFieldTelemetryMsg(tenantId, entityId, msg, callback)); }
private void forwardToActorSystem(CalculatedFieldLinkedTelemetryMsgProto linkedMsg, TbCallback callback) { var msg = linkedMsg.getMsg(); var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB()); var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB())); actorContext.tell(new CalculatedFieldLinkedTelemetryMsg(tenantId, entityId, linkedMsg, callback)); } private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) { return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB)); } @Override protected void stopConsumers() { super.stopConsumers(); stateService.stop(); // eventConsumer will be stopped by stateService } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCalculatedFieldConsumerService.java
2
请完成以下Java代码
public int getC_Invoice_Relation_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Relation_ID); } /** * C_Invoice_Relation_Type AD_Reference_ID=541475 * Reference name: C_Invoice_Relation_Types */ public static final int C_INVOICE_RELATION_TYPE_AD_Reference_ID=541475; /** PurchaseToSales = POtoSO */ public static final String C_INVOICE_RELATION_TYPE_PurchaseToSales = "POtoSO"; @Override public void setC_Invoice_Relation_Type (final java.lang.String C_Invoice_Relation_Type) { set_Value (COLUMNNAME_C_Invoice_Relation_Type, C_Invoice_Relation_Type); } @Override public java.lang.String getC_Invoice_Relation_Type() { return get_ValueAsString(COLUMNNAME_C_Invoice_Relation_Type); } @Override public org.compiere.model.I_C_Invoice getC_Invoice_To() {
return get_ValueAsPO(COLUMNNAME_C_Invoice_To_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice_To(final org.compiere.model.I_C_Invoice C_Invoice_To) { set_ValueFromPO(COLUMNNAME_C_Invoice_To_ID, org.compiere.model.I_C_Invoice.class, C_Invoice_To); } @Override public void setC_Invoice_To_ID (final int C_Invoice_To_ID) { if (C_Invoice_To_ID < 1) set_Value (COLUMNNAME_C_Invoice_To_ID, null); else set_Value (COLUMNNAME_C_Invoice_To_ID, C_Invoice_To_ID); } @Override public int getC_Invoice_To_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_To_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Relation.java
1
请完成以下Java代码
public FlatrateDataEntry save(@NonNull final FlatrateDataEntry entry) { final I_C_Flatrate_DataEntry entryRecord = load(entry.getId(), I_C_Flatrate_DataEntry.class); entryRecord.setC_UOM_ID(entry.getUomId().getRepoId()); entryRecord.setC_Flatrate_Term_ID(entry.getId().getFlatrateTermId().getRepoId()); final FlatrateDataEntry.FlatrateDataEntryBuilder result = entry.toBuilder().clearDetails(); int maxSeqNo = 0; for (final FlatrateDataEntryDetail detail : entry.getDetails()) { if (detail.getSeqNo() > maxSeqNo) { maxSeqNo = detail.getSeqNo(); } } maxSeqNo += 10; Quantity qtySum = Quantitys.zero(entry.getUomId()); for (final FlatrateDataEntryDetail detail : entry.getDetails()) { final I_C_Flatrate_DataEntry_Detail detailRecord = loadOrNew(detail.getId(), I_C_Flatrate_DataEntry_Detail.class); detailRecord.setC_Flatrate_DataEntry_ID(entry.getId().getRepoId()); detailRecord.setC_BPartner_Department_ID(BPartnerDepartmentId.toRepoId(detail.getBPartnerDepartment().getId())); detailRecord.setM_AttributeSetInstance_ID(AttributeSetInstanceId.toRepoId(detail.getAsiId())); final Quantity quantity = detail.getQuantity(); detailRecord.setQty_Reported(Quantitys.toBigDecimalOrNull(quantity)); if (quantity != null) { detailRecord.setC_UOM_ID(quantity.getUomId().getRepoId()); qtySum = qtySum.add(quantity); } else
{ detailRecord.setC_UOM_ID(entryRecord.getC_UOM_ID()); } if (detailRecord.getSeqNo() <= 0) { detailRecord.setSeqNo(maxSeqNo); maxSeqNo += 10; } saveRecord(detailRecord); final FlatrateDataEntryDetailId detailId = FlatrateDataEntryDetailId.ofRepoId(entry.getId(), detailRecord.getC_Flatrate_DataEntry_Detail_ID()); result.detail(detail.withId(detailId)); } entryRecord.setQty_Reported(qtySum.toBigDecimal()); saveRecord(entryRecord); return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\FlatrateDataEntryRepo.java
1
请完成以下Java代码
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_QtyCUsPerTU.equals(parameter.getColumnName()) && isSingleSelectedRow()) { return computeQtyToIssue(getSingleSelectedRow()); } else if (PARAM_IsShowAllParams.equals(parameter.getColumnName())) { return isSingleSelectedRow(); } else { return DEFAULT_VALUE_NOTAVAILABLE; } } private Quantity computeQtyToIssue(final PPOrderLineRow row) { final List<I_M_Source_HU> activeSourceHus = WEBUI_PP_Order_ProcessHelper.retrieveActiveSourceHus(row); if (activeSourceHus.isEmpty()) { throw new AdempiereException("@NoSelection@"); } final Quantity qtyLeftToIssue = row.getQtyPlan().subtract(row.getQty()); final BOMComponentIssueMethod issueMethod = row.getIssueMethod(); if (BOMComponentIssueMethod.IssueOnlyForReceived.equals(issueMethod)) { if (qtyLeftToIssue.signum() <= 0)
{ return qtyLeftToIssue.toZero(); } if (row.isProcessed()) { final I_PP_Order_BOMLine bomLine = ppOrderBOMDAO.getOrderBOMLineById(row.getOrderBOMLineId()); final DraftPPOrderQuantities draftQtys = huPPOrderQtyBL.getDraftPPOrderQuantities(row.getOrderId()); final Quantity quantityToIssueForWhatWasReceived = ppOrderBomBL.computeQtyToIssueBasedOnFinishedGoodReceipt(bomLine, row.getUom(), draftQtys); return qtyLeftToIssue.min(quantityToIssueForWhatWasReceived); } else { return qtyLeftToIssue; } } else { return qtyLeftToIssue; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_M_Source_HU_IssueCUQty.java
1
请完成以下Java代码
private MCashLine[] createCashLines(MCash cash) { ArrayList<MCashLine> cashLineList = new ArrayList<MCashLine>(); // From Bank (From) to CashLine MCashLine cashLine = new MCashLine (cash); cashLine.setAmount(p_Amount); cashLine.setC_BP_BankAccount_ID(p_From_C_BP_BankAccount_ID); cashLine.setC_Currency_ID(m_C_Currency_ID); if (p_Description != null) cashLine.setDescription(p_Description); else cashLine.setDescription(p_Name); cashLine.setCashType("T"); // Transfer if (!cashLine.save()) { throw new IllegalStateException("Could not create Cash line (From Bank)"); } cashLineList.add(cashLine); // From CashLine to Bank (To) cashLine = new MCashLine (cash); cashLine.setAmount(p_Amount.negate()); cashLine.setC_BP_BankAccount_ID(p_To_C_BP_BankAccount_ID); cashLine.setC_Currency_ID(m_C_Currency_ID); if (p_Description != null) cashLine.setDescription(p_Description); else cashLine.setDescription(p_Name); cashLine.setCashType("T"); // Transfer if (!cashLine.save()) { throw new IllegalStateException("Could not create Cash line (To Bank)"); } cashLineList.add(cashLine); MCashLine cashLines[] = new MCashLine[cashLineList.size()]; cashLineList.toArray(cashLines); return cashLines; } // createCashLines
/** * Generate CashJournal * */ private void generateBankTransfer() { // Create Cash & CashLines MCash cash = createCash(); MCashLine cashLines[]= createCashLines(cash); StringBuffer processMsg = new StringBuffer(cash.getDocumentNo()); cash.setDocAction(p_docAction); if (!cash.processIt(p_docAction)) { processMsg.append(" (NOT Processed)"); log.warn("Cash Processing failed: " + cash + " - " + cash.getProcessMsg()); addLog(cash.getC_Cash_ID(), cash.getStatementDate(), null, "Cash Processing failed: " + cash + " - " + cash.getProcessMsg() + " / please complete it manually"); } if (!cash.save()) { throw new IllegalStateException("Could not create Cash"); } // Add processing information to process log addLog(cash.getC_Cash_ID(), cash.getStatementDate(), null, processMsg.toString()); m_created++; } // generateBankTransfer } // ImmediateBankTransfer
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\process\ImmediateBankTransfer.java
1
请完成以下Spring Boot application配置
## Spring view resolver set up spring.mvc.view.prefix= /WEB-INF/jsp/ spring.mvc.view.suffix=.jsp ## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username = root spring.datasource.password = posilka2020 ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.hiberna
te.ddl-auto=update spring.datasource.driver = com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect logging.level.org.hibernate.SQL = debug spring.jpa.show-sql=true
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDBNoSec\src\main\resources\application.properties
2
请完成以下Java代码
public class CombiningLists { public static List<Object> usingNativeJava(List<Object> first, List<Object> second) { List<Object> combined = new ArrayList<>(); combined.addAll(first); combined.addAll(second); return combined; } public static List<Object> usingJava8ObjectStream(List<Object> first, List<Object> second) { List<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList()); return combined; } public static List<Object> usingJava8FlatMaps(List<Object> first, List<Object> second) { List<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList());
return combined; } public static List<Object> usingApacheCommons(List<Object> first, List<Object> second) { List<Object> combined = ListUtils.union(first, second); return combined; } public static List<Object> usingGuava(List<Object> first, List<Object> second) { Iterable<Object> combinedIterables = Iterables.unmodifiableIterable( Iterables.concat(first, second)); List<Object> combined = Lists.newArrayList(combinedIterables); return combined; } }
repos\tutorials-master\core-java-modules\core-java-collections\src\main\java\com\baeldung\collections\combiningcollections\CombiningLists.java
1
请完成以下Java代码
public Iterator<DistributionFacetId> iterator() {return set.iterator();} public boolean isEmpty() {return set.isEmpty();} public Set<WarehouseId> getWarehouseFromIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_FROM, DistributionFacetId::getWarehouseId);} public Set<WarehouseId> getWarehouseToIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_TO, DistributionFacetId::getWarehouseId);} public Set<OrderId> getSalesOrderIds() {return getValues(DistributionFacetGroupType.SALES_ORDER, DistributionFacetId::getSalesOrderId);} public Set<PPOrderId> getManufacturingOrderIds() {return getValues(DistributionFacetGroupType.MANUFACTURING_ORDER_NO, DistributionFacetId::getManufacturingOrderId);} public Set<LocalDate> getDatesPromised() {return getValues(DistributionFacetGroupType.DATE_PROMISED, DistributionFacetId::getDatePromised);} public Set<ProductId> getProductIds() {return getValues(DistributionFacetGroupType.PRODUCT, DistributionFacetId::getProductId);} public Set<Quantity> getQuantities() {return getValues(DistributionFacetGroupType.QUANTITY, DistributionFacetId::getQty);} public Set<ResourceId> getPlantIds() {return getValues(DistributionFacetGroupType.PLANT_RESOURCE_ID, DistributionFacetId::getPlantId);}
public <T> Set<T> getValues(DistributionFacetGroupType groupType, Function<DistributionFacetId, T> valueExtractor) { if (set.isEmpty()) { return ImmutableSet.of(); } return set.stream() .filter(facetId -> facetId.getGroup().equals(groupType)) .map(valueExtractor) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetIdsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public UpdateProcessDefinitionSuspensionStateBuilderImpl includeProcessInstances(boolean includeProcessInstance) { this.includeProcessInstances = includeProcessInstance; return this; } @Override public UpdateProcessDefinitionSuspensionStateBuilderImpl executionDate(Date date) { this.executionDate = date; return this; } @Override public UpdateProcessDefinitionSuspensionStateBuilderImpl processDefinitionWithoutTenantId() { this.processDefinitionTenantId = null; this.isTenantIdSet = true; return this; } @Override public UpdateProcessDefinitionSuspensionStateBuilderImpl processDefinitionTenantId(String tenantId) { ensureNotNull("tenantId", tenantId); this.processDefinitionTenantId = tenantId; this.isTenantIdSet = true; return this; } @Override public void activate() { validateParameters(); ActivateProcessDefinitionCmd command = new ActivateProcessDefinitionCmd(this); commandExecutor.execute(command); } @Override public void suspend() { validateParameters(); SuspendProcessDefinitionCmd command = new SuspendProcessDefinitionCmd(this); commandExecutor.execute(command); } protected void validateParameters() {
ensureOnlyOneNotNull("Need to specify either a process instance id or a process definition key.", processDefinitionId, processDefinitionKey); if(processDefinitionId != null && isTenantIdSet) { throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey(); } ensureNotNull("commandExecutor", commandExecutor); } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isIncludeProcessInstances() { return includeProcessInstances; } public Date getExecutionDate() { return executionDate; } public String getProcessDefinitionTenantId() { return processDefinitionTenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\UpdateProcessDefinitionSuspensionStateBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
InfoContributor grpcInfoContributor(final GrpcServerProperties properties, final Collection<BindableService> grpcServices) { final Map<String, Object> details = new LinkedHashMap<>(); details.put("port", properties.getPort()); if (properties.isReflectionServiceEnabled()) { // Only expose services via web-info if we do the same via grpc. final Map<String, List<String>> services = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); details.put("services", services); for (final BindableService grpcService : grpcServices) { final ServiceDescriptor serviceDescriptor = grpcService.bindService().getServiceDescriptor(); final List<String> methods = collectMethodNamesForService(serviceDescriptor); services.put(serviceDescriptor.getName(), methods); } } return new SimpleInfoContributor("grpc.server", details); }
/** * Gets all method names from the given service descriptor. * * @param serviceDescriptor The service descriptor to get the names from. * @return The newly created and sorted list of the method names. */ protected List<String> collectMethodNamesForService(final ServiceDescriptor serviceDescriptor) { final List<String> methods = new ArrayList<>(); for (final MethodDescriptor<?, ?> grpcMethod : serviceDescriptor.getMethods()) { methods.add(extractMethodName(grpcMethod)); } methods.sort(String.CASE_INSENSITIVE_ORDER); return methods; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerMetricAutoConfiguration.java
2
请完成以下Java代码
public @Nullable MultipartConfigElement getMultipartConfig() { return this.multipartConfig; } @Override protected String getDescription() { Assert.state(this.servlet != null, "Unable to return description for null servlet"); return "servlet " + getServletName(); } @Override protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); return servletContext.addServlet(name, this.servlet); } /** * Configure registration settings. Subclasses can override this method to perform * additional configuration if required. * @param registration the registration */ @Override protected void configure(ServletRegistration.Dynamic registration) { super.configure(registration); String[] urlMapping = StringUtils.toStringArray(this.urlMappings); if (urlMapping.length == 0 && this.alwaysMapUrl) { urlMapping = DEFAULT_MAPPINGS; } if (!ObjectUtils.isEmpty(urlMapping)) { registration.addMapping(urlMapping); } registration.setLoadOnStartup(this.loadOnStartup); if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig); } } /** * Returns the servlet name that will be registered. * @return the servlet name */ public String getServletName() { return getOrDeduceName(this.servlet); } @Override public String toString() { return getServletName() + " urls=" + getUrlMappings(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletRegistrationBean.java
1
请完成以下Java代码
public param setName(String name) { addAttribute("name",name); return(this); } /** Sets the value of this attribute. @param value sets the value attribute. */ public param setValue(String value) { addAttribute("value",value); return(this); } /** Sets the valuetype of this parameter. @param valuetype sets the name of this parameter.<br> ref|data|object convience varaibles provided as param.ref,param.data,param.object */ public param setValueType(String valuetype) { addAttribute("value",valuetype); return(this); } /** Sets the mime type of this object @param the mime type of this object */ public param setType(String cdata) { addAttribute("type",cdata); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public param addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public param addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this);
} /** Adds an Element to the element. @param element Adds an Element to the element. */ public param addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public param addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public param removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\param.java
1
请在Spring Boot框架中完成以下Java代码
public PageData<MobileAppBundleInfo> getTenantMobileAppBundleInfos(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @Parameter(description = "Case-insensitive 'substring' filter based on app's name") @RequestParam(required = false) String textSearch, @Parameter(description = SORT_PROPERTY_DESCRIPTION) @RequestParam(required = false) String sortProperty, @Parameter(description = SORT_ORDER_DESCRIPTION) @RequestParam(required = false) String sortOrder) throws ThingsboardException { PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); return mobileAppBundleService.findMobileAppBundleInfosByTenantId(getTenantId(), pageLink); } @ApiOperation(value = "Get mobile app bundle info by id (getMobileAppBundleInfoById)", notes = SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @GetMapping(value = "/mobile/bundle/info/{id}")
public MobileAppBundleInfo getMobileAppBundleInfoById(@PathVariable UUID id) throws ThingsboardException { MobileAppBundleId mobileAppBundleId = new MobileAppBundleId(id); return checkEntityId(mobileAppBundleId, mobileAppBundleService::findMobileAppBundleInfoById, Operation.READ); } @ApiOperation(value = "Delete Mobile App Bundle by ID (deleteMobileAppBundle)", notes = "Deletes Mobile App Bundle by ID. Referencing non-existing mobile app bundle Id will cause an error." + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @DeleteMapping(value = "/mobile/bundle/{id}") public void deleteMobileAppBundle(@PathVariable UUID id) throws Exception { MobileAppBundleId mobileAppBundleId = new MobileAppBundleId(id); MobileAppBundle mobileAppBundle = checkMobileAppBundleId(mobileAppBundleId, Operation.DELETE); tbMobileAppBundleService.delete(mobileAppBundle, getCurrentUser()); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\MobileAppBundleController.java
2
请完成以下Java代码
public ResponseEntity<List<MenuDto>> getMenuSuperior(@RequestBody List<Long> ids) { Set<MenuDto> menuDtos = new LinkedHashSet<>(); if(CollectionUtil.isNotEmpty(ids)){ for (Long id : ids) { MenuDto menuDto = menuService.findById(id); List<MenuDto> menuDtoList = menuService.getSuperior(menuDto, new ArrayList<>()); for (MenuDto menu : menuDtoList) { if(menu.getId().equals(menuDto.getPid())) { menu.setSubCount(menu.getSubCount() - 1); } } menuDtos.addAll(menuDtoList); } // 编辑菜单时不显示自己以及自己下级的数据,避免出现PID数据环形问题 menuDtos = menuDtos.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toSet()); return new ResponseEntity<>(menuService.buildTree(new ArrayList<>(menuDtos)),HttpStatus.OK); } return new ResponseEntity<>(menuService.getMenus(null),HttpStatus.OK); } @Log("新增菜单") @ApiOperation("新增菜单") @PostMapping @PreAuthorize("@el.check('menu:add')") public ResponseEntity<Object> createMenu(@Validated @RequestBody Menu resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } menuService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改菜单") @ApiOperation("修改菜单") @PutMapping @PreAuthorize("@el.check('menu:edit')") public ResponseEntity<Object> updateMenu(@Validated(Menu.Update.class) @RequestBody Menu resources){ menuService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除菜单") @ApiOperation("删除菜单") @DeleteMapping @PreAuthorize("@el.check('menu:del')") public ResponseEntity<Object> deleteMenu(@RequestBody Set<Long> ids){ Set<Menu> menuSet = new HashSet<>(); for (Long id : ids) { List<MenuDto> menuList = menuService.getMenus(id); menuSet.add(menuService.findOne(id)); menuSet = menuService.getChildMenus(menuMapper.toEntity(menuList), menuSet); } menuService.delete(menuSet); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\MenuController.java
1
请完成以下Java代码
public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first
*/ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionDistribution.java
1
请完成以下Java代码
public @NonNull DocumentReportInfo getDocumentReportInfo( @NonNull final TableRecordReference recordRef, @Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse) { final ShipperTransportationId shipperTransportationId = recordRef.getIdAssumingTableName(I_M_ShipperTransportation.Table_Name, ShipperTransportationId::ofRepoId); final I_M_ShipperTransportation shipperTransportation = shipperTransportationDAO.getById(shipperTransportationId); final BPartnerId shipperPartnerId = BPartnerId.ofRepoId(shipperTransportation.getShipper_BPartner_ID()); final I_C_BPartner shipperPartner = util.getBPartnerById(shipperPartnerId); final DocTypeId docTypeId = DocTypeId.ofRepoId(shipperTransportation.getC_DocType_ID()); final I_C_DocType docType = util.getDocTypeById(docTypeId); final Language language = util.getBPartnerLanguage(shipperPartner).orElse(null); final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder() .adTableId(recordRef.getAdTableId()) .bpartnerId(shipperPartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(shipperPartnerId, shipperTransportation.getShipper_Location_ID())) .docTypeId(docTypeId) .onlyCopiesGreaterZero(true) .build(); return DocumentReportInfo.builder() .recordRef(recordRef) .reportProcessId(reportProcessIdToUse) .copies(util.getDocumentCopies(docType, bpPrintFormatQuery)) .documentNo(shipperTransportation.getDocumentNo()) .bpartnerId(shipperPartnerId) .docTypeId(docTypeId) .language(language) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\ShipperTransportationReportAdvisor.java
1
请完成以下Java代码
private void runWebSocket() throws Exception { this.webSocket = true; String accept = getWebsocketAcceptResponse(); this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: " + accept); new Frame("{\"command\":\"hello\",\"protocols\":[\"http://livereload.com/protocols/official-7\"]," + "\"serverName\":\"spring-boot\"}") .write(this.outputStream); while (this.running) { readWebSocketFrame(); } } private void readWebSocketFrame() throws IOException { try { Frame frame = Frame.read(this.inputStream); if (frame.getType() == Frame.Type.PING) { writeWebSocketFrame(new Frame(Frame.Type.PONG)); } else if (frame.getType() == Frame.Type.CLOSE) { throw new ConnectionClosedException(); } else if (frame.getType() == Frame.Type.TEXT) { logger.debug(LogMessage.format("Received LiveReload text frame %s", frame)); } else { throw new IOException("Unexpected Frame Type " + frame.getType()); } } catch (SocketTimeoutException ex) { writeWebSocketFrame(new Frame(Frame.Type.PING)); Frame frame = Frame.read(this.inputStream); if (frame.getType() != Frame.Type.PONG) { throw new IllegalStateException("No Pong"); } } } /** * Trigger livereload for the client using this connection. * @throws IOException in case of I/O errors */ void triggerReload() throws IOException { if (this.webSocket) { logger.debug("Triggering LiveReload"); writeWebSocketFrame(new Frame("{\"command\":\"reload\",\"path\":\"/\"}")); } } private void writeWebSocketFrame(Frame frame) throws IOException {
frame.write(this.outputStream); } private String getWebsocketAcceptResponse() throws NoSuchAlgorithmException { Matcher matcher = WEBSOCKET_KEY_PATTERN.matcher(this.header); Assert.state(matcher.find(), "No Sec-WebSocket-Key"); String response = matcher.group(1).trim() + WEBSOCKET_GUID; MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(response.getBytes(), 0, response.length()); return Base64.getEncoder().encodeToString(messageDigest.digest()); } /** * Close the connection. * @throws IOException in case of I/O errors */ void close() throws IOException { this.running = false; this.socket.close(); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\Connection.java
1
请在Spring Boot框架中完成以下Java代码
public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) {
this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMappedSuperclassRepository\src\main\java\com\bookstore\entity\Author.java
2
请在Spring Boot框架中完成以下Java代码
public String getPRODUCTDESCTYPE() { return productdesctype; } /** * Sets the value of the productdesctype property. * * @param value * allowed object is * {@link String } * */ public void setPRODUCTDESCTYPE(String value) { this.productdesctype = value; } /** * Gets the value of the productdesclang property. * * @return * possible object is * {@link String } *
*/ public String getPRODUCTDESCLANG() { return productdesclang; } /** * Sets the value of the productdesclang property. * * @param value * allowed object is * {@link String } * */ public void setPRODUCTDESCLANG(String value) { this.productdesclang = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DPRDE1.java
2
请完成以下Java代码
public boolean hasComments(@NonNull final DocumentPath documentPath) { final TableRecordReference reference = documentDescriptorFactory.getTableRecordReferenceIfPossible(documentPath).orElse(null); if (reference == null) { return false; } final Map<TableRecordReference, Boolean> referencesWithComments = commentsRepository.hasComments(ImmutableList.of(reference)); return referencesWithComments.getOrDefault(reference, false); } @NonNull public ImmutableList<JSONComment> getRowCommentsAsJson(@NonNull final DocumentPath documentPath, final ZoneId zoneId) { final TableRecordReference tableRecordReference = documentDescriptorFactory.getTableRecordReference(documentPath); final List<CommentEntry> comments = commentsRepository.retrieveLastCommentEntries(tableRecordReference, 100); return comments.stream() .map(comment -> toJsonComment(comment, zoneId)) .sorted(Comparator.comparing(JSONComment::getCreated).reversed()) .collect(ImmutableList.toImmutableList()); } public void addComment(@NonNull final DocumentPath documentPath, @NonNull final JSONCommentCreateRequest jsonCommentCreateRequest) { final TableRecordReference tableRecordReference = documentDescriptorFactory.getTableRecordReference(documentPath);
commentsRepository.createCommentEntry(jsonCommentCreateRequest.getText(), tableRecordReference); } @NonNull private JSONComment toJsonComment(@NonNull final CommentEntry comment, final ZoneId zoneId) { final String text = comment.getText(); final String created = DateTimeConverters.toJson(comment.getCreated(), zoneId); final String createdBy = userDAO.retrieveUserFullName(comment.getCreatedBy()); return JSONComment.builder() .text(text) .created(created) .createdBy(createdBy) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\comments\CommentsService.java
1
请完成以下Java代码
private static POSCardReader extractCardReader(@Nullable final SumUpTransaction.CardReader sumUpCardReader) { if(sumUpCardReader == null) { return null; } return POSCardReader.builder() .externalId(POSCardReaderExternalId.ofString(sumUpCardReader.getExternalId().getAsString())) .name(sumUpCardReader.getName()) .build(); } @NonNull public static POSPaymentProcessingStatus toResponseStatus(final @NonNull SumUpTransactionStatus status, final boolean isRefunded) { if (SumUpTransactionStatus.SUCCESSFUL.equals(status)) { return isRefunded ? POSPaymentProcessingStatus.DELETED : POSPaymentProcessingStatus.SUCCESSFUL; } else if (SumUpTransactionStatus.CANCELLED.equals(status)) { return POSPaymentProcessingStatus.CANCELLED; } else if (SumUpTransactionStatus.FAILED.equals(status)) { return POSPaymentProcessingStatus.FAILED; } else if (SumUpTransactionStatus.PENDING.equals(status)) { return POSPaymentProcessingStatus.PENDING; } else { throw new AdempiereException("Unknown SumUp status: " + status);
} } public static SumUpPOSRef toPOSRef(@NonNull final POSOrderAndPaymentId posOrderAndPaymentId) { return SumUpPOSRef.builder() .posOrderId(posOrderAndPaymentId.getOrderId().getRepoId()) .posPaymentId(posOrderAndPaymentId.getPaymentId().getRepoId()) .build(); } @Nullable public static POSOrderAndPaymentId toPOSOrderAndPaymentId(@NonNull final SumUpPOSRef posRef) { return POSOrderAndPaymentId.ofRepoIdsOrNull(posRef.getPosOrderId(), posRef.getPosPaymentId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\sumup\SumUpUtils.java
1
请完成以下Java代码
private static String getMetadataIssuer(Map<String, Object> configuration) { if (configuration.containsKey("issuer")) { return configuration.get("issuer").toString(); } return "(unavailable)"; } private static Map<String, Object> getConfiguration(String issuer, RestOperations rest, UriComponents... uris) { String errorMessage = "Unable to resolve the Configuration with the provided Issuer of " + "\"" + issuer + "\""; for (UriComponents uri : uris) { try { RequestEntity<Void> request = RequestEntity.get(uri.toUriString()).build(); ResponseEntity<Map<String, Object>> response = rest.exchange(request, STRING_OBJECT_MAP); Map<String, Object> configuration = response.getBody(); Assert.isTrue(configuration.get("jwks_uri") != null, "The public JWK set URI must not be null"); return configuration; } catch (IllegalArgumentException ex) { throw ex; } catch (RuntimeException ex) { if (!(ex instanceof HttpClientErrorException && ((HttpClientErrorException) ex).getStatusCode().is4xxClientError())) { throw new IllegalArgumentException(errorMessage, ex); } // else try another endpoint } } throw new IllegalArgumentException(errorMessage);
} static UriComponents oidc(String issuer) { UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build(); // @formatter:off return UriComponentsBuilder.newInstance().uriComponents(uri) .replacePath(uri.getPath() + OIDC_METADATA_PATH) .build(); // @formatter:on } static UriComponents oidcRfc8414(String issuer) { UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build(); // @formatter:off return UriComponentsBuilder.newInstance().uriComponents(uri) .replacePath(OIDC_METADATA_PATH + uri.getPath()) .build(); // @formatter:on } static UriComponents oauth(String issuer) { UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build(); // @formatter:off return UriComponentsBuilder.newInstance().uriComponents(uri) .replacePath(OAUTH_METADATA_PATH + uri.getPath()) .build(); // @formatter:on } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtDecoderProviderConfigurationUtils.java
1
请完成以下Java代码
public CFrame showWindowByWindowId(final AdWindowId adWindowId) { for (int i = 0; i < hiddenWindows.size(); i++) { final CFrame hiddenFrame = hiddenWindows.get(i); if (AdWindowId.equals(hiddenFrame.getAdWindowId(), adWindowId)) { hiddenWindows.remove(i); // NOTE: we can safely remove here because we are also returning (no future iterations) logger.debug("Showing window: {}", hiddenFrame); hiddenFrame.setVisible(true); // De-iconify window - teo_sarca [ 1707221 ] final int state = hiddenFrame.getExtendedState(); if ((state & Frame.ICONIFIED) > 0) { hiddenFrame.setExtendedState(state & ~Frame.ICONIFIED); } // hiddenFrame.toFront(); return hiddenFrame; } } return null; } /** * Update all windows after look and feel changes. */ public Set<Window> updateUI() { final Set<Window> updated = new HashSet<>(); for (final Container c : windowsByWindowNo.values()) { final Window w = SwingUtils.getFrame(c); if (w == null) { continue; } if (updated.contains(w)) { continue; } SwingUtilities.updateComponentTreeUI(w); w.validate(); final RepaintManager mgr = RepaintManager.currentManager(w); final Component childs[] = w.getComponents();
for (final Component child : childs) { if (child instanceof JComponent) { mgr.markCompletelyDirty((JComponent)child); } } w.repaint(); updated.add(w); } for (final Window w : hiddenWindows) { if (updated.contains(w)) { continue; } SwingUtilities.updateComponentTreeUI(w); w.validate(); final RepaintManager mgr = RepaintManager.currentManager(w); final Component childs[] = w.getComponents(); for (final Component child : childs) { if (child instanceof JComponent) { mgr.markCompletelyDirty((JComponent)child); } } w.repaint(); updated.add(w); } return updated; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WindowsIndex.java
1
请完成以下Java代码
public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isRootProcessInstances() { return isRootProcessInstances; } public boolean isProcessDefinitionWithoutTenantId() { return isProcessDefinitionWithoutTenantId; } public boolean isLeafProcessInstances() { return isLeafProcessInstances; } public String[] getTenantIds() { return tenantIds; } @Override public ProcessInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl();
orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public ProcessInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public UserSexEnum getUserSex() { return userSex; }
public void setUserSex(UserSexEnum userSex) { this.userSex = userSex; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } @Override public String toString() { // TODO Auto-generated method stub return "userName " + this.userName + ", pasword " + this.passWord + "sex " + userSex.name(); } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-multi-mybatis-xml\src\main\java\com\neo\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public void setBatchNo(String batchNo) { this.batchNo = batchNo; } public Date getBillDate() { return billDate; } public void setBillDate(Date billDate) { this.billDate = billDate; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName == null ? null : productName.trim(); } public String getMerchantOrderNo() { return merchantOrderNo; } public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim(); } public String getTrxNo() { return trxNo; } public void setTrxNo(String trxNo) { this.trxNo = trxNo == null ? null : trxNo.trim(); } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo == null ? null : bankOrderNo.trim(); } public String getBankTrxNo() { return bankTrxNo; } public void setBankTrxNo(String bankTrxNo) { this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim(); } public BigDecimal getOrderAmount() { return orderAmount; } public void setOrderAmount(BigDecimal orderAmount) { this.orderAmount = orderAmount; } public BigDecimal getPlatIncome() { return platIncome; } public void setPlatIncome(BigDecimal platIncome) { this.platIncome = platIncome; } public BigDecimal getFeeRate() { return feeRate; } public void setFeeRate(BigDecimal feeRate) { this.feeRate = feeRate; } public BigDecimal getPlatCost() { return platCost; } public void setPlatCost(BigDecimal platCost) { this.platCost = platCost; } public BigDecimal getPlatProfit() { return platProfit; } public void setPlatProfit(BigDecimal platProfit) { this.platProfit = platProfit; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); } public String getPayWayName() {
return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime; } public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); } public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public Attribute get(String key) { return trie.get(key); } /** * 打分 * @param from * @param to * @return */ public Edge getEdge(Node from, Node to) { // 首先尝试词+词 Attribute attribute = get(from.compiledWord, to.compiledWord); if (attribute == null) attribute = get(from.compiledWord, WordNatureWeightModelMaker.wrapTag(to.label)); if (attribute == null) attribute = get(WordNatureWeightModelMaker.wrapTag(from.label), to.compiledWord); if (attribute == null) attribute = get(WordNatureWeightModelMaker.wrapTag(from.label), WordNatureWeightModelMaker.wrapTag(to.label)); if (attribute == null) { attribute = Attribute.NULL; } if (HanLP.Config.DEBUG) { System.out.println(from + " 到 " + to + " : " + attribute); } return new Edge(from.id, to.id, attribute.dependencyRelation[0], attribute.p[0]); } public Attribute get(String from, String to) { return get(from + "@" + to); } static class Attribute { final static Attribute NULL = new Attribute("未知", 10000.0f); /** * 依存关系 */ public String[] dependencyRelation; /** * 概率 */ public float[] p; public Attribute(int size) { dependencyRelation = new String[size]; p = new float[size];
} Attribute(String dr, float p) { dependencyRelation = new String[]{dr}; this.p = new float[]{p}; } /** * 加权 * @param boost */ public void setBoost(float boost) { for (int i = 0; i < p.length; ++i) { p[i] *= boost; } } @Override public String toString() { final StringBuilder sb = new StringBuilder(dependencyRelation.length * 10); for (int i = 0; i < dependencyRelation.length; ++i) { sb.append(dependencyRelation[i]).append(' ').append(p[i]).append(' '); } return sb.toString(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\WordNatureDependencyModel.java
1
请完成以下Java代码
private boolean isReferencedObjectValue(final String propertyName, final Object valueOld, final Object valueNew) { // TODO: optimize this method final POJOWrapper wrapperOld = getWrapper(valueOld); if (wrapperOld != null) { return true; } final POJOWrapper wrapper = getWrapper(valueNew); if (wrapper != null) { return true; } return false; } public boolean hasChanges() { if (isNew()) { return true; } final Set<String> changedPropertyNames = valuesOld.keySet(); for (final String propertyName : changedPropertyNames) { if (isValueChanged(propertyName)) { return true; } } return false; } public int getLoadCount() { return loadCount; } public final String getTrxName() { return _trxName; } public final String setTrxName(final String trxName) { final String trxNameOld = _trxName; _trxName = trxName; return trxNameOld; } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { return getWrapper(model).isOldValues(); }
public Evaluatee2 asEvaluatee() { return new Evaluatee2() { @Override public String get_ValueAsString(final String variableName) { if (!has_Variable(variableName)) { return ""; } final Object value = POJOWrapper.this.getValuesMap().get(variableName); return value == null ? "" : value.toString(); } @Override public boolean has_Variable(final String variableName) { return POJOWrapper.this.hasColumnName(variableName); } @Override public String get_ValueOldAsString(final String variableName) { throw new UnsupportedOperationException("not implemented"); } }; } public IModelInternalAccessor getModelInternalAccessor() { if (_modelInternalAccessor == null) { _modelInternalAccessor = new POJOModelInternalAccessor(this); } return _modelInternalAccessor; } POJOModelInternalAccessor _modelInternalAccessor = null; public static IModelInternalAccessor getModelInternalAccessor(final Object model) { final POJOWrapper wrapper = getWrapper(model); if (wrapper == null) { return null; } return wrapper.getModelInternalAccessor(); } public boolean isProcessed() { return hasColumnName("Processed") ? StringUtils.toBoolean(getValue("Processed", Object.class)) : false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
1
请完成以下Java代码
public void setC_OrderLine_ID (final int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID); } @Override public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); 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_OrderLine_Detail.java
1
请完成以下Java代码
public de.metas.inoutcandidate.model.I_M_ReceiptSchedule getM_ReceiptSchedule() { return get_ValueAsPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class); } @Override public void setM_ReceiptSchedule(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule M_ReceiptSchedule) { set_ValueFromPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class, M_ReceiptSchedule); } @Override public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID); } @Override
public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_ExportAudit.java
1
请完成以下Java代码
public void warmupByVHUIds(@NonNull final Collection<HuId> vhuIds) { entriesByVhuId.getAllOrLoad(vhuIds, this::retrieveEntriesByVHUId); } public ImmutableList<HUReservationEntry> getEntriesByVHUIds(@NonNull final Collection<HuId> vhuIds) { if (vhuIds.isEmpty()) { return ImmutableList.of(); } return entriesByVhuId.getAllOrLoad(vhuIds, this::retrieveEntriesByVHUId) .stream() .flatMap(Optionals::stream) .collect(ImmutableList.toImmutableList()); } private Map<HuId, Optional<HUReservationEntry>> retrieveEntriesByVHUId(@NonNull final Collection<HuId> vhuIds) { if (vhuIds.isEmpty()) { return ImmutableMap.of(); } // shall not happen final HashMap<HuId, Optional<HUReservationEntry>> result = new HashMap<>(vhuIds.size()); vhuIds.forEach(huId -> result.put(huId, Optional.empty())); queryBL.createQueryBuilder(I_M_HU_Reservation.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuIds) .create() .stream() .map(HUReservationRepository::toHUReservationEntry) .forEach(entry -> result.put(entry.getVhuId(), Optional.of(entry))); return ImmutableMap.copyOf(result); } public Optional<OrderLineId> getOrderLineIdByReservedVhuId(@NonNull final HuId vhuId) { return getEntryByVhuId(vhuId) .map(entry -> entry.getDocumentRef().getSalesOrderLineId()); } private Optional<HUReservationEntry> getEntryByVhuId(@NonNull final HuId vhuId) { return entriesByVhuId.getOrLoad(vhuId, this::retrieveEntryByVhuId); } private Optional<HUReservationEntry> retrieveEntryByVhuId(@NonNull final HuId vhuId) { return queryBL.createQueryBuilder(I_M_HU_Reservation.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuId) // we have a UC constraint on VHU_ID .create() .firstOnlyOptional(I_M_HU_Reservation.class) .map(HUReservationRepository::toHUReservationEntry); } private static HUReservationDocRef extractDocumentRef(@NonNull final I_M_HU_Reservation record)
{ return HUReservationDocRef.builder() .salesOrderLineId(OrderLineId.ofRepoIdOrNull(record.getC_OrderLineSO_ID())) .projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID())) .pickingJobStepId(PickingJobStepId.ofRepoIdOrNull(record.getM_Picking_Job_Step_ID())) .ddOrderLineId(DDOrderLineId.ofRepoIdOrNull(record.getDD_OrderLine_ID())) .build(); } public void transferReservation( @NonNull final Collection<HUReservationDocRef> from, @NonNull final HUReservationDocRef to, @NonNull final Set<HuId> onlyVHUIds) { if (from.size() == 1 && Objects.equals(from.iterator().next(), to)) { return; } final List<I_M_HU_Reservation> records = retrieveRecordsByDocumentRef(from, onlyVHUIds); if (records.isEmpty()) { return; } for (final I_M_HU_Reservation record : records) { updateRecordFromDocumentRef(record, to); saveRecord(record); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationRepository.java
1
请完成以下Java代码
public String getPickupDateAndTimeStart() { return pickupDate + "T" + timeFrom; } @JsonIgnore @NonNull public String getPickupDateAndTimeEnd() { return pickupDate + "T" + timeTo; } @JsonIgnore @Nullable public String getValue(@NonNull final String attributeValue) { switch (attributeValue) { case DeliveryMappingConstants.ATTRIBUTE_VALUE_PICKUP_DATE_AND_TIME_START: return getPickupDateAndTimeStart(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_PICKUP_DATE_AND_TIME_END: return getPickupDateAndTimeEnd(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_DELIVERY_DATE: return getDeliveryDate(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_CUSTOMER_REFERENCE: return getCustomerReference(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_COUNTRY_CODE: return getDeliveryAddress().getCountry(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_CONTACT_LASTNAME_AND_FIRSTNAME: return getDeliveryContact() != null ? getDeliveryContact().getName() : null; case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_DEPARTMENT: return getDeliveryAddress().getCompanyDepartment(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_COMPANY_NAME: return getDeliveryAddress().getCompanyName1();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_COMPANY_NAME: return getPickupAddress().getCompanyName1(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_COMPANY_NAME_2: return getPickupAddress().getCompanyName2(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_DEPARTMENT: return getPickupAddress().getCompanyDepartment(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_COUNTRY_CODE: return getPickupAddress().getCountry(); case DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPPER_PRODUCT_EXTERNAL_ID: return getShipperProduct() != null ? getShipperProduct().getCode() : null; case DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPPER_EORI: return getShipperEORI(); default: throw new IllegalArgumentException("Unknown attributeValue: " + attributeValue); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-delivery\src\main\java\de\metas\common\delivery\v1\json\request\JsonDeliveryRequest.java
1
请完成以下Java代码
private AdElementId getFieldElementIdOrNull(final I_AD_Field field) { if (field.getAD_Name_ID() > 0) { return AdElementId.ofRepoId(field.getAD_Name_ID()); } else if (field.getAD_Column_ID() > 0) { // the AD_Name_ID was set to null. Get back to the values from the AD_Column final I_AD_Column fieldColumn = field.getAD_Column(); return AdElementId.ofRepoId(fieldColumn.getAD_Element_ID()); } else { // Nothing to do. the element was not yet saved. return null; } } private void recreateElementLinkForField(final I_AD_Field field)
{ final AdFieldId adFieldId = AdFieldId.ofRepoIdOrNull(field.getAD_Field_ID()); if (adFieldId != null) { final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.recreateADElementLinkForFieldId(adFieldId); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void onBeforeFieldDelete(final I_AD_Field field) { final AdFieldId adFieldId = AdFieldId.ofRepoId(field.getAD_Field_ID()); final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); adWindowDAO.deleteUIElementsByFieldId(adFieldId); final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.deleteExistingADElementLinkForFieldId(adFieldId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\field\model\interceptor\AD_Field.java
1
请完成以下Java代码
public ProcessEngineException cannotAttachToTransitionInstance(MigratingInstance attachingInstance) { return new ProcessEngineException(exceptionMessage( "007", "{}", "Cannot attach instance '{}' to a transition instance", attachingInstance)); } public BadUserRequestException processDefinitionDoesNotExist(String processDefinitionId, String type) { return new BadUserRequestException(exceptionMessage( "008", "{} process definition with id '{}' does not exist", type, processDefinitionId )); } public ProcessEngineException cannotMigrateBetweenTenants(String sourceTenantId, String targetTenantId) { return new ProcessEngineException(exceptionMessage( "09", "Cannot migrate process instances between processes of different tenants ('{}' != '{}')", sourceTenantId, targetTenantId)); } public ProcessEngineException cannotMigrateInstanceBetweenTenants(String processInstanceId, String sourceTenantId, String targetTenantId) { String detailMessage = null; if (sourceTenantId != null) { detailMessage = exceptionMessage( "010", "Cannot migrate process instance '{}' to a process definition of a different tenant ('{}' != '{}')", processInstanceId, sourceTenantId, targetTenantId); }
else { detailMessage = exceptionMessage( "010", "Cannot migrate process instance '{}' without tenant to a process definition with a tenant ('{}')", processInstanceId, targetTenantId); } return new ProcessEngineException(detailMessage); } public ProcessEngineException cannotHandleChild(MigratingScopeInstance scopeInstance, MigratingProcessElementInstance childCandidate) { return new ProcessEngineException( exceptionMessage( "011", "Scope instance of type {} cannot have child of type {}", scopeInstance.getClass().getSimpleName(), childCandidate.getClass().getSimpleName()) ); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationLogger.java
1
请完成以下Java代码
public void setSQLStatement (final @Nullable java.lang.String SQLStatement) { set_Value (COLUMNNAME_SQLStatement, SQLStatement); } @Override public java.lang.String getSQLStatement() { return get_ValueAsString(COLUMNNAME_SQLStatement); } @Override public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } @Override public java.lang.String getTechnicalNote() { return get_ValueAsString(COLUMNNAME_TechnicalNote); } /** * Type AD_Reference_ID=540087 * Reference name: AD_Process Type */ public static final int TYPE_AD_Reference_ID=540087; /** SQL = SQL */ public static final String TYPE_SQL = "SQL"; /** Java = Java */ public static final String TYPE_Java = "Java"; /** Excel = Excel */ public static final String TYPE_Excel = "Excel"; /** JasperReportsSQL = JasperReportsSQL */ public static final String TYPE_JasperReportsSQL = "JasperReportsSQL"; /** JasperReportsJSON = JasperReportsJSON */ public static final String TYPE_JasperReportsJSON = "JasperReportsJSON"; /** PostgREST = PostgREST */ public static final String TYPE_PostgREST = "PostgREST";
@Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWorkflowValue (final @Nullable java.lang.String WorkflowValue) { set_Value (COLUMNNAME_WorkflowValue, WorkflowValue); } @Override public java.lang.String getWorkflowValue() { return get_ValueAsString(COLUMNNAME_WorkflowValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process.java
1
请在Spring Boot框架中完成以下Java代码
public List<AuthorNameBookTitle> fetchBooksAndAuthorsJpql() { return bookRepository.findBooksAndAuthorsJpql(); } // Books and authors (SQL) public List<AuthorNameBookTitle> fetchBooksAndAuthorsSql() { return bookRepository.findBooksAndAuthorsSql(); } // Authors and books (JPQL) public List<AuthorNameBookTitle> fetchAuthorsAndBooksJpql() { return authorRepository.findAuthorsAndBooksJpql(); } // Authors and books (SQL) public List<AuthorNameBookTitle> fetchAuthorsAndBooksSql() { return authorRepository.findAuthorsAndBooksSql(); } // Fetch authors and books filtering by author's genre and book's price (JPQL) public List<AuthorNameBookTitle> findAuthorsAndBooksByGenreAndPriceJpql(String genre, int price) {
return authorRepository.findAuthorsAndBooksByGenreAndPriceJpql(genre, price); } // Fetch authors and books filtering by author's genre and book's price (SQL) public List<AuthorNameBookTitle> findAuthorsAndBooksByGenreAndPriceSql(String genre, int price) { return authorRepository.findAuthorsAndBooksByGenreAndPriceSql(genre, price); } // Fetch books and authors filtering by author's genre and book's price (JPQL) public List<AuthorNameBookTitle> findBooksAndAuthorsByGenreAndPriceJpql(String genre, int price) { return bookRepository.findBooksAndAuthorsByGenreAndPriceJpql(genre, price); } // Fetch books and authors filtering by author's genre and book's price (SQL) public List<AuthorNameBookTitle> findBooksAndAuthorsByGenreAndPriceSql(String genre, int price) { return bookRepository.findBooksAndAuthorsByGenreAndPriceSql(genre, price); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaInnerJoins\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class); } @Override public void setDataEntry_SubTab(de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab) { set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab); } /** Set Unterregister. @param DataEntry_SubTab_ID Unterregister */ @Override public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID)); } /** Get Unterregister. @return Unterregister */ @Override public int getDataEntry_SubTab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) {
if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java
1
请完成以下Spring Boot application配置
spring: profiles: active: standalone --- spring: config: activate: on-profile: standalone data: redis: host: localhost password: 123456 port: 6379 database: 0 --- spring: config: activate: on-profile: sentinel data: redis: password: 123456 sentine
l: master: mymaster nodes: - 192.168.11.163:26379 - 192.168.11.164:26379 - 192.168.11.165:26379
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\resources\application.yml
2
请完成以下Java代码
public class Customer { private int id; private String name; private String address; public Customer() { super(); } public Customer(final String name, final String address) { this.name = name; this.address = address; } // public int getId() { return id; } public void setId(final int id) { this.id = id; }
public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(final String address) { this.address = address; } public void setCustomerAddress(final String address) { this.address = name + "," + address; } }
repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\example\Customer.java
1
请在Spring Boot框架中完成以下Java代码
public AcceptPaymentDisputeRequest revision(Integer revision) { this.revision = revision; return this; } /** * This integer value indicates the revision number of the payment dispute. This field is required. The current revision number for a payment dispute can be retrieved with the getPaymentDispute method. Each time an action is taken against a payment dispute, this integer value increases by 1. * * @return revision **/ @javax.annotation.Nullable @ApiModelProperty(value = "This integer value indicates the revision number of the payment dispute. This field is required. The current revision number for a payment dispute can be retrieved with the getPaymentDispute method. Each time an action is taken against a payment dispute, this integer value increases by 1.") public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AcceptPaymentDisputeRequest acceptPaymentDisputeRequest = (AcceptPaymentDisputeRequest)o; return Objects.equals(this.returnAddress, acceptPaymentDisputeRequest.returnAddress) && Objects.equals(this.revision, acceptPaymentDisputeRequest.revision); }
@Override public int hashCode() { return Objects.hash(returnAddress, revision); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AcceptPaymentDisputeRequest {\n"); sb.append(" returnAddress: ").append(toIndentedString(returnAddress)).append("\n"); sb.append(" revision: ").append(toIndentedString(revision)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AcceptPaymentDisputeRequest.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("documentNo", documentNo) .add("docBaseType", docBaseType) .add("docSubType", docSubType) .add("IsSOTrx", soTrx) .add("hasChanges", hasChanges) .add("docNoControlled", docNoControlled) .toString(); } @Override public String getDocBaseType() { return docBaseType; } @Override public String getDocSubType() { return docSubType; } @Override public boolean isSOTrx() { return soTrx; } @Override public boolean isHasChanges() { return hasChanges; } @Override public boolean isDocNoControlled() { return docNoControlled; } @Override public String getDocumentNo() { return documentNo; } public static final class Builder { private String docBaseType; private String docSubType; private boolean soTrx; private boolean hasChanges; private boolean docNoControlled; private String documentNo; private Builder() { super(); } public DocumentNoInfo build() { return new DocumentNoInfo(this); } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; }
public Builder setDocBaseType(final String docBaseType) { this.docBaseType = docBaseType; return this; } public Builder setDocSubType(final String docSubType) { this.docSubType = docSubType; return this; } public Builder setHasChanges(final boolean hasChanges) { this.hasChanges = hasChanges; return this; } public Builder setDocNoControlled(final boolean docNoControlled) { this.docNoControlled = docNoControlled; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { soTrx = isSOTrx; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoInfo.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } public I_AD_User getSalesRep() throws RuntimeException {
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunEntry.java
1
请完成以下Java代码
public void onEvent(final IEventBus eventBus, final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { logger.debug("TypedConsumerAsEventListener.onEvent - eventBodyType={}", eventBodyType.getName()); final String json = event.getBody(); final T obj = jsonDeserializer.readValue(json); eventConsumer.accept(obj); } } } @AllArgsConstructor @ToString private class GuavaEventListenerAdapter { @NonNull private final IEventListener eventListener; @Subscribe public void onEvent(@NonNull final Event event) { micrometerEventBusStatsCollector.incrementEventsDequeued(); micrometerEventBusStatsCollector .getEventProcessingTimer() .record(() -> { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { logger.debug("GuavaEventListenerAdapter.onEvent - eventListener to invoke={}", eventListener); invokeEventListener(this.eventListener, event); } }); } } private void invokeEventListener( @NonNull final IEventListener eventListener, @NonNull final Event event) { if (event.isWasLogged()) { invokeEventListenerWithLogging(eventListener, event); } else { eventListener.onEvent(this, event); } } private void invokeEventListenerWithLogging( @NonNull final IEventListener eventListener, @NonNull final Event event) { try (final EventLogEntryCollector ignored = EventLogEntryCollector.createThreadLocalForEvent(event)) { try
{ eventListener.onEvent(this, event); } catch (final RuntimeException ex) { if (!Adempiere.isUnitTestMode()) { final EventLogUserService eventLogUserService = SpringContextHolder.instance.getBean(EventLogUserService.class); eventLogUserService .newErrorLogEntry(eventListener.getClass(), ex) .createAndStore(); } else { logger.warn("Got exception while invoking eventListener={} with event={}", eventListener, event, ex); } } } } @Override public EventBusStats getStats() { return micrometerEventBusStatsCollector.snapshot(); } private void enqueueEvent0(final Event event) { if (Type.LOCAL == topic.getType()) { eventEnqueuer.enqueueLocalEvent(event, topic); } else { eventEnqueuer.enqueueDistributedEvent(event, topic); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBus.java
1
请完成以下Java代码
public class CleanableHistoricCaseInstanceReportResultEntity implements CleanableHistoricCaseInstanceReportResult { protected String caseDefinitionId; protected String caseDefinitionKey; protected String caseDefinitionName; protected int caseDefinitionVersion; protected Integer historyTimeToLive; protected long finishedCaseInstanceCount; protected long cleanableCaseInstanceCount; protected String tenantId; public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } public String getCaseDefinitionName() { return caseDefinitionName; } public void setCaseDefinitionName(String caseDefinitionName) { this.caseDefinitionName = caseDefinitionName; } public int getCaseDefinitionVersion() { return caseDefinitionVersion; } public void setCaseDefinitionVersion(int caseDefinitionVersion) { this.caseDefinitionVersion = caseDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; }
public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedCaseInstanceCount() { return finishedCaseInstanceCount; } public void setFinishedCaseInstanceCount(Long finishedCaseInstanceCount) { this.finishedCaseInstanceCount = finishedCaseInstanceCount; } public long getCleanableCaseInstanceCount() { return cleanableCaseInstanceCount; } public void setCleanableCaseInstanceCount(Long cleanableCaseInstanceCount) { this.cleanableCaseInstanceCount = cleanableCaseInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[caseDefinitionId = " + caseDefinitionId + ", caseDefinitionKey = " + caseDefinitionKey + ", caseDefinitionName = " + caseDefinitionName + ", caseDefinitionVersion = " + caseDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedCaseInstanceCount = " + finishedCaseInstanceCount + ", cleanableCaseInstanceCount = " + cleanableCaseInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricCaseInstanceReportResultEntity.java
1
请在Spring Boot框架中完成以下Java代码
public final class MongoAutoConfiguration { @Bean @ConditionalOnMissingBean(MongoConnectionDetails.class) PropertiesMongoConnectionDetails mongoConnectionDetails(MongoProperties properties, ObjectProvider<SslBundles> sslBundles) { return new PropertiesMongoConnectionDetails(properties, sslBundles.getIfAvailable()); } @Bean @ConditionalOnMissingBean MongoClient mongo(ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers, MongoClientSettings settings) { return new MongoClientFactory(builderCustomizers.orderedStream().toList()).createMongoClient(settings); } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(MongoClientSettings.class) static class MongoClientSettingsConfiguration {
@Bean MongoClientSettings mongoClientSettings() { return MongoClientSettings.builder().build(); } @Bean StandardMongoClientSettingsBuilderCustomizer standardMongoSettingsCustomizer(MongoProperties properties, MongoConnectionDetails connectionDetails) { return new StandardMongoClientSettingsBuilderCustomizer(connectionDetails, properties.getRepresentation().getUuid()); } } }
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\MongoAutoConfiguration.java
2
请完成以下Java代码
public UserOperationLogQuery userId(String userId) { ensureNotNull("userId", userId); this.userId = userId; return this; } public UserOperationLogQuery operationId(String operationId) { ensureNotNull("operationId", operationId); this.operationId = operationId; return this; } public UserOperationLogQuery externalTaskId(String externalTaskId) { ensureNotNull("externalTaskId", externalTaskId); this.externalTaskId = externalTaskId; return this; } public UserOperationLogQuery operationType(String operationType) { ensureNotNull("operationType", operationType); this.operationType = operationType; return this; } public UserOperationLogQuery property(String property) { ensureNotNull("property", property); this.property = property; return this; } public UserOperationLogQuery entityType(String entityType) { ensureNotNull("entityType", entityType); this.entityType = entityType; return this; } public UserOperationLogQuery entityTypeIn(String... entityTypes) { ensureNotNull("entity types", (Object[]) entityTypes); this.entityTypes = entityTypes; return this; } public UserOperationLogQuery category(String category) { ensureNotNull("category", category); this.category = category; return this; } public UserOperationLogQuery categoryIn(String... categories) { ensureNotNull("categories", (Object[]) categories); this.categories = categories; return this; } public UserOperationLogQuery afterTimestamp(Date after) { this.timestampAfter = after; return this; } public UserOperationLogQuery beforeTimestamp(Date before) { this.timestampBefore = before; return this; } public UserOperationLogQuery orderByTimestamp() { return orderBy(OperationLogQueryProperty.TIMESTAMP); }
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntryCountByQueryCriteria(this); } public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntriesByQueryCriteria(this, page); } public boolean isTenantIdSet() { return isTenantIdSet; } public UserOperationLogQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; this.isTenantIdSet = true; return this; } public UserOperationLogQuery withoutTenantId() { this.tenantIds = null; this.isTenantIdSet = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
1
请完成以下Java代码
private BasicDBObject getBasicDBObject(HttpServletRequest request, JoinPoint joinPoint) { // 基本信息 BasicDBObject r = new BasicDBObject(); r.append("requestURL", request.getRequestURL().toString()); r.append("requestURI", request.getRequestURI()); r.append("queryString", request.getQueryString()); r.append("remoteAddr", request.getRemoteAddr()); r.append("remoteHost", request.getRemoteHost()); r.append("remotePort", request.getRemotePort()); r.append("localAddr", request.getLocalAddr()); r.append("localName", request.getLocalName()); r.append("method", request.getMethod()); r.append("headers", getHeadersInfo(request)); r.append("parameters", request.getParameterMap()); r.append("classMethod", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); r.append("args", Arrays.toString(joinPoint.getArgs())); return r; } /** * 获取头信息 * * @param request
* @return */ private Map<String, String> getHeadersInfo(HttpServletRequest request) { Map<String, String> map = new HashMap<>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
repos\SpringBoot-Learning-master\1.x\Chapter4-2-5\src\main\java\com\didispace\aspect\WebLogAspect.java
1
请在Spring Boot框架中完成以下Java代码
HandlerMapper remoteDevToolsHealthCheckHandlerMapper(ServerProperties serverProperties) { Handler handler = new HttpStatusHandler(); Servlet servlet = serverProperties.getServlet(); String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : ""; return new UrlHandlerMapper(servletContextPath + this.properties.getRemote().getContextPath(), handler); } @Bean @ConditionalOnMissingBean DispatcherFilter remoteDevToolsDispatcherFilter(AccessManager accessManager, Collection<HandlerMapper> mappers) { Dispatcher dispatcher = new Dispatcher(accessManager, mappers); return new DispatcherFilter(dispatcher); } /** * Configuration for remote update and restarts. */ @Configuration(proxyBeanMethods = false) @ConditionalOnBooleanProperty(name = "spring.devtools.remote.restart.enabled", matchIfMissing = true) static class RemoteRestartConfiguration { @Bean @ConditionalOnMissingBean SourceDirectoryUrlFilter remoteRestartSourceDirectoryUrlFilter() { return new DefaultSourceDirectoryUrlFilter(); } @Bean @ConditionalOnMissingBean HttpRestartServer remoteRestartHttpRestartServer(SourceDirectoryUrlFilter sourceDirectoryUrlFilter) { return new HttpRestartServer(sourceDirectoryUrlFilter); }
@Bean @ConditionalOnMissingBean(name = "remoteRestartHandlerMapper") UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server, ServerProperties serverProperties, DevToolsProperties properties) { Servlet servlet = serverProperties.getServlet(); RemoteDevToolsProperties remote = properties.getRemote(); String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : ""; String url = servletContextPath + remote.getContextPath() + "/restart"; logger.warn(LogMessage.format("Listening for remote restart updates on %s", url)); Handler handler = new HttpRestartServerHandler(server); return new UrlHandlerMapper(url, handler); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsAutoConfiguration.java
2
请完成以下Java代码
public void setFollowUpDate(Date followUpDate) { this.followUpDate = followUpDate; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public void setDeleteReason(final String deleteReason) { this.deleteReason = deleteReason; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskId() { return taskId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public void setTaskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTaskState() { return taskState; } public void setTaskState(String taskState) { this.taskState = taskState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; }
public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[taskId" + taskId + ", assignee=" + assignee + ", owner=" + owner + ", name=" + name + ", description=" + description + ", dueDate=" + dueDate + ", followUpDate=" + followUpDate + ", priority=" + priority + ", parentTaskId=" + parentTaskId + ", deleteReason=" + deleteReason + ", taskDefinitionKey=" + taskDefinitionKey + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", activityInstanceId=" + activityInstanceId + ", tenantId=" + tenantId + ", taskState=" + taskState + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringCloudS3Service { private static final Logger logger = LoggerFactory.getLogger(SpringCloudS3Service.class); @Autowired AmazonS3 amazonS3; @Autowired SpringCloudS3 springCloudS3; public void createBucket(String bucketName) { logger.debug("Creating S3 bucket: {}", bucketName); amazonS3.createBucket(bucketName); logger.info("{} bucket created successfully", bucketName); } public void downloadObject(String bucketName, String objectName) { String s3Url = "s3://" + bucketName + "/" + objectName; try { springCloudS3.downloadS3Object(s3Url); logger.info("{} file download result: {}", objectName, new File(objectName).exists()); } catch (IOException e) { logger.error(e.getMessage(), e); } } public void uploadObject(String bucketName, String objectName) { String s3Url = "s3://" + bucketName + "/" + objectName; File file = new File(objectName); try { springCloudS3.uploadFileToS3(file, s3Url);
logger.info("{} file uploaded to S3", objectName); } catch (IOException e) { logger.error(e.getMessage(), e); } } public void deleteBucket(String bucketName) { logger.trace("Deleting S3 objects under {} bucket...", bucketName); ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName); for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) { logger.info("Deleting S3 object: {}", objectSummary.getKey()); amazonS3.deleteObject(bucketName, objectSummary.getKey()); } logger.info("Deleting S3 bucket: {}", bucketName); amazonS3.deleteBucket(bucketName); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\java\com\baeldung\spring\cloud\aws\s3\SpringCloudS3Service.java
2
请完成以下Java代码
public boolean isValidEAN13Product(@NonNull final EAN13 ean13, @NonNull final ProductId expectedProductId) { return getGS1ProductCodesCollection(expectedProductId).isValidProductNo(ean13, null); } @Override public boolean isValidEAN13Product(@NonNull final EAN13 ean13, @NonNull final ProductId expectedProductId, @Nullable final BPartnerId bpartnerId) { return getGS1ProductCodesCollection(expectedProductId).isValidProductNo(ean13, bpartnerId); } @Override public Set<ProductId> getProductIdsMatchingQueryString( @NonNull final String queryString, @NonNull final ClientId clientId, @NonNull final QueryLimit limit) { return productsRepo.getProductIdsMatchingQueryString(queryString, clientId, limit); } @Override @NonNull public List<I_M_Product> getByIds(@NonNull final Set<ProductId> productIds) { return productsRepo.getByIds(productIds); } @Override public boolean isExistingValue(@NonNull final String value, @NonNull final ClientId clientId) { return productsRepo.isExistingValue(value, clientId); } @Override public void setProductCodeFieldsFromGTIN(@NonNull final I_M_Product record, @Nullable final GTIN gtin)
{ record.setGTIN(gtin != null ? gtin.getAsString() : null); record.setUPC(gtin != null ? gtin.getAsString() : null); if (gtin != null) { record.setEAN13_ProductCode(null); } } @Override public void setProductCodeFieldsFromEAN13ProductCode(@NonNull final I_M_Product record, @Nullable final EAN13ProductCode ean13ProductCode) { record.setEAN13_ProductCode(ean13ProductCode != null ? ean13ProductCode.getAsString() : null); if (ean13ProductCode != null) { record.setGTIN(null); record.setUPC(null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductBL.java
1
请完成以下Java代码
public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public V remove(Object key) { V removedValue = super.remove(key); if (removedValue != null) { removeFromTrackingMaps(key); } return removedValue; } @Override public boolean remove(Object key, Object value) { boolean removed = super.remove(key, value); if (removed) { removeFromTrackingMaps(key); } return removed; } @Override public void clear() { super.clear(); numberToKey.clear(); keyToNumber.clear(); } public V getRandomValue() { if (this.isEmpty()) { return null; } int randomNumber = ThreadLocalRandom.current().nextInt(this.size()); K randomKey = numberToKey.get(randomNumber); return this.get(randomKey); } private void removeFromTrackingMaps(Object key) { @SuppressWarnings("unchecked") K keyToRemove = (K) key; Integer numberToRemove = keyToNumber.get(keyToRemove); if (numberToRemove == null) { return;
} int mapSize = this.size(); int lastIndex = mapSize; if (numberToRemove == lastIndex) { numberToKey.remove(numberToRemove); keyToNumber.remove(keyToRemove); } else { K lastKey = numberToKey.get(lastIndex); if (lastKey == null) { numberToKey.remove(numberToRemove); keyToNumber.remove(keyToRemove); return; } numberToKey.put(numberToRemove, lastKey); keyToNumber.put(lastKey, numberToRemove); numberToKey.remove(lastIndex); keyToNumber.remove(keyToRemove); } } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\RandomizedMap.java
1
请在Spring Boot框架中完成以下Java代码
public class BookService implements IBookService { private static final Set<Book> BOOKS_DATA = initializeData(); @Override public Book getBookWithTitle(String title) { return BOOKS_DATA.stream() .filter(book -> book.getTitle().equals(title)) .findFirst() .orElse(null); } @Override public List<Book> getAllBooks() { return new ArrayList<>(BOOKS_DATA); } @Override public Book addBook(Book book) { BOOKS_DATA.add(book); return book; }
@Override public Book updateBook(Book book) { BOOKS_DATA.removeIf(b -> Objects.equals(b.getId(), book.getId())); BOOKS_DATA.add(book); return book; } @Override public boolean deleteBook(Book book) { return BOOKS_DATA.remove(book); } private static Set<Book> initializeData() { Book book = new Book(1, "J.R.R. Tolkien", "The Lord of the Rings"); Set<Book> books = new HashSet<>(); books.add(book); return books; } }
repos\tutorials-master\graphql-modules\graphql-spqr\src\main\java\com\baeldung\spqr\BookService.java
2
请完成以下Java代码
public String getChangeType() { return changeType; } public void setChangeType(String changeType) { this.changeType = changeType; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeType() { return scopeType; }
public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public boolean containsProcessedElementId(String elementId) { return this.processedElementIds.contains(elementId); } public void addProcessedElementId(String elementId) { this.processedElementIds.add(elementId); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variablelistener\VariableListenerSessionData.java
1
请完成以下Java代码
public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Long getDurationInMillis() { if(durationInMillis != null) { return durationInMillis; } else if(startTime != null && endTime != null) {
return endTime.getTime() - startTime.getTime(); } else { return null; } } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public Long getDurationRaw() { return durationInMillis; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricScopeInstanceEvent.java
1
请完成以下Java代码
public @Nullable Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (Objects.equals(PARAM_Shipper, parameter.getColumnName())) { return CollectionUtils.singleElement(helper.getShipperIds(getSelectedShipmentScheduleIds())); } else if (Objects.equals(PARAM_IsIncludeCarrierAdviseManual, parameter.getColumnName())) { return false; } else { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } @Override protected String doIt() { helper.updateEligibleShipmentSchedules( CarrierAdviseUpdateRequest.builder() .query(ShipmentScheduleQuery.builder() .shipperId(p_ShipperId) .shipmentScheduleIds(getSelectedShipmentScheduleIds()) .build()) .isIncludeCarrierAdviseManual(p_IsIncludeCarrierAdviseManual) .carrierProductId(p_CarrierProduct)
.carrierGoodsTypeId(p_GoodsType) .carrierServiceIds(getCarrierServiceIds()) .build() ); return JavaProcess.MSG_OK; } private ImmutableSet<ShipmentScheduleId> getSelectedShipmentScheduleIds() { return getSelectedIds(ShipmentScheduleId::ofRepoId, rowsLimit); } private ImmutableSet<CarrierServiceId> getCarrierServiceIds() { return Stream.of(p_CarrierProductService, p_CarrierProductService2, p_CarrierProductService3) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons.webui\src\main\java\de\metas\shipper\gateway\commons\webui\M_ShipmentSchedule_Advise_Manual.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((emailAddress == null) ? 0 : emailAddress.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override 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 void setAD_ReportView_ID (int AD_ReportView_ID) { if (AD_ReportView_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_ReportView_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_ReportView_ID, Integer.valueOf(AD_ReportView_ID)); } /** Get Report View. @return View used to generate this report */ public int getAD_ReportView_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReportView_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_ReportView_ID())); } /** Set Function Column. @param FunctionColumn Overwrite Column with Function */ public void setFunctionColumn (String FunctionColumn) { set_Value (COLUMNNAME_FunctionColumn, FunctionColumn); } /** Get Function Column. @return Overwrite Column with Function */ public String getFunctionColumn () { return (String)get_Value(COLUMNNAME_FunctionColumn); }
/** Set SQL Group Function. @param IsGroupFunction This function will generate a Group By Clause */ public void setIsGroupFunction (boolean IsGroupFunction) { set_Value (COLUMNNAME_IsGroupFunction, Boolean.valueOf(IsGroupFunction)); } /** Get SQL Group Function. @return This function will generate a Group By Clause */ public boolean isGroupFunction () { Object oo = get_Value(COLUMNNAME_IsGroupFunction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView_Col.java
1
请完成以下Java代码
public class AddRequestParameterGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory { @Override public GatewayFilter apply(NameValueConfig config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String name = Objects.requireNonNull(config.getName(), "name must not be null"); String rawValue = Objects.requireNonNull(config.getValue(), "value must not be null"); URI uri = exchange.getRequest().getURI(); StringBuilder query = new StringBuilder(); String originalQuery = uri.getRawQuery(); if (StringUtils.hasText(originalQuery)) { query.append(originalQuery); if (originalQuery.charAt(originalQuery.length() - 1) != '&') { query.append('&'); } } String value = ServerWebExchangeUtils.expand(exchange, rawValue); // TODO urlencode? query.append(name); query.append('='); query.append(value); boolean encoded = containsEncodedParts(uri); try { URI newUri = UriComponentsBuilder.fromUri(uri) .replaceQuery(query.toString()) .build(encoded) .toUri(); ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build(); return chain.filter(exchange.mutate().request(request).build()); }
catch (RuntimeException ex) { throw new IllegalStateException("Invalid URI query: \"" + query.toString() + "\""); } } @Override public String toString() { String name = config.getName(); String value = config.getValue(); return filterToStringCreator(AddRequestParameterGatewayFilterFactory.this) .append(name != null ? name : "", value != null ? value : "") .toString(); } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AddRequestParameterGatewayFilterFactory.java
1
请完成以下Java代码
public class SetVariablesAsyncCmd extends AbstractSetVariableAsyncCmd implements Command<Void> { protected String caseInstanceId; protected Map<String, Object> variables; public SetVariablesAsyncCmd(String caseInstanceId, Map<String, Object> variables) { this.caseInstanceId = caseInstanceId; this.variables = variables; } @Override public Void execute(CommandContext commandContext) { if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("caseInstanceId is null"); } if (variables == null) { throw new FlowableIllegalArgumentException("variables is null"); } if (variables.isEmpty()) { throw new FlowableIllegalArgumentException("variables is empty"); } CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); CaseInstanceEntity caseInstanceEntity = cmmnEngineConfiguration.getCaseInstanceEntityManager().findById(caseInstanceId);
if (caseInstanceEntity == null) { throw new FlowableObjectNotFoundException("No case instance found for id " + caseInstanceId, CaseInstanceEntity.class); } for (String variableName : variables.keySet()) { addVariable(false, caseInstanceId, null, variableName, variables.get(variableName), caseInstanceEntity.getTenantId(), cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableService()); } createSetAsyncVariablesJob(caseInstanceEntity, cmmnEngineConfiguration); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SetVariablesAsyncCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class UserEntity { @Id @Column(name = "id") private String id; @OneToOne @JoinColumn(name = "address") private AddressEntity address; @Column(name = "name") private String name; @Column(name = "email") private String email; @Column(name = "enabled") private Boolean enabled; public String getId() { return id; } public void setId(String id) { this.id = id; } public AddressEntity getAddress() { return address; } public void setAddress(AddressEntity address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserEntity that = (UserEntity) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "UserEntity{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", email='" + email + '\'' + ", enabled=" + enabled + '}'; } }
repos\spring-examples-java-17\spring-data\src\main\java\itx\examples\springdata\entity\UserEntity.java
2
请完成以下Java代码
public class User { @Id private String id; private String name; private Integer age; @DBRef @Field("email") @CascadeSave private EmailAddress emailAddress; private Integer yearOfBirth; public User() { } public User(String name, Integer age) { this.name = name; this.age = age; } public String getId() { return id; } public void setId(final String id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getAge() { return age; }
public void setAge(final Integer age) { this.age = age; } public EmailAddress getEmailAddress() { return emailAddress; } public void setEmailAddress(final EmailAddress emailAddress) { this.emailAddress = emailAddress; } public Integer getYearOfBirth() { return yearOfBirth; } public void setYearOfBirth(final Integer yearOfBirth) { this.yearOfBirth = yearOfBirth; } }
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\model\User.java
1
请完成以下Java代码
public Iterator<DocTax> iterator() { return taxesByTaxId.values().iterator(); } public Optional<DocTax> getByTaxId(@Nullable final TaxId taxId) { if (taxId == null) { return Optional.empty(); } return Optional.ofNullable(taxesByTaxId.get(taxId)); } public void mapEach(@NonNull final UnaryOperator<DocTax> mapper) { final ImmutableSet<TaxId> taxIds = ImmutableSet.copyOf(taxesByTaxId.keySet()); // IMPORTANT: take a snapshot for (final TaxId taxId : taxIds) {
taxesByTaxId.compute(taxId, (k, docTax) -> mapper.apply(docTax)); } } public void add(@NonNull final DocTax docTax) { final TaxId taxId = docTax.getTaxId(); final DocTax existingDocTax = taxesByTaxId.get(taxId); if (existingDocTax != null) { throw new AdempiereException("Cannot add " + docTax + " since there is already a tax: " + existingDocTax); } taxesByTaxId.put(taxId, docTax); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxesList.java
1
请完成以下Java代码
public static String toGlobalQRCodeJsonString(final HUQRCode qrCode) { return toGlobalQRCode(qrCode).getAsString(); } public static GlobalQRCode toGlobalQRCode(final HUQRCode qrCode) { return JsonConverterV1.toGlobalQRCode(HUQRCodeJsonConverter.GLOBAL_QRCODE_TYPE, qrCode); } public static HUQRCode fromGlobalQRCodeJsonString(@NonNull final String qrCodeString) { return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString)); } public static HUQRCode fromGlobalQRCode(final GlobalQRCode globalQRCode) { if (!isHandled(globalQRCode)) { throw new AdempiereException(INVALID_QR_CODE_ERROR_MSG) .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long } // // IMPORTANT: keep in sync with huQRCodes.js // final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION)) {
return JsonConverterV1.fromGlobalQRCode(globalQRCode); } else { throw new AdempiereException(INVALID_QR_VERSION_ERROR_MSG) .setParameter("version", version); } } public static JsonDisplayableQRCode toRenderedJson(@NonNull final HUQRCode huQRCode) { return JsonDisplayableQRCode.builder() .code(toGlobalQRCodeJsonString(huQRCode)) .displayable(huQRCode.toDisplayableQRCode()) .build(); } public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode) { return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\json\HUQRCodeJsonConverter.java
1
请完成以下Java代码
public class ArrayListBenchmark { @State(Scope.Thread) public static class MyState { List<Employee> employeeList = new ArrayList<>(); Vector<Employee> employeeVector = new Vector<>(); //LinkedList<Employee> employeeList = new LinkedList<>(); long iterations = 100000; Employee employee = new Employee(100L, "Harry"); int employeeIndex = -1; @Setup(Level.Trial) public void setUp() { for (long i = 0; i < iterations; i++) { employeeList.add(new Employee(i, "John")); employeeVector.add(new Employee(i, "John")); } employeeList.add(employee); employeeVector.add(employee); employeeIndex = employeeList.indexOf(employee); } } @Benchmark public void testAddAt(ArrayListBenchmark.MyState state) { state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); } @Benchmark public boolean testContains(ArrayListBenchmark.MyState state) { return state.employeeList.contains(state.employee); } @Benchmark public boolean testContainsVector(ArrayListBenchmark.MyState state) { return state.employeeVector.contains(state.employee); } @Benchmark
public int testIndexOf(ArrayListBenchmark.MyState state) { return state.employeeList.indexOf(state.employee); } @Benchmark public Employee testGet(ArrayListBenchmark.MyState state) { return state.employeeList.get(state.employeeIndex); } @Benchmark public Employee testVectorGet(ArrayListBenchmark.MyState state) { return state.employeeVector.get(state.employeeIndex); } @Benchmark public boolean testRemove(ArrayListBenchmark.MyState state) { return state.employeeList.remove(state.employee); } @Benchmark public void testAdd(ArrayListBenchmark.MyState state) { state.employeeList.add(new Employee(state.iterations + 1, "John")); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(ArrayListBenchmark.class.getSimpleName()).threads(3) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-3\src\main\java\com\baeldung\collections\arraylistvsvector\ArrayListBenchmark.java
1
请在Spring Boot框架中完成以下Java代码
private Consumer<Collection<Saml2Error>> validateRequest(LogoutResponse response, RelyingPartyRegistration registration) { return (errors) -> { validateIssuer(response, registration).accept(errors); validateDestination(response, registration).accept(errors); validateStatus(response).accept(errors); }; } private Consumer<Collection<Saml2Error>> validateIssuer(LogoutResponse response, RelyingPartyRegistration registration) { return (errors) -> { if (response.getIssuer() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to find issuer in LogoutResponse")); return; } String issuer = response.getIssuer().getValue(); if (!issuer.equals(registration.getAssertingPartyMetadata().getEntityId())) { errors .add(new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to match issuer to configured issuer")); } }; } private Consumer<Collection<Saml2Error>> validateDestination(LogoutResponse response, RelyingPartyRegistration registration) { return (errors) -> { if (response.getDestination() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to find destination in LogoutResponse")); return; } String destination = response.getDestination(); if (!destination.equals(registration.getSingleLogoutServiceResponseLocation())) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to match destination to configured destination")); } }; } private Consumer<Collection<Saml2Error>> validateStatus(LogoutResponse response) { return (errors) -> { if (response.getStatus() == null) { return; } if (response.getStatus().getStatusCode() == null) { return; }
if (StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue())) { return; } if (StatusCode.PARTIAL_LOGOUT.equals(response.getStatus().getStatusCode().getValue())) { return; } errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Response indicated logout failed")); }; } private Consumer<Collection<Saml2Error>> validateLogoutRequest(LogoutResponse response, String id) { return (errors) -> { if (response.getInResponseTo() == null) { return; } if (response.getInResponseTo().equals(id)) { return; } errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "LogoutResponse InResponseTo doesn't match ID of associated LogoutRequest")); }; } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\BaseOpenSamlLogoutResponseValidator.java
2
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String email; public User(){} public User(String name, String email) { this.name = name; this.email = email; } public void setName(String name) { this.name = name; }
public void setEmail(String email) { this.email = email; } public long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\entities\User.java
2
请完成以下Java代码
public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; } protected void updateResultCollection(DelegateExecution childExecution, DelegateExecution miRootExecution) { if (miRootExecution != null && hasLoopDataOutputRef()) { Object loopDataOutputReference = miRootExecution.getVariableLocal(getLoopDataOutputRef()); List<Object> resultCollection; if (loopDataOutputReference instanceof List) { resultCollection = (List<Object>) loopDataOutputReference; } else { resultCollection = new ArrayList<>(); } resultCollection.add(getResultElementItem(childExecution)); setLoopVariable(miRootExecution, getLoopDataOutputRef(), resultCollection); } } protected Object getResultElementItem(DelegateExecution childExecution) { return getResultElementItem(childExecution.getVariablesLocal()); } protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected Object getResultElementItem(Map<String, Object> availableVariables) {
if (hasOutputDataItem()) { return availableVariables.get(getOutputDataItem()); } else { //exclude from the result all the built-in multi-instances variables //and loopDataOutputRef itself that may exist in the context depending // on the variable propagation List<String> resultItemExclusions = Arrays.asList( getLoopDataOutputRef(), getCollectionElementIndexVariable(), NUMBER_OF_INSTANCES, NUMBER_OF_COMPLETED_INSTANCES, NUMBER_OF_ACTIVE_INSTANCES ); HashMap<String, Object> resultItem = new HashMap<>(availableVariables); resultItemExclusions.forEach(resultItem.keySet()::remove); return resultItem; } } protected void propagateLoopDataOutputRefToProcessInstance(ExecutionEntity miRootExecution) { if (hasLoopDataOutputRef()) { miRootExecution .getProcessInstance() .setVariable(getLoopDataOutputRef(), miRootExecution.getVariable(getLoopDataOutputRef())); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
1
请完成以下Java代码
public static final FindPanelBuilder builder() { return new FindPanelBuilder(); } /** Logger */ private static final transient Logger log = LogManager.getLogger(Find.class); private final FindPanel findPanel; private final FindPanelActionListener findPanelActionListener = new FindPanelActionListener() { @Override public void onSearch(boolean triggeredFromSearchField) { if (triggeredFromSearchField && findPanel.getTotalRecords() <= 0) { return; } dispose(); }; @Override public void onCancel() { dispose(); }; @Override public void onOpenAsNewRecord() { dispose(); }; }; Find(final FindPanelBuilder builder) { super(builder.getParentFrame(), Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Find") + ": " + builder.getTitle(), true // modal=true ); findPanel = builder.buildFindPanel(); // metas: tsa: begin if (findPanel.isDisposed()) { this.dispose(); return; } findPanel.setActionListener(findPanelActionListener); // Set panel size // NOTE: we are setting such a big width because the table from advanced panel shall be displayed nicely. final int findPanelHeight = AdempierePLAF.getInt(FindPanelUI.KEY_Dialog_Height, FindPanelUI.DEFAULT_Dialog_Height); findPanel.setPreferredSize(new Dimension(950, findPanelHeight)); setIconImage(Images.getImage2("Find24")); this.setContentPane(findPanel); // teo_sarca, [ 1670847 ] Find dialog: closing and canceling need same // functionality this.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) {
findPanel.requestFocus(); } @Override public void windowClosing(WindowEvent e) { findPanel.doCancel(); } }); AEnv.showCenterWindow(builder.getParentFrame(), this); } // Find @Override public void dispose() { findPanel.dispose(); removeAll(); super.dispose(); } // dispose /************************************************************************** * Get Query - Retrieve result * * @return String representation of query */ public MQuery getQuery() { return findPanel.getQuery(); } // getQuery /** * @return true if cancel button pressed */ public boolean isCancel() { return findPanel.isCancel(); } } // Find
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\Find.java
1
请完成以下Java代码
public static EventLogEntryCollector createThreadLocalForEvent(@NonNull final Event event) { final EventLogEntryCollector previousEntryCollector = threadLocalCollector.get(); final EventLogEntryCollector entryCollector = new EventLogEntryCollector(event, previousEntryCollector); threadLocalCollector.set(entryCollector); return entryCollector; } public static EventLogEntryCollector getThreadLocal() { final EventLogEntryCollector eventLogCollector = threadLocalCollector.get(); Check.errorIf(eventLogCollector == null, "Missing thread-local EventLogEntryCollector instance. It is expected that one was created using createThreadLocalForEvent()."); return eventLogCollector; } public void addEventLog(@NonNull final EventLogEntryRequest eventLogRequest) { final EventLogEntry eventLogEntry = EventLogEntry.builder() .uuid(event.getUuid()) .clientId(eventLogRequest.getClientId()) .orgId(eventLogRequest.getOrgId()) .processed(eventLogRequest.isProcessed()) .error(eventLogRequest.isError()) .adIssueId(eventLogRequest.getAdIssueId()) .message(eventLogRequest.getMessage()) .eventHandlerClass(eventLogRequest.getEventHandlerClass()) .build(); eventLogEntries.add(eventLogEntry); } @Override public void close() { // Restore previous entry collector // or clear the current one if (previousEntryCollector != null) { threadLocalCollector.set(previousEntryCollector); }
else { threadLocalCollector.remove(); } // Avoid throwing exception because EventLogService is not available in unit tests if (Adempiere.isUnitTestMode()) { return; } try { final EventLogService eventStoreService = SpringContextHolder.instance.getBean(EventLogService.class); eventStoreService.saveEventLogEntries(eventLogEntries); } catch (final Exception ex) { logger.warn("Failed saving {}. Ignored", eventLogEntries, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogEntryCollector.java
1
请完成以下Java代码
public void addEventListener(ActivitiEventListener listenerToAdd) { eventSupport.addEventListener(listenerToAdd); } @Override public void addEventListener(ActivitiEventListener listenerToAdd, ActivitiEventType... types) { eventSupport.addEventListener(listenerToAdd, types); } @Override public void removeEventListener(ActivitiEventListener listenerToRemove) { eventSupport.removeEventListener(listenerToRemove); } @Override public void dispatchEvent(ActivitiEvent event) { if (enabled) { eventSupport.dispatchEvent(event); } if (event.getType() == ActivitiEventType.ENTITY_DELETED && event instanceof ActivitiEntityEvent) { ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event; if (entityEvent.getEntity() instanceof ProcessDefinition) { // process definition deleted event doesn't need to be dispatched to event listeners return; } } // Try getting hold of the Process definition, based on the process definition key, if a context is active CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { BpmnModel bpmnModel = extractBpmnModelFromEvent(event); if (bpmnModel != null) { ((ActivitiEventSupport) bpmnModel.getEventSupport()).dispatchEvent(event); } } } /** * In case no process-context is active, this method attempts to extract a process-definition based on the event. In case it's an event related to an entity, this can be deducted by inspecting the * entity, without additional queries to the database. * * If not an entity-related event, the process-definition will be retrieved based on the processDefinitionId (if filled in). This requires an additional query to the database in case not already
* cached. However, queries will only occur when the definition is not yet in the cache, which is very unlikely to happen, unless evicted. * * @param event * @return */ protected BpmnModel extractBpmnModelFromEvent(ActivitiEvent event) { BpmnModel result = null; if (result == null && event.getProcessDefinitionId() != null) { ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition( event.getProcessDefinitionId(), true ); if (processDefinition != null) { result = Context.getProcessEngineConfiguration() .getDeploymentManager() .resolveProcessDefinition(processDefinition) .getBpmnModel(); } } return result; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventDispatcherImpl.java
1
请完成以下Java代码
public void attachmentWasStored( @NonNull final AttachmentEntry attachmentEntry, @NonNull final URI storageIdentifier) { final ImmutableList<I_C_Doc_Outbound_Log> docOutboundLogRecords = attachmentEntry .getLinkedRecords() .stream() .filter(this::isDocOutBoundLogReference) .map(ref -> ref.getModel(I_C_Doc_Outbound_Log.class)) .collect(ImmutableList.toImmutableList()); final ImmutableList.Builder<I_C_Doc_Outbound_Log_Line> createdLogLineRecords = ImmutableList.builder(); for (final I_C_Doc_Outbound_Log docOutboundLogRecord : docOutboundLogRecords) { final I_C_Doc_Outbound_Log_Line docOutboundLogLineRecord = DocOutboundUtils.createOutboundLogLineRecord(docOutboundLogRecord); docOutboundLogLineRecord.setAction(ArchiveAction.ATTACHMENT_STORED.getCode()); docOutboundLogLineRecord.setStoreURI(storageIdentifier.toString()); saveRecord(docOutboundLogLineRecord); createdLogLineRecords.add(docOutboundLogLineRecord);
docOutboundLogRecord.setDateLastStore(SystemTime.asTimestamp()); saveRecord(docOutboundLogRecord); } attachmentEntryService.createAttachmentLinks( ImmutableList.of(attachmentEntry), createdLogLineRecords.build()); } private boolean isDocOutBoundLogReference(ITableRecordReference ref) { return I_C_Doc_Outbound_Log.Table_Name.equals(ref.getTableName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\storage\attachments\DocOutboundAttachmentStoredListener.java
1
请完成以下Java代码
public JSONMenuNode getPath( @RequestParam(name = PARAM_Type) final JSONMenuNodeType jsonType, @RequestParam(name = PARAM_ElementId) final String elementIdStr, @RequestParam(name = PARAM_IncludeLastNode, required = false, defaultValue = "false") @Parameter(description = "Shall we include the last node") final boolean includeLastNode) { userSession.assertLoggedIn(); final MenuNodeType menuNodeType = jsonType.toMenuNodeType(); final DocumentId elementId = DocumentId.of(elementIdStr); final List<MenuNode> path = getMenuTree() .getPath(menuNodeType, elementId) .orElseGet(() -> getPathOfMissingElement(menuNodeType, elementId, userSession.getAD_Language())); return JSONMenuNode.ofPath(path, includeLastNode, menuTreeRepository); } private List<MenuNode> getPathOfMissingElement(final MenuNodeType type, final DocumentId elementId, final String adLanguage) { if (type == MenuNodeType.Window) { final String caption = documentDescriptorFactory.getDocumentDescriptor(WindowId.of(elementId)) .getLayout() .getCaption(adLanguage); return ImmutableList.of(MenuNode.builder() .setType(type, elementId) .setCaption(caption) .setAD_Menu_ID_None() .build()); } else { throw new NoMenuNodesFoundException("No menu node found for type=" + type + " and elementId=" + elementId); } } @GetMapping("/queryPaths") public JSONMenuNode query( @RequestParam(name = PARAM_NameQuery) final String nameQuery, @RequestParam(name = PARAM_ChildrenLimit, required = false, defaultValue = "0") final int childrenLimit, @RequestParam(name = "childrenInclusive", required = false, defaultValue = "false") @Parameter(description = "true if groups that were matched shall be populated with it's leafs, even if those leafs are not matching") final boolean includeLeafsIfGroupAccepted) {
userSession.assertLoggedIn(); final MenuNode rootFiltered = getMenuTree() .filter(nameQuery, includeLeafsIfGroupAccepted); if (rootFiltered == null) { throw new NoMenuNodesFoundException(); } if (rootFiltered.getChildren().isEmpty()) { throw new NoMenuNodesFoundException(); } return JSONMenuNode.builder(rootFiltered) .setMaxLeafNodes(childrenLimit) .setIsFavoriteProvider(menuTreeRepository) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuRestController.java
1
请完成以下Java代码
public class ConvertPrimitivesArrayToList { public static void failConvert() { int[] input = new int[]{1,2,3,4}; // List<Integer> inputAsList = Arrays.asList(input); } public static List<Integer> iterateConvert(int[] input) { List<Integer> output = new ArrayList<Integer>(); for (int value : input) { output.add(value); } return output; } public static List<Integer> streamConvert(int[] input) { List<Integer> output = Arrays.stream(input).boxed().collect(Collectors.toList()); return output;
} public static List<Integer> streamConvertIntStream(int[] input) { List<Integer> output = IntStream.of(input).boxed().collect(Collectors.toList()); return output; } public static List<Integer> guavaConvert(int[] input) { List<Integer> output = Ints.asList(input); return output; } public static List<Integer> apacheCommonConvert(int[] input) { Integer[] outputBoxed = ArrayUtils.toObject(input); List<Integer> output = Arrays.asList(outputBoxed); return output; } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\convertarrayprimitives\ConvertPrimitivesArrayToList.java
1
请在Spring Boot框架中完成以下Java代码
public Builder getBuilder(String registrationId) { ClientRegistration.Builder builder = getBuilder(registrationId, ClientAuthenticationMethod.CLIENT_SECRET_POST, DEFAULT_REDIRECT_URL); builder.scope("users.read", "tweet.read"); builder.authorizationUri("https://x.com/i/oauth2/authorize"); builder.tokenUri("https://api.x.com/2/oauth2/token"); builder.userInfoUri("https://api.x.com/2/users/me"); builder.userNameAttributeName("username"); builder.clientName("X"); return builder; } }, OKTA { @Override public Builder getBuilder(String registrationId) { ClientRegistration.Builder builder = getBuilder(registrationId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, DEFAULT_REDIRECT_URL); builder.scope("openid", "profile", "email"); builder.userNameAttributeName(IdTokenClaimNames.SUB); builder.clientName("Okta"); return builder; } }; private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}"; protected final ClientRegistration.Builder getBuilder(String registrationId, ClientAuthenticationMethod method,
String redirectUri) { ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(registrationId); builder.clientAuthenticationMethod(method); builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE); builder.redirectUri(redirectUri); return builder; } /** * Create a new * {@link org.springframework.security.oauth2.client.registration.ClientRegistration.Builder * ClientRegistration.Builder} pre-configured with provider defaults. * @param registrationId the registration-id used with the new builder * @return a builder instance */ public abstract ClientRegistration.Builder getBuilder(String registrationId); }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\oauth2\client\CommonOAuth2Provider.java
2
请完成以下Java代码
public java.sql.Timestamp getPreparationTime_2 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_2); } /** Set Bereitstellungszeit Mi. @param PreparationTime_3 Preparation time for wednesday */ @Override public void setPreparationTime_3 (java.sql.Timestamp PreparationTime_3) { set_Value (COLUMNNAME_PreparationTime_3, PreparationTime_3); } /** Get Bereitstellungszeit Mi. @return Preparation time for wednesday */ @Override public java.sql.Timestamp getPreparationTime_3 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_3); } /** Set Bereitstellungszeit Do. @param PreparationTime_4 Preparation time for thursday */ @Override public void setPreparationTime_4 (java.sql.Timestamp PreparationTime_4) { set_Value (COLUMNNAME_PreparationTime_4, PreparationTime_4); } /** Get Bereitstellungszeit Do. @return Preparation time for thursday */ @Override public java.sql.Timestamp getPreparationTime_4 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_4); } /** Set Bereitstellungszeit Fr. @param PreparationTime_5 Preparation time for Friday */ @Override public void setPreparationTime_5 (java.sql.Timestamp PreparationTime_5) { set_Value (COLUMNNAME_PreparationTime_5, PreparationTime_5); } /** Get Bereitstellungszeit Fr. @return Preparation time for Friday */ @Override public java.sql.Timestamp getPreparationTime_5 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_5); } /** Set Bereitstellungszeit Sa. @param PreparationTime_6 Preparation time for Saturday */ @Override public void setPreparationTime_6 (java.sql.Timestamp PreparationTime_6) { set_Value (COLUMNNAME_PreparationTime_6, PreparationTime_6); } /** Get Bereitstellungszeit Sa. @return Preparation time for Saturday */ @Override public java.sql.Timestamp getPreparationTime_6 () {
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_6); } /** Set Bereitstellungszeit So. @param PreparationTime_7 Preparation time for Sunday */ @Override public void setPreparationTime_7 (java.sql.Timestamp PreparationTime_7) { set_Value (COLUMNNAME_PreparationTime_7, PreparationTime_7); } /** Get Bereitstellungszeit So. @return Preparation time for Sunday */ @Override public java.sql.Timestamp getPreparationTime_7 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_7); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersion.java
1
请完成以下Java代码
private ImmutableList<DBFunction> retrieveAvailableImportFunctionsByTableName(@NonNull final String tableName) { final StringBuilder sql = new StringBuilder("SELECT routines.specific_schema, routines.routine_name FROM information_schema.routines ") .append(" WHERE routines.routine_name ILIKE ? ") .append(" ORDER BY routines.routine_name "); final List<Object> sqlParams = Arrays.<Object> asList(tableName + "_%"); return ImmutableList.copyOf(DB.retrieveRowsOutOfTrx(sql.toString(), sqlParams, rs -> retrieveDBFunction(rs))); } private DBFunction retrieveDBFunction(@NonNull final ResultSet rs) throws SQLException { final String specific_schema = rs.getString("specific_schema"); final String routine_name = rs.getString("routine_name"); return DBFunction.builder() .schema(specific_schema) .name(routine_name) .build();
} private boolean isEligibleAfterRowFunction(@NonNull final DBFunction function) { final String routine_name = function.getName(); return StringUtils.containsIgnoreCase(routine_name, IMPORT_AFTER_ROW); } private boolean isEligibleAfterAllFunction(@NonNull final DBFunction function) { final String routine_name = function.getName(); return StringUtils.containsIgnoreCase(routine_name, IMPORT_AFTER_ALL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\DBFunctionsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public void setZIP(String value) { this.zip = value; } /** * Gets the value of the town property. * * @return * possible object is * {@link String } * */ public String getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is * {@link String } * */ public void setTown(String value) { this.town = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link String } * */ public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */
public void setCountry(String value) { this.country = value; } /** * Details about the contact person at the delivery point. * * @return * possible object is * {@link ContactType } * */ public ContactType getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link ContactType } * */ public void setContact(ContactType value) { this.contact = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DeliveryPointDetails.java
2
请完成以下Java代码
public class LinesProcessor implements Tasklet, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesProcessor.class); private List<Line> lines; @Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { for (Line line : lines) { long age = ChronoUnit.YEARS.between(line.getDob(), LocalDate.now()); logger.debug("Calculated age " + age + " for line " + line.toString()); line.setAge(age); } return RepeatStatus.FINISHED; }
@Override public void beforeStep(StepExecution stepExecution) { ExecutionContext executionContext = stepExecution .getJobExecution() .getExecutionContext(); this.lines = (List<Line>) executionContext.get("lines"); logger.debug("Lines Processor initialized."); } @Override public ExitStatus afterStep(StepExecution stepExecution) { logger.debug("Lines Processor ended."); return ExitStatus.COMPLETED; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\tasklets\LinesProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public final class DateUtils { @Nullable public static LocalDate toLocalDate(@Nullable final java.sql.Date date) { return date != null ? date.toLocalDate() : null; } @NonNull public static java.sql.Date toSqlDate(@NonNull final LocalDate date) { return java.sql.Date.valueOf(date); } public static boolean between( @NonNull final LocalDate date, @Nullable final LocalDate dateFrom, @Nullable final LocalDate dateTo) { if (dateFrom != null && dateFrom.compareTo(date) > 0) { return false; } return dateTo == null || date.compareTo(dateTo) <= 0; }
public static String getDayName(@NonNull final LocalDate date, @NonNull final Locale locale) { return date.format(DateTimeFormatter.ofPattern("EEEE", locale)); } public static ArrayList<LocalDate> getDaysList(final LocalDate startDate, final LocalDate endDate) { final ArrayList<LocalDate> result = new ArrayList<>(); for (LocalDate date = startDate; date.compareTo(endDate) <= 0; date = date.plusDays(1)) { result.add(date); } return result; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\DateUtils.java
2
请完成以下Java代码
public class ActivitiProcessStartedEventImpl extends ActivitiEntityWithVariablesEventImpl implements FlowableProcessStartedEvent { protected final String nestedProcessInstanceId; protected final String nestedProcessDefinitionId; @SuppressWarnings("rawtypes") public ActivitiProcessStartedEventImpl(final Object entity, final Map variables, final boolean localScope) { super(entity, variables, localScope, FlowableEngineEventType.PROCESS_STARTED); if (entity instanceof ExecutionEntity) { final ExecutionEntity superExecution = ((ExecutionEntity) entity).getSuperExecution(); if (superExecution != null) { this.nestedProcessDefinitionId = superExecution.getProcessDefinitionId(); this.nestedProcessInstanceId = superExecution.getProcessInstanceId(); } else { this.nestedProcessDefinitionId = null; this.nestedProcessInstanceId = null; } } else { this.nestedProcessDefinitionId = null;
this.nestedProcessInstanceId = null; } } @Override public String getNestedProcessInstanceId() { return this.nestedProcessInstanceId; } @Override public String getNestedProcessDefinitionId() { return this.nestedProcessDefinitionId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiProcessStartedEventImpl.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override
public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStandardQty (final BigDecimal StandardQty) { set_Value (COLUMNNAME_StandardQty, StandardQty); } @Override public BigDecimal getStandardQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StandardQty); 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_Phase.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderMapping { @SerializedName("orderId") private String orderId = null; @SerializedName("salesId") private String salesId = null; @SerializedName("updated") private OffsetDateTime updated = null; public OrderMapping orderId(String orderId) { this.orderId = orderId; return this; } /** * Alberta-Id der Bestellung * @return orderId **/ @Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", required = true, description = "Alberta-Id der Bestellung") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public OrderMapping salesId(String salesId) { this.salesId = salesId; return this; } /** * Id des Auftrags aus WaWi * @return salesId **/ @Schema(example = "A123445", description = "Id des Auftrags aus WaWi") public String getSalesId() { return salesId; } public void setSalesId(String salesId) { this.salesId = salesId; } public OrderMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(Object o) { if (this == o) { return true;
} if (o == null || getClass() != o.getClass()) { return false; } OrderMapping orderMapping = (OrderMapping) o; return Objects.equals(this.orderId, orderMapping.orderId) && Objects.equals(this.salesId, orderMapping.salesId) && Objects.equals(this.updated, orderMapping.updated); } @Override public int hashCode() { return Objects.hash(orderId, salesId, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderMapping {\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" salesId: ").append(toIndentedString(salesId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderMapping.java
2
请完成以下Java代码
public String getPassword() { return password; } public UserDO setPassword(String password) { this.password = password; return this; } public Date getCreateTime() { return createTime; } public UserDO setCreateTime(Date createTime) { this.createTime = createTime; return this; }
public Integer getDeleted() { return deleted; } public UserDO setDeleted(Integer deleted) { this.deleted = deleted; return this; } public Integer getTenantId() { return tenantId; } public UserDO setTenantId(Integer tenantId) { this.tenantId = tenantId; return this; } }
repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\dataobject\UserDO.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public int getProcessDefinitionVersion() { return processDefinitionVersion; } public void setProcessDefinitionVersion(int processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedProcessInstanceCount() { return finishedProcessInstanceCount; } public void setFinishedProcessInstanceCount(Long finishedProcessInstanceCount) { this.finishedProcessInstanceCount = finishedProcessInstanceCount; } public long getCleanableProcessInstanceCount() { return cleanableProcessInstanceCount; }
public void setCleanableProcessInstanceCount(Long cleanableProcessInstanceCount) { this.cleanableProcessInstanceCount = cleanableProcessInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[processDefinitionId = " + processDefinitionId + ", processDefinitionKey = " + processDefinitionKey + ", processDefinitionName = " + processDefinitionName + ", processDefinitionVersion = " + processDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedProcessInstanceCount = " + finishedProcessInstanceCount + ", cleanableProcessInstanceCount = " + cleanableProcessInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricProcessInstanceReportResultEntity.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<String> getCaseDefinitionKeys() { return caseDefinitionKeys; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups; } public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; }
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public Set<String> getScopeIds() { return scopeIds; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskInstanceQueryImpl.java
2
请完成以下Java代码
public void setInitialAnswer(final int initialAnswer) { // If the inial answer did not actual changed, do nothing if (this._initialAnswer == initialAnswer) { return; } // // Configure buttons accelerator (KeyStroke) and RootPane's default button final JRootPane rootPane = getRootPane(); final CButton okButton = confirmPanel.getOKButton(); final AppsAction okAction = (AppsAction)okButton.getAction(); final CButton cancelButton = confirmPanel.getCancelButton(); final AppsAction cancelAction = (AppsAction)cancelButton.getAction(); if (initialAnswer == A_OK) { okAction.setDefaultAccelerator(); cancelAction.setDefaultAccelerator(); rootPane.setDefaultButton(okButton); } else if (initialAnswer == A_CANCEL) { // NOTE: we need to set the OK's Accelerator keystroke to null because in most of the cases it is "Enter" // and we want to prevent user for hiting ENTER by mistake okAction.setAccelerator(null); cancelAction.setDefaultAccelerator(); rootPane.setDefaultButton(cancelButton); } else { throw new IllegalArgumentException("Unknown inital answer: " + initialAnswer); } // // Finally, set the new inial answer this._initialAnswer = initialAnswer; } public int getInitialAnswer() { return this._initialAnswer; } /**
* Request focus on inital answer. */ private void focusInitialAnswerButton() { final CButton defaultButton; if (_initialAnswer == A_OK) { defaultButton = confirmPanel.getOKButton(); } else if (_initialAnswer == A_CANCEL) { defaultButton = confirmPanel.getCancelButton(); } else { return; } defaultButton.requestFocusInWindow(); } } // ADialogDialog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ADialogDialog.java
1
请完成以下Java代码
public BigDecimal getDiscount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Discount); return bd != null ? bd : BigDecimal.ZERO; } /** * IfForeignDiscountsExist AD_Reference_ID=541401 * Reference name: C_SubscrDiscount_Line_IfForeignDiscountsExist */ public static final int IFFOREIGNDISCOUNTSEXIST_AD_Reference_ID=541401; /** Use_Other_Discount = Use_Other_Discount */ public static final String IFFOREIGNDISCOUNTSEXIST_Use_Other_Discount = "Use_Other_Discount"; /** Use_Our_Discount = Use_Our_Discount */ public static final String IFFOREIGNDISCOUNTSEXIST_Use_Our_Discount = "Use_Our_Discount"; @Override public void setIfForeignDiscountsExist (final java.lang.String IfForeignDiscountsExist) { set_Value (COLUMNNAME_IfForeignDiscountsExist, IfForeignDiscountsExist); } @Override public java.lang.String getIfForeignDiscountsExist() { return get_ValueAsString(COLUMNNAME_IfForeignDiscountsExist); } @Override public void setMatchIfTermEndsWithCalendarYear (final boolean MatchIfTermEndsWithCalendarYear) { set_Value (COLUMNNAME_MatchIfTermEndsWithCalendarYear, MatchIfTermEndsWithCalendarYear); } @Override public boolean isMatchIfTermEndsWithCalendarYear() { return get_ValueAsBoolean(COLUMNNAME_MatchIfTermEndsWithCalendarYear); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStartDay (final int StartDay) { set_Value (COLUMNNAME_StartDay, StartDay); } @Override public int getStartDay() { return get_ValueAsInt(COLUMNNAME_StartDay); } @Override public void setStartMonth (final int StartMonth) { set_Value (COLUMNNAME_StartMonth, StartMonth); } @Override public int getStartMonth() { return get_ValueAsInt(COLUMNNAME_StartMonth); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount_Line.java
1
请完成以下Java代码
public static int getCalloutId(final GridTab mTab, final String colName) { final Integer id = (Integer)mTab.getValue(colName); if (id == null || id <= 0) { return 0; } return id; } /** * For a {@link Timestamp} representing e.g. "17.12.2009 15:14:34" this method returns a timestamp representing * "17.12.2009 00:00:00". * * @param ctx * @param ts * @return */ public static Timestamp removeTime(final Timestamp ts) { final DateFormat fmt = DateFormat.getDateInstance(DateFormat.LONG); final String strDate = fmt.format(ts); java.util.Date date; try { date = fmt.parse(strDate); } catch (ParseException e) { throw new AdempiereException(e); } final Timestamp currentDate = new Timestamp(date.getTime()); return currentDate; } public static GridTab getGridTabForTableAndWindow(final Properties ctx, final int windowNo, final int AD_Window_ID, final int AD_Table_ID, final boolean startWithEmptyQuery) { final GridWindowVO wVO = GridWindowVO.create(ctx, windowNo, AdWindowId.ofRepoId(AD_Window_ID)); if (wVO == null) { MWindow w = new MWindow(Env.getCtx(), AD_Window_ID, null); throw new AdempiereException("No access to window - " + w.getName() + " (AD_Window_ID=" + AD_Window_ID + ")");
} final GridWindow gridWindow = new GridWindow(wVO); // GridTab tab = null; int tabIndex = -1; for (int i = 0; i < gridWindow.getTabCount(); i++) { GridTab t = gridWindow.getTab(i); if (t.getAD_Table_ID() == AD_Table_ID) { tab = t; tabIndex = i; break; } } if (tab == null) { throw new AdempiereException("No Tab found for AD_Table_ID=" + AD_Table_ID + ", Window:" + gridWindow.getName()); } gridWindow.initTab(tabIndex); // if (startWithEmptyQuery) { tab.setQuery(MQuery.getEqualQuery("1", "2")); tab.query(false); } return tab; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\MiscUtils.java
1
请完成以下Java代码
protected void reportExecution(TenantId tenantId, CustomerId customerId) { apiUsageReportClient.ifPresent(client -> client.report(tenantId, customerId, ApiUsageRecordKey.JS_EXEC_COUNT, 1)); } @Override protected JsScriptExecutionTask doInvokeFunction(UUID scriptId, Object[] args) { return new JsScriptExecutionTask(doInvokeFunction(scriptId, scriptInfoMap.get(scriptId), args)); } @Override protected ListenableFuture<UUID> doEvalScript(TenantId tenantId, ScriptType scriptType, String scriptBody, UUID scriptId, String[] argNames) { String scriptHash = hash(tenantId, scriptBody); String functionName = constructFunctionName(scriptId, scriptHash); String jsScript = generateJsScript(scriptType, functionName, scriptBody, argNames); return doEval(scriptId, new JsScriptInfo(scriptHash, functionName), jsScript); } @Override protected void doRelease(UUID scriptId) throws Exception { doRelease(scriptId, scriptInfoMap.remove(scriptId)); } @Override public String validate(TenantId tenantId, String scriptBody) { String errorMessage = super.validate(tenantId, scriptBody); if (errorMessage == null) { return JsValidator.validate(scriptBody); } return errorMessage; }
protected abstract ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo jsInfo, String scriptBody); protected abstract ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo jsInfo, Object[] args); protected abstract void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws Exception; private String generateJsScript(ScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == ScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); } throw new RuntimeException("No script factory implemented for scriptType: " + scriptType); } protected String constructFunctionName(UUID scriptId, String scriptHash) { return "invokeInternal_" + scriptId.toString().replace('-', '_'); } protected String hash(TenantId tenantId, String scriptBody) { return Hashing.murmur3_128().newHasher() .putLong(tenantId.getId().getMostSignificantBits()) .putLong(tenantId.getId().getLeastSignificantBits()) .putUnencodedChars(scriptBody) .hash().toString(); } @Override protected StatsType getStatsType() { return StatsType.JS_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\AbstractJsInvokeService.java
1