instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setM_CostRevaluation_ID (final int M_CostRevaluation_ID) { if (M_CostRevaluation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, M_CostRevaluation_ID); } @Override public int getM_CostRevaluation_ID() { return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID); } @Override public void setM_CostRevaluationLine_ID (final int M_CostRevaluationLine_ID) { if (M_CostRevaluationLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, M_CostRevaluationLine_ID); } @Override public int getM_CostRevaluationLine_ID() { return get_ValueAsInt(COLUMNNAME_M_CostRevaluationLine_ID); } @Override public org.compiere.model.I_M_CostType getM_CostType() { return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class); } @Override public void setM_CostType(final org.compiere.model.I_M_CostType M_CostType) { set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType); } @Override public void setM_CostType_ID (final int M_CostType_ID)
{ if (M_CostType_ID < 1) set_Value (COLUMNNAME_M_CostType_ID, null); else set_Value (COLUMNNAME_M_CostType_ID, M_CostType_ID); } @Override public int getM_CostType_ID() { return get_ValueAsInt(COLUMNNAME_M_CostType_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 setNewCostPrice (final BigDecimal NewCostPrice) { set_Value (COLUMNNAME_NewCostPrice, NewCostPrice); } @Override public BigDecimal getNewCostPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NewCostPrice); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluationLine.java
1
请完成以下Java代码
public class Dashboard extends DashboardInfo implements ExportableEntity<DashboardId> { private static final long serialVersionUID = 872682138346187503L; private transient JsonNode configuration; @Getter @Setter private DashboardId externalId; @Getter @Setter private List<ResourceExportData> resources; public Dashboard() { super(); } public Dashboard(DashboardId id) { super(id); } public Dashboard(DashboardInfo dashboardInfo) { super(dashboardInfo); } public Dashboard(Dashboard dashboard) { super(dashboard); this.configuration = dashboard.getConfiguration(); this.externalId = dashboard.getExternalId(); this.resources = dashboard.getResources() != null ? new ArrayList<>(dashboard.getResources()) : null; } @Schema(description = "JSON object with main configuration of the dashboard: layouts, widgets, aliases, etc. " + "The JSON structure of the dashboard configuration is quite complex. " + "The easiest way to learn it is to export existing dashboard to JSON." , implementation = com.fasterxml.jackson.databind.JsonNode.class) public JsonNode getConfiguration() { return configuration; } public void setConfiguration(JsonNode configuration) { this.configuration = configuration;
} @JsonIgnore public List<ObjectNode> getEntityAliasesConfig() { return getChildObjects("entityAliases"); } @JsonIgnore public List<ObjectNode> getWidgetsConfig() { return getChildObjects("widgets"); } @JsonIgnore private List<ObjectNode> getChildObjects(String propertyName) { return Optional.ofNullable(configuration) .map(config -> config.get(propertyName)) .filter(node -> !node.isEmpty() && (node.isObject() || node.isArray())) .map(node -> Streams.stream(node.elements()) .filter(JsonNode::isObject) .map(jsonNode -> (ObjectNode) jsonNode) .collect(Collectors.toList())) .orElse(Collections.emptyList()); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Dashboard [tenantId="); builder.append(getTenantId()); builder.append(", title="); builder.append(getTitle()); builder.append(", configuration="); builder.append(configuration); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Dashboard.java
1
请完成以下Java代码
public InvoiceRow build() { return new InvoiceRow(this); } public Builder setOrgId(final OrgId orgId) { this.orgId = orgId; return this; } public Builder setC_Invoice_ID(final int C_Invoice_ID) { this.C_Invoice_ID = C_Invoice_ID; return this; } public Builder setC_Order_ID(final int C_Order_ID) { this.C_Order_ID = C_Order_ID; return this; } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; } public Builder setDocTypeName(final String docTypeName) { this.docTypeName = docTypeName; return this; } public Builder setDateInvoiced(final Date dateInvoiced) { this.dateInvoiced = dateInvoiced; return this; } public Builder setDateAcct(final Date dateAcct) { this.dateAcct = dateAcct; return this; } public Builder setC_BPartner_ID(final int C_BPartner_ID) { this.C_BPartner_ID = C_BPartner_ID; return this; } public Builder setBPartnerName(final String BPartnerName) { this.BPartnerName = BPartnerName; return this; } public Builder setCurrencyISOCode(final CurrencyCode currencyISOCode) { this.currencyISOCode = currencyISOCode; return this; } public Builder setGrandTotal(final BigDecimal grandTotal) {
this.grandTotal = grandTotal; return this; } public Builder setGrandTotalConv(final BigDecimal grandTotalConv) { this.grandTotalConv = grandTotalConv; return this; } public Builder setOpenAmtConv(final BigDecimal openAmtConv) { this.openAmtConv = openAmtConv; return this; } public Builder setDiscount(final BigDecimal discount) { this.discount = discount; return this; } public Builder setPaymentRequestAmt(final BigDecimal paymentRequestAmt) { Check.assumeNotNull(paymentRequestAmt, "paymentRequestAmt not null"); this.paymentRequestAmtSupplier = Suppliers.ofInstance(paymentRequestAmt); return this; } public Builder setPaymentRequestAmt(final Supplier<BigDecimal> paymentRequestAmtSupplier) { this.paymentRequestAmtSupplier = paymentRequestAmtSupplier; return this; } public Builder setMultiplierAP(final BigDecimal multiplierAP) { this.multiplierAP = multiplierAP; return this; } public Builder setIsPrepayOrder(final boolean isPrepayOrder) { this.isPrepayOrder = isPrepayOrder; return this; } public Builder setPOReference(final String POReference) { this.POReference = POReference; return this; } public Builder setCreditMemo(final boolean creditMemo) { this.creditMemo = creditMemo; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceRow.java
1
请完成以下Java代码
public void setLot (java.lang.String Lot) { set_Value (COLUMNNAME_Lot, Lot); } /** Get Los-Nr.. @return Los-Nummer (alphanumerisch) */ @Override public java.lang.String getLot () { return (java.lang.String)get_Value(COLUMNNAME_Lot); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_Product_LotNumber_Quarantine. @param M_Product_LotNumber_Quarantine_ID M_Product_LotNumber_Quarantine */ @Override public void setM_Product_LotNumber_Quarantine_ID (int M_Product_LotNumber_Quarantine_ID) { if (M_Product_LotNumber_Quarantine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, Integer.valueOf(M_Product_LotNumber_Quarantine_ID)); } /** Get M_Product_LotNumber_Quarantine. @return M_Product_LotNumber_Quarantine */ @Override public int getM_Product_LotNumber_Quarantine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_LotNumber_Quarantine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\product\model\X_M_Product_LotNumber_Quarantine.java
1
请完成以下Java代码
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
请完成以下Java代码
public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids) { if (ids.isEmpty()) { return LookupValuesList.EMPTY; } return ids.stream() .map(NullLookupDataSource::toUnknownLookupValue) .filter(Objects::nonNull) .collect(LookupValuesList.collect()); } @Override public List<CCacheStats> getCacheStats()
{ return ImmutableList.of(); } @Override public void cacheInvalidate() { } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\NullLookupDataSource.java
1
请完成以下Java代码
public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public byte[] getBytes() { return bytes; } @Override public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override
public Object getPersistentState() { return DmnResourceEntityImpl.class; } @Override public boolean isGenerated() { return false; } @Override public void setGenerated(boolean generated) { this.generated = generated; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "ResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DmnResourceEntityImpl.java
1
请完成以下Java代码
public class MActivity extends X_C_Activity { /** * */ private static final long serialVersionUID = 3014706648686670575L; /** Static Cache */ private static CCache<Integer, MActivity> s_cache = new CCache<Integer, MActivity>(Table_Name, 30); /** * Get/Load Activity [CACHED] * @param ctx context * @param C_Activity_ID * @return activity or null */ public static MActivity get(Properties ctx, int C_Activity_ID) { if (C_Activity_ID <= 0) { return null; } // Try cache MActivity activity = s_cache.get(C_Activity_ID); if (activity != null) { return activity; } // Load from DB activity = new MActivity(ctx, C_Activity_ID, null); if (activity.get_ID() == C_Activity_ID) { s_cache.put(C_Activity_ID, activity); } else { activity = null; } return activity; } /** * Standard Constructor * @param ctx context * @param C_Activity_ID id * @param trxName transaction */ public MActivity (Properties ctx, int C_Activity_ID, String trxName) { super (ctx, C_Activity_ID, trxName); } // MActivity /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MActivity (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MActivity
/** * After Save. * Insert * - create tree * @param newRecord insert * @param success save success * @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (newRecord) insert_Tree(MTree_Base.TREETYPE_Activity); // Value/Name change if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) MAccount.updateValueDescription(getCtx(), "C_Activity_ID=" + getC_Activity_ID(), get_TrxName()); return true; } // afterSave /** * After Delete * @param success * @return deleted */ protected boolean afterDelete (boolean success) { if (success) delete_Tree(MTree_Base.TREETYPE_Activity); return success; } // afterDelete } // MActivity
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MActivity.java
1
请在Spring Boot框架中完成以下Java代码
public void setPort(@Nullable Integer port) { this.port = port; } public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public String getProtocol() { return this.protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public Charset getDefaultEncoding() { return this.defaultEncoding; } public void setDefaultEncoding(Charset defaultEncoding) { this.defaultEncoding = defaultEncoding; } public Map<String, String> getProperties() { return this.properties; } public @Nullable String getJndiName() { return this.jndiName; } public void setJndiName(@Nullable String jndiName) { this.jndiName = jndiName; } public Ssl getSsl() { return this.ssl; } public static class Ssl {
/** * Whether to enable SSL support. If enabled, 'mail.(protocol).ssl.enable' * property is set to 'true'. */ private boolean enabled; /** * SSL bundle name. If set, 'mail.(protocol).ssl.socketFactory' property is set to * an SSLSocketFactory obtained from the corresponding SSL bundle. * <p> * Note that the STARTTLS command can use the corresponding SSLSocketFactory, even * if the 'mail.(protocol).ssl.enable' property is not set. */ private @Nullable String bundle; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } }
repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailProperties.java
2
请完成以下Java代码
public boolean login() throws LoginException { this.authen = this.securityContextHolderStrategy.getContext().getAuthentication(); if (this.authen != null) { return true; } String msg = "Login cannot complete, authentication not found in security context"; if (!this.ignoreMissingAuthentication) { throw new LoginException(msg); } log.warn(msg); return false; } /** * Log out the <code>Subject</code>.
* @return true if this method succeeded, or false if this <code>LoginModule</code> * should be ignored. */ @Override public boolean logout() { if (this.authen == null) { return false; } Assert.notNull(this.subject, "subject cannot be null"); this.subject.getPrincipals().remove(this.authen); this.authen = null; return true; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\jaas\SecurityContextLoginModule.java
1
请在Spring Boot框架中完成以下Java代码
public Result<IPage<OssFile>> queryPageList(OssFile file, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { Result<IPage<OssFile>> result = new Result<>(); QueryWrapper<OssFile> queryWrapper = QueryGenerator.initQueryWrapper(file, req.getParameterMap()); Page<OssFile> page = new Page<>(pageNo, pageSize); IPage<OssFile> pageList = ossFileService.page(page, queryWrapper); result.setSuccess(true); result.setResult(pageList); return result; } @ResponseBody @PostMapping("/upload") //@RequiresRoles("admin") @RequiresPermissions("system:ossFile:upload") public Result upload(@RequestParam("file") MultipartFile multipartFile) { Result result = new Result(); try { ossFileService.upload(multipartFile); result.success("上传成功!"); } catch (Exception ex) { log.info(ex.getMessage(), ex); result.error500("上传失败"); } return result; } @ResponseBody @DeleteMapping("/delete") public Result delete(@RequestParam(name = "id") String id) { Result result = new Result(); OssFile file = ossFileService.getById(id); if (file == null) { result.error500("未找到对应实体"); }else { boolean ok = ossFileService.delete(file); result.success("删除成功!"); } return result;
} /** * 通过id查询. */ @ResponseBody @GetMapping("/queryById") public Result<OssFile> queryById(@RequestParam(name = "id") String id) { Result<OssFile> result = new Result<>(); OssFile file = ossFileService.getById(id); if (file == null) { result.error500("未找到对应实体"); } else { result.setResult(file); result.setSuccess(true); } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\oss\controller\OssFileController.java
2
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306 spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.dat
asource.initialization-mode=always spring.datasource.platform=mysql spring.jpa.open-in-view=false
repos\Hibernate-SpringBoot-master\HibernateSpringBootMatchEntitiesToTablesTwoSchemas\src\main\resources\application.properties
2
请完成以下Java代码
public @Nullable WebServer getWebServer() { return this.webServer; } /** * Utility class to store and restore any user defined scopes. This allows scopes to * be registered in an ApplicationContextInitializer in the same way as they would in * a classic non-embedded web application context. */ public static class ExistingWebApplicationScopes { private static final Set<String> SCOPES; static { Set<String> scopes = new LinkedHashSet<>(); scopes.add(WebApplicationContext.SCOPE_REQUEST); scopes.add(WebApplicationContext.SCOPE_SESSION); SCOPES = Collections.unmodifiableSet(scopes); } private final ConfigurableListableBeanFactory beanFactory; private final Map<String, Scope> scopes = new HashMap<>(); public ExistingWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) { this.beanFactory = beanFactory; for (String scopeName : SCOPES) { Scope scope = beanFactory.getRegisteredScope(scopeName);
if (scope != null) { this.scopes.put(scopeName, scope); } } } public void restore() { this.scopes.forEach((key, value) -> { if (logger.isInfoEnabled()) { logger.info("Restoring user defined scope " + key); } this.beanFactory.registerScope(key, value); }); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletWebServerApplicationContext.java
1
请完成以下Java代码
static void main(String[] args) { String mode = System.getProperty("jarmode"); boolean disableSystemExit = Boolean.getBoolean(DISABLE_SYSTEM_EXIT); try { runJarMode(mode, args); if (disableSystemExit) { System.setProperty(SUPPRESSED_SYSTEM_EXIT_CODE, "0"); } } catch (Throwable ex) { printError(ex); if (disableSystemExit) { System.setProperty(SUPPRESSED_SYSTEM_EXIT_CODE, "1"); return; } System.exit(1); } } private static void runJarMode(String mode, String[] args) { List<JarMode> candidates = SpringFactoriesLoader.loadFactories(JarMode.class,
ClassUtils.getDefaultClassLoader()); for (JarMode candidate : candidates) { if (candidate.accepts(mode)) { candidate.run(mode, args); return; } } throw new JarModeErrorException("Unsupported jarmode '" + mode + "'"); } private static void printError(Throwable ex) { if (ex instanceof JarModeErrorException) { String message = ex.getMessage(); System.err.println("Error: " + message); System.err.println(); return; } ex.printStackTrace(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\JarModeRunner.java
1
请完成以下Java代码
public String getSerNo () { return (String)get_Value(COLUMNNAME_SerNo); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_ValueNoCheck (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL);
} /** Set Version No. @param VersionNo Version Number */ public void setVersionNo (String VersionNo) { set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo); } /** Get Version No. @return Version Number */ public String getVersionNo () { return (String)get_Value(COLUMNNAME_VersionNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Delivery.java
1
请完成以下Java代码
public void sendNotification(@NonNull final WFUserNotification notification) { notificationBL.sendAfterCommit(UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC) .recipientUserId(notification.getUserId()) .contentADMessage(notification.getContent().getAdMessage()) .contentADMessageParams(notification.getContent().getParams()) .targetAction(notification.getDocumentToOpen() != null ? UserNotificationRequest.TargetRecordAction.of(notification.getDocumentToOpen()) : null) .build()); } public MailTextBuilder newMailTextBuilder( @NonNull final TableRecordReference documentRef, @NonNull final MailTemplateId mailTemplateId) { return mailService.newMailTextBuilder(mailTemplateId) .recordAndUpdateBPartnerAndContact(getPO(documentRef)); }
public void save(@NonNull final WFEventAudit audit) { auditRepo.save(audit); } public void addEventAudit(@NonNull final WFEventAudit audit) { auditList.add(audit); } public void createNewAttachment( @NonNull final Object referencedRecord, @NonNull final File file) { attachmentEntryService.createNewAttachment(referencedRecord, file); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WorkflowExecutionContext.java
1
请完成以下Java代码
public abstract class ExecutableScript { /** The language of the script. Used to resolve the * {@link ScriptEngine}. */ protected final String language; protected ExecutableScript(String language) { this.language = language; } /** * The language in which the script is written. * @return the language */ public String getLanguage() { return language; } /** * <p>Evaluates the script using the provided engine and bindings</p> * * @param scriptEngine the script engine to use for evaluating the script. * @param variableScope the variable scope of the execution * @param bindings the bindings to use for evaluating the script. * @throws ProcessEngineException in case the script cannot be evaluated. * @return the result of the script evaluation */ public Object execute(ScriptEngine scriptEngine, VariableScope variableScope, Bindings bindings) { return evaluate(scriptEngine, variableScope, bindings); } protected String getActivityIdExceptionMessage(VariableScope variableScope) { String activityId = null; String definitionIdMessage = ""; if (variableScope instanceof DelegateExecution) { activityId = ((DelegateExecution) variableScope).getCurrentActivityId(); definitionIdMessage = " in the process definition with id '" + ((DelegateExecution) variableScope).getProcessDefinitionId() + "'";
} else if (variableScope instanceof TaskEntity) { TaskEntity task = (TaskEntity) variableScope; if (task.getExecution() != null) { activityId = task.getExecution().getActivityId(); definitionIdMessage = " in the process definition with id '" + task.getProcessDefinitionId() + "'"; } if (task.getCaseExecution() != null) { activityId = task.getCaseExecution().getActivityId(); definitionIdMessage = " in the case definition with id '" + task.getCaseDefinitionId() + "'"; } } else if (variableScope instanceof DelegateCaseExecution) { activityId = ((DelegateCaseExecution) variableScope).getActivityId(); definitionIdMessage = " in the case definition with id '" + ((DelegateCaseExecution) variableScope).getCaseDefinitionId() + "'"; } if (activityId == null) { return ""; } else { return " while executing activity '" + activityId + "'" + definitionIdMessage; } } protected abstract Object evaluate(ScriptEngine scriptEngine, VariableScope variableScope, Bindings bindings); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\ExecutableScript.java
1
请完成以下Java代码
private List<FactLine> createFactLines(final FactLine baseLine, final GLDistributionResult glDistribution) { final List<GLDistributionResultLine> glDistributionLines = glDistribution.getResultLines(); if (glDistributionLines.isEmpty()) { return ImmutableList.of(); } final List<FactLine> factLines = new ArrayList<>(glDistributionLines.size()); for (final GLDistributionResultLine glDistributionLine : glDistributionLines) { final FactLine factLine = createFactLine(baseLine, glDistributionLine); if (factLine == null) { continue; } factLines.add(factLine); } return factLines; } private FactLine createFactLine(final FactLine baseLine, final GLDistributionResultLine glDistributionLine) { final BigDecimal amount = glDistributionLine.getAmount(); if (amount.signum() == 0) { return null; } final AccountDimension accountDimension = glDistributionLine.getAccountDimension(); final MAccount account = MAccount.get(Env.getCtx(), accountDimension); final FactLine factLine = FactLine.builder() .services(baseLine.getServices()) .doc(baseLine.getDoc()) .docLine(baseLine.getDocLine()) .docRecordRef(baseLine.getDocRecordRef()) .Line_ID(baseLine.getLine_ID()) .SubLine_ID(baseLine.getSubLine_ID()) .postingType(baseLine.getPostingType()) .acctSchema(baseLine.getAcctSchema()) .account(account) .accountConceptualName(null) .additionalDescription(glDistributionLine.getDescription()) .qty(baseLine.getQty() != null ? Quantitys.of(glDistributionLine.getQty(), baseLine.getQty().getUomId()) : null) .build();
// // Update accounting dimensions factLine.updateFromDimension(AccountDimension.builder() .applyOverrides(accountDimension) .clearC_AcctSchema_ID() .clearSegmentValue(AcctSegmentType.Account) .build()); // Amount setAmountToFactLine(glDistributionLine, factLine); logger.debug("{}", factLine); return factLine; } private void setAmountToFactLine( @NonNull final GLDistributionResultLine glDistributionLine, @NonNull final FactLine factLine) { final Money amount = Money.of(glDistributionLine.getAmount(), glDistributionLine.getCurrencyId()); switch (glDistributionLine.getAmountSign()) { case CREDIT: factLine.setAmtSource(null, amount); break; case DEBIT: factLine.setAmtSource(amount, null); break; case DETECT: if (amount.signum() < 0) { factLine.setAmtSource(null, amount.negate()); } else { factLine.setAmtSource(amount, null); } break; } factLine.convert(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactGLDistributor.java
1
请完成以下Java代码
public void onMessage(Message message) { try { TextMessage textMessage = (TextMessage) message; String producerPing = textMessage.getText(); if (producerPing.equals("marco")) { acknowledge("polo"); } } catch (JMSException e) { throw new IllegalStateException(e); } } private void acknowledge(String text) throws JMSException { Connection connection = null; Session session = null; try { connection = connectionFactory.createConnection(); connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer ackSender = session.createProducer(ackQueue); ackSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage(text); ackSender.send(message); } finally { session.close(); connection.close(); } } }
repos\tutorials-master\spring-ejb-modules\ejb-beans\src\main\java\com\baeldung\ejbspringcomparison\ejb\messagedriven\RecieverMDB.java
1
请在Spring Boot框架中完成以下Java代码
public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @ApiModelProperty(example = "kermit") public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } @ApiModelProperty(example = "kermit") public String getEndUserId() { return endUserId; } public void setEndUserId(String endUserId) { this.endUserId = endUserId; } @ApiModelProperty(example = "3") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "null") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @ApiModelProperty(example = "active") public String getState() { return state; }
public void setState(String state) { this.state = state; } @ApiModelProperty(example = "123") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public PostSaleAuthenticationProgram getAuthenticityVerification() { return authenticityVerification; } public void setAuthenticityVerification(PostSaleAuthenticationProgram authenticityVerification) { this.authenticityVerification = authenticityVerification; } public Program fulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram) { this.fulfillmentProgram = fulfillmentProgram; return this; } /** * Get fulfillmentProgram * * @return fulfillmentProgram **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public EbayFulfillmentProgram getFulfillmentProgram() { return fulfillmentProgram; } public void setFulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram) { this.fulfillmentProgram = fulfillmentProgram; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Program program = (Program)o; return Objects.equals(this.authenticityVerification, program.authenticityVerification) && Objects.equals(this.fulfillmentProgram, program.fulfillmentProgram); } @Override public int hashCode()
{ return Objects.hash(authenticityVerification, fulfillmentProgram); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Program {\n"); sb.append(" authenticityVerification: ").append(toIndentedString(authenticityVerification)).append("\n"); sb.append(" fulfillmentProgram: ").append(toIndentedString(fulfillmentProgram)).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\Program.java
2
请在Spring Boot框架中完成以下Java代码
static RootBeanDefinition parseAuthoritiesPopulator(Element elt, ParserContext parserContext) { String groupSearchFilter = elt.getAttribute(ATT_GROUP_SEARCH_FILTER); String groupSearchBase = elt.getAttribute(ATT_GROUP_SEARCH_BASE); String groupRoleAttribute = elt.getAttribute(ATT_GROUP_ROLE_ATTRIBUTE); String rolePrefix = elt.getAttribute(ATT_ROLE_PREFIX); if (!StringUtils.hasText(groupSearchFilter)) { groupSearchFilter = DEF_GROUP_SEARCH_FILTER; } if (!StringUtils.hasText(groupSearchBase)) { groupSearchBase = DEF_GROUP_SEARCH_BASE; } BeanDefinitionBuilder populator = BeanDefinitionBuilder.rootBeanDefinition(LDAP_AUTHORITIES_POPULATOR_CLASS); populator.getRawBeanDefinition().setSource(parserContext.extractSource(elt)); populator.addConstructorArgValue(parseServerReference(elt, parserContext)); populator.addConstructorArgValue(groupSearchBase);
populator.addPropertyValue("groupSearchFilter", groupSearchFilter); populator.addPropertyValue("searchSubtree", Boolean.TRUE); if (StringUtils.hasText(rolePrefix)) { if ("none".equals(rolePrefix)) { rolePrefix = ""; } populator.addPropertyValue("rolePrefix", rolePrefix); } if (StringUtils.hasLength(groupRoleAttribute)) { populator.addPropertyValue("groupRoleAttribute", groupRoleAttribute); } return (RootBeanDefinition) populator.getBeanDefinition(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapUserServiceBeanDefinitionParser.java
2
请在Spring Boot框架中完成以下Java代码
public int hashCode() { int hashValue = super.hashCode(); hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPool()); return hashValue; } /** * @inheritDoc */ @Override public String toString() { return String.format("ConnectionEndpoint [%1$s] from Pool [%2$s]", super.toString(), getPool().map(Pool::getName).orElse("")); } }
@SuppressWarnings("unused") protected static class SocketCreationException extends RuntimeException { protected SocketCreationException() { } protected SocketCreationException(String message) { super(message); } protected SocketCreationException(Throwable cause) { super(cause); } protected SocketCreationException(String message, Throwable cause) { super(message, cause); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAwareConfiguration.java
2
请完成以下Java代码
public JsonExternalReferenceLookupResponse lookup( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are looking for") // @PathVariable("orgCode") // @NonNull final String orgCode, @RequestBody @NonNull final JsonExternalReferenceLookupRequest request) { return externalReferenceRestControllerService.performLookup(orgCode, request); } // note that we are not going to update references because they are not supposed to change @PostMapping("{orgCode}") public ResponseEntity<?> insert( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are inserting") // @PathVariable("orgCode") // @NonNull final String orgCode, @RequestBody @NonNull final JsonExternalReferenceCreateRequest request) { externalReferenceRestControllerService.performInsert(orgCode, request);
return ResponseEntity.ok().build(); } @PutMapping("/upsert/{orgCode}") public ResponseEntity<?> upsert( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are upserting") // @PathVariable("orgCode") // @Nullable final String orgCode, @RequestBody @NonNull final JsonRequestExternalReferenceUpsert request) { externalReferenceRestControllerService.performUpsert(request, orgCode); return ResponseEntity.ok().build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\v1\ExternalReferenceRestController.java
1
请完成以下Java代码
protected String doIt() throws Exception { createRecord(p_MsgText); // // Set Custom PrintFormat if needed if (p_AD_PrintFormat_ID > 0) { final MPrintFormat pf = MPrintFormat.get(getCtx(), p_AD_PrintFormat_ID, false); getResult().setPrintFormat(pf); } // // Jasper Report else if (isJasperReport()) { startJasper(); } return "OK"; } private void createRecord(String text) { MADBoilerPlate.createSpoolRecord(getCtx(), getAD_Client_ID(), getPinstanceId(), text, get_TrxName()); } private boolean isJasperReport() { final String whereClause = I_AD_Process.COLUMNNAME_AD_Process_ID + "=?" + " AND " + I_AD_Process.COLUMNNAME_JasperReport + " IS NOT NULL"; return new Query(getCtx(), I_AD_Process.Table_Name, whereClause, get_TrxName())
.setParameters(getProcessInfo().getAdProcessId()) .anyMatch(); } private void startJasper() { ProcessInfo.builder() .setCtx(getCtx()) .setProcessCalledFrom(getProcessInfo().getProcessCalledFrom()) .setAD_Client_ID(getAD_Client_ID()) .setAD_User_ID(getAD_User_ID()) .setPInstanceId(getPinstanceId()) .setAD_Process_ID(0) .setTableName(I_T_BoilerPlate_Spool.Table_Name) // .buildAndPrepareExecution() .onErrorThrowException() .executeSync(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilerPlate_Report.java
1
请完成以下Java代码
protected JButton createArrowButton() { return super.createArrowButton(); } public JButton getArrowButton() { return arrowButton; } /** * Set Icon of arrow button * */ public void setIcon(Icon defaultIcon) { ((MetalComboBoxButton)arrowButton).setComboIcon(defaultIcon); } // setIcon /** * Create Popup * * @return {@link AdempiereComboPopup} */ @Override protected ComboPopup createPopup() { final AdempiereComboPopup popup = new AdempiereComboPopup(comboBox); popup.getAccessibleContext().setAccessibleParent(comboBox); return popup; } public ComboPopup getComboPopup() { return popup; } public static final ComboPopup getComboPopup(final JComboBox<?> comboBox) { final ComboBoxUI comboBoxUI = comboBox.getUI(); if (comboBoxUI instanceof AdempiereComboBoxUI) { return ((AdempiereComboBoxUI)comboBoxUI).getComboPopup(); } // // Fallback: // Back door our way to finding the inner JList. // // it is unknown whether this functionality will work outside of Sun's // implementation, but the code is safe and will "fail gracefully" on // other systems // // see javax.swing.plaf.basic.BasicComboBoxUI.getAccessibleChild(JComponent, int) final Accessible a = comboBoxUI.getAccessibleChild(comboBox, 0); if (a instanceof ComboPopup) { return (ComboPopup)a; } else { return null; } }
public static class AdempiereComboPopup extends BasicComboPopup { private static final long serialVersionUID = 3226003169560939486L; public AdempiereComboPopup(final JComboBox<Object> combo) { super(combo); } @Override protected int getPopupHeightForRowCount(final int maxRowCount) { // ensure the combo box sized for the amount of data to be displayed final int itemCount = comboBox.getItemCount(); int rows = itemCount < maxRowCount ? itemCount : maxRowCount; if (rows <= 0) rows = 1; return super.getPopupHeightForRowCount(1) * rows; } @Override protected void configureScroller() { super.configureScroller(); // In case user scrolls inside a combobox popup, we want to prevent closing the popup no matter if it could be scrolled or not. scroller.putClientProperty(AdempiereScrollPaneUI.PROPERTY_DisableWheelEventForwardToParent, true); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereComboBoxUI.java
1
请完成以下Java代码
public abstract class AbstractMonitoringBL implements IMonitoringBL { /** * NOTE: don't access this field on methods which are not synchronized/thread safe. */ private final Map<String, IMeter> names2Meters = new HashMap<String, IMeter>(); @Override public final synchronized IMeter createOrGet(final String moduleName, final String meterName) { Check.errorIf(Check.isEmpty(moduleName), "Param 'moduleName' may not be empty"); Check.errorIf(Check.isEmpty(meterName), "Param 'meterName' may not be empty"); final String jmxName = mkJmxName(moduleName, meterName); if (names2Meters.containsKey(jmxName)) { return names2Meters.get(jmxName); }
final Meter meter = new Meter(); registerJMX(jmxName, meter); names2Meters.put(jmxName, meter); return meter; } private final String mkJmxName(final String moduleName, final String meterName) { final String jmxName = moduleName + ":type=" + meterName; return jmxName; } protected abstract void registerJMX(final String jmxName, final Meter meter); }
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\api\impl\AbstractMonitoringBL.java
1
请完成以下Java代码
private void updateMigrationStatus() { Services.get(IMigrationBL.class).updateStatus(migration); } @Override public String getStatusDescription() { final String statusCode = migration.getStatusCode(); if (action == Action.Apply) { if (X_AD_Migration.STATUSCODE_Applied.equals(statusCode)) { return "Migration successful"; } else if (X_AD_Migration.STATUSCODE_PartiallyApplied.equals(statusCode)) { return "Migration partially applied. Please review migration steps for errors."; } else if (X_AD_Migration.STATUSCODE_Failed.equals(statusCode)) { return "Migration failed. Please review migration steps for errors."; } } else if (action == Action.Rollback) { if (X_AD_Migration.STATUSCODE_Unapplied.equals(statusCode)) { return "Rollback successful."; } else if (X_AD_Migration.STATUSCODE_PartiallyApplied.equals(statusCode)) { return "Migration partially rollback. Please review migration steps for errors."; } else { return "Rollback failed. Please review migration steps for errors."; } } // // Default return "@Action@=" + action + ", @StatusCode@=" + statusCode; } @Override public List<Exception> getExecutionErrors() { if (executionErrors == null) { return Collections.emptyList();
} else { return new ArrayList<>(executionErrors); } } private final void log(String msg, String resolution, boolean isError) { if (isError && !logger.isErrorEnabled()) { return; } if (!isError && !logger.isInfoEnabled()) { return; } final StringBuffer sb = new StringBuffer(); sb.append(Services.get(IMigrationBL.class).getSummary(migration)); if (!Check.isEmpty(msg, true)) { sb.append(": ").append(msg.trim()); } if (resolution != null) { sb.append(" [").append(resolution).append("]"); } if (isError) { logger.error(sb.toString()); } else { logger.info(sb.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutor.java
1
请完成以下Java代码
public class DingTalkNotifier extends AbstractContentNotifier { private static final String DEFAULT_MESSAGE = "#{name} #{id} is #{status}"; private RestTemplate restTemplate; /** * Webhook URI for the DingTalk API. */ private String webhookUrl; /** * Secret for DingTalk. */ @Nullable private String secret; public DingTalkNotifier(InstanceRepository repository, RestTemplate restTemplate) { super(repository); this.restTemplate = restTemplate; } @Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono .fromRunnable(() -> restTemplate.postForEntity(buildUrl(), createMessage(event, instance), Void.class)); } private String buildUrl() { Long timestamp = System.currentTimeMillis(); return String.format("%s&timestamp=%s&sign=%s", webhookUrl, timestamp, getSign(timestamp)); } protected Object createMessage(InstanceEvent event, Instance instance) { Map<String, Object> messageJson = new HashMap<>(); messageJson.put("msgtype", "text"); Map<String, Object> content = new HashMap<>(); content.put("content", createContent(event, instance)); messageJson.put("text", content); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(messageJson, headers); } @Override protected String getDefaultMessage() {
return DEFAULT_MESSAGE; } private String getSign(Long timestamp) { try { String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); return URLEncoder.encode(new String(Base64.encodeBase64(signData)), StandardCharsets.UTF_8); } catch (Exception ex) { log.warn("Failed to sign message", ex); } return ""; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String getWebhookUrl() { return webhookUrl; } public void setWebhookUrl(String webhookUrl) { this.webhookUrl = webhookUrl; } @Nullable public String getSecret() { return secret; } public void setSecret(@Nullable String secret) { this.secret = secret; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\DingTalkNotifier.java
1
请完成以下Java代码
public class EDI_DesadvPackGenerateCSV_FileForSSCC_Labels extends EDI_GenerateCSV_FileForSSCC_Labels { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (context.getSelectionSize().isMoreThanOneSelected()) { final IQueryFilter<I_EDI_Desadv_Pack> selectedRecordsFilter = context.getQueryFilter(I_EDI_Desadv_Pack.class); final int differentConfigsSize = queryBL .createQueryBuilder(I_EDI_Desadv_Pack.class) .filter(selectedRecordsFilter) .andCollect(I_EDI_Desadv.COLUMN_EDI_Desadv_ID, I_EDI_Desadv.class) .create() .list() .stream() .map(ediDesadv -> BPartnerId.ofRepoId(ediDesadv.getC_BPartner_ID())) .map(bpartnerId -> zebraConfigRepository.retrieveZebraConfigId(bpartnerId, zebraConfigRepository.getDefaultZebraConfigId())) .collect(Collectors.toSet()) .size(); if (differentConfigsSize > 1) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(EDI_GenerateCSV_FileForSSCC_Labels.MSG_DIFFERENT_ZEBRA_CONFIG_NOT_SUPPORTED)); } } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final IQueryFilter<I_EDI_Desadv_Pack> selectedRecordsFilter = getProcessInfo() .getQueryFilterOrElse(ConstantQueryFilter.of(false));
final List<EDIDesadvPackId> list = queryBL .createQueryBuilder(I_EDI_Desadv_Pack.class) .filter(selectedRecordsFilter) .create() .stream() .map(I_EDI_Desadv_Pack::getEDI_Desadv_Pack_ID) .map(EDIDesadvPackId::ofRepoId) .collect(ImmutableList.toImmutableList()); if (!Check.isEmpty(list)) { generateCSV_FileForSSCC_Labels(list); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_DesadvPackGenerateCSV_FileForSSCC_Labels.java
1
请完成以下Java代码
public int getAD_OrgType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgType_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_PrintColor getAD_PrintColor() throws RuntimeException { return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name) .getPO(getAD_PrintColor_ID(), get_TrxName()); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_Value (COLUMNNAME_AD_PrintColor_ID, null); else set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgType.java
1
请完成以下Java代码
public String getHelp(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); return adProcessTrl.getHelp(); } public Icon getIcon() { final I_AD_Process adProcess = adProcessSupplier.get(); final String iconName; if (adProcess.getAD_Form_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WINDOW); } else if (adProcess.getAD_Workflow_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WORKFLOW); } else if (adProcess.isReport()) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_REPORT); } else { iconName = MTreeNode.getIconName(MTreeNode.TYPE_PROCESS); } return Images.getImageIcon2(iconName);
} private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get(); } public boolean isEnabled() { return getPreconditionsResolution().isAccepted(); } public boolean isSilentRejection() { return getPreconditionsResolution().isInternal(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\SwingRelatedProcessDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public static String lpadZero(final String value, final int size) { if (value == null) { throw new IllegalArgumentException("value is null"); } final String valueFixed = value.trim(); final String s = "0000000000000000000" + valueFixed; return s.substring(s.length() - size); } public static String mkOwnOrderNumber(final String documentNo) { final String sevenDigitString = documentNo.length() <= 7 ? documentNo : documentNo.substring(documentNo.length() - 7); return "006" + lpadZero(sevenDigitString, 7); } /** * Remove trailing zeros after decimal separator * * @return <code>bd</code> without trailing zeros after separator; if argument is NULL then NULL will be retu */ // NOTE: this is copy-paste of de.metas.util.NumberUtils.stripTrailingDecimalZeros(BigDecimal) public static BigDecimal stripTrailingDecimalZeros(final BigDecimal bd) { if (bd == null) { return null; } // // Remove all trailing zeros BigDecimal result = bd.stripTrailingZeros();
// Fix very weird java 6 bug: stripTrailingZeros doesn't work on 0 itself // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes if (result.signum() == 0) { result = BigDecimal.ZERO; } // // If after removing our scale is negative, we can safely set the scale to ZERO because we don't want to get rid of zeros before decimal point if (result.scale() < 0) { result = result.setScale(0, RoundingMode.UNNECESSARY); } return result; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\Util.java
2
请完成以下Java代码
public class SimplePBEStringEncryptor implements PBEStringEncryptor { private final PBEByteEncryptor delegate; /** * <p>Constructor for SimplePBEStringEncryptor.</p> * * @param delegate a {@link org.jasypt.encryption.pbe.PBEByteEncryptor} object */ public SimplePBEStringEncryptor(PBEByteEncryptor delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override @SneakyThrows public String encrypt(String message) {
return Base64.getEncoder().encodeToString(delegate.encrypt(message.getBytes(StandardCharsets.UTF_8))); } /** {@inheritDoc} */ @Override @SneakyThrows public String decrypt(String encryptedMessage) { return new String(delegate.decrypt(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8); } /** {@inheritDoc} */ @Override @SneakyThrows public void setPassword(String password) { throw new IllegalAccessException("Not Implemented, use delegate"); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimplePBEStringEncryptor.java
1
请完成以下Java代码
public void setOnMouseMove (String script) { addAttribute ("onmousemove", script); } /** * The onmouseout event occurs when the pointing device is moved away from * an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOut (String script) { addAttribute ("onmouseout", script); } /** * The onkeypress event occurs when a key is pressed and released over an * element. This attribute may be used with most elements. * * @param script script */ public void setOnKeyPress (String script) {
addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements. * * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\acronym.java
1
请完成以下Java代码
public I_C_ChargeType getC_ChargeType() throws RuntimeException { return (I_C_ChargeType)MTable.get(getCtx(), I_C_ChargeType.Table_Name) .getPO(getC_ChargeType_ID(), get_TrxName()); } /** Set Charge Type. @param C_ChargeType_ID Charge Type */ public void setC_ChargeType_ID (int C_ChargeType_ID) { if (C_ChargeType_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, Integer.valueOf(C_ChargeType_ID)); } /** Get Charge Type. @return Charge Type */ public int getC_ChargeType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_DocType getC_DocType() throws RuntimeException { return (I_C_DocType)MTable.get(getCtx(), I_C_DocType.Table_Name) .getPO(getC_DocType_ID(), get_TrxName()); } /** Set Document Type. @param C_DocType_ID Document type or rules */ public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Document Type. @return Document type or rules */ public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Allow Negative. @param IsAllowNegative Allow Negative */ public void setIsAllowNegative (boolean IsAllowNegative)
{ set_Value (COLUMNNAME_IsAllowNegative, Boolean.valueOf(IsAllowNegative)); } /** Get Allow Negative. @return Allow Negative */ public boolean isAllowNegative () { Object oo = get_Value(COLUMNNAME_IsAllowNegative); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Allow Positive. @param IsAllowPositive Allow Positive */ public void setIsAllowPositive (boolean IsAllowPositive) { set_Value (COLUMNNAME_IsAllowPositive, Boolean.valueOf(IsAllowPositive)); } /** Get Allow Positive. @return Allow Positive */ public boolean isAllowPositive () { Object oo = get_Value(COLUMNNAME_IsAllowPositive); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType_DocType.java
1
请完成以下Java代码
protected final void collectHUAndItemIds(final Set<Integer> startHUIds, final Set<Integer> huIdsCollector, final Set<Integer> huItemIdsCollector) { Set<Integer> huIdsToCheck = new HashSet<>(startHUIds); while (!huIdsToCheck.isEmpty()) { huIdsCollector.addAll(huIdsToCheck); final Set<Integer> huItemIds = retrieveM_HU_Item_Ids(huIdsToCheck); huItemIdsCollector.addAll(huItemIds); final Set<Integer> includedHUIds = retrieveIncludedM_HUIds(huItemIds); huIdsToCheck = new HashSet<>(includedHUIds); huIdsToCheck.removeAll(huIdsCollector); } } private final Set<Integer> retrieveM_HU_Item_Ids(final Set<Integer> huIds) { if (huIds.isEmpty()) { return Collections.emptySet(); } final List<Integer> huItemIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Item.class, getContext()) .addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds) .create() .listIds();
return new HashSet<>(huItemIdsList); } private final Set<Integer> retrieveIncludedM_HUIds(final Set<Integer> huItemIds) { if (huItemIds.isEmpty()) { return Collections.emptySet(); } final List<Integer> huIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class, getContext()) .addInArrayOrAllFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItemIds) .create() .listIds(); return new HashSet<>(huIdsList); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_SnapshotHandler.java
1
请完成以下Java代码
public DocTypeId getOrderDocTypeIdOrNull(@Nullable final OrderDocType orderDocType, final OrgId orgId) { if (orderDocType == null) { return null; } final DocBaseType docBaseType = DocBaseType.SalesOrder; final DocSubType docSubType; if (OrderDocType.PrepayOrder.equals(orderDocType)) { docSubType = DocSubType.PrepayOrder; } else {
docSubType = DocSubType.StandardOrder; } final I_AD_Org orgRecord = orgsDAO.getById(orgId); final DocTypeQuery query = DocTypeQuery .builder() .docBaseType(docBaseType) .docSubType(docSubType) .adClientId(orgRecord.getAD_Client_ID()) .adOrgId(orgRecord.getAD_Org_ID()) .build(); return docTypeDAO.getDocTypeId(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\DocTypeService.java
1
请完成以下Java代码
public double getUsage() { return NumberUtil.mul(NumberUtil.div(total - free, total, 4), 100); } /** * 获取JDK名称 */ public String getName() { return ManagementFactory.getRuntimeMXBean().getVmName(); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getHome() { return home; } public void setHome(String home) { this.home = home;
} public void setStartTime(String startTime) { this.startTime = startTime; } public String getStartTime() { return DateUtil.formatDateTime(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())); } public void setRunTime(String runTime) { this.runTime = runTime; } public String getRunTime() { long startTime = ManagementFactory.getRuntimeMXBean().getStartTime(); return DateUtil.formatBetween(DateUtil.current(false) - startTime); } }
repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Jvm.java
1
请完成以下Java代码
public abstract class BaseSqlEntity<D> implements BaseEntity<D> { @Id @Column(name = ModelConstants.ID_PROPERTY, columnDefinition = "uuid") @GeneratedId protected UUID id; @Column(name = ModelConstants.CREATED_TIME_PROPERTY, updatable = false) protected long createdTime; public BaseSqlEntity() { } public BaseSqlEntity(BaseData<?> domain) { this.id = domain.getUuidId(); this.createdTime = domain.getCreatedTime(); } public BaseSqlEntity(BaseSqlEntity<?> entity) { this.id = entity.id; this.createdTime = entity.createdTime; } @Override public UUID getUuid() { return id; } @Override public void setUuid(UUID id) { this.id = id; } @Override public long getCreatedTime() { return createdTime; } public void setCreatedTime(long createdTime) { if (createdTime > 0) { this.createdTime = createdTime; } } protected static UUID getUuid(UUIDBased uuidBased) { if (uuidBased != null) { return uuidBased.getId(); } else { return null; } } protected static UUID getTenantUuid(TenantId tenantId) { if (tenantId != null) { return tenantId.getId(); } else {
return EntityId.NULL_UUID; } } protected static <I> I getEntityId(UUID uuid, Function<UUID, I> creator) { return DaoUtil.toEntityId(uuid, creator); } protected static TenantId getTenantId(UUID uuid) { if (uuid != null && !uuid.equals(EntityId.NULL_UUID)) { return TenantId.fromUUID(uuid); } else { return TenantId.SYS_TENANT_ID; } } protected JsonNode toJson(Object value) { if (value != null) { return JacksonUtil.valueToTree(value); } else { return null; } } protected <T> T fromJson(JsonNode json, Class<T> type) { return JacksonUtil.convertValue(json, type); } protected String listToString(List<?> list) { if (list != null) { return StringUtils.join(list, ','); } else { return ""; } } protected <E> List<E> listFromString(String string, Function<String, E> mappingFunction) { if (string != null) { return Arrays.stream(StringUtils.split(string, ',')) .filter(StringUtils::isNotBlank) .map(mappingFunction).collect(Collectors.toList()); } else { return Collections.emptyList(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\BaseSqlEntity.java
1
请完成以下Java代码
public static AuthenticatorAttestationResponseBuilder builder() { return new AuthenticatorAttestationResponseBuilder(); } /** * Builds {@link AuthenticatorAssertionResponse}. * * @author Rob Winch * @since 6.4 */ public static final class AuthenticatorAttestationResponseBuilder { @SuppressWarnings("NullAway.Init") private Bytes attestationObject; private @Nullable List<AuthenticatorTransport> transports; @SuppressWarnings("NullAway.Init") private Bytes clientDataJSON; private AuthenticatorAttestationResponseBuilder() { } /** * Sets the {@link #getAttestationObject()} property. * @param attestationObject the attestation object. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder attestationObject(Bytes attestationObject) { this.attestationObject = attestationObject; return this; } /** * Sets the {@link #getTransports()} property. * @param transports the transports * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder transports(AuthenticatorTransport... transports) { return transports(Arrays.asList(transports)); } /** * Sets the {@link #getTransports()} property. * @param transports the transports
* @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder transports(List<AuthenticatorTransport> transports) { this.transports = transports; return this; } /** * Sets the {@link #getClientDataJSON()} property. * @param clientDataJSON the client data JSON. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder clientDataJSON(Bytes clientDataJSON) { this.clientDataJSON = clientDataJSON; return this; } /** * Builds a {@link AuthenticatorAssertionResponse}. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponse build() { return new AuthenticatorAttestationResponse(this.clientDataJSON, this.attestationObject, this.transports); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorAttestationResponse.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public double getItemPrice() { return itemPrice; } public void setItemPrice(double itemPrice) { this.itemPrice = itemPrice; } public ItemType getItemType() { return itemType; } public void setItemType(ItemType itemType) { this.itemType = itemType; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public Seller getSeller() { return seller;
} public void setSeller(Seller seller) { this.seller = seller; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; return id == item.id && Double.compare(item.itemPrice, itemPrice) == 0 && Objects.equals(itemName, item.itemName) && itemType == item.itemType && Objects.equals(createdOn, item.createdOn) && Objects.equals(seller, item.seller); } @Override public int hashCode() { return Objects.hash(id, itemName, itemPrice, itemType, createdOn, seller); } }
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkeyjoincolumn\Item.java
1
请完成以下Java代码
public void registerChannelModel(ChannelModel channelModel, String tenantId, EventRegistry eventRegistry, EventRepositoryService eventRepositoryService, boolean fallbackToDefaultTenant) { if (channelModel instanceof DelegateExpressionInboundChannelModel) { registerChannelModel((DelegateExpressionInboundChannelModel) channelModel, tenantId, eventRegistry); } } protected void registerChannelModel(DelegateExpressionInboundChannelModel channelModel, String tenantId, EventRegistry eventRegistry) { String delegateExpression = channelModel.getAdapterDelegateExpression(); if (StringUtils.isNotEmpty(delegateExpression)) { VariableContainerWrapper variableContainer = new VariableContainerWrapper(Collections.emptyMap()); variableContainer.setVariable("tenantId", tenantId); variableContainer.setTenantId(tenantId); Object channelAdapter = engineConfiguration.getExpressionManager() .createExpression(delegateExpression) .getValue(variableContainer); if (!(channelAdapter instanceof InboundEventChannelAdapter)) { throw new FlowableException( "DelegateExpression inbound channel model with key " + channelModel.getKey() + " resolved channel adapter delegate expression to " + channelAdapter + " which is not of type " + InboundEventChannelAdapter.class); } channelModel.setInboundEventChannelAdapter(channelAdapter); ((InboundEventChannelAdapter) channelAdapter).setEventRegistry(eventRegistry); ((InboundEventChannelAdapter) channelAdapter).setInboundChannelModel(channelModel);
} } @Override public void unregisterChannelModel(ChannelModel channelModel, String tenantId, EventRepositoryService eventRepositoryService) { // Nothing to do } public HasExpressionManagerEngineConfiguration getEngineConfiguration() { return engineConfiguration; } public void setEngineConfiguration(HasExpressionManagerEngineConfiguration engineConfiguration) { this.engineConfiguration = engineConfiguration; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\pipeline\DelegateExpressionInboundChannelModelProcessor.java
1
请完成以下Java代码
protected void resetAdditional(@NonNull final JsonCacheResetResponse response, @NonNull final JsonCacheResetRequest request) { { final boolean forgetNotSavedDocuments = request.getValueAsBoolean(CACHE_RESET_PARAM_forgetNotSavedDocuments); final String documentsResult = documentCollection.cacheReset(forgetNotSavedDocuments); response.addLog("documents: " + documentsResult + " (" + CACHE_RESET_PARAM_forgetNotSavedDocuments + "=" + forgetNotSavedDocuments + ")"); } { menuTreeRepo.cacheReset(); response.addLog("menuTreeRepo: cache invalidated"); } { processesController.cacheReset(); response.addLog("processesController: cache invalidated"); } { ViewColumnHelper.cacheReset();
response.addLog("viewColumnHelper: cache invalidated"); } } @GetMapping("/lookups/stats") public JsonGetStatsResponse getLookupCacheStats() { assertAuth(); return lookupDataSourceFactory.getCacheStats() .stream() .sorted(DEFAULT_ORDER_BY) .map(JsonCacheStats::of) .collect(JsonGetStatsResponse.collect()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\admin\CacheRestController.java
1
请完成以下Java代码
public void setRevision(int revision) { this.revision = revision; } public void setPermissions(int permissions) { this.permissions = permissions; } public int getPermissions() { return permissions; } public Set<Permission> getCachedPermissions() { return cachedPermissions; } public int getRevisionNext() { return revision + 1; } public Object getPersistentState() { HashMap<String, Object> state = new HashMap<String, Object>(); state.put("userId", userId); state.put("groupId", groupId); state.put("resourceType", resourceType); state.put("resourceId", resourceId); state.put("permissions", permissions); state.put("removalTime", removalTime); state.put("rootProcessInstanceId", rootProcessInstanceId); return state; } @Override public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId;
} @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", authorizationType=" + authorizationType + ", permissions=" + permissions + ", userId=" + userId + ", groupId=" + groupId + ", resourceType=" + resourceType + ", resourceId=" + resourceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationEntity.java
1
请完成以下Java代码
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 de.metas.async.model.I_C_Async_Batch getParent_Async_Batch() { return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class); } @Override public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch) { set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch); } @Override public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID)
{ if (Parent_Async_Batch_ID < 1) set_Value (COLUMNNAME_Parent_Async_Batch_ID, null); else set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID); } @Override public int getParent_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java
1
请完成以下Java代码
private PropertySource<?> makeEncryptable(PropertySource<?> propertySource) { return propertyConverter.makeEncryptable(propertySource); } /** {@inheritDoc} */ @Override public void addFirst(PropertySource<?> propertySource) { envCopy.addFirst(propertySource); super.addFirst(makeEncryptable(propertySource)); } /** {@inheritDoc} */ @Override public void addLast(PropertySource<?> propertySource) { envCopy.addLast(propertySource); super.addLast(makeEncryptable(propertySource)); } /** {@inheritDoc} */ public void addLastClean(PropertySource<?> propertySource) { envCopy.addLast(propertySource); super.addLast(propertySource); } /** {@inheritDoc} */ @Override public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) { envCopy.addBefore(relativePropertySourceName, propertySource); super.addBefore(relativePropertySourceName, makeEncryptable(propertySource)); } /** {@inheritDoc} */ @Override
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) { envCopy.addAfter(relativePropertySourceName, propertySource); super.addAfter(relativePropertySourceName, makeEncryptable(propertySource)); } /** {@inheritDoc} */ @Override public void replace(String name, PropertySource<?> propertySource) { envCopy.replace(name, propertySource); super.replace(name, makeEncryptable(propertySource)); } /** {@inheritDoc} */ @Override public PropertySource<?> remove(String name) { envCopy.remove(name); PropertySource<?> ps = super.remove(name); // Return the original source unwrapping the Encryptable wrappers. Spring boot does some weird things // with property sources by type on its initialization. In particular, BootstrapApplicationListener // reorders property sources by removing sources by name and applies type checks which break when // the returned property source type is not what Spring Boot expects. while (ps instanceof EncryptablePropertySource) { ps = ((EncryptablePropertySource<?>) ps).getDelegate(); } return ps; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableMutablePropertySourcesWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public void configure() { JacksonDataFormat jacksonDataFormat = new JacksonDataFormat(); jacksonDataFormat.setPrettyPrint(true); from("direct:sendWhatsAppMessage") .setHeader("Authorization", constant("Bearer " + apiToken)) .setHeader("Content-Type", constant("application/json")) .marshal(jacksonDataFormat) .process(exchange -> { logger.debug("Sending JSON: {}", exchange.getIn().getBody(String.class)); }).to(apiUrl).process(exchange -> { logger.debug("Response: {}", exchange.getIn().getBody(String.class)); }); } }); } public void sendWhatsAppMessage(String toNumber, String message) { Map<String, Object> body = new HashMap<>(); body.put("messaging_product", "whatsapp"); body.put("to", toNumber); body.put("type", "text"); Map<String, String> text = new HashMap<>(); text.put("body", message); body.put("text", text); producerTemplate.sendBody("direct:sendWhatsAppMessage", body); }
public void processIncomingMessage(String payload) { try { JsonNode jsonNode = objectMapper.readTree(payload); JsonNode messages = jsonNode.at("/entry/0/changes/0/value/messages"); if (messages.isArray() && messages.size() > 0) { String receivedText = messages.get(0).at("/text/body").asText(); String fromNumber = messages.get(0).at("/from").asText(); logger.debug(fromNumber + " sent the message: " + receivedText); this.sendWhatsAppMessage(fromNumber, chatbotService.getResponse(receivedText)); } } catch (Exception e) { logger.error("Error processing incoming payload: {} ", payload, e); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-3\src\main\java\com\baeldung\chatbot\service\WhatsAppService.java
2
请完成以下Java代码
public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * * @return AD_User_ID */ @Override public int getDoc_User_ID() { return getCreatedBy(); } // getDoc_User_ID /** * Get Document Currency * * @return C_Currency_ID */ @Override public int getC_Currency_ID() { // MPriceList pl = MPriceList.get(getCtx(), getM_PriceList_ID()); // return pl.getC_Currency_ID(); return 0; } // getC_Currency_ID /** * Is Reversal * * @return true if this movement is a reversal of an original movement */ private boolean isReversal()
{ return Services.get(IMovementBL.class).isReversal(this); } // isReversal /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MMovement
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMovement.java
1
请完成以下Java代码
public void onDelete(final ICalloutRecord calloutRecord) { try { tabCallout.onDelete(calloutRecord); } catch (final Exception e) { handleException("onDelete", calloutRecord, e); } } @Override public void onRefresh(final ICalloutRecord calloutRecord) { try { tabCallout.onRefresh(calloutRecord); } catch (final Exception e) { handleException("onRefresh", calloutRecord, e); } } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { try { tabCallout.onRefreshAll(calloutRecord); } catch (final Exception e) { handleException("onRefreshAll", calloutRecord, e); }
} @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { try { tabCallout.onAfterQuery(calloutRecord); } catch (final Exception e) { handleException("onAfterQuery", calloutRecord, e); } } private static final class StatefulExceptionHandledTabCallout extends ExceptionHandledTabCallout implements IStatefulTabCallout { private StatefulExceptionHandledTabCallout(final IStatefulTabCallout tabCallout) { super(tabCallout); } @Override public void onInit(final ICalloutRecord calloutRecord) { try { ((IStatefulTabCallout)tabCallout).onInit(calloutRecord); } catch (final Exception e) { handleException("onInit", calloutRecord, e); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\ExceptionHandledTabCallout.java
1
请完成以下Java代码
private ImmutableSet<ProductId> extractProductIds(final IHUStorage storage) { return storage.getProductStorages() .stream() .map(IHUProductStorage::getProductId) .collect(ImmutableSet.toImmutableSet()); } private I_M_HU extractHU(final ViewRowAttributesKey key) { final HuId huId = HuId.ofRepoId(key.getHuId().toInt()); final I_M_HU hu = handlingUnitsRepo.getByIdOutOfTrx(huId); if (hu == null) { throw new IllegalArgumentException("No HU found for M_HU_ID=" + huId); } return hu; } private static DocumentPath toDocumentPath(final ViewRowAttributesKey key) { final DocumentId documentTypeId = key.getHuId(); final DocumentId huEditorRowId = key.getHuEditorRowId(); return DocumentPath.rootDocumentPath(DocumentType.ViewRecordAttributes, documentTypeId, huEditorRowId); } private IAttributeStorageFactory getAttributeStorageFactory() { return _attributeStorageFactory.get(); } private IAttributeStorageFactory createAttributeStorageFactory() {
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); return attributeStorageFactoryService.createHUAttributeStorageFactory(storageFactory); } @Override public void invalidateAll() { // // Destroy AttributeStorageFactory _attributeStorageFactory.forget(); // // Destroy attribute documents rowAttributesByKey.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesProvider.java
1
请在Spring Boot框架中完成以下Java代码
public void updateWhileSaving( @NonNull final I_SAP_GLJournal record, @NonNull final Consumer<SAPGLJournal> consumer) { final SAPGLJournalId glJournalId = SAPGLJournalLoaderAndSaver.extractId(record); final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.addToCacheAndAvoidSaving(record); loaderAndSaver.updateById(glJournalId, consumer); } public void updateById( @NonNull final SAPGLJournalId glJournalId, @NonNull final Consumer<SAPGLJournal> consumer) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.updateById(glJournalId, consumer); } public <R> R updateById( @NonNull final SAPGLJournalId glJournalId, @NonNull final Function<SAPGLJournal, R> processor) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); return loaderAndSaver.updateById(glJournalId, processor); } public DocStatus getDocStatus(final SAPGLJournalId glJournalId) { final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); return loader.getDocStatus(glJournalId); } @NonNull
public SAPGLJournal create( @NonNull final SAPGLJournalCreateRequest createRequest, @NonNull final SAPGLJournalCurrencyConverter currencyConverter) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); return loaderAndSaver.create(createRequest, currencyConverter); } public void save(@NonNull final SAPGLJournal sapglJournal) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.save(sapglJournal); } public SAPGLJournalLineId acquireLineId(@NonNull final SAPGLJournalId sapGLJournalId) { final int lineRepoId = DB.getNextID(ClientId.METASFRESH.getRepoId(), I_SAP_GLJournalLine.Table_Name); return SAPGLJournalLineId.ofRepoId(sapGLJournalId, lineRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalRepository.java
2
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique
*/ @Override public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Payroll.java
1
请完成以下Java代码
public Food.FoodDelivery buildData() { Food.FoodDelivery.Builder foodData = Food.FoodDelivery.newBuilder(); Food.Menu pizzaMenu = Food.Menu.newBuilder() .putItems("Margherita", 12.99f) .putItems("Pepperoni", 14.99f) .build(); Food.Menu sushiMenu = Food.Menu.newBuilder() .putItems("Salmon Roll", 10.50f) .putItems("Tuna Roll", 12.33f) .build(); foodData.putRestaurants("Pizza Place", pizzaMenu); foodData.putRestaurants("Sushi Place", sushiMenu); return foodData.build(); } public void serializeToFile(Food.FoodDelivery delivery) { try (FileOutputStream fos = new FileOutputStream(FILE_PATH)) { delivery.writeTo(fos); logger.info("Successfully wrote to the file."); } catch (IOException ioe) { logger.warning("Error serializing the Map or writing the file"); } } public Food.FoodDelivery deserializeFromFile(Food.FoodDelivery delivery) { try (FileInputStream fis = new FileInputStream(FILE_PATH)) { return Food.FoodDelivery.parseFrom(fis); } catch (FileNotFoundException e) { logger.severe(String.format("File not found: %s location", FILE_PATH)); return Food.FoodDelivery.newBuilder()
.build(); } catch (IOException e) { logger.warning(String.format("Error reading file: %s location", FILE_PATH)); return Food.FoodDelivery.newBuilder() .build(); } } public void displayRestaurants(Food.FoodDelivery delivery) { Map<String, Food.Menu> restaurants = delivery.getRestaurantsMap(); for (Map.Entry<String, Food.Menu> restaurant : restaurants.entrySet()) { logger.info("Restaurant: " + restaurant.getKey()); restaurant.getValue() .getItemsMap() .forEach((menuItem, price) -> logger.info(String.format(" - %s costs $ %f", menuItem, price))); } } }
repos\tutorials-master\google-protocol-buffer\src\main\java\com\baeldung\mapinprotobuf\FoodDelivery.java
1
请完成以下Java代码
public String getIncidentMessageLike() { return incidentMessageLike; } public String getVersionTag() { return versionTag; } public boolean isStartableInTasklist() { return isStartableInTasklist; } public boolean isNotStartableInTasklist() { return isNotStartableInTasklist; } public boolean isStartablePermissionCheck() { return startablePermissionCheck; } public void setProcessDefinitionCreatePermissionChecks(List<PermissionCheck> processDefinitionCreatePermissionChecks) { this.processDefinitionCreatePermissionChecks = processDefinitionCreatePermissionChecks; } public List<PermissionCheck> getProcessDefinitionCreatePermissionChecks() { return processDefinitionCreatePermissionChecks; } public boolean isShouldJoinDeploymentTable() { return shouldJoinDeploymentTable; } public void addProcessDefinitionCreatePermissionCheck(CompositePermissionCheck processDefinitionCreatePermissionCheck) { processDefinitionCreatePermissionChecks.addAll(processDefinitionCreatePermissionCheck.getAllPermissionChecks()); }
public List<String> getCandidateGroups() { if (cachedCandidateGroups != null) { return cachedCandidateGroups; } if(authorizationUserId != null) { List<Group> groups = Context.getCommandContext() .getReadOnlyIdentityProvider() .createGroupQuery() .groupMember(authorizationUserId) .list(); cachedCandidateGroups = groups.stream().map(Group::getId).collect(Collectors.toList()); } return cachedCandidateGroups; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class EventConsumer { private final Logger LOGGER = LoggerFactory.getLogger(EventConsumer.class); private final Map<String, DataMessageAsyncEvent> messages; private final AccountService accountService; @Autowired public EventConsumer(AccountService accountService) { this.accountService = accountService; this.messages = new ConcurrentHashMap<>(); } public Collection<DataMessageAsyncEvent> getMessages() { return Collections.unmodifiableCollection(this.messages.values()); } public void resetMessages() { this.messages.clear(); } @KafkaListener(topics = "prod-con-test-topic") public void consume(EventWrapper<? extends AsyncEvent> message) throws IOException { LOGGER.info("#### Consumed message -> {} {}", message.getType()); if (message.getType().equals(DataMessageAsyncEvent.class)) {
EventWrapper<DataMessageAsyncEvent> wrapper = (EventWrapper<DataMessageAsyncEvent>)message; messages.put(wrapper.getEvent().getId(), wrapper.getEvent()); } else if (message.getType().equals(CreateAccountAsyncEvent.class)) { EventWrapper<CreateAccountAsyncEvent> wrapper = (EventWrapper<CreateAccountAsyncEvent>)message; accountService.createAccount(wrapper.getEvent()); } else if (message.getType().equals(DeleteAccountAsyncEvent.class)) { EventWrapper<DeleteAccountAsyncEvent> wrapper = (EventWrapper<DeleteAccountAsyncEvent>)message; accountService.deleteAccount(wrapper.getEvent()); } else if (message.getType().equals(TransferFundsAsyncEvent.class)) { EventWrapper<TransferFundsAsyncEvent> wrapper = (EventWrapper<TransferFundsAsyncEvent>)message; accountService.transferFunds(wrapper.getEvent()); } else if (message.getType().equals(DepositAccountAsyncEvent.class)) { EventWrapper<DepositAccountAsyncEvent> wrapper = (EventWrapper<DepositAccountAsyncEvent>)message; accountService.depositFunds(wrapper.getEvent()); } else { LOGGER.error("ERROR: unsupported message type {}", message.getType()); } } }
repos\spring-examples-java-17\spring-kafka\kafka-consumer\src\main\java\itx\examples\spring\kafka\consumer\service\EventConsumer.java
2
请在Spring Boot框架中完成以下Java代码
public void handleEvent(@NonNull final PurchaseCandidateAdvisedEvent event) { final SupplyRequiredDescriptor supplyRequiredDescriptor = event.getSupplyRequiredDescriptor(); final DemandDetail demandDetail = DemandDetail.forSupplyRequiredDescriptorOrNull(supplyRequiredDescriptor); final PurchaseDetail purchaseDetail = PurchaseDetail.builder() .qty(supplyRequiredDescriptor.getQtyToSupplyBD()) .vendorRepoId(event.getVendorId()) .purchaseCandidateRepoId(-1) .productPlanningRepoId(event.getProductPlanningId()) .advised(Flag.TRUE) .build(); // see if there is an existing supply candidate to work with Candidate.CandidateBuilder candidateBuilder = null; if (supplyRequiredDescriptor.getSupplyCandidateId() > 0) { final CandidatesQuery supplyCandidateQuery = CandidatesQuery.fromId( CandidateId.ofRepoId(supplyRequiredDescriptor.getSupplyCandidateId())); final Candidate existingCandidate = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(supplyCandidateQuery); if (existingCandidate != null) { candidateBuilder = existingCandidate.toBuilder(); } } if (candidateBuilder == null) { candidateBuilder = Candidate.builder(); } // put out data into the new or preexisting candidate final Candidate supplyCandidate = candidateBuilder .clientAndOrgId(event.getClientAndOrgId()) .id(CandidateId.ofRepoIdOrNull(supplyRequiredDescriptor.getSupplyCandidateId())) .type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PURCHASE) .materialDescriptor(supplyRequiredDescriptor.getMaterialDescriptor()) .businessCaseDetail(purchaseDetail) .additionalDemandDetail(demandDetail) .simulated(supplyRequiredDescriptor.isSimulated()) .build(); final MaterialDispoGroupId groupId = candidateChangeHandler.onCandidateNewOrChange(supplyCandidate).getGroupId().orElse(null); if (event.isDirectlyCreatePurchaseCandidate()) { if (groupId == null) { throw new AdempiereException("No groupId"); } // the group contains just one item, i.e. the supplyCandidate, but for the same of generic-ness we use that same interface that's also used for production and distribution requestMaterialOrderService.requestMaterialOrderForCandidates(groupId, event.getEventDescriptor()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateAdvisedHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class StorageProperties { private String identity; private String credential; private String region; private String bucketName; private String proxyEndpoint; private String localFileBaseDirectory; public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public String getCredential() { return credential; } public void setCredential(String credential) { this.credential = credential; } public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; } public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getProxyEndpoint() { return proxyEndpoint; } public void setProxyEndpoint(String proxyEndpoint) { this.proxyEndpoint = proxyEndpoint; } public String getLocalFileBaseDirectory() { return localFileBaseDirectory; } public void setLocalFileBaseDirectory(String localFileBaseDirectory) { this.localFileBaseDirectory = localFileBaseDirectory; } }
repos\tutorials-master\aws-modules\s3proxy\src\main\java\com\baeldung\s3proxy\StorageProperties.java
2
请完成以下Java代码
public BigDecimal getUrsprungsbetrag() { return ursprungsbetrag; } public void setUrsprungsbetrag(BigDecimal ursprungsbetrag) { this.ursprungsbetrag = ursprungsbetrag; } public String getUrsprungsbetragWaehrung() { return ursprungsbetragWaehrung; } public void setUrsprungsbetragWaehrung(String ursprungsbetragWaehrung) { this.ursprungsbetragWaehrung = ursprungsbetragWaehrung; } public BigDecimal getGebuehrenbetrag() { return gebuehrenbetrag; } public void setGebuehrenbetrag(BigDecimal gebuehrenbetrag) { this.gebuehrenbetrag = gebuehrenbetrag; } public String getGebuehrenbetragWaehrung() { return gebuehrenbetragWaehrung; } public void setGebuehrenbetragWaehrung(String gebuehrenbetragWaehrung) { this.gebuehrenbetragWaehrung = gebuehrenbetragWaehrung; } public String getMehrzweckfeld() { return mehrzweckfeld; } public void setMehrzweckfeld(String mehrzweckfeld) { this.mehrzweckfeld = mehrzweckfeld; } public BigInteger getGeschaeftsvorfallCode() { return geschaeftsvorfallCode; } public void setGeschaeftsvorfallCode(BigInteger geschaeftsvorfallCode) { this.geschaeftsvorfallCode = geschaeftsvorfallCode; } public String getBuchungstext() { return buchungstext; } public void setBuchungstext(String buchungstext) { this.buchungstext = buchungstext; } public String getPrimanotennummer() { return primanotennummer; } public void setPrimanotennummer(String primanotennummer) { this.primanotennummer = primanotennummer; } public String getVerwendungszweck() { return verwendungszweck;
} public void setVerwendungszweck(String verwendungszweck) { this.verwendungszweck = verwendungszweck; } public String getPartnerBlz() { return partnerBlz; } public void setPartnerBlz(String partnerBlz) { this.partnerBlz = partnerBlz; } public String getPartnerKtoNr() { return partnerKtoNr; } public void setPartnerKtoNr(String partnerKtoNr) { this.partnerKtoNr = partnerKtoNr; } public String getPartnerName() { return partnerName; } public void setPartnerName(String partnerName) { this.partnerName = partnerName; } public String getTextschluessel() { return textschluessel; } public void setTextschluessel(String textschluessel) { this.textschluessel = textschluessel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java
1
请完成以下Java代码
class NShiftConfigMap { public static final NShiftConfigMap EMPTY = new NShiftConfigMap(ImmutableList.of()); private final ImmutableMap<ShipperId, NShiftConfig> byShipperId; private NShiftConfigMap(final List<NShiftConfig> list) { this.byShipperId = Maps.uniqueIndex(list, NShiftConfig::getShipperId); } public static NShiftConfigMap ofList(final List<NShiftConfig> list) { return list.isEmpty() ? null : new NShiftConfigMap(list); }
public static Collector<NShiftConfig, ?, NShiftConfigMap> collect() { return GuavaCollectors.collectUsingListAccumulator(NShiftConfigMap::ofList); } public @NonNull NShiftConfig getByShipperId(final @NonNull ShipperId shipperId) { final NShiftConfig config = byShipperId.get(shipperId); if (config == null) { throw new AdempiereException("No config found for shipper: " + shipperId); } return config; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.nshift\src\main\java\de\metas\shipper\gateway\nshift\config\NShiftConfigMap.java
1
请完成以下Java代码
public void reenqueuePPOrders(final I_M_PriceList_Version plv) { final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class); final IQueryBL queryBL = Services.get(IQueryBL.class); final IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class); final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); final IMaterialTrackingPPOrderDAO materialTrackingPPOrderDAO = Services.get(IMaterialTrackingPPOrderDAO.class); final org.compiere.model.I_M_PriceList_Version previousPLV = priceListDAO.retrievePreviousVersionOrNull(plv, true); final ICompositeQueryFilter<I_C_Invoice_Candidate> plvFilter = queryBL.createCompositeQueryFilter(I_C_Invoice_Candidate.class) .setJoinOr() .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_M_PriceList_Version_ID, plv.getM_PriceList_Version_ID()); if (previousPLV != null) { plvFilter.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_M_PriceList_Version_ID, previousPLV.getM_PriceList_Version_ID()); } final int ppOrderTableID = adTableDAO.retrieveTableId(I_PP_Order.Table_Name); final List<Map<String, Object>> listDistinct = queryBL.createQueryBuilder(I_C_Invoice_Candidate.class, plv) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false) .filter(plvFilter) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID, ppOrderTableID) .andCollectChildren(I_C_Invoice_Detail.COLUMN_C_Invoice_Candidate_ID, I_C_Invoice_Detail.class) .addNotEqualsFilter(I_C_Invoice_Detail.COLUMNNAME_PP_Order_ID, null) .orderBy().addColumn(I_C_Invoice_Detail.COLUMNNAME_C_Invoice_Detail_ID).endOrderBy()
.create() .listDistinct(I_C_Invoice_Detail.COLUMNNAME_PP_Order_ID); for (final Map<String, Object> colName2Value : listDistinct) { final Integer ppOrderId = (Integer)colName2Value.get(I_C_Invoice_Detail.COLUMNNAME_PP_Order_ID); if (ppOrderId == null) { continue; // imho this can't happen, but better safe than sorry } final I_PP_Order ppOrder = InterfaceWrapperHelper.create( InterfaceWrapperHelper.getCtx(plv), ppOrderId, I_PP_Order.class, InterfaceWrapperHelper.getTrxName(plv)); ppOrder.setIsInvoiceCandidate(false); InterfaceWrapperHelper.save(ppOrder); // need to delete them, because if a PLV was un-processed, then its IC would not be deleted materialTrackingPPOrderDAO.deleteRelatedUnprocessedICs(ppOrder); invoiceCandidateHandlerBL.invalidateCandidatesFor(ppOrder); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\M_PriceList_Version.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[activityId=" + activityId + ", activityName=" + activityName + ", activityType=" + activityType + ", activityInstanceId=" + activityInstanceId
+ ", activityInstanceState=" + activityInstanceState + ", parentActivityInstanceId=" + parentActivityInstanceId + ", calledProcessInstanceId=" + calledProcessInstanceId + ", calledCaseInstanceId=" + calledCaseInstanceId + ", taskId=" + taskId + ", taskAssignee=" + taskAssignee + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricActivityInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class M_PriceList { @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }) public void assertBasePricingIsValid(final I_M_PriceList priceList) { final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class); // final PriceListVersionId basePriceListVersionId = priceListsRepo.getBasePriceListVersionIdForPricingCalculationOrNull(plv); // if (basePriceListVersionId != null) // { final int basePriceListId = priceList.getBasePriceList_ID(); if (basePriceListId <= 0) { // nothing to do return; } final I_M_PriceList basePriceList = priceListsRepo.getById(basePriceListId); // final CurrencyId baseCurrencyId = CurrencyId.ofRepoId(basePriceList.getC_Currency_ID()); final CurrencyId currencyId = CurrencyId.ofRepoId(priceList.getC_Currency_ID()); if (!CurrencyId.equals(baseCurrencyId, currencyId)) { throw new AdempiereException("@PriceListAndBasePriceListCurrencyMismatchError@") .markAsUserValidationError(); }
final CountryId baseCountryId = CountryId.ofRepoIdOrNull(basePriceList.getC_Country_ID()); final CountryId countryId = CountryId.ofRepoIdOrNull(priceList.getC_Country_ID()); if (!CountryId.equals(baseCountryId, countryId)) { throw new AdempiereException("@PriceListAndBasePriceListCountryMismatchError@") .markAsUserValidationError(); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_PriceList.COLUMNNAME_Name }) public void updatePLVName(@NonNull final I_M_PriceList priceList) { final IPriceListBL priceListBL = Services.get(IPriceListBL.class); priceListBL.updateAllPLVName(priceList.getName(), PriceListId.ofRepoId(priceList.getM_PriceList_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\interceptor\M_PriceList.java
2
请在Spring Boot框架中完成以下Java代码
public List<JAXBElement<ReductionAndSurchargeBaseType>> getReductionListLineItemOrSurchargeListLineItem() { if (reductionListLineItemOrSurchargeListLineItem == null) { reductionListLineItemOrSurchargeListLineItem = new ArrayList<JAXBElement<ReductionAndSurchargeBaseType>>(); } return this.reductionListLineItemOrSurchargeListLineItem; } /** * Gets the value of the totalReductionAndSurchargeListLineItem property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTotalReductionAndSurchargeListLineItem() {
return totalReductionAndSurchargeListLineItem; } /** * Sets the value of the totalReductionAndSurchargeListLineItem property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTotalReductionAndSurchargeListLineItem(BigDecimal value) { this.totalReductionAndSurchargeListLineItem = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ReductionAndSurchargeListLineItemDetailsType.java
2
请在Spring Boot框架中完成以下Java代码
public class RolePermLoggingBL implements IRolePermLoggingBL { @Override public void logWindowAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logWindowAccess(roleId, id, access); } @Override public void logWindowAccess(RoleId roleId, AdWindowId id, Boolean access, String description) { MRolePermRequest.logWindowAccess(roleId, id, access, description); } @Override public void logFormAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logFormAccess(roleId, id, access); } @Override public void logProcessAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logProcessAccess(roleId, id, access); }
@Override public void logTaskAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logTaskAccess(roleId, id, access); } @Override public void logWorkflowAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logWorkflowAccess(roleId, id, access); } @Override public void logDocActionAccess(RoleId roleId, DocTypeId docTypeId, String docAction, Boolean access) { MRolePermRequest.logDocActionAccess(roleId, docTypeId, docAction, access); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\service\impl\RolePermLoggingBL.java
2
请完成以下Java代码
private static class SalesOrderLineCandidate { @Nullable private ProductId bomProductId; private boolean addProductToPriceList; // // Quotation info: @NonNull private final GroupId quotationGroupId; @NonNull private final String quotationGroupName; @NonNull final OrgId orgId; @NonNull final ProductId quotationTemplateProductId;
@NonNull final BigDecimal price; @NonNull final BigDecimal qty; @NonNull final UomId uomId; @NonNull final TaxCategoryId taxCategoryId; // // Additional quotation lines to copy directly @NonNull @Default private final ImmutableList<I_C_OrderLine> additionalQuotationLines = ImmutableList.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\CreateSalesOrderAndBOMsFromQuotationCommand.java
1
请在Spring Boot框架中完成以下Java代码
public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public Attachment contentType(String contentType) { this.contentType = contentType; return this; } /** * MIME type der Datei * @return contentType **/ @Schema(example = "image/png", description = "MIME type der Datei") public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public Attachment uploadDate(String uploadDate) { this.uploadDate = uploadDate; return this; } /** * Der Zeitstempel des Hochladens * @return uploadDate **/ @Schema(example = "2020-11-18T10:33:08.995Z", description = "Der Zeitstempel des Hochladens") public String getUploadDate() { return uploadDate; } public void setUploadDate(String uploadDate) { this.uploadDate = uploadDate; } public Attachment metadata(AttachmentMetadata metadata) { this.metadata = metadata; return this; } /** * Get metadata * @return metadata **/ @Schema(description = "") public AttachmentMetadata getMetadata() { return metadata; } public void setMetadata(AttachmentMetadata metadata) { this.metadata = metadata; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Attachment attachment = (Attachment) o; return Objects.equals(this._id, attachment._id) && Objects.equals(this.filename, attachment.filename) &&
Objects.equals(this.contentType, attachment.contentType) && Objects.equals(this.uploadDate, attachment.uploadDate) && Objects.equals(this.metadata, attachment.metadata); } @Override public int hashCode() { return Objects.hash(_id, filename, contentType, uploadDate, metadata); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Attachment {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" filename: ").append(toIndentedString(filename)).append("\n"); sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); sb.append(" uploadDate: ").append(toIndentedString(uploadDate)).append("\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).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(java.lang.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-document-api\src\main\java\io\swagger\client\model\Attachment.java
2
请在Spring Boot框架中完成以下Java代码
protected DataResponse<HistoricDetailResponse> getQueryResponse(HistoricDetailQueryRequest queryRequest, Map<String, String> allRequestParams) { HistoricDetailQuery query = historyService.createHistoricDetailQuery(); // Populate query based on request if (queryRequest.getProcessInstanceId() != null) { query.processInstanceId(queryRequest.getProcessInstanceId()); } if (queryRequest.getExecutionId() != null) { query.executionId(queryRequest.getExecutionId()); } if (queryRequest.getActivityInstanceId() != null) { query.activityInstanceId(queryRequest.getActivityInstanceId()); } if (queryRequest.getTaskId() != null) { query.taskId(queryRequest.getTaskId()); } if (queryRequest.getSelectOnlyFormProperties() != null) { if (queryRequest.getSelectOnlyFormProperties()) {
query.formProperties(); } } if (queryRequest.getSelectOnlyVariableUpdates() != null) { if (queryRequest.getSelectOnlyVariableUpdates()) { query.variableUpdates(); } } if (restApiInterceptor != null) { restApiInterceptor.accessHistoryDetailInfoWithQuery(query, queryRequest); } return paginateList(allRequestParams, queryRequest, query, "processInstanceId", allowedSortProperties, restResponseFactory::createHistoricDetailResponse); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailBaseResource.java
2
请完成以下Java代码
public String toString() { return defaultValue; } @Override public String translate(final String adLanguage) { return trlMap.getOrDefault(adLanguage, defaultValue); } @Override public String getDefaultValue() { return defaultValue;
} @Override public Set<String> getAD_Languages() { return trlMap.keySet(); } @JsonIgnore // needed for snapshot testing public boolean isEmpty() { return defaultValue.isEmpty() && trlMap.values().stream().allMatch(String::isEmpty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ImmutableTranslatableString.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private int age; private String name; private String genre; @Column(insertable = false, updatable = false) long total; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) {
this.name = name; } public 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; } public long getTotal() { return total; } @Override public String toString() { return "{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootListEntityOffsetPaginationExtraColumn\src\main\java\com\bookstore\entity\Author.java
2
请完成以下Java代码
public void invalidate(@NonNull final CacheInvalidateMultiRequest request, @NonNull final ModelCacheInvalidationTiming timing) { // // Reset model cache // * only on AFTER event // * only if it's not NEW event because in case of NEW, the model was not already in cache, for sure if (timing.isAfter() && !timing.isNew()) { modelCacheService.invalidate(request); } // // Reset cache // NOTE: we need to do it even for newly created records because there are some aggregates which are cached (e.g. all lines for a given document), // so in case a new record pops in, those caches shall be reset.. CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit(ITrx.TRXNAME_ThreadInherited, request); } public CacheInvalidateMultiRequest createRequestOrNull( @NonNull final ICacheSourceModel model, @NonNull final ModelCacheInvalidationTiming timing) { final String tableName = model.getTableName(); final HashSet<CacheInvalidateRequest> requests = getRequestFactoriesByTableName(tableName, timing) .stream() .map(requestFactory -> requestFactory.createRequestsFromModel(model, timing)) .filter(Objects::nonNull) .flatMap(List::stream) .filter(Objects::nonNull) .collect(Collectors.toCollection(HashSet::new)); // final CacheInvalidateRequest request = createChildRecordInvalidateUsingRootRecordReference(model); if (request != null) { requests.add(request); }
// if (requests.isEmpty()) { return null; } return CacheInvalidateMultiRequest.of(requests); } private CacheInvalidateRequest createChildRecordInvalidateUsingRootRecordReference(final ICacheSourceModel model) { final TableRecordReference rootRecordReference = model.getRootRecordReferenceOrNull(); if (rootRecordReference == null) { return null; } final String modelTableName = model.getTableName(); final int modelRecordId = model.getRecordId(); return CacheInvalidateRequest.builder() .rootRecord(rootRecordReference.getTableName(), rootRecordReference.getRecord_ID()) .childRecord(modelTableName, modelRecordId) .build(); } private Set<ModelCacheInvalidateRequestFactory> getRequestFactoriesByTableName(@NonNull final String tableName, @NonNull final ModelCacheInvalidationTiming timing) { final Set<ModelCacheInvalidateRequestFactory> factories = factoryGroups.stream() .flatMap(factoryGroup -> factoryGroup.getFactoriesByTableName(tableName, timing).stream()) .collect(ImmutableSet.toImmutableSet()); return factories != null && !factories.isEmpty() ? factories : DEFAULT_REQUEST_FACTORIES; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ModelCacheInvalidationService.java
1
请完成以下Java代码
public String getTableNameEffective() { return childTableName != null ? childTableName : rootTableName; } public static final class Builder { private String rootTableName; private int rootRecordId = -1; private String childTableName; private int childRecordId = -1; private Builder() { } public CacheInvalidateRequest build() { final String debugFrom = DEBUG ? Trace.toOneLineStackTraceString() : null; return new CacheInvalidateRequest(rootTableName, rootRecordId, childTableName, childRecordId, debugFrom); } public Builder rootRecord(@NonNull final String tableName, final int recordId) {
Check.assume(recordId >= 0, "recordId >= 0"); rootTableName = tableName; rootRecordId = recordId; return this; } public Builder childRecord(@NonNull final String tableName, final int recordId) { Check.assume(recordId >= 0, "recordId >= 0"); childTableName = tableName; childRecordId = recordId; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\CacheInvalidateRequest.java
1
请完成以下Java代码
public JobDefinitionQuery active() { this.suspensionState = SuspensionState.ACTIVE; return this; } public JobDefinitionQuery suspended() { this.suspensionState = SuspensionState.SUSPENDED; return this; } public JobDefinitionQuery withOverridingJobPriority() { this.withOverridingJobPriority = true; return this; } public JobDefinitionQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public JobDefinitionQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public JobDefinitionQuery includeJobDefinitionsWithoutTenantId() { this.includeJobDefinitionsWithoutTenantId = true; return this; } // order by /////////////////////////////////////////// public JobDefinitionQuery orderByJobDefinitionId() { return orderBy(JobDefinitionQueryProperty.JOB_DEFINITION_ID); } public JobDefinitionQuery orderByActivityId() { return orderBy(JobDefinitionQueryProperty.ACTIVITY_ID); } public JobDefinitionQuery orderByProcessDefinitionId() { return orderBy(JobDefinitionQueryProperty.PROCESS_DEFINITION_ID); } public JobDefinitionQuery orderByProcessDefinitionKey() { return orderBy(JobDefinitionQueryProperty.PROCESS_DEFINITION_KEY); } public JobDefinitionQuery orderByJobType() { return orderBy(JobDefinitionQueryProperty.JOB_TYPE); } public JobDefinitionQuery orderByJobConfiguration() { return orderBy(JobDefinitionQueryProperty.JOB_CONFIGURATION); }
public JobDefinitionQuery orderByTenantId() { return orderBy(JobDefinitionQueryProperty.TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefinitionCountByQueryCriteria(this); } @Override public List<JobDefinition> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefnitionByQueryCriteria(this, page); } // getters ///////////////////////////////////////////// public String getId() { return id; } public String[] getActivityIds() { return activityIds; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getJobType() { return jobType; } public String getJobConfiguration() { return jobConfiguration; } public SuspensionState getSuspensionState() { return suspensionState; } public Boolean getWithOverridingJobPriority() { return withOverridingJobPriority; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobDefinitionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public int updateBrand(Long id, PmsBrandParam pmsBrandParam) { PmsBrand pmsBrand = new PmsBrand(); BeanUtils.copyProperties(pmsBrandParam, pmsBrand); pmsBrand.setId(id); //如果创建时首字母为空,取名称的第一个为首字母 if (StrUtil.isEmpty(pmsBrand.getFirstLetter())) { pmsBrand.setFirstLetter(pmsBrand.getName().substring(0, 1)); } //更新品牌时要更新商品中的品牌名称 PmsProduct product = new PmsProduct(); product.setBrandName(pmsBrand.getName()); PmsProductExample example = new PmsProductExample(); example.createCriteria().andBrandIdEqualTo(id); productMapper.updateByExampleSelective(product,example); return brandMapper.updateByPrimaryKeySelective(pmsBrand); } @Override public int deleteBrand(Long id) { return brandMapper.deleteByPrimaryKey(id); } @Override public int deleteBrand(List<Long> ids) { PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.deleteByExample(pmsBrandExample); } @Override public List<PmsBrand> listBrand(String keyword, Integer showStatus, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); PmsBrandExample pmsBrandExample = new PmsBrandExample();
pmsBrandExample.setOrderByClause("sort desc"); PmsBrandExample.Criteria criteria = pmsBrandExample.createCriteria(); if (!StrUtil.isEmpty(keyword)) { criteria.andNameLike("%" + keyword + "%"); } if(showStatus!=null){ criteria.andShowStatusEqualTo(showStatus); } return brandMapper.selectByExample(pmsBrandExample); } @Override public PmsBrand getBrand(Long id) { return brandMapper.selectByPrimaryKey(id); } @Override public int updateShowStatus(List<Long> ids, Integer showStatus) { PmsBrand pmsBrand = new PmsBrand(); pmsBrand.setShowStatus(showStatus); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample); } @Override public int updateFactoryStatus(List<Long> ids, Integer factoryStatus) { PmsBrand pmsBrand = new PmsBrand(); pmsBrand.setFactoryStatus(factoryStatus); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsBrandServiceImpl.java
2
请完成以下Java代码
class JWTAuthenticationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { ofNullable(request.getHeader(AUTHORIZATION)) .map(authHeader -> authHeader.substring("Token ".length())) .map(JWT::new) .ifPresent(getContext()::setAuthentication); filterChain.doFilter(request, response); } @SuppressWarnings("java:S2160") static class JWT extends AbstractAuthenticationToken { private final String token;
private JWT(String token) { super(null); this.token = token; } @Override public Object getPrincipal() { return token; } @Override public Object getCredentials() { return null; } } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\security\JWTAuthenticationFilter.java
1
请完成以下Java代码
public boolean isDeveloperMode() { return developerModeBL.isEnabled(); } public I_M_HU_PI getVirtualPI(final Properties ctx) { return getHandlingUnitsDAO().retrieveVirtualPI(ctx); } public I_M_HU_Item getFirstNotPureVirtualItem(@NonNull final I_M_HU_Item item) { final IHandlingUnitsDAO handlingUnitsDAO = getHandlingUnitsDAO(); I_M_HU_Item itemFirstNotPureVirtual = item; while (itemFirstNotPureVirtual != null && handlingUnitsBL.isPureVirtual(itemFirstNotPureVirtual)) { final I_M_HU parentHU = itemFirstNotPureVirtual.getM_HU(); itemFirstNotPureVirtual = handlingUnitsDAO.retrieveParentItem(parentHU); } // shall not happen if (itemFirstNotPureVirtual == null) { throw new AdempiereException("No not pure virtual HU item found for " + item); } return itemFirstNotPureVirtual; } public boolean isVirtual(final I_M_HU_Item item) { return handlingUnitsBL.isVirtual(item); } public List<I_M_HU_Item> retrieveItems(@NonNull final I_M_HU hu) { return getHandlingUnitsDAO().retrieveItems(hu); } public HUItemType getItemType(final I_M_HU_Item item)
{ return HUItemType.ofCode(handlingUnitsBL.getItemType(item)); } public List<I_M_HU> retrieveIncludedHUs(final I_M_HU_Item item) { return getHandlingUnitsDAO().retrieveIncludedHUs(item); } public I_M_HU_PI getIncluded_HU_PI(@NonNull final I_M_HU_Item item) { return handlingUnitsBL.getIncludedPI(item); } public void deleteHU(final I_M_HU hu) { getHandlingUnitsDAO().delete(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\AllocationStrategySupportingServicesFacade.java
1
请完成以下Java代码
public class Product { private final Money price; public Product(Money price) { super(); this.price = price; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Product other = (Product) obj; if (price == null) { if (other.price != null) { return false; } } else if (!price.equals(other.price)) { return false; } return true; } @Override public int hashCode() { final int prime = 31;
int result = 1; result = prime * result + ((price == null) ? 0 : price.hashCode()); return result; } @Override public String toString() { return "Product [price=" + price + "]"; } Money getPrice() { return price; } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\Product.java
1
请完成以下Java代码
public AppPluginRegistry<T> getAppPluginRegistry() { return pluginRegistry; } /** * Load the {@link ProcessEngineProvider} spi implementation. * * @return */ protected ProcessEngineProvider loadProcessEngineProvider() { ServiceLoader<ProcessEngineProvider> loader = ServiceLoader.load(ProcessEngineProvider.class); try { return loader.iterator().next(); } catch (NoSuchElementException e) { String message = String.format("No implementation for the %s spi found on classpath", ProcessEngineProvider.class.getName()); throw new IllegalStateException(message, e); } }
public List<PluginResourceOverride> getResourceOverrides() { if(resourceOverrides == null) { initResourceOverrides(); } return resourceOverrides; } protected synchronized void initResourceOverrides() { if(resourceOverrides == null) { // double-checked sync, do not remove resourceOverrides = new ArrayList<PluginResourceOverride>(); List<T> plugins = pluginRegistry.getPlugins(); for (T p : plugins) { resourceOverrides.addAll(p.getResourceOverrides()); } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\AbstractAppRuntimeDelegate.java
1
请完成以下Java代码
public void setFromAddress(@NonNull final BPartnerLocationAddressPart address) { setExistingLocationId(address.getExistingLocationId()); setAddress1(address.getAddress1()); setAddress2(address.getAddress2()); setAddress3(address.getAddress3()); setAddress4(address.getAddress4()); setCity(address.getCity()); setCountryCode(address.getCountryCode()); setPoBox(address.getPoBox()); setPostal(address.getPostal()); setRegion(address.getRegion()); setDistrict(address.getDistrict()); }
@Nullable public LocationId getExistingLocationIdNotNull() { return Check.assumeNotNull(getExistingLocationId(), "existingLocationId not null: {}", this); } /** * Can be used if this instance's ID is known to be not null. */ @NonNull public BPartnerLocationId getIdNotNull() { return Check.assumeNotNull(id, "id may not be null at this point"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerLocation.java
1
请在Spring Boot框架中完成以下Java代码
public Queue demo10Queue2() { return new Queue(Demo10Message.QUEUE_2); } @Bean public Queue demo10Queue3() { return new Queue(Demo10Message.QUEUE_3); } // 创建 Direct Exchange @Bean public DirectExchange demo10Exchange() { return new DirectExchange(Demo10Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding @Bean public Binding demo10Binding0() { return BindingBuilder.bind(demo10Queue0()).to(demo10Exchange()).with("0"); }
@Bean public Binding demo10Binding1() { return BindingBuilder.bind(demo10Queue1()).to(demo10Exchange()).with("1"); } @Bean public Binding demo10Binding2() { return BindingBuilder.bind(demo10Queue2()).to(demo10Exchange()).with("2"); } @Bean public Binding demo10Binding3() { return BindingBuilder.bind(demo10Queue3()).to(demo10Exchange()).with("3"); } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-orderly\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
String getValueFromCache(String key) { // simulate a long running computation try { System.out.println("getting value for "+ key); Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(System.err); } return key + "Value"; } public org.infinispan.Cache<String, String> getEmbeddedCache() { return embeddedCache; } public Cache getQuarkusCache() { return anotherCache; } @CacheInvalidateAll(cacheName = CACHE_NAME)
public void clearAll() { // simulate a long running computation try { System.out.println("clearing cache " + CACHE_NAME); Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @CacheInvalidate(cacheName = CACHE_NAME) public void clear(String key) { } }
repos\tutorials-master\quarkus-modules\quarkus-infinispan-embedded\src\main\java\com\baeldung\quarkus\infinispan\InfinispanAnnotatedCacheService.java
1
请完成以下Java代码
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
请完成以下Java代码
public class IncomingConsumer { private static final String TOPIC_NAME = "incoming-topic"; private final ProcessorService processorService; @KafkaListener(topics = TOPIC_NAME) @AsyncListener(operation = @AsyncOperation( channelName = TOPIC_NAME, description = "More details for the incoming topic", headers = @AsyncOperation.Headers( schemaName = "SpringKafkaDefaultHeadersIncomingPayloadDto", values = { // this header is generated by Spring by default @AsyncOperation.Headers.Header( name = DEFAULT_CLASSID_FIELD_NAME,
description = "Spring Type Id Header", value = "com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto" ), } ) ) ) @KafkaAsyncOperationBinding public void consume(IncomingPayloadDto payload) { log.info("Received new message: {}", payload.toString()); processorService.doHandle(payload); } }
repos\tutorials-master\spring-boot-modules\spring-boot-documentation\src\main\java\com\baeldung\boot\documentation\springwolf\adapter\incoming\IncomingConsumer.java
1
请完成以下Java代码
private void validateProduct(@NonNull final I_M_Product product) { try { trxManager.runInNewTrx(() -> checkProductById(product)); } catch (final Exception ex) { product.setIsVerified(false); InterfaceWrapperHelper.save(product); throw AdempiereException.wrapIfNeeded(ex); } } private void checkProductById(@NonNull final I_M_Product product) { if (!product.isBOM()) { log.info("Product is not a BOM"); // No BOM - should not happen, but no problem return; } // Check this level checkProductBOMCyclesAndMarkAsVerified(product); // Get Default BOM from this product final I_PP_Product_BOM bom = productBOMDAO.getDefaultBOMByProductId(ProductId.ofRepoId(product.getM_Product_ID())) .orElseThrow(() -> new AdempiereException(NO_DEFAULT_PP_PRODUCT_BOM_FOR_PRODUCT_MESSAGE_KEY, product.getValue() + "_" + product.getName()));
// Check All BOM Lines for (final I_PP_Product_BOMLine tbomline : productBOMDAO.retrieveLines(bom)) { final ProductId productId = ProductId.ofRepoId(tbomline.getM_Product_ID()); final I_M_Product bomLineProduct = productBL.getById(productId); checkProductBOMCyclesAndMarkAsVerified(bomLineProduct); } } private void checkProductBOMCyclesAndMarkAsVerified(final I_M_Product product) { final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); productBOMBL.checkCycles(productId); product.setIsVerified(true); InterfaceWrapperHelper.save(product); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Product_BOM_Check.java
1
请完成以下Java代码
public void apply(final Object model) { for (final IGridTabRowBuilder builder : builders) { if (!builder.isValid()) { logger.debug("Skip builder because it's not valid: {}", builder); continue; } builder.apply(model); logger.debug("Applied {} to {}", new Object[] { builder, model }); } } @Override public boolean isCreateNewRecord() { boolean createNewRecord = true; for (final IGridTabRowBuilder builder : builders) { if (!builder.isValid()) { createNewRecord = false; continue; } if (!builder.isCreateNewRecord()) { createNewRecord = false; } } return createNewRecord; } /** * @return true if at least one builder is valid */ @Override public boolean isValid()
{ for (final IGridTabRowBuilder builder : builders) { if (builder.isValid()) { return true; } } return false; } @Override public void setSource(Object model) { for (final IGridTabRowBuilder builder : builders) { builder.setSource(model); } } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\impl\CompositeGridTabRowBuilder.java
1
请完成以下Java代码
public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; }
@Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", type=" + type + ", userId=" + userId + ", key=" + key + ", value=" + value + ", password=" + password + ", parentId=" + parentId + ", details=" + details + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityInfoEntity.java
1
请完成以下Java代码
private static ImmutableList<Integer> findAllHUsWithAShipperTransportation(@NonNull final ImmutableList<Integer> allHuIds) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQuery<I_M_ShipperTransportation> subQuery__M_ShipperTransportation = queryBL .createQueryBuilder(I_M_ShipperTransportation.class) .create(); final IQuery<I_M_ShippingPackage> subQuery__M_ShippingPackage__M_ShipperTransportation = queryBL .createQueryBuilder(I_M_ShippingPackage.class) .addInSubQueryFilter() .matchingColumnNames(I_M_ShippingPackage.COLUMNNAME_M_ShipperTransportation_ID, I_M_ShipperTransportation.COLUMNNAME_M_ShipperTransportation_ID) .subQuery(subQuery__M_ShipperTransportation) .end() .create(); final IQuery<I_M_Package> subQuery__M_Package__M_ShippingPackage__M_ShipperTransportation = queryBL .createQueryBuilder(I_M_Package.class) .addInSubQueryFilter() .matchingColumnNames(I_M_Package.COLUMNNAME_M_Package_ID, I_M_ShippingPackage.COLUMNNAME_M_Package_ID) .subQuery(subQuery__M_ShippingPackage__M_ShipperTransportation)
.end() .create(); final List<Integer> list = queryBL .createQueryBuilder(I_M_Package_HU.class) .addInArrayFilter(I_M_Package_HU.COLUMNNAME_M_HU_ID, allHuIds) .addInSubQueryFilter() .matchingColumnNames(I_M_Package_HU.COLUMNNAME_M_Package_ID, I_M_Package.COLUMNNAME_M_Package_ID) .subQuery(subQuery__M_Package__M_ShippingPackage__M_ShipperTransportation) .end() .andCollect(I_M_Package_HU.COLUMN_M_HU_ID, I_M_HU.class) .create() .listIds(); return ImmutableList.copyOf(list); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\InOutToTransportationOrderService.java
1
请完成以下Java代码
public class ExpressionUtils { public static final List<Function> userDefinedFunctions = new ArrayList<>(); static { userDefinedFunctions.add( new Function("ln") { @Override public double apply(double... args) { return Math.log(args[0]); } } ); userDefinedFunctions.add( new Function("lg") { @Override public double apply(double... args) { return Math.log10(args[0]); } } ); userDefinedFunctions.add( new Function("logab", 2) { @Override public double apply(double... args) { return Math.log(args[1]) / Math.log(args[0]); } } ); userDefinedFunctions.add(Functions.getBuiltinFunction("sin")); userDefinedFunctions.add(Functions.getBuiltinFunction("cos")); userDefinedFunctions.add(Functions.getBuiltinFunction("tan")); userDefinedFunctions.add(Functions.getBuiltinFunction("cot")); userDefinedFunctions.add(Functions.getBuiltinFunction("log")); userDefinedFunctions.add(Functions.getBuiltinFunction("log2")); userDefinedFunctions.add(Functions.getBuiltinFunction("log10"));
userDefinedFunctions.add(Functions.getBuiltinFunction("log1p")); userDefinedFunctions.add(Functions.getBuiltinFunction("abs")); userDefinedFunctions.add(Functions.getBuiltinFunction("acos")); userDefinedFunctions.add(Functions.getBuiltinFunction("asin")); userDefinedFunctions.add(Functions.getBuiltinFunction("atan")); userDefinedFunctions.add(Functions.getBuiltinFunction("cbrt")); userDefinedFunctions.add(Functions.getBuiltinFunction("floor")); userDefinedFunctions.add(Functions.getBuiltinFunction("sinh")); userDefinedFunctions.add(Functions.getBuiltinFunction("sqrt")); userDefinedFunctions.add(Functions.getBuiltinFunction("tanh")); userDefinedFunctions.add(Functions.getBuiltinFunction("cosh")); userDefinedFunctions.add(Functions.getBuiltinFunction("ceil")); userDefinedFunctions.add(Functions.getBuiltinFunction("pow")); userDefinedFunctions.add(Functions.getBuiltinFunction("exp")); userDefinedFunctions.add(Functions.getBuiltinFunction("expm1")); userDefinedFunctions.add(Functions.getBuiltinFunction("signum")); } public static Expression createExpression(String expression, Set<String> variables) { return new ExpressionBuilder(expression) .functions(userDefinedFunctions) .implicitMultiplication(true) .operator() .variables(variables) .build(); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\ExpressionUtils.java
1
请完成以下Java代码
public void setImplementationType(String implementationType) { implementationTypeAttribute.setValue(this, implementationType); } public Collection<InputDecisionParameter> getInputs() { return inputCollection.get(this); } public Collection<OutputDecisionParameter> getOutputs() { return outputCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Decision.class, CMMN_ELEMENT_DECISION) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Decision>() { public Decision newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionImpl(instanceContext); } });
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE) .defaultValue("http://www.omg.org/spec/CMMN/DecisionType/Unspecified") .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputCollection = sequenceBuilder.elementCollection(InputDecisionParameter.class) .build(); outputCollection = sequenceBuilder.elementCollection(OutputDecisionParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionImpl.java
1
请完成以下Java代码
public void onDateWorkComplete(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkComplete(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DeliveryDays, skipIfCopying = true) public void onDeliveryDays(final I_C_RfQ rfq) { if (InterfaceWrapperHelper.isNull(rfq, I_C_RfQ.COLUMNNAME_DeliveryDays)) { return; } final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDeliveryDays(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_C_RfQ_Topic_ID, skipIfCopying = true)
public void onC_RfQTopic(final I_C_RfQ rfq) { final I_C_RfQ_Topic rfqTopic = rfq.getC_RfQ_Topic(); if (rfqTopic == null) { return; } final String rfqTypeDefault = rfqTopic.getRfQType(); if (rfqTypeDefault != null) { rfq.setRfQType(rfqTypeDefault); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\model\interceptor\C_RfQ.java
1
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Distribution List. @param M_DistributionList_ID Distribution Lists allow to distribute products to a selected list of partners */ public void setM_DistributionList_ID (int M_DistributionList_ID) { if (M_DistributionList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID)); } /** Get Distribution List. @return Distribution Lists allow to distribute products to a selected list of partners */ public int getM_DistributionList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Total Ratio. @param RatioTotal Total of relative weight in a distribution */ public void setRatioTotal (BigDecimal RatioTotal) { set_Value (COLUMNNAME_RatioTotal, RatioTotal); } /** Get Total Ratio. @return Total of relative weight in a distribution */ public BigDecimal getRatioTotal () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RatioTotal); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionList.java
1
请完成以下Java代码
public void setData(T data) { this.data = data; } public String getCurrentTime() { return currentTime; } public void setCurrentTime(String currentTime) { this.currentTime = currentTime; } //提供几种构造方法 public BaseResp(int code, String message, T data) { this.code = code; this.message = message; this.data = data; this.currentTime = new Date().toString(); } public BaseResp(int code, ResultStatus resultStatus,String message) { this.code = code; this.message = message; this.data = data; this.currentTime = new Date().toString(); }
public BaseResp(ResultStatus resultStatus) { this.code = resultStatus.getErrorCode(); this.message = resultStatus.getErrorMsg(); this.data = data; this.currentTime = new Date().toString(); } public BaseResp(ResultStatus resultStatus, T data) { this.code = resultStatus.getErrorCode(); this.message = resultStatus.getErrorMsg(); this.data = data; this.currentTime = new Date().toString(); } }
repos\spring-boot-quick-master\quick-rabbitmq\src\main\java\com\quick\mq\util\BaseResp.java
1
请在Spring Boot框架中完成以下Java代码
public ClientId createClient(CreateClientRequest createClientRequest) throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder() .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(createClientRequest))) .uri(URI.create(baseUri + "/client")) .header("Content-Type", "application/json") .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } return mapper.readValue(response.body(), ClientId.class); } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); } } @Override public Collection<Client> getClients() throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create(baseUri + "/clients")) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } return mapper.readValue(response.body(), new TypeReference<List<Client>>(){}); } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); }
} @Override public void deleteClient(ClientId id) throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder() .DELETE() .uri(URI.create(baseUri + "/client/" + id.getId())) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); } } }
repos\spring-examples-java-17\spring-bank\bank-client\src\main\java\itx\examples\springbank\client\service\AdminServiceImpl.java
2
请完成以下Java代码
protected void setElementProperty(String id, String propertyName, JsonNode propertyValue, ObjectNode infoNode) { ObjectNode bpmnNode = createOrGetBpmnNode(infoNode); if (!bpmnNode.has(id)) { bpmnNode.putObject(id); } ((ObjectNode) bpmnNode.get(id)).set(propertyName, propertyValue); } protected void removeElementProperty(String id, String propertyName, ObjectNode infoNode) { ObjectNode bpmnNode = createOrGetBpmnNode(infoNode); if (bpmnNode.has(id)) { ObjectNode activityNode = (ObjectNode) bpmnNode.get(id); if (activityNode.has(propertyName)) { activityNode.remove(propertyName); } } } protected ObjectNode createOrGetBpmnNode(ObjectNode infoNode) { if (!infoNode.has(BPMN_NODE)) { infoNode.putObject(BPMN_NODE); } return (ObjectNode) infoNode.get(BPMN_NODE); } protected ObjectNode getBpmnNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(BPMN_NODE); } protected void setLocalizationProperty(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) { ObjectNode localizationNode = createOrGetLocalizationNode(infoNode);
if (!localizationNode.has(language)) { localizationNode.putObject(language); } ObjectNode languageNode = (ObjectNode) localizationNode.get(language); if (!languageNode.has(id)) { languageNode.putObject(id); } ((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue); } protected ObjectNode createOrGetLocalizationNode(ObjectNode infoNode) { if (!infoNode.has(LOCALIZATION_NODE)) { infoNode.putObject(LOCALIZATION_NODE); } return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } protected ObjectNode getLocalizationNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DynamicBpmnServiceImpl.java
1
请完成以下Java代码
private void load(final XMLLoader loader) { loader.load(ITrx.TRXNAME_None); for (Object o : loader.getObjects()) { if (o instanceof I_AD_Migration) { final I_AD_Migration migration = (I_AD_Migration)o; execute(migration); } else { logger.warn("Unhandled type " + o + " [SKIP]"); } }
} private void execute(I_AD_Migration migration) { final Properties ctx = InterfaceWrapperHelper.getCtx(migration); final int migrationId = migration.getAD_Migration_ID(); final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class); final IMigrationExecutorContext migrationCtx = executorProvider.createInitialContext(ctx); migrationCtx.setFailOnFirstError(true); final IMigrationExecutor executor = executorProvider.newMigrationExecutor(migrationCtx, migrationId); executor.setCommitLevel(IMigrationExecutor.CommitLevel.Batch); executor.execute(IMigrationExecutor.Action.Apply); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\MigrationLoader.java
1
请在Spring Boot框架中完成以下Java代码
private PaymentAllocationId saveCandidate_InboundPaymentToOutboundPayment(AllocationLineCandidate candidate) { final Money payAmt = candidate.getAmounts().getPayAmt(); Check.assumeEquals(candidate.getAmounts(), AllocationAmounts.builder() .payAmt(payAmt) .build()); final C_AllocationHdr_Builder allocationBuilder = newC_AllocationHdr_Builder(candidate) // // Outgoing payment line .addLine() .skipIfAllAmountsAreZero() .orgId(candidate.getOrgId()) .bpartnerId(candidate.getBpartnerId()) .paymentId(extractPaymentId(candidate.getPayableDocumentRef())) // .amount(payAmt.toBigDecimal()) .overUnderAmt(candidate.getPayableOverUnderAmt().toBigDecimal()) .lineDone() // // Incoming payment line .addLine() .skipIfAllAmountsAreZero() .orgId(candidate.getOrgId()) .bpartnerId(candidate.getBpartnerId()) .paymentId(extractPaymentId(candidate.getPaymentDocumentRef())) // .amount(payAmt.negate().toBigDecimal()) .overUnderAmt(candidate.getPaymentOverUnderAmt().toBigDecimal()) .lineDone(); return createAndComplete(allocationBuilder); } private static InvoiceId extractInvoiceId(@NonNull final TableRecordReference recordRef) { return recordRef.getIdAssumingTableName(I_C_Invoice.Table_Name, InvoiceId::ofRepoId); } private static PaymentId extractPaymentId(@NonNull final TableRecordReference recordRef) { return recordRef.getIdAssumingTableName(I_C_Payment.Table_Name, PaymentId::ofRepoId); } private C_AllocationHdr_Builder newC_AllocationHdr_Builder(final AllocationLineCandidate candidate) { return allocationBL.newBuilder()
.orgId(candidate.getOrgId()) .currencyId(candidate.getCurrencyId()) .dateTrx(candidate.getDateTrx()) .dateAcct(candidate.getDateAcct()) .manual(true); // flag it as manually created by user } @Nullable private PaymentAllocationId createAndComplete(final C_AllocationHdr_Builder allocationBuilder) { final I_C_AllocationHdr allocationHdr = allocationBuilder.createAndComplete(); if (allocationHdr == null) { return null; } // final ImmutableList<I_C_AllocationLine> lines = allocationBuilder.getC_AllocationLines(); updateCounter_AllocationLine_ID(lines); return PaymentAllocationId.ofRepoId(allocationHdr.getC_AllocationHdr_ID()); } /** * Sets the counter allocation line - that means the mathcing line * The id is set only if we have 2 line: credit memo - invoice; purchase invoice - sales invoice; incoming payment - outgoing payment * * @param lines */ private void updateCounter_AllocationLine_ID(final ImmutableList<I_C_AllocationLine> lines) { if (lines.size() != 2) { return; } // final I_C_AllocationLine al1 = lines.get(0); final I_C_AllocationLine al2 = lines.get(1); al1.setCounter_AllocationLine_ID(al2.getC_AllocationLine_ID()); allocationDAO.save(al1); // al2.setCounter_AllocationLine_ID(al1.getC_AllocationLine_ID()); allocationDAO.save(al2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\AllocationLineCandidateSaver.java
2
请完成以下Java代码
public void initialize(VariableTypes types) { if (variableInstanceEntity == null) { VariableType type = types.findVariableType(value); if (type instanceof ByteArrayType) { throw new ActivitiIllegalArgumentException("Variables of type ByteArray cannot be used to query"); } else if (type instanceof JPAEntityVariableType && operator != QueryOperator.EQUALS) { throw new ActivitiIllegalArgumentException( "JPA entity variables can only be used in 'variableValueEquals'" ); } else if (type instanceof JPAEntityListVariableType) { throw new ActivitiIllegalArgumentException( "Variables containing a list of JPA entities cannot be used to query" ); } else { // Type implementation determines which fields are set on the entity variableInstanceEntity = Context.getCommandContext() .getVariableInstanceEntityManager() .create(name, type, value); } } } public String getName() { return name; } public String getOperator() { if (operator != null) { return operator.toString(); } return QueryOperator.EQUALS.toString(); } public String getTextValue() { if (variableInstanceEntity != null) { return variableInstanceEntity.getTextValue(); } return null; } public Long getLongValue() {
if (variableInstanceEntity != null) { return variableInstanceEntity.getLongValue(); } return null; } public Double getDoubleValue() { if (variableInstanceEntity != null) { return variableInstanceEntity.getDoubleValue(); } return null; } public String getTextValue2() { if (variableInstanceEntity != null) { return variableInstanceEntity.getTextValue2(); } return null; } public String getType() { if (variableInstanceEntity != null) { return variableInstanceEntity.getType().getTypeName(); } return null; } public boolean isLocal() { return local; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\QueryVariableValue.java
1
请完成以下Java代码
public String getHeader(String name) { List<String> list = header(name); if (list != null && !list.isEmpty()) { return list.iterator().next(); } return super.getHeader(name); } } } /** * Convenience class that converts an incoming request input stream into a form that can * be easily deserialized to a Java object using Spring message converters. It is only * used in a local forward dispatch, in which case there is a danger that the request body * will need to be read and analysed more than once. Apart from using the message * converters the other main feature of this class is that the request body is cached and * can be read repeatedly as necessary. * * @author Dave Syer * */ class ServletOutputToInputConverter extends HttpServletResponseWrapper { private StringBuilder builder = new StringBuilder(); ServletOutputToInputConverter(HttpServletResponse response) { super(response); } @Override public ServletOutputStream getOutputStream() throws IOException { return new ServletOutputStream() { @Override public void write(int b) throws IOException { builder.append(Character.valueOf((char) b)); } @Override public void setWriteListener(WriteListener listener) { } @Override
public boolean isReady() { return true; } }; } public ServletInputStream getInputStream() { ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes()); return new ServletInputStream() { @Override public int read() throws IOException { return body.read(); } @Override public void setReadListener(ReadListener listener) { } @Override public boolean isReady() { return true; } @Override public boolean isFinished() { return body.available() <= 0; } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
1
请完成以下Java代码
private String computeKey(String serverSecret, String content) { String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret); String keyPayload = content + ":" + sha512Hex; return Utf8.decode(Base64.getEncoder().encode(Utf8.encode(keyPayload))); } @Override public @Nullable Token verifyToken(String key) { if (key == null || "".equals(key)) { return null; } String[] tokens = StringUtils .delimitedListToStringArray(Utf8.decode(Base64.getDecoder().decode(Utf8.encode(key))), ":"); Assert.isTrue(tokens.length >= 4, () -> "Expected 4 or more tokens but found " + tokens.length); long creationTime; try { creationTime = Long.decode(tokens[0]); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Expected number but found " + tokens[0]); } String serverSecret = computeServerSecretApplicableAt(creationTime); String pseudoRandomNumber = tokens[1]; // Permit extendedInfo to itself contain ":" characters StringBuilder extendedInfo = new StringBuilder(); for (int i = 2; i < tokens.length - 1; i++) { if (i > 2) { extendedInfo.append(":"); } extendedInfo.append(tokens[i]); } String sha1Hex = tokens[tokens.length - 1]; // Verification String content = creationTime + ":" + pseudoRandomNumber + ":" + extendedInfo.toString(); String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret); Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure"); return new DefaultToken(key, creationTime, extendedInfo.toString()); } /** * @return a pseudo random number (hex encoded) */
private String generatePseudoRandomNumber() { byte[] randomBytes = new byte[this.pseudoRandomNumberBytes]; this.secureRandom.nextBytes(randomBytes); return new String(Hex.encode(randomBytes)); } private String computeServerSecretApplicableAt(long time) { return this.serverSecret + ":" + Long.valueOf(time % this.serverInteger).intValue(); } /** * @param serverSecret the new secret, which can contain a ":" if desired (never being * sent to the client) */ public void setServerSecret(String serverSecret) { this.serverSecret = serverSecret; } public void setSecureRandom(SecureRandom secureRandom) { this.secureRandom = secureRandom; } /** * @param pseudoRandomNumberBytes changes the number of bytes issued (must be &gt;= 0; * defaults to 256) */ public void setPseudoRandomNumberBytes(int pseudoRandomNumberBytes) { Assert.isTrue(pseudoRandomNumberBytes >= 0, "Must have a positive pseudo random number bit size"); this.pseudoRandomNumberBytes = pseudoRandomNumberBytes; } public void setServerInteger(Integer serverInteger) { this.serverInteger = serverInteger; } @Override public void afterPropertiesSet() { Assert.hasText(this.serverSecret, "Server secret required"); Assert.notNull(this.serverInteger, "Server integer required"); Assert.notNull(this.secureRandom, "SecureRandom instance required"); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\token\KeyBasedPersistenceTokenService.java
1
请完成以下Java代码
public int getC_ILCandHandler_ID() { return get_ValueAsInt(COLUMNNAME_C_ILCandHandler_ID); } @Override public void setClassname (final java.lang.String Classname) { set_Value (COLUMNNAME_Classname, Classname); } @Override public java.lang.String getClassname() { return get_ValueAsString(COLUMNNAME_Classname); } @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); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override
public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @Override public void setIs_AD_User_InCharge_UI_Setting (final boolean Is_AD_User_InCharge_UI_Setting) { set_Value (COLUMNNAME_Is_AD_User_InCharge_UI_Setting, Is_AD_User_InCharge_UI_Setting); } @Override public boolean is_AD_User_InCharge_UI_Setting() { return get_ValueAsBoolean(COLUMNNAME_Is_AD_User_InCharge_UI_Setting); } @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 setTableName (final java.lang.String TableName) { set_Value (COLUMNNAME_TableName, TableName); } @Override public java.lang.String getTableName() { return get_ValueAsString(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_ILCandHandler.java
1