instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Spring Boot application配置
server: port: 8080 shutdown: graceful spring: datasource: platform: portgres initialization-mode: always #schema: classpath:script/sql/schema.sql data: classpath:script/sql/data.sql jpa: database: POSTGRESQL show-sql: true generate-ddl: true properties: hibernate: dialect: org.hiberna
te.dialect.PostgreSQLDialect hibernate: ddl-auto: none lifecycle: timeout-per-shutdown-phase: 20s logging: level: root: info
repos\spring-examples-java-17\spring-data\src\main\resources\application.yml
2
请完成以下Java代码
public Set<String> getFailCodes() { return failCodes; } public void setFailCodes(Set<String> failCodes) { this.failCodes = failCodes; } public Set<String> getHandleCodes() { return handleCodes; } public void setHandleCodes(Set<String> handleCodes) { this.handleCodes = handleCodes; } public boolean isIgnoreErrors() { return ignoreErrors; } public void setIgnoreErrors(boolean ignoreErrors) { this.ignoreErrors = ignoreErrors; } public boolean isSaveRequest() { return saveRequest; } public void setSaveRequest(boolean saveRequest) { this.saveRequest = saveRequest; } public boolean isSaveResponse() { return saveResponse; } public void setSaveResponse(boolean saveResponse) { this.saveResponse = saveResponse; } public boolean isSaveResponseTransient() { return saveResponseTransient; } public void setSaveResponseTransient(boolean saveResponseTransient) {
this.saveResponseTransient = saveResponseTransient; } public boolean isSaveResponseAsJson() { return saveResponseAsJson; } public void setSaveResponseAsJson(boolean saveResponseAsJson) { this.saveResponseAsJson = saveResponseAsJson; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public boolean isNoRedirects() { return httpRequest.isNoRedirects(); } } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\BaseHttpActivityDelegate.java
1
请完成以下Java代码
public InvalidDependencyInformation getDependencies() { return this.dependencies; } public void triggerInvalidDependencies(List<String> dependencies) { this.dependencies = new InvalidDependencyInformation(dependencies); } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid) .add("javaVersion=" + this.javaVersion) .add("language=" + this.language) .add("configurationFileFormat=" + this.configurationFileFormat) .add("packaging=" + this.packaging) .add("type=" + this.type) .add("dependencies=" + this.dependencies) .add("message='" + this.message + "'") .toString(); } } /**
* Invalid dependencies information. */ public static class InvalidDependencyInformation { private boolean invalid = true; private final List<String> values; public InvalidDependencyInformation(List<String> values) { this.values = values; } public boolean isInvalid() { return this.invalid; } public List<String> getValues() { return this.values; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString(); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
1
请完成以下Java代码
public static FileInfo getFile(String groupName, String remoteFileName) { try { StorageClient storageClient = getStorageClient(); return storageClient.get_file_info(groupName, remoteFileName); } catch (IOException e) { logger.error("IO Exception: Get File from Fast DFS failed", e); } catch (Exception e) { logger.error("Non IO Exception: Get File from Fast DFS failed", e); } return null; } public static InputStream downFile(String groupName, String remoteFileName) { try { StorageClient storageClient = getStorageClient(); byte[] fileByte = storageClient.download_file(groupName, remoteFileName); InputStream ins = new ByteArrayInputStream(fileByte); return ins; } catch (IOException e) { logger.error("IO Exception: Get File from Fast DFS failed", e); } catch (Exception e) { logger.error("Non IO Exception: Get File from Fast DFS failed", e); } return null; } public static void deleteFile(String groupName, String remoteFileName) throws Exception { StorageClient storageClient = getStorageClient(); int i = storageClient.delete_file(groupName, remoteFileName); logger.info("delete file successfully!!!" + i); } public static StorageServer[] getStoreStorages(String groupName)
throws IOException { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getConnection(); return trackerClient.getStoreStorages(trackerServer, groupName); } public static ServerInfo[] getFetchStorages(String groupName, String remoteFileName) throws IOException { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getConnection(); return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName); } public static String getTrackerUrl() throws IOException { return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/"; } private static StorageClient getStorageClient() throws IOException { TrackerServer trackerServer = getTrackerServer(); StorageClient storageClient = new StorageClient(trackerServer, null); return storageClient; } private static TrackerServer getTrackerServer() throws IOException { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getConnection(); return trackerServer; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\fastdfs\FastDFSClient.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping("/") public String viewHome(Model model){ List<Employee> employeeList = employeeService.listAll(); model.addAttribute("employeeList", employeeList); return "index"; } @RequestMapping("/new") public String showNewProductPage(Model model) { Employee employee = new Employee(); model.addAttribute("employee", employee); return "new_employee"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String saveEmployee(@ModelAttribute("employee") Employee employee) { employeeService.save(employee); return "redirect:/"; }
@RequestMapping("/edit/{id}") public ModelAndView showEditEmployeePage(@PathVariable(name = "id") int id){ ModelAndView mav = new ModelAndView("edit_employee"); Employee employee1= employeeService.get(id); mav.addObject("employee", employee1); return mav; } @RequestMapping(value = "/delete/{id}") public String deleteEmp(@PathVariable(name = "id") int id) { employeeService.delete(id); return "redirect:/"; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Employee-Salary\src\main\java\spring\project\controller\EmployeeController.java
2
请完成以下Java代码
public void activate() { validateParameters(); ActivateJobDefinitionCmd command = new ActivateJobDefinitionCmd(this); commandExecutor.execute(command); } @Override public void suspend() { validateParameters(); SuspendJobDefinitionCmd command = new SuspendJobDefinitionCmd(this); commandExecutor.execute(command); } protected void validateParameters() { ensureOnlyOneNotNull("Need to specify either a job definition id, a process definition id or a process definition key.", jobDefinitionId, processDefinitionId, processDefinitionKey); if (isProcessDefinitionTenantIdSet && (jobDefinitionId != null || processDefinitionId != null)) { throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey(); } ensureNotNull("commandExecutor", commandExecutor); } public String getProcessDefinitionKey() { return processDefinitionKey;
} public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionTenantId() { return processDefinitionTenantId; } public boolean isProcessDefinitionTenantIdSet() { return isProcessDefinitionTenantIdSet; } public String getJobDefinitionId() { return jobDefinitionId; } public boolean isIncludeJobs() { return includeJobs; } public Date getExecutionDate() { return executionDate; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\UpdateJobDefinitionSuspensionStateBuilderImpl.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclaration.java
1
请完成以下Java代码
public abstract class CallingTaskActivityBehavior extends TaskActivityBehavior { protected static final CmmnBehaviorLogger LOG = ProcessEngineLogger.CMNN_BEHAVIOR_LOGGER; protected BaseCallableElement callableElement; public void onManualCompletion(CmmnActivityExecution execution) { // Throw always an exception! // It should not be possible to complete a calling // task manually. If the called instance has // been completed, the associated task will // be notified to complete automatically. String id = execution.getId(); throw LOG.forbiddenManualCompletitionException("complete", id, getTypeName()); } public BaseCallableElement getCallableElement() { return callableElement; } public void setCallableElement(BaseCallableElement callableElement) { this.callableElement = callableElement; } protected String getDefinitionKey(CmmnActivityExecution execution) { CmmnExecution caseExecution = (CmmnExecution) execution; return getCallableElement().getDefinitionKey(caseExecution); } protected Integer getVersion(CmmnActivityExecution execution) { CmmnExecution caseExecution = (CmmnExecution) execution; return getCallableElement().getVersion(caseExecution); }
protected String getDeploymentId(CmmnActivityExecution execution) { return getCallableElement().getDeploymentId(); } protected CallableElementBinding getBinding() { return getCallableElement().getBinding(); } protected boolean isLatestBinding() { return getCallableElement().isLatestBinding(); } protected boolean isDeploymentBinding() { return getCallableElement().isDeploymentBinding(); } protected boolean isVersionBinding() { return getCallableElement().isVersionBinding(); } protected boolean isVersionTagBinding() { return getCallableElement().isVersionTagBinding(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\CallingTaskActivityBehavior.java
1
请完成以下Java代码
public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); }
@Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock_WarehouseAndProduct_v.java
1
请完成以下Java代码
public Date parse(String value) throws DateTimeException { DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder() .appendPattern(getDateFormatPattern()) .toFormatter() .withZone(getZoneId()); try { ZonedDateTime zonedDateTime = dateTimeFormatter.parse(value, ZonedDateTime::from); return Date.from(zonedDateTime.toInstant()); } catch (DateTimeException e) { LocalDate localDate = dateTimeFormatter.parse(String.valueOf(value), LocalDate::from); return Date.from(localDate.atStartOfDay().atZone(getZoneId()).toInstant()); } } public Date toDate(Object value) { if (value instanceof String) { return parse((String) value); } if (value instanceof Date) { return (Date) value; } if (value instanceof Long) { return new Date((long) value);
} if (value instanceof LocalDate) { return Date.from(((LocalDate) value).atStartOfDay(getZoneId()).toInstant()); } if (value instanceof LocalDateTime) { return Date.from(((LocalDateTime) value).atZone(getZoneId()).toInstant()); } if (value instanceof ZonedDateTime) { return Date.from(((ZonedDateTime) value).toInstant()); } throw new DateTimeException( MessageFormat.format("Error while parsing date. Type: {0}, value: {1}", value.getClass().getName(), value) ); } }
repos\Activiti-develop\activiti-core-common\activiti-common-util\src\main\java\org\activiti\common\util\DateFormatterProvider.java
1
请完成以下Java代码
public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set SubLine ID. @param SubLine_ID Transaction sub line ID (internal) */ @Override public void setSubLine_ID (int SubLine_ID) { if (SubLine_ID < 1) set_ValueNoCheck (COLUMNNAME_SubLine_ID, null); else set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID)); } /** Get SubLine ID. @return Transaction sub line ID (internal) */ @Override public int getSubLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest.java
1
请完成以下Java代码
public class CreateAdjustmentChargeFromInvoice extends JavaProcess implements IProcessPrecondition { private final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); private final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); @Param(mandatory = true, parameterName = "C_DocType_ID") private int p_C_DocType_ID; @Override protected String doIt() throws Exception { final I_C_DocType docType = docTypeDAO.getById(p_C_DocType_ID); final DocBaseAndSubType docBaseAndSubType = DocBaseAndSubType.of(X_C_DocType.DOCBASETYPE_ARInvoice, docType.getDocSubType()); final AdjustmentChargeCreateRequest adjustmentChargeCreateRequest = AdjustmentChargeCreateRequest.builder() .invoiceID(InvoiceId.ofRepoId(getRecord_ID())) .docBaseAndSubTYpe(docBaseAndSubType) .build(); invoiceBL.adjustmentCharge(adjustmentChargeCreateRequest); return MSG_OK; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{ if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\invoice\process\CreateAdjustmentChargeFromInvoice.java
1
请完成以下Java代码
public void afterSaveOfNextTermForPredecessor(final de.metas.contracts.model.I_C_Flatrate_Term next, final de.metas.contracts.model.I_C_Flatrate_Term predecessor) { final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class); final I_C_Flatrate_Term oldTermtoUse = InterfaceWrapperHelper.create(predecessor, I_C_Flatrate_Term.class); final I_C_Flatrate_Term newTermtoUse = InterfaceWrapperHelper.create(next, I_C_Flatrate_Term.class); newTermtoUse.setPMM_Product(oldTermtoUse.getPMM_Product()); InterfaceWrapperHelper.save(newTermtoUse); final List<I_C_Flatrate_DataEntry> oldDataEntries = flatrateDAO.retrieveDataEntries(predecessor, null, null); final PMMContractBuilder builder = newPMMContractBuilder(newTermtoUse) .setComplete(false); oldDataEntries .forEach(e -> { Check.errorUnless(e.getC_Period() != null, "{} has a missing C_Period", e); final Timestamp dateOldEntry = e.getC_Period().getStartDate(); final Timestamp dateNewEntry; if (dateOldEntry.before(newTermtoUse.getStartDate())) { dateNewEntry = TimeUtil.addYears(dateOldEntry, 1); } else { dateNewEntry = dateOldEntry; }
if (InterfaceWrapperHelper.isNull(e, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM)) { // if the current entry has a null value, then also the new entry shall have a null value builder.setFlatrateAmtPerUOM(dateNewEntry, null); } else { builder.setFlatrateAmtPerUOM(dateNewEntry, e.getFlatrateAmtPerUOM()); } builder.addQtyPlanned(dateNewEntry, e.getQty_Planned()); }); builder.build(); } @VisibleForTesting PMMContractBuilder newPMMContractBuilder(final I_C_Flatrate_Term term) { return PMMContractBuilder.newBuilder(term); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\contracts\ProcurementFlatrateHandler.java
1
请完成以下Java代码
public int getC_Project_User_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_User_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsAccommodationBooking (final boolean IsAccommodationBooking) { set_Value (COLUMNNAME_IsAccommodationBooking, IsAccommodationBooking); } @Override public boolean isAccommodationBooking() { return get_ValueAsBoolean(COLUMNNAME_IsAccommodationBooking); }
@Override public org.compiere.model.I_R_Status getR_Status() { return get_ValueAsPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class); } @Override public void setR_Status(final org.compiere.model.I_R_Status R_Status) { set_ValueFromPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class, R_Status); } @Override public void setR_Status_ID (final int R_Status_ID) { if (R_Status_ID < 1) set_Value (COLUMNNAME_R_Status_ID, null); else set_Value (COLUMNNAME_R_Status_ID, R_Status_ID); } @Override public int getR_Status_ID() { return get_ValueAsInt(COLUMNNAME_R_Status_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_User.java
1
请完成以下Java代码
public static class Composer { private Set<INamePairPredicate> collectedPredicates = null; private Composer() { super(); } public INamePairPredicate build() { if (collectedPredicates == null || collectedPredicates.isEmpty()) { return ACCEPT_ALL; } else if (collectedPredicates.size() == 1) { return collectedPredicates.iterator().next(); } else { return new ComposedNamePairPredicate(collectedPredicates); } } public Composer add(@Nullable final INamePairPredicate predicate) { if (predicate == null || predicate == ACCEPT_ALL)
{ return this; } if (collectedPredicates == null) { collectedPredicates = new LinkedHashSet<>(); } if (collectedPredicates.contains(predicate)) { return this; } collectedPredicates.add(predicate); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\NamePairPredicates.java
1
请完成以下Java代码
public class ConvertHashMapStringToHashMapObjectUsingtoString { public String name; public int age; public ConvertHashMapStringToHashMapObjectUsingtoString(String name, int age) { this.name = name; this.age = age; } public static ConvertHashMapStringToHashMapObjectUsingtoString deserializeCustomObject(String valueString) { if (valueString.startsWith("{") && valueString.endsWith("}")) { valueString = valueString.substring(1, valueString.length() - 1); String[] parts = valueString.split(","); String name = null; int age = -1; for (String part : parts) { String[] keyValue = part.split("="); if (keyValue.length == 2) { String key = keyValue[0].trim(); String val = keyValue[1].trim(); if (key.equals("name")) { name = val; } else if (key.equals("age")) { age = Integer.parseInt(val); } } } if (name != null && age >= 0) { return new ConvertHashMapStringToHashMapObjectUsingtoString(name, age);
} } return new ConvertHashMapStringToHashMapObjectUsingtoString("", -1); } public static void main(String[] args) { String hashMapString = "{key1={name=John, age=30}, key2={name=Alice, age=25}}"; String keyValuePairs = hashMapString.replaceAll("[{}\\s]", ""); String[] pairs = keyValuePairs.split(","); Map<String, ConvertHashMapStringToHashMapObjectUsingtoString> actualHashMap = new HashMap<>(); for (String pair : pairs) { String[] keyValue = pair.split("="); if (keyValue.length == 2) { String key = keyValue[0]; ConvertHashMapStringToHashMapObjectUsingtoString value = deserializeCustomObject(keyValue[1]); actualHashMap.put(key, value); } } System.out.println(actualHashMap); } @Override public String toString() { return "{name=" + name + ", age=" + age + "}"; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-7\src\main\java\com\baeldung\map\ConvertHashMapStringToHashMapObjectUsingtoString.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaConfig implements TransactionManagementConfigurer { @Value("${dataSource.driverClassName}") private String driver; @Value("${dataSource.url}") private String url; @Value("${dataSource.username}") private String username; @Value("${dataSource.password}") private String password; @Value("${hibernate.dialect}") private String dialect; @Value("${hibernate.hbm2ddl.auto}") private String hbm2ddlAuto; @Value("${spring.datasource.maximumPoolSize}") private int maximumPoolSize; @Bean public HikariDataSource configureDataSource() { HikariConfig config = new HikariConfig(); config.setDriverClassName(driver); config.setJdbcUrl(url); config.setUsername(username); config.setPassword(password); config.setMaximumPoolSize(maximumPoolSize);
config.setConnectionTimeout(60000); config.setIdleTimeout(60000); config.setLeakDetectionThreshold(60000); return new HikariDataSource(config); } @Bean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean configureEntityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(configureDataSource()); entityManagerFactoryBean.setPackagesToScan("com.urunov"); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect); jpaProperties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, hbm2ddlAuto); entityManagerFactoryBean.setJpaProperties(jpaProperties); return entityManagerFactoryBean; } @Bean(name = "transactionManager") public PlatformTransactionManager annotationDrivenTransactionManager() { return new JpaTransactionManager(); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\configure\JpaConfig.java
2
请完成以下Java代码
protected String encode(String username, String password) { String token = base64Encode((username + ":" + password).getBytes(StandardCharsets.UTF_8)); return "Basic " + token; } private static @Nullable String getMetadataValue(Instance instance, String[] keys) { Map<String, String> metadata = instance.getRegistration().getMetadata(); for (String key : keys) { String value = metadata.get(key); if (value != null) { return value; } } return null; } private static String base64Encode(byte[] src) { if (src.length == 0) { return ""; } byte[] dest = Base64.getEncoder().encode(src); return new String(dest, StandardCharsets.UTF_8); } @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor
public static class InstanceCredentials { /** * user name for this instance */ @lombok.NonNull private String userName; /** * user password for this instance */ @lombok.NonNull private String userPassword; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\BasicAuthHttpHeaderProvider.java
1
请完成以下Java代码
public boolean hasChildElements() { return true; } @Override public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_GENERIC_EVENT_LISTENER; } @Override protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { String listenerType = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_TYPE); if ("signal".equals(listenerType)) { SignalEventListener signalEventListener = new SignalEventListener(); signalEventListener.setSignalRef(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_SIGNAL_REF)); return convertCommonAttributes(xtr, signalEventListener); } else if ("variable".equals(listenerType)) { VariableEventListener variableEventListener = new VariableEventListener(); variableEventListener.setVariableName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_VARIABLE_NAME)); variableEventListener.setVariableChangeType(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_VARIABLE_CHANGE_TYPE)); return convertCommonAttributes(xtr, variableEventListener); } else if ("intent".equals(listenerType)) { IntentEventListener intentEventListener = new IntentEventListener(); return convertCommonAttributes(xtr, intentEventListener);
} else if ("reactivate".equals(listenerType)) { ReactivateEventListener reactivateEventListener = new ReactivateEventListener(); return convertCommonAttributes(xtr, reactivateEventListener); } else { GenericEventListener genericEventListener = new GenericEventListener(); return convertCommonAttributes(xtr, genericEventListener); } } protected EventListener convertCommonAttributes(XMLStreamReader xtr, EventListener listener) { listener.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); listener.setAvailableConditionExpression(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION)); return listener; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\GenericEventListenerXmlConverter.java
1
请完成以下Java代码
public void setPA_MeasureCalc_ID (int PA_MeasureCalc_ID) { if (PA_MeasureCalc_ID < 1) set_Value (COLUMNNAME_PA_MeasureCalc_ID, null); else set_Value (COLUMNNAME_PA_MeasureCalc_ID, Integer.valueOf(PA_MeasureCalc_ID)); } /** Get Measure Calculation. @return Calculation method for measuring performance */ public int getPA_MeasureCalc_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_MeasureCalc_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Measure. @param PA_Measure_ID Concrete Performance Measurement */ public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Ratio getPA_Ratio() throws RuntimeException { return (I_PA_Ratio)MTable.get(getCtx(), I_PA_Ratio.Table_Name) .getPO(getPA_Ratio_ID(), get_TrxName()); } /** Set Ratio. @param PA_Ratio_ID Performace Ratio */ public void setPA_Ratio_ID (int PA_Ratio_ID) { if (PA_Ratio_ID < 1) set_Value (COLUMNNAME_PA_Ratio_ID, null);
else set_Value (COLUMNNAME_PA_Ratio_ID, Integer.valueOf(PA_Ratio_ID)); } /** Get Ratio. @return Performace Ratio */ public int getPA_Ratio_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Measure.java
1
请完成以下Java代码
public Date getTime() { return getStartTime(); } @Override public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public Long getWorkTimeInMillis() { if (endTime == null || claimTime == null) { return null; } return endTime.getTime() - claimTime.getTime(); } public Map<String, Object> getTaskLocalVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() != null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables;
} public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityImpl.java
1
请完成以下Java代码
public class EventPayloadToXmlStringSerializer implements OutboundEventSerializer { @Override public String serialize(EventInstance eventInstance) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement(eventInstance.getEventKey()); doc.appendChild(rootElement); if (!eventInstance.getPayloadInstances().isEmpty()) { for (EventPayloadInstance payloadInstance : eventInstance.getPayloadInstances()) { if (!payloadInstance.getEventPayloadDefinition().isNotForBody()) { Element element = doc.createElement(payloadInstance.getDefinitionName()); element.setTextContent(payloadInstance.getValue().toString()); rootElement.appendChild(element); }
} } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { throw new FlowableException("XML serialization failed for " + eventInstance, e); } } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\serialization\EventPayloadToXmlStringSerializer.java
1
请在Spring Boot框架中完成以下Java代码
public List<CommentResponse> getComments(@ApiParam(name = "taskId") @PathVariable String taskId) { HistoricTaskInstance task = getHistoricTaskFromRequest(taskId); return restResponseFactory.createRestCommentList(taskService.getTaskComments(task.getId())); } @ApiOperation(value = "Create a new comment on a task", tags = { "Task Comments" }, nickname = "createTaskComments", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the comment was created and the result is returned."), @ApiResponse(code = 400, message = "Indicates the comment is missing from the request."), @ApiResponse(code = 404, message = "Indicates the requested task was not found.") }) @PostMapping(value = "/runtime/tasks/{taskId}/comments", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public CommentResponse createComment(@ApiParam(name = "taskId") @PathVariable String taskId, @RequestBody CommentRequest comment) { Task task = getTaskFromRequestWithoutAccessCheck(taskId); if (comment.getMessage() == null) { throw new FlowableIllegalArgumentException("Comment text is required.");
} if (restApiInterceptor != null) { restApiInterceptor.createTaskComment(task, comment); } String processInstanceId = null; if (comment.isSaveProcessInstanceId()) { Task taskEntity = taskService.createTaskQuery().taskId(task.getId()).singleResult(); processInstanceId = taskEntity.getProcessInstanceId(); } Comment createdComment = taskService.addComment(task.getId(), processInstanceId, comment.getMessage()); return restResponseFactory.createRestComment(createdComment); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskCommentCollectionResource.java
2
请完成以下Java代码
public void setC_ReferenceNo_Doc_ID (int C_ReferenceNo_Doc_ID) { if (C_ReferenceNo_Doc_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Doc_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Doc_ID, Integer.valueOf(C_ReferenceNo_Doc_ID)); } /** Get Referenced Document. @return Referenced Document */ @Override public int getC_ReferenceNo_Doc_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Doc_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.document.refid.model.I_C_ReferenceNo getC_ReferenceNo() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class); } @Override public void setC_ReferenceNo(de.metas.document.refid.model.I_C_ReferenceNo C_ReferenceNo) { set_ValueFromPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class, C_ReferenceNo); } /** Set Reference No. @param C_ReferenceNo_ID Reference No */ @Override public void setC_ReferenceNo_ID (int C_ReferenceNo_ID) { if (C_ReferenceNo_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID)); } /** Get Reference No.
@return Reference No */ @Override public int getC_ReferenceNo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Doc.java
1
请在Spring Boot框架中完成以下Java代码
public void addIssueProgress(@NonNull final AddIssueProgressRequest request) { final IssueEntity issueEntity = issueRepository.getById(request.getIssueId()); issueEntity.addIssueEffort(request.getBookedEffort()); issueEntity.addAggregatedEffort(request.getBookedEffort()); recomputeLatestActivityOnIssue(issueEntity); issueRepository.save(issueEntity); if(issueEntity.getParentIssueId() != null) { issueRepository .buildUpStreamIssueHierarchy(issueEntity.getParentIssueId()) .getUpStreamForId(issueEntity.getParentIssueId()) .forEach(parentIssue -> { parentIssue.addAggregatedEffort(request.getBookedEffort()); recomputeLatestActivityOnSubIssues(parentIssue); issueRepository.save(parentIssue); }); } } private void recomputeLatestActivityOnSubIssues(@NonNull final IssueEntity issueEntity) { final ImmutableList<IssueEntity> subIssues = issueRepository.getDirectlyLinkedSubIssues(issueEntity.getIssueId()); final Instant mostRecentActivity = subIssues .stream() .map(IssueEntity::getLatestActivity) .filter(Objects::nonNull)
.max(Instant::compareTo) .orElse(null); issueEntity.setLatestActivityOnSubIssues(mostRecentActivity); } private void recomputeLatestActivityOnIssue(@NonNull final IssueEntity issueEntity) { final ImmutableList<TimeBooking> timeBookings = timeBookingRepository.getAllByIssueId(issueEntity.getIssueId()); final Instant latestActivityDate = timeBookings.stream() .map(TimeBooking::getBookedDate) .max(Instant::compareTo) .orElse(null); issueEntity.setLatestActivityOnIssue(latestActivityDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\IssueService.java
2
请完成以下Java代码
public HttpRequest getHttpRequest() { return httpRequest; } public void setHttpRequest(HttpRequest httpRequest) { this.httpRequest = httpRequest; } public Set<String> getFailCodes() { return failCodes; } public void setFailCodes(Set<String> failCodes) { this.failCodes = failCodes; } public Set<String> getHandleCodes() { return handleCodes; } public void setHandleCodes(Set<String> handleCodes) { this.handleCodes = handleCodes; } public boolean isIgnoreErrors() { return ignoreErrors; } public void setIgnoreErrors(boolean ignoreErrors) { this.ignoreErrors = ignoreErrors; } public boolean isSaveRequest() { return saveRequest; } public void setSaveRequest(boolean saveRequest) { this.saveRequest = saveRequest; } public boolean isSaveResponse() { return saveResponse; } public void setSaveResponse(boolean saveResponse) { this.saveResponse = saveResponse;
} public boolean isSaveResponseTransient() { return saveResponseTransient; } public void setSaveResponseTransient(boolean saveResponseTransient) { this.saveResponseTransient = saveResponseTransient; } public boolean isSaveResponseAsJson() { return saveResponseAsJson; } public void setSaveResponseAsJson(boolean saveResponseAsJson) { this.saveResponseAsJson = saveResponseAsJson; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public boolean isNoRedirects() { return httpRequest.isNoRedirects(); } } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\BaseHttpActivityDelegate.java
1
请完成以下Java代码
default Set<String> getDependsOnTableNames() { return ImmutableSet.of(); } default Class<?> getValueClass() { return isNumericKey() ? IntegerLookupValue.class : StringLookupValue.class; } default int getSearchStringMinLength() { return -1; } default Optional<Duration> getSearchStartDelay() { return Optional.empty(); } default <T extends LookupDescriptor> T cast(final Class<T> ignoredLookupDescriptorClass) { @SuppressWarnings("unchecked") final T thisCasted = (T)this; return thisCasted; }
default <T extends LookupDescriptor> T castOrNull(final Class<T> lookupDescriptorClass) { if (lookupDescriptorClass.isAssignableFrom(getClass())) { @SuppressWarnings("unchecked") final T thisCasted = (T)this; return thisCasted; } return null; } default TooltipType getTooltipType() { return TooltipType.DEFAULT; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptor.java
1
请完成以下Java代码
public int getPA_ReportSource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportSource_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set 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 Report Line Set Name. @param ReportLineSetName Name of the Report Line Set */ public void setReportLineSetName (String ReportLineSetName) { set_Value (COLUMNNAME_ReportLineSetName, ReportLineSetName); } /** Get Report Line Set Name. @return Name of the Report Line Set */ public String getReportLineSetName () { return (String)get_Value(COLUMNNAME_ReportLineSetName); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_ReportLine.java
1
请完成以下Java代码
public Boolean getReadyForProcessing() { return readyForProcessing; } /** * @param readyForProcessing the readyForProcessing to set */ public WorkPackageQuery setReadyForProcessing(final Boolean readyForProcessing) { this.readyForProcessing = readyForProcessing; return this; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getError() */ @Override public Boolean getError() { return error; } /** * @param error the error to set */ public void setError(final Boolean error) { this.error = error; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getSkippedTimeoutMillis() */ @Override public long getSkippedTimeoutMillis() { return skippedTimeoutMillis; } /** * @param skippedTimeoutMillis the skippedTimeoutMillis to set */ public void setSkippedTimeoutMillis(final long skippedTimeoutMillis) { Check.assume(skippedTimeoutMillis >= 0, "skippedTimeoutMillis >= 0"); this.skippedTimeoutMillis = skippedTimeoutMillis; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getPackageProcessorIds() */ @Override @Nullable public Set<QueuePackageProcessorId> getPackageProcessorIds() { return packageProcessorIds; } /** * @param packageProcessorIds the packageProcessorIds to set */ public void setPackageProcessorIds(@Nullable final Set<QueuePackageProcessorId> packageProcessorIds) { if (packageProcessorIds != null) {
Check.assumeNotEmpty(packageProcessorIds, "packageProcessorIds cannot be empty!"); } this.packageProcessorIds = packageProcessorIds; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getPriorityFrom() */ @Override public String getPriorityFrom() { return priorityFrom; } /** * @param priorityFrom the priorityFrom to set */ public void setPriorityFrom(final String priorityFrom) { this.priorityFrom = priorityFrom; } @Override public String toString() { return "WorkPackageQuery [" + "processed=" + processed + ", readyForProcessing=" + readyForProcessing + ", error=" + error + ", skippedTimeoutMillis=" + skippedTimeoutMillis + ", packageProcessorIds=" + packageProcessorIds + ", priorityFrom=" + priorityFrom + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQuery.java
1
请在Spring Boot框架中完成以下Java代码
public final class InsertIntoImportTableResult { // // Configuration @Nullable @With URI fromResource; String toImportTableName; @NonNull String importFormatName; @Nullable DataImportConfigId dataImportConfigId; // // Result @NonNull Duration duration; @NonNull DataImportRunId dataImportRunId; int countTotalRows; int countValidRows; @NonNull @Singular ImmutableList<Error> errors; public boolean hasErrors() {
return !getErrors().isEmpty(); } public int getCountErrors() { return getErrors().size(); } @Builder @Value public static class Error { String message; int lineNo; @NonNull String lineContent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\InsertIntoImportTableResult.java
2
请完成以下Java代码
public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedCaseInstanceCount() { return finishedCaseInstanceCount; } public void setFinishedCaseInstanceCount(Long finishedCaseInstanceCount) { this.finishedCaseInstanceCount = finishedCaseInstanceCount; } public long getCleanableCaseInstanceCount() { return cleanableCaseInstanceCount; } public void setCleanableCaseInstanceCount(Long cleanableCaseInstanceCount) { this.cleanableCaseInstanceCount = cleanableCaseInstanceCount; } public String getTenantId() {
return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[caseDefinitionId = " + caseDefinitionId + ", caseDefinitionKey = " + caseDefinitionKey + ", caseDefinitionName = " + caseDefinitionName + ", caseDefinitionVersion = " + caseDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedCaseInstanceCount = " + finishedCaseInstanceCount + ", cleanableCaseInstanceCount = " + cleanableCaseInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricCaseInstanceReportResultEntity.java
1
请完成以下Java代码
public Set<String> keySet() { return inputVariableContainer.getVariableNames(); } @Override public int size() { return inputVariableContainer.getVariableNames().size(); } @Override public Collection<Object> values() { Set<String> variableNames = inputVariableContainer.getVariableNames(); List<Object> values = new ArrayList<>(variableNames.size()); for (String key : variableNames) { values.add(inputVariableContainer.getVariable(key)); } return values; } @Override public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); }
@Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } protected Map<String, Object> getVariables() { if (this.scopeContainer instanceof VariableScope) { return ((VariableScope) this.scopeContainer).getVariables(); } return Collections.emptyMap(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public boolean removeTags(String title, List<String> tags) { UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title), Updates.pullAll(TAGS_FIELD, tags)); return result.getModifiedCount() == 1; } /** * Utility method used to map a MongoDB document into a {@link Post}. * * @param document * the document to map * @return a {@link Post} object equivalent to the document passed as * argument */ @SuppressWarnings("unchecked") private static Post documentToPost(Document document) { Post post = new Post();
post.setTitle(document.getString(DBCollection.ID_FIELD_NAME)); post.setAuthor(document.getString("author")); post.setTags((List<String>) document.get(TAGS_FIELD)); return post; } /* * (non-Javadoc) * * @see java.io.Closeable#close() */ @Override public void close() throws IOException { mongoClient.close(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\tagging\TagRepository.java
1
请完成以下Java代码
private int getWindowNo() { return Env.getWindowNo(getParent()); } private void addHeaderLine(final String labelText, final Component field) { if (labelText != null) { final Properties ctx = Env.getCtx(); final CLabel label = new CLabel(Services.get(IMsgBL.class).translate(ctx, labelText)); headerPanel.add(label, new GridBagConstraints(0, m_headerLine, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 10, 0, 5), 0, 0)); } headerPanel.add(field, new GridBagConstraints(1, m_headerLine, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 10), 1, 0)); // m_headerLine++; } private int m_headerLine = 0; private BoilerPlateContext attributes; private boolean m_isPrinted = false; private boolean m_isPressedOK = false; private boolean m_isPrintOnOK = false; /** * Set Message */ public void setMessage(final String newMessage) { m_message = newMessage; fMessage.setText(m_message); fMessage.setCaretPosition(0); } // setMessage /** * Get Message */ public String getMessage() { m_message = fMessage.getText(); return m_message; } // getMessage public void setAttributes(final BoilerPlateContext attributes) { this.attributes = attributes; fMessage.setAttributes(attributes); } public BoilerPlateContext getAttributes() { return attributes; } /** * Action Listener - Send email */ @Override public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals(ConfirmPanel.A_OK)) { try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); confirmPanel.getOKButton().setEnabled(false); // if (m_isPrintOnOK) { m_isPrinted = fMessage.print(); } } finally { confirmPanel.getOKButton().setEnabled(true); setCursor(Cursor.getDefaultCursor());
} // m_isPrinted = true; m_isPressedOK = true; dispose(); } else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) { dispose(); } } // actionPerformed public void setPrintOnOK(final boolean value) { m_isPrintOnOK = value; } public boolean isPressedOK() { return m_isPressedOK; } public boolean isPrinted() { return m_isPrinted; } public File getPDF() { return fMessage.getPDF(getTitle()); } public RichTextEditor getRichTextEditor() { return fMessage; } } // Letter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\LetterDialog.java
1
请在Spring Boot框架中完成以下Java代码
public class TextModerationService { private final OpenAiModerationModel openAiModerationModel; @Autowired public TextModerationService(OpenAiModerationModel openAiModerationModel) { this.openAiModerationModel = openAiModerationModel; } public String moderate(String text) { ModerationPrompt moderationRequest = new ModerationPrompt(text); ModerationResponse response = openAiModerationModel.call(moderationRequest); Moderation output = response.getResult().getOutput(); return output.getResults().stream() .map(this::buildModerationResult) .collect(Collectors.joining("\n")); } private String buildModerationResult(ModerationResult moderationResult) { Categories categories = moderationResult.getCategories();
String violations = Stream.of( Map.entry("Sexual", categories.isSexual()), Map.entry("Hate", categories.isHate()), Map.entry("Harassment", categories.isHarassment()), Map.entry("Self-Harm", categories.isSelfHarm()), Map.entry("Sexual/Minors", categories.isSexualMinors()), Map.entry("Hate/Threatening", categories.isHateThreatening()), Map.entry("Violence/Graphic", categories.isViolenceGraphic()), Map.entry("Self-Harm/Intent", categories.isSelfHarmIntent()), Map.entry("Self-Harm/Instructions", categories.isSelfHarmInstructions()), Map.entry("Harassment/Threatening", categories.isHarassmentThreatening()), Map.entry("Violence", categories.isViolence())) .filter(entry -> Boolean.TRUE.equals(entry.getValue())) .map(Map.Entry::getKey) .collect(Collectors.joining(", ")); return violations.isEmpty() ? "No category violations detected." : "Violated categories: " + violations; } }
repos\tutorials-master\spring-ai-modules\spring-ai-4\src\main\java\com\baeldung\springai\moderation\TextModerationService.java
2
请完成以下Spring Boot application配置
#Updated at Tue Apr 04 15:03:53 BST 2017 #Tue Apr 04 15:03:53 BST 2017 spring.datasource.driver-class-name=org.hsqldb.jdbcDriver spring.datasource.url=jdbc\:hsqldb\:mem\:roo spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy s
pring.messages.encoding=ISO-8859-1 spring.messages.fallback-to-system-locale=false spring.thymeleaf.mode=html
repos\tutorials-master\spring-roo\src\main\resources\application.properties
2
请完成以下Java代码
public List<User> search(String text) { // get the full text entity manager FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search. getFullTextEntityManager(entityManager); // create the query using Hibernate Search query DSL QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory() .buildQueryBuilder().forEntity(User.class).get(); // a very basic query by keywords org.apache.lucene.search.Query query = queryBuilder .keyword() .onFields("name", "city", "email")
.matching(text) .createQuery(); // wrap Lucene query in an Hibernate Query object org.hibernate.search.jpa.FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, User.class); // execute search and return results (sorted by relevance as default) @SuppressWarnings("unchecked") List<User> results = jpaQuery.getResultList(); return results; } // method search } // class
repos\spring-boot-samples-master\spring-boot-hibernate-search\src\main\java\netgloo\search\UserSearch.java
1
请完成以下Java代码
public List<T> findAll() { return entityManager.createQuery("from " + clazz.getName()).getResultList(); } public void create(final T entity) { entityManager.persist(entity); } public T update(final T entity) { return entityManager.merge(entity); } public void delete(final T entity) { entityManager.remove(entity); } public void deleteById(final long entityId) { final T entity = findOne(entityId); delete(entity); } public long countAllRowsUsingHibernateCriteria() { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.setProjection(Projections.rowCount()); Long count = (Long) criteria.uniqueResult(); return count != null ? count : 0L; } public long getFooCountByBarNameUsingHibernateCriteria(String barName) {
Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } public long getFooCountByBarNameAndFooNameUsingHibernateCriteria(String barName, String fooName) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.add(Restrictions.eq("name", fooName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernate\cache\dao\AbstractJpaDAO.java
1
请在Spring Boot框架中完成以下Java代码
public static class DeletedPPOrderLineDescriptor { public static DeletedPPOrderLineDescriptor ofPPOrderLine(@NonNull final PPOrderLine ppOrderLine) { final PPOrderLineData ppOrderLineData = ppOrderLine.getPpOrderLineData(); return DeletedPPOrderLineDescriptor.builder() .issueOrReceiveDate(ppOrderLineData.getIssueOrReceiveDate()) .ppOrderLineId(ppOrderLine.getPpOrderLineId()) .productDescriptor(ppOrderLineData.getProductDescriptor()) .qtyRequired(ppOrderLineData.getQtyRequired()) .qtyDelivered(ppOrderLineData.getQtyDelivered()) .build(); } int ppOrderLineId; ProductDescriptor productDescriptor; Instant issueOrReceiveDate; BigDecimal qtyRequired; BigDecimal qtyDelivered; @JsonCreator private DeletedPPOrderLineDescriptor( @JsonProperty("ppOrderLineId") final int ppOrderLineId, @JsonProperty("productDescriptor") @NonNull final ProductDescriptor productDescriptor, @JsonProperty("issueOrReceiveDate") @NonNull final Instant issueOrReceiveDate, @JsonProperty("qtyRequired") @NonNull final BigDecimal qtyRequired, @JsonProperty("qtyDelivered") @NonNull final BigDecimal qtyDelivered) { this.ppOrderLineId = Check.assumeGreaterThanZero(ppOrderLineId, "ppOrderLineId"); this.productDescriptor = productDescriptor;
this.issueOrReceiveDate = issueOrReceiveDate; this.qtyRequired = qtyRequired; this.qtyDelivered = qtyDelivered; } } @Nullable @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_PP_Order.Table_Name, ppOrderAfterChanges.getPpOrderId()); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderChangedEvent.java
2
请完成以下Java代码
public static InvoiceDocBaseType ofCode(@NonNull final String code) { return index.ofCode(code); } public static InvoiceDocBaseType ofNullableCode(@Nullable final String code) { return index.ofNullableCode(code); } public static InvoiceDocBaseType ofSOTrxAndCreditMemo(@NonNull final SOTrx soTrx, final boolean creditMemo) { if (soTrx.isSales()) { return !creditMemo ? CustomerInvoice : CustomerCreditMemo; } else // purchase { return !creditMemo ? VendorInvoice : VendorCreditMemo; } } public static InvoiceDocBaseType ofDocBaseType(@NonNull final DocBaseType docBaseType) { return ofCode(docBaseType.getCode()); } @Override public String getCode() { return getDocBaseType().getCode(); } public boolean isSales() { return getSoTrx().isSales(); } public boolean isPurchase() { return getSoTrx().isPurchase(); } /** * @return is Account Payable (AP), aka purchase
* @see #isPurchase() */ public boolean isAP() {return isPurchase();} public boolean isCustomerInvoice() { return this == CustomerInvoice; } public boolean isCustomerCreditMemo() { return this == CustomerCreditMemo; } public boolean isVendorCreditMemo() { return this == VendorCreditMemo; } public boolean isIncomingCash() { return (isSales() && !isCreditMemo()) // ARI || (isPurchase() && isCreditMemo()) // APC ; } public boolean isOutgoingCash() { return !isIncomingCash(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceDocBaseType.java
1
请完成以下Java代码
public NamePair get (final IValidationContext evalCtx, Object value) { if (value == null) return null; int M_AttributeSetInstance_ID = 0; if (value instanceof Integer) M_AttributeSetInstance_ID = ((Integer)value).intValue(); else { try { M_AttributeSetInstance_ID = Integer.parseInt(value.toString()); } catch (Exception e) { log.error("Value=" + value, e); } } if (M_AttributeSetInstance_ID == 0) return NO_INSTANCE; // String Description = null; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement("SELECT Description " + "FROM M_AttributeSetInstance " + "WHERE M_AttributeSetInstance_ID=?", null); pstmt.setInt(1, M_AttributeSetInstance_ID); rs = pstmt.executeQuery(); if (rs.next()) { Description = rs.getString(1); // Description if (Description == null || Description.length() == 0) { if (LogManager.isLevelFine()) Description = "{" + M_AttributeSetInstance_ID + "}"; else Description = ""; } } } catch (Exception e) { log.error("get", e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } if (Description == null) return null; return new KeyNamePair (M_AttributeSetInstance_ID, Description); } // get /** * Dispose * @see org.compiere.model.Lookup#dispose() */ @Override public void dispose() { log.debug("");
super.dispose(); } // dispose /** * Return data as sorted Array - not implemented * @param mandatory mandatory * @param onlyValidated only validated * @param onlyActive only active * @param temporary force load for temporary display * @return null */ @Override public ArrayList<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { log.error("Not implemented"); return null; } // getArray @Override public String getTableName() { return I_M_AttributeSetInstance.Table_Name; } /** * Get underlying fully qualified Table.Column Name. * Used for VLookup.actionButton (Zoom) * @return column name */ @Override public String getColumnName() { return I_M_AttributeSetInstance.Table_Name + "." + I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID; } // getColumnName @Override public String getColumnNameNotFQ() { return I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID; } } // MPAttribute
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPAttributeLookup.java
1
请完成以下Java代码
private static void updateRowPKFromIDServer(final String tableName, final String pkColumnName, final Map<String, Object> whereClause) { final int id = MSequence.getNextProjectID_HTTP(tableName); if (id <= 0) { throw new AdempiereException("Failed retrieving ID for " + tableName + " from ID server"); } final StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(tableName).append(" SET ").append(pkColumnName).append("=").append(id); sql.append(" WHERE 1=1"); for (final Map.Entry<String, Object> e : whereClause.entrySet()) { final String columnName = e.getKey(); final Object value = e.getValue(); sql.append(" AND ").append(columnName).append("=").append(DB.TO_SQL(value)); } DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); } private void updatePKFromDBSequence(final String tableName, final String pkColumnName) { final int count = DB.executeUpdateAndThrowExceptionOnFail( "UPDATE " + tableName + " SET " + pkColumnName + "=" + DB.TO_TABLESEQUENCE_NEXTVAL(tableName) + " WHERE " + pkColumnName + " IS NULL", new Object[] {}, ITrx.TRXNAME_ThreadInherited); addLog("Updated {}.{} for {} rows using local DB sequence", tableName, pkColumnName, count); } private void executeDDL(final String sql) { DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); addLog("DDL: " + sql); } private void addToTabs(final I_AD_Column column) { final int adTableId = column.getAD_Table_ID(); queryBL.createQueryBuilder(I_AD_Tab.class, column) .addEqualsFilter(I_AD_Tab.COLUMNNAME_AD_Table_ID, adTableId) .create()
.stream(I_AD_Tab.class) .forEach(tab -> createAD_Field(tab, column)); } private void createAD_Field(final I_AD_Tab tab, final I_AD_Column column) { final String fieldEntityType = null; // auto final I_AD_Field field; try { final boolean displayedIfNotIDColumn = true; // actually doesn't matter because PK probably is an ID column anyways field = AD_Tab_CreateFields.createADField(tab, column, displayedIfNotIDColumn, fieldEntityType); // log final I_AD_Window window = tab.getAD_Window(); addLog("@Created@ " + window + " -> " + tab + " -> " + field); } catch (final Exception ex) { logger.warn("Failed creating AD_Field for {} in {}", column, tab, ex); addLog("@Error@ creating AD_Field for {} in {}: {}", column, tab, ex.getLocalizedMessage()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\TablePrimaryKeyGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public class DataSourceController { //自动配置,因此可以直接通过 @Autowired 注入进来 @Autowired DataSource dataSource; // 查询数据源信息 @GetMapping("/datasource") public Map<String, Object> datasource() throws SQLException { Map result = new HashMap(); result.put("数据源类名", dataSource.getClass()+""); // 获取数据库连接对象 Connection connection = dataSource.getConnection(); // 判断连接对象是否为空 result.put("能否正确获得连接", connection != null); connection.close(); return result; } // 查询数据源信息 @GetMapping("/datasource2") public Map<String, Object> datasource2() throws SQLException {
DruidDataSource druidDataSource = (DruidDataSource)dataSource; Map result = new HashMap(); result.put("数据源类名", druidDataSource.getClass()+""); // 获取数据库连接对象 Connection connection = druidDataSource.getConnection(); // 判断连接对象是否为空 result.put("能否正确获得连接", connection != null); result.put("initialSize值为",druidDataSource.getInitialSize()); result.put("maxActive值为",druidDataSource.getMaxActive()); result.put("minIdle值为",druidDataSource.getMinIdle()); result.put("validationQuery值为",druidDataSource.getValidationQuery()); result.put("maxWait值为",druidDataSource.getMaxWait()); connection.close(); return result; } }
repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-druid\src\main\java\cn\lanqiao\springboot3\controller\DataSourceController.java
2
请完成以下Java代码
default ITrxItemExecutorBuilder<IT, RT> setProcessor(final Consumer<IT> processor) { Preconditions.checkNotNull(processor, "processor is null"); setProcessor(new TrxItemProcessorAdapter<IT, RT>() { @Override public void process(IT item) throws Exception { processor.accept(item); } }); return this; } /** * Sets exception handler to be used if processing fails. * * @see ITrxItemProcessorExecutor#setExceptionHandler(ITrxItemExceptionHandler) * @see ITrxItemProcessorExecutor#DEFAULT_ExceptionHandler */ ITrxItemExecutorBuilder<IT, RT> setExceptionHandler(ITrxItemExceptionHandler exceptionHandler); /** * Specifies what to do if processing an item fails. * * @see ITrxItemProcessorExecutor#DEFAULT_OnItemErrorPolicy for the default value. * * task https://github.com/metasfresh/metasfresh/issues/302 */ ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(OnItemErrorPolicy onItemErrorPolicy); /** * Sets how many items we shall maximally process in one batch/transaction. *
* @param itemsPerBatch items per batch or {@link Integer#MAX_VALUE} if you want to not enforce the restriction. */ ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(int itemsPerBatch); /** * Sets if the executor shall use transaction savepoints on individual chunks internally. * This setting is only relevant, if the executor's parent-trx is null (see {@link #setContext(Properties, String)}). * <p> * If <code>true</code> and the executor has an external not-null transaction, * then the executor will create a {@link ITrxSavepoint} when starting a new chunk. * If a chunk fails and is canceled, the executor will roll back to the savepoint. * Without a savepoint, the executor will not roll back. * * * @see ITrxItemProcessorExecutor#setUseTrxSavepoints(boolean) */ ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(boolean useTrxSavepoints); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\ITrxItemExecutorBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("step1", jobRepository) .<String, String>chunk(2, transactionManager) .reader(flatFileItemReader()) .processor(itemProcessor()) .writer(itemWriter()) .build(); } @Bean @StepScope public FlatFileItemReader<String> flatFileItemReader() { return new FlatFileItemReaderBuilder<String>() .name("itemReader") .resource(new ClassPathResource("data.csv")) .lineMapper(new PassThroughLineMapper()) .saveState(true) .build(); } @Bean public RestartItemProcessor itemProcessor() { return new RestartItemProcessor(); } @Bean public ItemWriter<String> itemWriter() { return items -> { System.out.println("Writing items:");
for (String item : items) { System.out.println("- " + item); } }; } static class RestartItemProcessor implements ItemProcessor<String, String> { private boolean failOnItem3 = true; public void setFailOnItem3(boolean failOnItem3) { this.failOnItem3 = failOnItem3; } @Override public String process(String item) throws Exception { System.out.println("Processing: " + item + " (failOnItem3=" + failOnItem3 + ")"); if (failOnItem3 && item.equals("Item3")) { throw new RuntimeException("Simulated failure on Item3"); } return "PROCESSED " + item; } } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\restartjob\BatchConfig.java
2
请完成以下Java代码
public static ArticleTitle of(String title) { return new ArticleTitle(title, slugFromTitle(title)); } private ArticleTitle(String title, String slug) { this.title = title; this.slug = slug; } protected ArticleTitle() { } private static String slugFromTitle(String title) { return title.toLowerCase() .replaceAll("\\$,'\"|\\s|\\.|\\?", "-") .replaceAll("-{2,}", "-") .replaceAll("(^-)|(-$)", ""); } public String getSlug() {
return slug; } public String getTitle() { return title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArticleTitle that = (ArticleTitle) o; return slug.equals(that.slug); } @Override public int hashCode() { return Objects.hash(slug); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\ArticleTitle.java
1
请完成以下Java代码
private boolean isProcessedByFutureEvent(final I_PMM_PurchaseCandidate candidate, final I_PMM_QtyReport_Event currentEvent) { if (candidate == null) { return false; } final int lastQtyReportEventId = candidate.getLast_QtyReport_Event_ID(); if (lastQtyReportEventId > currentEvent.getPMM_QtyReport_Event_ID()) { return true; } return false; } public String getProcessSummary() { return "@Processed@ #" + countProcessed.get() + ", @IsError@ #" + countErrors.get() + ", @Skipped@ #" + countSkipped.get(); } @VisibleForTesting
static PMMBalanceChangeEvent createPMMBalanceChangeEvent(final I_PMM_QtyReport_Event qtyReportEvent) { final BigDecimal qtyPromisedDiff = qtyReportEvent.getQtyPromised().subtract(qtyReportEvent.getQtyPromised_Old()); final BigDecimal qtyPromisedTUDiff = qtyReportEvent.getQtyPromised_TU().subtract(qtyReportEvent.getQtyPromised_TU_Old()); final PMMBalanceChangeEvent event = PMMBalanceChangeEvent.builder() .setC_BPartner_ID(qtyReportEvent.getC_BPartner_ID()) .setM_Product_ID(qtyReportEvent.getM_Product_ID()) .setM_AttributeSetInstance_ID(qtyReportEvent.getM_AttributeSetInstance_ID()) .setM_HU_PI_Item_Product_ID(qtyReportEvent.getM_HU_PI_Item_Product_ID()) .setC_Flatrate_DataEntry_ID(qtyReportEvent.getC_Flatrate_DataEntry_ID()) // .setDate(qtyReportEvent.getDatePromised()) // .setQtyPromised(qtyPromisedDiff, qtyPromisedTUDiff) // .build(); logger.trace("Created event {} from {}", event, qtyReportEvent); return event; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMQtyReportEventTrxItemProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class SysDataLogController { @Autowired private ISysDataLogService service; @RequestMapping(value = "/list", method = RequestMethod.GET) public Result<IPage<SysDataLog>> queryPageList(SysDataLog dataLog,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) { Result<IPage<SysDataLog>> result = new Result<IPage<SysDataLog>>(); dataLog.setType(CommonConstant.DATA_LOG_TYPE_JSON); QueryWrapper<SysDataLog> queryWrapper = QueryGenerator.initQueryWrapper(dataLog, req.getParameterMap()); Page<SysDataLog> page = new Page<SysDataLog>(pageNo, pageSize); IPage<SysDataLog> pageList = service.page(page, queryWrapper); log.info("查询当前页:"+pageList.getCurrent()); log.info("查询当前页数量:"+pageList.getSize()); log.info("查询结果数量:"+pageList.getRecords().size()); log.info("数据总数:"+pageList.getTotal()); result.setSuccess(true); result.setResult(pageList); return result; } /** * 查询对比数据 * @param req * @return */ @RequestMapping(value = "/queryCompareList", method = RequestMethod.GET) public Result<List<SysDataLog>> queryCompareList(HttpServletRequest req) { Result<List<SysDataLog>> result = new Result<>(); String dataId1 = req.getParameter("dataId1"); String dataId2 = req.getParameter("dataId2"); List<String> idList = new ArrayList<String>(); idList.add(dataId1); idList.add(dataId2); try { List<SysDataLog> list = (List<SysDataLog>) service.listByIds(idList); result.setResult(list); result.setSuccess(true); } catch (Exception e) { log.error(e.getMessage(),e); } return result; } /**
* 查询版本信息 * @param req * @return */ @RequestMapping(value = "/queryDataVerList", method = RequestMethod.GET) public Result<List<SysDataLog>> queryDataVerList(HttpServletRequest req) { Result<List<SysDataLog>> result = new Result<>(); String dataTable = req.getParameter("dataTable"); String dataId = req.getParameter("dataId"); QueryWrapper<SysDataLog> queryWrapper = new QueryWrapper<SysDataLog>(); queryWrapper.eq("data_table", dataTable); queryWrapper.eq("data_id", dataId); // 代码逻辑说明: 新增查询条件-type String type = req.getParameter("type"); if (oConvertUtils.isNotEmpty(type)) { queryWrapper.eq("type", type); } // 按时间倒序排 queryWrapper.orderByDesc("create_time"); List<SysDataLog> list = service.list(queryWrapper); if(list==null||list.size()<=0) { result.error500("未找到版本信息"); }else { result.setResult(list); result.setSuccess(true); } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDataLogController.java
2
请完成以下Java代码
public class InputClauseImpl extends DmnElementImpl implements InputClause { protected static ChildElement<InputExpression> inputExpressionChild; protected static ChildElement<InputValues> inputValuesChild; // camunda extensions protected static Attribute<String> camundaInputVariableAttribute; public InputClauseImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public InputExpression getInputExpression() { return inputExpressionChild.getChild(this); } public void setInputExpression(InputExpression inputExpression) { inputExpressionChild.setChild(this, inputExpression); } public InputValues getInputValues() { return inputValuesChild.getChild(this); } public void setInputValues(InputValues inputValues) { inputValuesChild.setChild(this, inputValues); } // camunda extensions public String getCamundaInputVariable() { return camundaInputVariableAttribute.getValue(this); }
public void setCamundaInputVariable(String inputVariable) { camundaInputVariableAttribute.setValue(this, inputVariable); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InputClause.class, DMN_ELEMENT_INPUT_CLAUSE) .namespaceUri(LATEST_DMN_NS) .extendsType(DmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<InputClause>() { public InputClause newInstance(ModelTypeInstanceContext instanceContext) { return new InputClauseImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputExpressionChild = sequenceBuilder.element(InputExpression.class) .required() .build(); inputValuesChild = sequenceBuilder.element(InputValues.class) .build(); // camunda extensions camundaInputVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_INPUT_VARIABLE) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\InputClauseImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PoemSubmission { @GetMapping("/poem/success") public String getSuccess(HttpServletRequest request) { Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { Poem poem = (Poem) inputFlashMap.get("poem"); return "success"; } else { return "redirect:/poem/submit"; } } @PostMapping("/poem/submit") public RedirectView submitPost( HttpServletRequest request, @ModelAttribute Poem poem,
RedirectAttributes redirectAttributes) { if (Poem.isValidPoem(poem)) { redirectAttributes.addFlashAttribute("poem", poem); return new RedirectView("/poem/success", true); } else { return new RedirectView("/poem/submit", true); } } @GetMapping("/poem/submit") public String submitGet(Model model) { model.addAttribute("poem", new Poem()); return "submit"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-3\src\main\java\com\baeldung\flash_attributes\controllers\PoemSubmission.java
2
请完成以下Java代码
private static TreeMap<Double ,Set<String>> sortScoreMap(TreeMap<String, Double> scoreMap) { TreeMap<Double, Set<String>> result = new TreeMap<Double, Set<String>>(Collections.reverseOrder()); for (Map.Entry<String, Double> entry : scoreMap.entrySet()) { Set<String> sentenceSet = result.get(entry.getValue()); if (sentenceSet == null) { sentenceSet = new HashSet<String>(); result.put(entry.getValue(), sentenceSet); } sentenceSet.add(entry.getKey()); } return result; } /**
* 从map的值中找出最大值,这个值是从0开始的 * @param map * @return */ private static Double max(Map<String, Double> map) { Double theMax = 0.0; for (Double v : map.values()) { theMax = Math.max(theMax, v); } return theMax; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\suggest\Suggester.java
1
请完成以下Java代码
public void run() { startLatch.countDown(); try (Statement st = conn.createStatement()) { log.debug("notifierTask: enabling notifications for channel {}", channelName); st.execute("LISTEN " + channelName); PGConnection pgConn = conn.unwrap(PGConnection.class); while (!Thread.currentThread() .isInterrupted()) { log.debug("notifierTask: wainting for notifications. channel={}", channelName); PGNotification[] nts = pgConn.getNotifications(); log.debug("notifierTask: processing {} notification(s)", nts.length); for (PGNotification n : nts) { Message<?> msg = convertNotification(n); getDispatcher().dispatch(msg); } } } catch (SQLException sex) { // TODO: Handle exceptions } finally { stopLatch.countDown(); } } @SuppressWarnings("unchecked") private Message<?> convertNotification(PGNotification n) { String payload = n.getParameter(); try { JsonNode root = om.readTree(payload); if (!root.isObject()) { return new ErrorMessage(new IllegalArgumentException("Message is not a JSON Object")); } Map<String, Object> hdr; JsonNode headers = root.path(HEADER_FIELD);
if (headers.isObject()) { hdr = om.treeToValue(headers, Map.class); } else { hdr = Collections.emptyMap(); } JsonNode body = root.path(BODY_FIELD); return MessageBuilder .withPayload(body.isTextual()?body.asText():body) .copyHeaders(hdr) .build(); } catch (Exception ex) { return new ErrorMessage(ex); } } } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\postgresqlnotify\PostgresSubscribableChannel.java
1
请完成以下Java代码
private static class ScriptLocationResolver { private final ResourcePatternResolver resourcePatternResolver; ScriptLocationResolver(ResourceLoader resourceLoader) { this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); } private List<Resource> resolve(String location) throws IOException { List<Resource> resources = new ArrayList<>( Arrays.asList(this.resourcePatternResolver.getResources(location))); resources.sort((r1, r2) -> { try { return r1.getURL().toString().compareTo(r2.getURL().toString()); } catch (IOException ex) { return 0; } }); return resources; } } /** * Scripts to be used to initialize the database. * * @since 3.0.0 */ public static class Scripts implements Iterable<Resource> { private final List<Resource> resources; private boolean continueOnError; private String separator = ";"; private @Nullable Charset encoding; public Scripts(List<Resource> resources) { this.resources = resources; }
@Override public Iterator<Resource> iterator() { return this.resources.iterator(); } public Scripts continueOnError(boolean continueOnError) { this.continueOnError = continueOnError; return this; } public boolean isContinueOnError() { return this.continueOnError; } public Scripts separator(String separator) { this.separator = separator; return this; } public String getSeparator() { return this.separator; } public Scripts encoding(@Nullable Charset encoding) { this.encoding = encoding; return this; } public @Nullable Charset getEncoding() { return this.encoding; } } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\AbstractScriptDatabaseInitializer.java
1
请完成以下Java代码
public int getM_ProductBOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductBOM_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_ProductOperation getM_ProductOperation() throws RuntimeException { return (I_M_ProductOperation)MTable.get(getCtx(), I_M_ProductOperation.Table_Name) .getPO(getM_ProductOperation_ID(), get_TrxName()); } /** Set Product Operation. @param M_ProductOperation_ID Product Manufacturing Operation */ public void setM_ProductOperation_ID (int M_ProductOperation_ID) { if (M_ProductOperation_ID < 1) set_Value (COLUMNNAME_M_ProductOperation_ID, null); else set_Value (COLUMNNAME_M_ProductOperation_ID, Integer.valueOf(M_ProductOperation_ID)); } /** Get Product Operation. @return Product Manufacturing Operation */ public int getM_ProductOperation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMProduct.java
1
请完成以下Java代码
public class C_Printing_Queue_ResetAggregationKeys extends JavaProcess { @Override protected void prepare() { // nothing to prepare here } @Override protected String doIt() throws Exception { final IQueryFilter<I_C_Printing_Queue> queryFilter = getProcessInfo().getQueryFilterOrElseFalse(); final Iterator<I_C_Printing_Queue> iterator = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Printing_Queue.class, getCtx(), getTrxName()) .filter(queryFilter) .orderBy().addColumn(I_C_Printing_Queue.COLUMN_C_Printing_Queue_ID)
.endOrderBy() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterate(I_C_Printing_Queue.class); final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class); for(final I_C_Printing_Queue item: IteratorUtils.asIterable(iterator)) { printingQueueBL.setItemAggregationKey(item); InterfaceWrapperHelper.save(item); } return "@Success@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Printing_Queue_ResetAggregationKeys.java
1
请在Spring Boot框架中完成以下Java代码
public final class XADataSourceAutoConfiguration implements BeanClassLoaderAware { @SuppressWarnings("NullAway.Init") private ClassLoader classLoader; @Bean @ConditionalOnMissingBean(JdbcConnectionDetails.class) PropertiesJdbcConnectionDetails jdbcConnectionDetails(DataSourceProperties properties) { return new PropertiesJdbcConnectionDetails(properties); } @Bean DataSource dataSource(XADataSourceWrapper wrapper, DataSourceProperties properties, JdbcConnectionDetails connectionDetails, ObjectProvider<XADataSource> xaDataSource) throws Exception { return wrapper .wrapDataSource(xaDataSource.getIfAvailable(() -> createXaDataSource(properties, connectionDetails))); } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } private XADataSource createXaDataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) { String className = connectionDetails.getXaDataSourceClassName(); Assert.state(StringUtils.hasLength(className), "No XA DataSource class name specified"); XADataSource dataSource = createXaDataSourceInstance(className); bindXaProperties(dataSource, properties, connectionDetails); return dataSource; } private XADataSource createXaDataSourceInstance(String className) { try { Class<?> dataSourceClass = ClassUtils.forName(className, this.classLoader); Object instance = BeanUtils.instantiateClass(dataSourceClass);
Assert.state(instance instanceof XADataSource, () -> "DataSource class " + className + " is not an XADataSource"); return (XADataSource) instance; } catch (Exception ex) { throw new IllegalStateException("Unable to create XADataSource instance from '" + className + "'"); } } private void bindXaProperties(XADataSource target, DataSourceProperties dataSourceProperties, JdbcConnectionDetails connectionDetails) { Binder binder = new Binder(getBinderSource(dataSourceProperties, connectionDetails)); binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(target)); } private ConfigurationPropertySource getBinderSource(DataSourceProperties dataSourceProperties, JdbcConnectionDetails connectionDetails) { Map<Object, Object> properties = new HashMap<>(dataSourceProperties.getXa().getProperties()); properties.computeIfAbsent("user", (key) -> connectionDetails.getUsername()); properties.computeIfAbsent("password", (key) -> connectionDetails.getPassword()); try { properties.computeIfAbsent("url", (key) -> connectionDetails.getJdbcUrl()); } catch (DataSourceBeanCreationException ex) { // Continue as not all XA DataSource's require a URL } MapConfigurationPropertySource source = new MapConfigurationPropertySource(properties); ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("user", "username"); return source.withAliases(aliases); } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\XADataSourceAutoConfiguration.java
2
请完成以下Java代码
public class ErrorReceivedListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNErrorReceivedEvent>> processRuntimeEventListeners; private ToErrorReceivedConverter converter; public ErrorReceivedListenerDelegate( List<BPMNElementEventListener<BPMNErrorReceivedEvent>> processRuntimeEventListeners, ToErrorReceivedConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiErrorEvent) { converter .from((ActivitiErrorEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNErrorReceivedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ErrorReceivedListenerDelegate.java
1
请完成以下Java代码
public void setTimeToLive(Duration timeToLive) { forEach((caching) -> caching.setTimeToLive(timeToLive)); } @Override public void clear() { forEach(ConfigurationPropertyCaching::clear); } @Override public CacheOverride override() { CacheOverrides override = new CacheOverrides(); forEach(override::add); return override; } private void forEach(Consumer<ConfigurationPropertyCaching> action) { if (this.sources != null) { for (ConfigurationPropertySource source : this.sources) { ConfigurationPropertyCaching caching = CachingConfigurationPropertySource.find(source); if (caching != null) { action.accept(caching); } } } }
/** * Composite {@link CacheOverride}. */ private final class CacheOverrides implements CacheOverride { private List<CacheOverride> overrides = new ArrayList<>(); void add(ConfigurationPropertyCaching caching) { this.overrides.add(caching.override()); } @Override public void close() { this.overrides.forEach(CacheOverride::close); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertySourcesCaching.java
1
请完成以下Java代码
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getSourceProcessDefinitionId() { return sourceProcessDefinitionId; } public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetProcessDefinitionId() { return targetProcessDefinitionId;
} public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public String getMigrationMessage() { return migrationMessage; } public void setMigrationMessage(String migrationMessage) { this.migrationMessage = migrationMessage; } public String getMigrationStacktrace() { return migrationStacktrace; } public void setMigrationStacktrace(String migrationStacktrace) { this.migrationStacktrace = migrationStacktrace; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceBatchMigrationPartResult.java
1
请完成以下Java代码
public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** * TypeMRP AD_Reference_ID=53230 * Reference name: _MRP Type */ public static final int TYPEMRP_AD_Reference_ID=53230; /** Demand = D */ public static final String TYPEMRP_Demand = "D"; /** Supply = S */ public static final String TYPEMRP_Supply = "S"; /** Set TypeMRP. @param TypeMRP TypeMRP */ @Override public void setTypeMRP (java.lang.String TypeMRP) { set_Value (COLUMNNAME_TypeMRP, TypeMRP); } /** Get TypeMRP. @return TypeMRP */ @Override public java.lang.String getTypeMRP () { return (java.lang.String)get_Value(COLUMNNAME_TypeMRP); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique
*/ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.math.BigDecimal Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.math.BigDecimal getVersion () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
1
请完成以下Java代码
public int getP_WIP_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); }
/** Get Verarbeiten. @return Verarbeiten */ @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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Category_Acct.java
1
请完成以下Java代码
SpecificRelationTypeRelatedDocumentsProvider findRelatedDocumentsProvider(@NonNull final I_AD_RelationType relationType) { final ADRefListItem roleSourceItem = adReferenceService.retrieveListItemOrNull(X_AD_RelationType.ROLE_SOURCE_AD_Reference_ID, relationType.getRole_Source()); final ITranslatableString roleSourceDisplayName = roleSourceItem == null ? null : roleSourceItem.getName(); final ADRefListItem roleTargetItem = adReferenceService.retrieveListItemOrNull(X_AD_RelationType.ROLE_TARGET_AD_Reference_ID, relationType.getRole_Target()); final ITranslatableString roleTargetDisplayName = roleTargetItem == null ? null : roleTargetItem.getName(); return SpecificRelationTypeRelatedDocumentsProvider.builder() .setAdReferenceService(adReferenceService) .setCustomizedWindowInfoMap(customizedWindowInfoMapRepository.get()) .setAD_RelationType_ID(relationType.getAD_RelationType_ID()) .setInternalName(relationType.getInternalName()) // .setSource_Reference_ID(relationType.getAD_Reference_Source_ID()) .setSourceRoleDisplayName(roleSourceDisplayName) // .setTarget_Reference_AD(relationType.getAD_Reference_Target_ID())
.setTargetRoleDisplayName(roleTargetDisplayName) // .setIsTableRecordIdTarget(relationType.isTableRecordIdTarget()) // .buildOrNull(); } public SpecificRelationTypeRelatedDocumentsProvider getRelatedDocumentsProviderBySourceTableNameAndInternalName(final String zoomOriginTableName, final String internalName) { return getRelatedDocumentsProvidersBySourceDocumentTableName(zoomOriginTableName) .stream() .filter(provider -> Objects.equals(internalName, provider.getInternalName())) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No related documents provider found for sourceTableName=" + zoomOriginTableName + ", internalName=" + internalName)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\relation_type\RelationTypeRelatedDocumentsProvidersFactory.java
1
请完成以下Java代码
public String getComname() { return comname; } public void setComname(String comname) { this.comname = comname; } public String getComaddress() { return comaddress; } public void setComaddress(String comaddress) { this.comaddress = comaddress; }
public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "DomainDetail{" + "id='" + id + '\'' + ", sitename='" + sitename + '\'' + ", sitedomain='" + sitedomain + '\'' + ", sitetype='" + sitetype + '\'' + ", cdate='" + cdate + '\'' + ", comtype='" + comtype + '\'' + ", comname='" + comname + '\'' + ", comaddress='" + comaddress + '\'' + ", updateTime='" + updateTime + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-feign\src\main\java\com\quick\feign\entity\DomainDetail.java
1
请完成以下Java代码
public class InvocationArguments implements Iterable<Object> { public static InvocationArguments from(Object... arguments) { return new InvocationArguments(arguments); } private final Object[] arguments; /** * Constructs a new instance of {@link InvocationArguments} initialized with the given array of * {@link Object arguments}. * * @param arguments array of {@link Object arguments} indicating the values passed to the {@link Method} invocation * parameters; may be {@literal null}. */ public InvocationArguments(Object[] arguments) { this.arguments = arguments != null ? arguments : new Object[0]; } protected Object[] getArguments() { return this.arguments; } @SuppressWarnings("unchecked") protected <T> T getArgumentAt(int index) { return (T) getArguments()[index]; } @Override public Iterator<Object> iterator() {
return new Iterator<Object>() { int index = 0; @Override public boolean hasNext() { return this.index < InvocationArguments.this.getArguments().length; } @Override public Object next() { return InvocationArguments.this.getArguments()[this.index++]; } }; } public int size() { return this.arguments.length; } @Override public String toString() { return Arrays.toString(getArguments()); } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\util\function\InvocationArguments.java
1
请完成以下Java代码
public class OidcUserInfoAuthenticationToken extends AbstractAuthenticationToken { @Serial private static final long serialVersionUID = -3463488286180103730L; private final Authentication principal; private final OidcUserInfo userInfo; /** * Constructs an {@code OidcUserInfoAuthenticationToken} using the provided * parameters. * @param principal the principal */ public OidcUserInfoAuthenticationToken(Authentication principal) { super(Collections.emptyList()); Assert.notNull(principal, "principal cannot be null"); this.principal = principal; this.userInfo = null; setAuthenticated(false); } /** * Constructs an {@code OidcUserInfoAuthenticationToken} using the provided * parameters. * @param principal the authenticated principal * @param userInfo the UserInfo claims */
public OidcUserInfoAuthenticationToken(Authentication principal, OidcUserInfo userInfo) { super(Collections.emptyList()); Assert.notNull(principal, "principal cannot be null"); Assert.notNull(userInfo, "userInfo cannot be null"); this.principal = principal; this.userInfo = userInfo; setAuthenticated(true); } @Override public Object getPrincipal() { return this.principal; } @Override public Object getCredentials() { return ""; } /** * Returns the UserInfo claims. * @return the UserInfo claims */ public OidcUserInfo getUserInfo() { return this.userInfo; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcUserInfoAuthenticationToken.java
1
请完成以下Java代码
public String getWebParam5 () { return (String)get_Value(COLUMNNAME_WebParam5); } /** Set Web Parameter 6. @param WebParam6 Web Site Parameter 6 (default footer right) */ public void setWebParam6 (String WebParam6) { set_Value (COLUMNNAME_WebParam6, WebParam6); } /** Get Web Parameter 6. @return Web Site Parameter 6 (default footer right) */ public String getWebParam6 () { return (String)get_Value(COLUMNNAME_WebParam6); } /** Set Web Store EMail. @param WStoreEMail EMail address used as the sender (From) */ public void setWStoreEMail (String WStoreEMail) { set_Value (COLUMNNAME_WStoreEMail, WStoreEMail); } /** Get Web Store EMail. @return EMail address used as the sender (From) */ public String getWStoreEMail () { return (String)get_Value(COLUMNNAME_WStoreEMail); } /** Set Web Store. @param W_Store_ID A Web Store of the Client */ public void setW_Store_ID (int W_Store_ID) { if (W_Store_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Store_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID)); } /** Get Web Store. @return A Web Store of the Client */ public int getW_Store_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set WebStore User. @param WStoreUser User ID of the Web Store EMail address */ public void setWStoreUser (String WStoreUser) { set_Value (COLUMNNAME_WStoreUser, WStoreUser); } /** Get WebStore User. @return User ID of the Web Store EMail address */ public String getWStoreUser () { return (String)get_Value(COLUMNNAME_WStoreUser); } /** Set WebStore Password. @param WStoreUserPW Password of the Web Store EMail address */ public void setWStoreUserPW (String WStoreUserPW) { set_Value (COLUMNNAME_WStoreUserPW, WStoreUserPW); } /** Get WebStore Password. @return Password of the Web Store EMail address */ public String getWStoreUserPW () { return (String)get_Value(COLUMNNAME_WStoreUserPW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Store.java
1
请完成以下Java代码
protected void initCaseInstanceEvent(HistoricCaseInstanceEventEntity evt, CaseExecutionEntity caseExecutionEntity, HistoryEventTypes eventType) { evt.setId(caseExecutionEntity.getCaseInstanceId()); evt.setEventType(eventType.getEventName()); evt.setCaseDefinitionId(caseExecutionEntity.getCaseDefinitionId()); evt.setCaseInstanceId(caseExecutionEntity.getCaseInstanceId()); evt.setCaseExecutionId(caseExecutionEntity.getId()); evt.setBusinessKey(caseExecutionEntity.getBusinessKey()); evt.setState(caseExecutionEntity.getState()); evt.setTenantId(caseExecutionEntity.getTenantId()); } protected HistoricCaseActivityInstanceEventEntity newCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { return new HistoricCaseActivityInstanceEventEntity(); } protected HistoricCaseActivityInstanceEventEntity loadCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { return newCaseActivityInstanceEventEntity(caseExecutionEntity); } protected void initCaseActivityInstanceEvent(HistoricCaseActivityInstanceEventEntity evt, CaseExecutionEntity caseExecutionEntity, HistoryEventTypes eventType) { evt.setId(caseExecutionEntity.getId()); evt.setParentCaseActivityInstanceId(caseExecutionEntity.getParentId()); evt.setEventType(eventType.getEventName());
evt.setCaseDefinitionId(caseExecutionEntity.getCaseDefinitionId()); evt.setCaseInstanceId(caseExecutionEntity.getCaseInstanceId()); evt.setCaseExecutionId(caseExecutionEntity.getId()); evt.setCaseActivityInstanceState(caseExecutionEntity.getState()); evt.setRequired(caseExecutionEntity.isRequired()); evt.setCaseActivityId(caseExecutionEntity.getActivityId()); evt.setCaseActivityName(caseExecutionEntity.getActivityName()); evt.setCaseActivityType(caseExecutionEntity.getActivityType()); evt.setTenantId(caseExecutionEntity.getTenantId()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultCmmnHistoryEventProducer.java
1
请完成以下Java代码
public Builder setRecord_ID(final int record_ID) { this.record_ID = record_ID; return this; } public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) {
this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请在Spring Boot框架中完成以下Java代码
public class ServiceRepairProjectCostCollector { @NonNull ServiceRepairProjectCostCollectorId id; @NonNull ServiceRepairProjectTaskId taskId; @NonNull ServiceRepairProjectCostCollectorType type; @NonNull ProductId productId; @NonNull AttributeSetInstanceId asiId; @NonNull WarrantyCase warrantyCase; @NonNull Quantity qtyReserved; @NonNull Quantity qtyConsumed; @Nullable HuId vhuId; @Nullable OrderAndLineId customerQuotationLineId; @Builder private ServiceRepairProjectCostCollector( @NonNull final ServiceRepairProjectCostCollectorId id, @Nullable final ServiceRepairProjectTaskId taskId, @NonNull final ServiceRepairProjectCostCollectorType type, @NonNull final ProductId productId, @NonNull final AttributeSetInstanceId asiId, @NonNull final WarrantyCase warrantyCase, @NonNull final Quantity qtyReserved, @NonNull final Quantity qtyConsumed, @Nullable final HuId vhuId, @Nullable final OrderAndLineId customerQuotationLineId)
{ Check.assume(taskId == null || ProjectId.equals(id.getProjectId(), taskId.getProjectId()), "projectId not matching: {}, {}", id, taskId); Quantity.getCommonUomIdOfAll(qtyReserved, qtyConsumed); this.id = id; this.taskId = taskId; this.type = type; this.productId = productId; this.asiId = asiId; this.warrantyCase = warrantyCase; this.qtyReserved = qtyReserved; this.qtyConsumed = qtyConsumed; this.vhuId = vhuId; this.customerQuotationLineId = customerQuotationLineId; } public UomId getUomId() { return Quantity.getCommonUomIdOfAll(qtyReserved, qtyConsumed); } public Quantity getQtyReservedOrConsumed() { return getQtyReserved().add(getQtyConsumed()); } public boolean isNotIncludedInCustomerQuotation() { return getCustomerQuotationLineId() == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectCostCollector.java
2
请完成以下Java代码
public HUQueryBuilder setIncludeAfterPickingLocator(final boolean includeAfterPickingLocator) { locators.setIncludeAfterPickingLocator(includeAfterPickingLocator); return this; } @Override public HUQueryBuilder setExcludeHUsOnPickingSlot(final boolean excludeHUsOnPickingSlot) { _excludeHUsOnPickingSlot = excludeHUsOnPickingSlot; return this; } @Override public IHUQueryBuilder setExcludeReservedToOtherThan(@Nullable final HUReservationDocRef documentRef) { _excludeReservedToOtherThanRef = documentRef; return this;
} @Override public IHUQueryBuilder setExcludeReserved() { _excludeReserved = true; return this; } @Override public IHUQueryBuilder setIgnoreHUsScheduledInDDOrder(final boolean ignoreHUsScheduledInDDOrder) { this.ignoreHUsScheduledInDDOrder = ignoreHUsScheduledInDDOrder; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder.java
1
请完成以下Java代码
public class AProcess { private final AProcessModel model = new AProcessModel(); private final APanel parent; private final AppsAction action; /** * * @param parent * @param small if <code>true</code> then use a small icon * @return */ public static AppsAction createAppsAction(final APanel parent, final boolean small) { final AProcess app = new AProcess(parent, small); return app.action; } private AProcess(final APanel parent, final boolean small) { super(); this.parent = parent; action = AppsAction.builder() .setAction(model.getActionName()) .setSmallSize(small) .build(); action.setDelegate(event -> showPopup()); } private Properties getCtx() { return Env.getCtx(); } private JPopupMenu getPopupMenu() { final Properties ctx = getCtx(); final List<SwingRelatedProcessDescriptor> processes = model.fetchProcesses(ctx, parent.getCurrentTab()); if (processes.isEmpty()) { return null; } final String adLanguage = Env.getAD_Language(ctx); final JPopupMenu popup = new JPopupMenu("ProcessMenu"); processes.stream() .map(process -> createProcessMenuItem(process, adLanguage)) .sorted(Comparator.comparing(CMenuItem::getText)) .forEach(mi -> popup.add(mi)); return popup; } public void showPopup() { final JPopupMenu popup = getPopupMenu(); if (popup == null) { return; } final AbstractButton button = action.getButton(); if (button.isShowing()) { popup.show(button, 0, button.getHeight()); // below button } }
private CMenuItem createProcessMenuItem(final SwingRelatedProcessDescriptor process, final String adLanguage) { final CMenuItem mi = new CMenuItem(process.getCaption(adLanguage)); mi.setIcon(process.getIcon()); mi.setToolTipText(process.getDescription(adLanguage)); if (process.isEnabled()) { mi.setEnabled(true); mi.addActionListener(event -> startProcess(process)); } else { mi.setEnabled(false); mi.setToolTipText(process.getDisabledReason(adLanguage)); } return mi; } private void startProcess(final SwingRelatedProcessDescriptor process) { final String adLanguage = Env.getAD_Language(getCtx()); final VButton button = new VButton( "StartProcess", // columnName, false, // mandatory, false, // isReadOnly, true, // isUpdateable, process.getCaption(adLanguage), process.getDescription(adLanguage), process.getHelp(adLanguage), process.getAD_Process_ID()); // Invoke action parent.actionButton(button); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\AProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class DataImportRunId implements RepoIdAware { @JsonCreator public static DataImportRunId ofRepoId(final int repoId) { return new DataImportRunId(repoId); } public static DataImportRunId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new DataImportRunId(repoId) : null; } int repoId; private DataImportRunId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "C_DataImport_Run_ID"); } @JsonValue @Override public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final DataImportRunId id) { return id != null ? id.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportRunId.java
2
请完成以下Java代码
public org.compiere.model.I_C_ValidCombination getUnrealizedLoss_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setUnrealizedLoss_A(org.compiere.model.I_C_ValidCombination UnrealizedLoss_A) { set_ValueFromPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedLoss_A); } /** Set Nicht realisierte Währungsverluste. @param UnrealizedLoss_Acct Konto für nicht realisierte Währungsverluste */ @Override public void setUnrealizedLoss_Acct (int UnrealizedLoss_Acct)
{ set_Value (COLUMNNAME_UnrealizedLoss_Acct, Integer.valueOf(UnrealizedLoss_Acct)); } /** Get Nicht realisierte Währungsverluste. @return Konto für nicht realisierte Währungsverluste */ @Override public int getUnrealizedLoss_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedLoss_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency_Acct.java
1
请完成以下Java代码
public void setC_VAT_Code_ID (int C_VAT_Code_ID) { if (C_VAT_Code_ID < 1) set_ValueNoCheck (COLUMNNAME_C_VAT_Code_ID, null); else set_ValueNoCheck (COLUMNNAME_C_VAT_Code_ID, Integer.valueOf(C_VAT_Code_ID)); } /** Get VAT Code. @return VAT Code */ @Override public int getC_VAT_Code_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_VAT_Code_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ @Override public void setIsSOTrx (java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public java.lang.String getIsSOTrx () {
return (java.lang.String)get_Value(COLUMNNAME_IsSOTrx); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set VAT Code. @param VATCode VAT Code */ @Override public void setVATCode (java.lang.String VATCode) { set_Value (COLUMNNAME_VATCode, VATCode); } /** Get VAT Code. @return VAT Code */ @Override public java.lang.String getVATCode () { return (java.lang.String)get_Value(COLUMNNAME_VATCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_C_VAT_Code.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PPOrderLineRow pickingSlotRow = getSingleSelectedRow(); if (!pickingSlotRow.isSourceHU()) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_SOURCE_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final PPOrderLineRow rowToProcess = getSingleSelectedRow();
final HuId huId = rowToProcess.getHuId(); // unselect the row we just deleted the record of, to avoid an 'EntityNotFoundException' final boolean sourceWasDeleted = SourceHUsService.get().deleteSourceHuMarker(huId); if (sourceWasDeleted) { getView().invalidateAll(); } invalidateView(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_M_Source_HU_Delete.java
1
请完成以下Java代码
public void setModule (final @Nullable java.lang.String Module) { set_Value (COLUMNNAME_Module, Module); } @Override public java.lang.String getModule() { return get_ValueAsString(COLUMNNAME_Module); } @Override public void setMsgText (final @Nullable java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setSource_Record_ID (final int Source_Record_ID) { if (Source_Record_ID < 1) set_Value (COLUMNNAME_Source_Record_ID, null); else set_Value (COLUMNNAME_Source_Record_ID, Source_Record_ID); } @Override public int getSource_Record_ID() { return get_ValueAsInt(COLUMNNAME_Source_Record_ID); } @Override public void setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_Value (COLUMNNAME_Source_Table_ID, null); else set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID); }
@Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setTarget_Record_ID (final int Target_Record_ID) { if (Target_Record_ID < 1) set_Value (COLUMNNAME_Target_Record_ID, null); else set_Value (COLUMNNAME_Target_Record_ID, Target_Record_ID); } @Override public int getTarget_Record_ID() { return get_ValueAsInt(COLUMNNAME_Target_Record_ID); } @Override public void setTarget_Table_ID (final int Target_Table_ID) { if (Target_Table_ID < 1) set_Value (COLUMNNAME_Target_Table_ID, null); else set_Value (COLUMNNAME_Target_Table_ID, Target_Table_ID); } @Override public int getTarget_Table_ID() { return get_ValueAsInt(COLUMNNAME_Target_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Log.java
1
请完成以下Java代码
private IWorkPackageQueue getQueue() { return workPackageQueueFactory.getQueueForEnqueuing(Env.getCtx(), GenerateDDOrderFromDDOrderCandidate.class); } private ILockCommand toWorkPackageElementsLocker(final @NonNull DDOrderCandidateEnqueueRequest request) { final PInstanceId selectionId = request.getSelectionId(); final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, selectionId.getRepoId()); return lockManager .lock() .setOwner(lockOwner) .setAutoCleanup(false) .setFailIfAlreadyLocked(true) .setRecordsBySelection(I_DD_Order_Candidate.class, selectionId); } private static String toJsonString(@NonNull final DDOrderCandidateEnqueueRequest request) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(request); } catch (final JsonProcessingException e)
{ throw new AdempiereException("Cannot convert to json: " + request, e); } } public static DDOrderCandidateEnqueueRequest extractRequest(@NonNull final IParams params) { final String jsonString = params.getParameterAsString(WP_PARAM_request); try { return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(jsonString, DDOrderCandidateEnqueueRequest.class); } catch (final JsonProcessingException e) { throw new AdempiereException("Cannot read json: " + jsonString, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\async\DDOrderCandidateEnqueueService.java
1
请完成以下Java代码
public NonCaseString replaceAll(String regex, String replacement) { return NonCaseString.of(this.value.replaceAll(regex, replacement)); } public NonCaseString substring(int beginIndex) { return NonCaseString.of(this.value.substring(beginIndex)); } public NonCaseString substring(int beginIndex, int endIndex) { return NonCaseString.of(this.value.substring(beginIndex, endIndex)); } public boolean isNotEmpty() { return !this.value.isEmpty(); } @Override public int length() { return this.value.length(); } @Override public char charAt(int index) { return this.value.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.value.subSequence(start, end);
} public String[] split(String regex) { return this.value.split(regex); } /** * @return 原始字符串 */ public String get() { return this.value; } @Override public String toString() { return this.value; } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java
1
请在Spring Boot框架中完成以下Java代码
public Queue msv3ServerRequestsQueue() { return new Queue(QUEUENAME_MSV3ServerRequests); } @Bean(name = QUEUENAME_UserChangedEvents) public Queue userChangedEventsQueue() { return new Queue(QUEUENAME_UserChangedEvents); } @Bean(name = QUEUENAME_StockAvailabilityUpdatedEvent) public Queue stockAvailabilityUpdatedEventQueue() { return new Queue(QUEUENAME_StockAvailabilityUpdatedEvent); } @Bean(name = QUEUENAME_ProductExcludeUpdatedEvents) public Queue productExcludeUpdatedEventsQueue() { return new Queue(QUEUENAME_ProductExcludeUpdatedEvents); } @Bean(name = QUEUENAME_SyncOrderRequestEvents) public Queue syncOrderRequestEventsQueue() { return new Queue(QUEUENAME_SyncOrderRequestEvents); } @Bean(name = QUEUENAME_SyncOrderResponseEvents) public Queue syncOrderResponseEventsQueue() { return new Queue(QUEUENAME_SyncOrderResponseEvents); } // Note: with spring boot-2 this somehow didn't work anymore. It didn't create the queues in rabbitmq, so i added the code above, which works. // @Bean // List<Declarable> queuesAndBindings() // {
// return ImmutableList.<Declarable> builder() // .addAll(createQueueExchangeAndBinding(QUEUENAME_MSV3ServerRequests)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_UserChangedEvents)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_StockAvailabilityUpdatedEvent)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_ProductExcludeUpdatedEvents)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_SyncOrderRequestEvents)) // .addAll(createQueueExchangeAndBinding(QUEUENAME_SyncOrderResponseEvents)) // .build(); // } // private static List<Declarable> createQueueExchangeAndBinding(final String queueName) // { // final Queue queue = QueueBuilder.nonDurable(queueName).build(); // final TopicExchange exchange = new TopicExchange(queueName + "-exchange"); // final Binding binding = BindingBuilder.bind(queue).to(exchange).with(queueName); // return ImmutableList.<Declarable> of(queue, exchange, binding); // } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\RabbitMQConfig.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Image[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Image. @param AD_Image_ID Image or Icon */ public void setAD_Image_ID (int AD_Image_ID) { if (AD_Image_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Image_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID)); } /** Get Image. @return Image or Icon */ public int getAD_Image_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID); if (ii == null) return 0; return ii.intValue(); } /** Set BinaryData. @param BinaryData Binary Data */ public void setBinaryData (byte[] BinaryData) { set_Value (COLUMNNAME_BinaryData, BinaryData); } /** Get BinaryData. @return Binary Data */ public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) {
set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Image URL. @param ImageURL URL of image */ public void setImageURL (String ImageURL) { set_Value (COLUMNNAME_ImageURL, ImageURL); } /** Get Image URL. @return URL of image */ public String getImageURL () { return (String)get_Value(COLUMNNAME_ImageURL); } /** 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_Image.java
1
请完成以下Java代码
public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Zahlwert. @param ValueNumber Numeric Value */ @Override
public void setValueNumber (java.math.BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } /** Get Zahlwert. @return Numeric Value */ @Override public java.math.BigDecimal getValueNumber () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_ProductAttribute.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_User_ID())); } /** Set Opt-out Date. @param OptOutDate Date the contact opted out */ public void setOptOutDate (Timestamp OptOutDate) { set_ValueNoCheck (COLUMNNAME_OptOutDate, OptOutDate); } /** Get Opt-out Date. @return Date the contact opted out */ public Timestamp getOptOutDate () { return (Timestamp)get_Value(COLUMNNAME_OptOutDate); } public I_R_InterestArea getR_InterestArea() throws RuntimeException { return (I_R_InterestArea)MTable.get(getCtx(), I_R_InterestArea.Table_Name) .getPO(getR_InterestArea_ID(), get_TrxName()); } /** Set Interest Area. @param R_InterestArea_ID Interest Area or Topic */ public void setR_InterestArea_ID (int R_InterestArea_ID) { if (R_InterestArea_ID < 1) set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null); else set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID)); } /** Get Interest Area.
@return Interest Area or Topic */ public int getR_InterestArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Subscribe Date. @param SubscribeDate Date the contact actively subscribed */ public void setSubscribeDate (Timestamp SubscribeDate) { set_ValueNoCheck (COLUMNNAME_SubscribeDate, SubscribeDate); } /** Get Subscribe Date. @return Date the contact actively subscribed */ public Timestamp getSubscribeDate () { return (Timestamp)get_Value(COLUMNNAME_SubscribeDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_ContactInterest.java
1
请完成以下Java代码
public void setVariablesLocal(Map<String, ?> variables, boolean skipJavaSerializationFormatCheck) { super.setVariablesLocal(variables, skipJavaSerializationFormatCheck); Context.getCommandContext().getDbEntityManager().forceUpdate(this); } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); if (processDefinitionId != null) { referenceIdAndClass.put(processDefinitionId, ProcessDefinitionEntity.class); } if (processInstanceId != null) { referenceIdAndClass.put(processInstanceId, ExecutionEntity.class); } if (executionId != null) { referenceIdAndClass.put(executionId, ExecutionEntity.class); } if (caseDefinitionId != null) { referenceIdAndClass.put(caseDefinitionId, CaseDefinitionEntity.class); } if (caseExecutionId != null) { referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class); } return referenceIdAndClass; } public void bpmnError(String errorCode, String errorMessage, Map<String, Object> variables) { ensureTaskActive(); ActivityExecution activityExecution = getExecution(); BpmnError bpmnError = null; if (errorMessage != null) { bpmnError = new BpmnError(errorCode, errorMessage); } else { bpmnError = new BpmnError(errorCode); } try { if (variables != null && !variables.isEmpty()) { activityExecution.setVariables(variables); } BpmnExceptionHandler.propagateBpmnError(bpmnError, activityExecution); } catch (Exception ex) { throw ProcessEngineLogger.CMD_LOGGER.exceptionBpmnErrorPropagationFailed(errorCode, ex); } } @Override public boolean hasAttachment() { return attachmentExists;
} @Override public boolean hasComment() { return commentExists; } public void escalation(String escalationCode, Map<String, Object> variables) { ensureTaskActive(); ActivityExecution activityExecution = getExecution(); if (variables != null && !variables.isEmpty()) { activityExecution.setVariables(variables); } EscalationHandler.propagateEscalation(activityExecution, escalationCode); } public static enum TaskState { STATE_INIT ("Init"), STATE_CREATED ("Created"), STATE_COMPLETED ("Completed"), STATE_DELETED ("Deleted"), STATE_UPDATED ("Updated"); private String taskState; private TaskState(String taskState) { this.taskState = taskState; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskEntity.java
1
请完成以下Java代码
public InvoiceCandBLCreateInvoices setIgnoreInvoiceSchedule(final boolean ignoreInvoiceSchedule) { this._ignoreInvoiceSchedule = ignoreInvoiceSchedule; return this; } private boolean isIgnoreInvoiceSchedule() { if (_ignoreInvoiceSchedule != null) { return _ignoreInvoiceSchedule; } final IInvoicingParams invoicingParams = getInvoicingParams(); if (invoicingParams != null) { return invoicingParams.isIgnoreInvoiceSchedule(); } return false; } @Override public InvoiceCandBLCreateInvoices setCollector(final IInvoiceGenerateResult collector) { this._collector = collector; return this;
} private IInvoiceGenerateResult getCollector() { if (_collector == null) { // note that we don't want to store the actual invoices in the result if there is a change to encounter memory problems _collector = invoiceCandBL.createInvoiceGenerateResult(_invoicingParams != null && _invoicingParams.isStoreInvoicesInResult()); } return _collector; } @Override public IInvoiceGenerator setInvoicingParams(final @NonNull IInvoicingParams invoicingParams) { this._invoicingParams = invoicingParams; return this; } private IInvoicingParams getInvoicingParams() { return _invoicingParams; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandBLCreateInvoices.java
1
请完成以下Java代码
public DefaultView filterView( @NonNull final IView view, @NonNull final JSONFilterViewRequest filterViewRequest, @NonNull final Supplier<IViewsRepository> viewsRepo_NOTUSED) { return filterView(DefaultView.cast(view), filterViewRequest); } private DefaultView filterView( @NonNull final DefaultView view, @NonNull final JSONFilterViewRequest filterViewRequest) { final DocumentFilterDescriptorsProvider filterDescriptors = view.getViewDataRepository().getViewFilterDescriptors(); final DocumentFilterList newFilters = filterViewRequest.getFiltersUnwrapped(filterDescriptors); // final DocumentFilterList newFiltersExcludingFacets = newFilters.retainOnlyNonFacetFilters(); // // final DocumentFilterList currentFiltersExcludingFacets = view.getFilters().retainOnlyNonFacetFilters(); // // if (DocumentFilterList.equals(currentFiltersExcludingFacets, newFiltersExcludingFacets)) // { // // TODO // throw new AdempiereException("TODO"); // }
// else { return createView(CreateViewRequest.filterViewBuilder(view) .setFilters(newFilters) .build()); } } public SqlViewKeyColumnNamesMap getKeyColumnNamesMap(@NonNull final WindowId windowId) { final SqlViewBinding sqlBindings = viewLayouts.getViewBinding(windowId, DocumentFieldDescriptor.Characteristic.PublicField, ViewProfileId.NULL); return sqlBindings.getSqlViewKeyColumnNamesMap(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewFactory.java
1
请完成以下Java代码
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricPlanItemInstance with id: ") .append(id); if (getName() != null) { sb.append(", name: ").append(getName()); } sb.append(", definitionId: ")
.append(planItemDefinitionId) .append(", state: ") .append(state); sb .append(", caseInstanceId: ") .append(caseInstanceId) .append(", caseDefinitionId: ") .append(caseDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricPlanItemInstanceEntityImpl.java
1
请完成以下Java代码
public void setC_OLCand_ID (final int C_OLCand_ID) { if (C_OLCand_ID < 1) set_Value (COLUMNNAME_C_OLCand_ID, null); else set_Value (COLUMNNAME_C_OLCand_ID, C_OLCand_ID); } @Override public int getC_OLCand_ID() { return get_ValueAsInt(COLUMNNAME_C_OLCand_ID); } @Override public void setC_OLCand_Paypal_ID (final int C_OLCand_Paypal_ID) { if (C_OLCand_Paypal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OLCand_Paypal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OLCand_Paypal_ID, C_OLCand_Paypal_ID); } @Override public int getC_OLCand_Paypal_ID() {
return get_ValueAsInt(COLUMNNAME_C_OLCand_Paypal_ID); } @Override public void setPayPal_Token (final @Nullable java.lang.String PayPal_Token) { set_Value (COLUMNNAME_PayPal_Token, PayPal_Token); } @Override public java.lang.String getPayPal_Token() { return get_ValueAsString(COLUMNNAME_PayPal_Token); } @Override public void setPayPal_Transaction_ID (final @Nullable java.lang.String PayPal_Transaction_ID) { set_Value (COLUMNNAME_PayPal_Transaction_ID, PayPal_Transaction_ID); } @Override public java.lang.String getPayPal_Transaction_ID() { return get_ValueAsString(COLUMNNAME_PayPal_Transaction_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_C_OLCand_Paypal.java
1
请完成以下Java代码
public boolean open(String[] args) { Option cmd = new Option(); try { Args.parse(cmd, args); } catch (IllegalArgumentException e) { System.err.println("invalid arguments"); return false; } String model = cmd.model; int nbest = cmd.nbest; int vlevel = cmd.verbose; double costFactor = cmd.cost_factor; return open(model, nbest, vlevel, costFactor); } public boolean open(InputStream stream, int nbest, int vlevel, double costFactor) { featureIndex_ = new DecoderFeatureIndex(); nbest_ = nbest; vlevel_ = vlevel; if (costFactor > 0) { featureIndex_.setCostFactor_(costFactor); } return featureIndex_.open(stream); } public boolean open(String model, int nbest, int vlevel, double costFactor) { try { InputStream stream = IOUtil.newInputStream(model); return open(stream, nbest, vlevel, costFactor); } catch (Exception e) { return false; } } public String getTemplate() { if (featureIndex_ != null) { return featureIndex_.getTemplate(); } else { return null;
} } public int getNbest_() { return nbest_; } public void setNbest_(int nbest_) { this.nbest_ = nbest_; } public int getVlevel_() { return vlevel_; } public void setVlevel_(int vlevel_) { this.vlevel_ = vlevel_; } public DecoderFeatureIndex getFeatureIndex_() { return featureIndex_; } public void setFeatureIndex_(DecoderFeatureIndex featureIndex_) { this.featureIndex_ = featureIndex_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\ModelImpl.java
1
请完成以下Java代码
public boolean commit(UUID trId, Map<K, V> pendingPuts) { lock.lock(); try { var tr = transactions.get(trId); var success = !tr.isFailed(); if (success) { for (K key : tr.getKeys()) { Set<UUID> otherTransactions = objectTransactions.get(key); if (otherTransactions != null) { for (UUID otherTrId : otherTransactions) { if (trId == null || !trId.equals(otherTrId)) { transactions.get(otherTrId).setFailed(true); } } } } pendingPuts.forEach(this::doPutIfAbsent); } removeTransaction(trId); return success; } finally { lock.unlock(); } } void rollback(UUID id) { lock.lock(); try { removeTransaction(id); } finally { lock.unlock(); } } private void removeTransaction(UUID id) { CaffeineTbCacheTransaction<K, V> transaction = transactions.remove(id); if (transaction != null) { for (var key : transaction.getKeys()) {
Set<UUID> transactions = objectTransactions.get(key); if (transactions != null) { transactions.remove(id); if (transactions.isEmpty()) { objectTransactions.remove(key); } } } } } protected void failAllTransactionsByKey(K key) { Set<UUID> transactionsIds = objectTransactions.get(key); if (transactionsIds != null) { for (UUID otherTrId : transactionsIds) { transactions.get(otherTrId).setFailed(true); } } } }
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\CaffeineTbTransactionalCache.java
1
请完成以下Java代码
public class ActivitiStateHandlerRegistration { private Map<Integer, String> processVariablesExpected = new ConcurrentHashMap<Integer, String>(); private Method handlerMethod; private Object handler; private String stateName; private String beanName; private int processVariablesIndex = -1; private int processIdIndex = -1; private String processName; public ActivitiStateHandlerRegistration( Map<Integer, String> processVariablesExpected, Method handlerMethod, Object handler, String stateName, String beanName, int processVariablesIndex, int processIdIndex, String processName) { this.processVariablesExpected = processVariablesExpected; this.handlerMethod = handlerMethod; this.handler = handler; this.stateName = stateName; this.beanName = beanName; this.processVariablesIndex = processVariablesIndex; this.processIdIndex = processIdIndex; this.processName = processName; } public int getProcessVariablesIndex() { return processVariablesIndex; } public int getProcessIdIndex() { return processIdIndex; } public boolean requiresProcessId() { return this.processIdIndex > -1; } public boolean requiresProcessVariablesMap() { return processVariablesIndex > -1; } public String getBeanName() { return beanName; } public Map<Integer, String> getProcessVariablesExpected() { return processVariablesExpected; } public Method getHandlerMethod() { return handlerMethod; }
public Object getHandler() { return handler; } public String getStateName() { return stateName; } public String getProcessName() { return processName; } @Override public String toString() { return super.toString() + "[" + "processVariablesExpected=" + processVariablesExpected + ", " + "handlerMethod=" + handlerMethod + ", " + "handler=" + handler + ", " + "stateName=" + stateName + ", " + "beanName=" + beanName + ", " + "processVariablesIndex=" + processVariablesIndex + ", " + "processIdIndex=" + processIdIndex + ", " + "processName=" + processName + "]"; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\registry\ActivitiStateHandlerRegistration.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-producer-application cloud: # Spring Cloud Stream 配置项,对应 BindingServiceProperties 类 stream: # Binder 配置项,对应 BinderProperties Map binders: rabbit001: type: rabbit # 设置 Binder 的类型 environment: # 设置 Binder 的环境配置 # 如果是 RabbitMQ 类型的时候,则对应的是 RabbitProperties 类 spring: rabbitmq: host: 127.0.0.1 # RabbitMQ 服务的地址 port: 5672 # RabbitMQ 服务的端口 username: guest # RabbitMQ 服务的账号 password: guest # RabbitMQ 服务的密码 publisher-returns: true # 设置消息是否回退,默认为 false publisher-confirm-type: simple # 设置开启消息确认模型,默认为 null 不进行确认 # Binding 配置项,对应 BindingProperties Map bindings: demo01-output: destination: DEMO-TOPIC-01 # 目的地。这里使用 RabbitMQ Exchange content-type: application/json # 内容格式。这里使用 JSON binder: rabbit001 # 设置使用的
Binder 名字 producer: error-channel-enabled: true # 是否开启异常 Channel,默认为 false 关闭 # RabbitMQ 自定义 Binding 配置项,对应 RabbitBindingProperties Map rabbit: bindings: demo01-output: # RabbitMQ Producer 配置项,对应 RabbitProducerProperties 类 producer: confirm-ack-channel: demo01-producer-confirm # 设置发送确认的 Channel,默认为 null server: port: 18080
repos\SpringBoot-Labs-master\labx-10-spring-cloud-stream-rabbitmq\labx-10-sc-stream-rabbitmq-producer-confirm\src\main\resources\application.yml
2
请完成以下Java代码
public void onInterestAmtChanged(final @NonNull I_C_BankStatementLine bsl) { getAmountsCallout(bsl).onInterestAmtChanged(bsl); } @CalloutMethod(columnNames = I_C_BankStatementLine.COLUMNNAME_C_Invoice_ID) public void onC_Invoice_ID_Changed(@NonNull final I_C_BankStatementLine bsl) { final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(bsl.getC_Invoice_ID()); if (invoiceId == null) { return; } bankStatementBL.updateLineFromInvoice(bsl, invoiceId); } private static void updateTrxAmt(final I_C_BankStatementLine bsl) { bsl.setTrxAmt(BankStatementLineAmounts.of(bsl) .addDifferenceToTrxAmt() .getTrxAmt()); } private interface AmountsCallout { void onStmtAmtChanged(final I_C_BankStatementLine bsl); void onTrxAmtChanged(final I_C_BankStatementLine bsl); void onBankFeeAmtChanged(final I_C_BankStatementLine bsl); void onChargeAmtChanged(final I_C_BankStatementLine bsl); void onInterestAmtChanged(final I_C_BankStatementLine bsl); } public static class BankStatementLineAmountsCallout implements AmountsCallout { @Override public void onStmtAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onTrxAmtChanged(final I_C_BankStatementLine bsl) { bsl.setBankFeeAmt(BankStatementLineAmounts.of(bsl) .addDifferenceToBankFeeAmt() .getBankFeeAmt()); } @Override public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onChargeAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onInterestAmtChanged(final I_C_BankStatementLine bsl) {
updateTrxAmt(bsl); } } public static class CashJournalLineAmountsCallout implements AmountsCallout { @Override public void onStmtAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onTrxAmtChanged(final I_C_BankStatementLine bsl) { // i.e. set the TrxAmt back. // user shall not be allowed to change it // instead, StmtAmt can be changed updateTrxAmt(bsl); } @Override public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl) { bsl.setBankFeeAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } @Override public void onChargeAmtChanged(final I_C_BankStatementLine bsl) { bsl.setChargeAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } @Override public void onInterestAmtChanged(final I_C_BankStatementLine bsl) { bsl.setInterestAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\callout\C_BankStatementLine.java
1
请完成以下Java代码
private static UomId extractUomId(final I_PP_Order_Weighting_Run record) { return UomId.ofRepoId(record.getC_UOM_ID()); } @NonNull static PPOrderWeightingRunId extractId(final @NonNull I_PP_Order_Weighting_Run record) { return PPOrderWeightingRunId.ofRepoId(record.getPP_Order_Weighting_Run_ID()); } public void save(final PPOrderWeightingRun weightingRun) { final I_PP_Order_Weighting_Run record = getRecordById(weightingRun.getId()); updateRecord(record, weightingRun); saveRecordIfAllowed(record); final ArrayList<I_PP_Order_Weighting_RunCheck> checkRecords = getCheckRecordsByRunId(weightingRun.getId()); final ImmutableMap<PPOrderWeightingRunCheckId, I_PP_Order_Weighting_RunCheck> checkRecordsById = Maps.uniqueIndex(checkRecords, PPOrderWeightingRunLoaderAndSaver::extractId); // // UPDATE final HashSet<PPOrderWeightingRunCheckId> savedIds = new HashSet<>(); for (final PPOrderWeightingRunCheck check : weightingRun.getChecks()) { final I_PP_Order_Weighting_RunCheck checkRecord = checkRecordsById.get(check.getId()); if (checkRecord == null) { throw new AdempiereException("@NotFound@ " + check.getId()); // shall not happen } updateRecord(checkRecord, check); InterfaceWrapperHelper.save(checkRecord); savedIds.add(check.getId()); } // // DELETE if (checkRecords.size() != savedIds.size()) { for (final Iterator<I_PP_Order_Weighting_RunCheck> it = checkRecords.iterator(); it.hasNext(); ) {
final I_PP_Order_Weighting_RunCheck checkRecord = it.next(); final PPOrderWeightingRunCheckId id = extractId(checkRecord); if (!savedIds.contains(id)) { it.remove(); InterfaceWrapperHelper.delete(checkRecord); } } } } private void saveRecordIfAllowed(final I_PP_Order_Weighting_Run record) { if (runIdToAvoidSaving.contains(extractId(record))) { return; } InterfaceWrapperHelper.save(record); } private void updateRecord(@NonNull final I_PP_Order_Weighting_Run record, @NonNull final PPOrderWeightingRun from) { record.setMinWeight(from.getTargetWeightRange().lowerEndpoint().toBigDecimal()); record.setMaxWeight(from.getTargetWeightRange().upperEndpoint().toBigDecimal()); record.setIsToleranceExceeded(from.isToleranceExceeded()); record.setProcessed(from.isProcessed()); } private void updateRecord(final I_PP_Order_Weighting_RunCheck checkRecord, final PPOrderWeightingRunCheck from) { checkRecord.setWeight(from.getWeight().toBigDecimal()); checkRecord.setC_UOM_ID(from.getWeight().getUomId().getRepoId()); checkRecord.setIsToleranceExceeded(from.isToleranceExceeded()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunLoaderAndSaver.java
1
请在Spring Boot框架中完成以下Java代码
public class AppRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(AppRunner.class); private final GitHubLookupService gitHubLookupService; public AppRunner(GitHubLookupService gitHubLookupService) { this.gitHubLookupService = gitHubLookupService; } @Override public void run(String... args) throws Exception { // Start the clock long start = System.currentTimeMillis(); // Kick of multiple, asynchronous lookups CompletableFuture<User> page1 = gitHubLookupService.findUser("vector4wang"); CompletableFuture<User> page2 = gitHubLookupService.findUser("Zhuinden"); CompletableFuture<User> page3 = gitHubLookupService.findUser("xialeistudio"); Future<User> futurePage1 = gitHubLookupService.findUser2("vector4wang");
Future<User> futurePage2 = gitHubLookupService.findUser2("Zhuinden"); Future<User> futurePage3 = gitHubLookupService.findUser2("xialeistudio"); logger.info("--> " + futurePage1.get()); logger.info("--> " + futurePage2.get()); logger.info("--> " + futurePage3.get()); // Wait until they are all done CompletableFuture.allOf(page1,page2,page3).join(); // Print results, including elapsed time logger.info("Elapsed time: " + (System.currentTimeMillis() - start)); logger.info("--> " + page1.get()); logger.info("--> " + page2.get()); logger.info("--> " + page3.get()); } }
repos\spring-boot-quick-master\quick-async\src\main\java\com\async\init\AppRunner.java
2
请在Spring Boot框架中完成以下Java代码
public TbEntitySubEvent toEvent(ComponentLifecycleEvent type) { seqNumber++; var result = TbEntitySubEvent.builder().tenantId(tenantId).entityId(entityId).type(type).seqNumber(seqNumber); if (!ComponentLifecycleEvent.DELETED.equals(type)) { result.info(state.copy(seqNumber)); } return result.build(); } public boolean isNf() { return state.notifications; } public boolean isEmpty() { return subs.isEmpty(); } public TbSubscription<?> registerPendingSubscription(TbSubscription<?> subscription, TbEntitySubEvent event) { if (TbSubscriptionType.ATTRIBUTES.equals(subscription.getType())) { if (event != null) { log.trace("[{}][{}] Registering new pending attributes subscription event: {} for subscription: {}", tenantId, entityId, event.getSeqNumber(), subscription.getSubscriptionId()); pendingAttributesEvent = event.getSeqNumber(); pendingAttributesEventTs = System.currentTimeMillis(); pendingSubs.computeIfAbsent(pendingAttributesEvent, e -> new HashSet<>()).add(subscription); } else if (pendingAttributesEvent > 0) { log.trace("[{}][{}] Registering pending attributes subscription {} for event: {} ", tenantId, entityId, subscription.getSubscriptionId(), pendingAttributesEvent); pendingSubs.computeIfAbsent(pendingAttributesEvent, e -> new HashSet<>()).add(subscription); } else { return subscription; } } else if (subscription instanceof TbTimeSeriesSubscription) { if (event != null) { log.trace("[{}][{}] Registering new pending time-series subscription event: {} for subscription: {}", tenantId, entityId, event.getSeqNumber(), subscription.getSubscriptionId()); pendingTimeSeriesEvent = event.getSeqNumber();
pendingTimeSeriesEventTs = System.currentTimeMillis(); pendingSubs.computeIfAbsent(pendingTimeSeriesEvent, e -> new HashSet<>()).add(subscription); } else if (pendingTimeSeriesEvent > 0) { log.trace("[{}][{}] Registering pending time-series subscription {} for event: {} ", tenantId, entityId, subscription.getSubscriptionId(), pendingTimeSeriesEvent); pendingSubs.computeIfAbsent(pendingTimeSeriesEvent, e -> new HashSet<>()).add(subscription); } else { return subscription; } } return null; } public Set<TbSubscription<?>> clearPendingSubscriptions(int seqNumber) { if (pendingTimeSeriesEvent == seqNumber) { pendingTimeSeriesEvent = 0; pendingTimeSeriesEventTs = 0L; } else if (pendingAttributesEvent == seqNumber) { pendingAttributesEvent = 0; pendingAttributesEventTs = 0L; } return pendingSubs.remove(seqNumber); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbEntityLocalSubsInfo.java
2
请完成以下Java代码
static void removeWithForLoopDecrementOnRemove(List<Integer> list, int element) { for (int i = 0; i < list.size(); i++) { if (Objects.equals(element, list.get(i))) { list.remove(i); i--; } } } static void removeWithForLoopIncrementIfRemains(List<Integer> list, int element) { for (int i = 0; i < list.size();) { if (Objects.equals(element, list.get(i))) { list.remove(i); } else { i++; } } } static void removeWithForEachLoop(List<Integer> list, int element) { for (Integer number : list) { if (Objects.equals(number, element)) { list.remove(number); } } } static void removeWithIterator(List<Integer> list, int element) { for (Iterator<Integer> i = list.iterator(); i.hasNext();) { Integer number = i.next(); if (Objects.equals(number, element)) { i.remove(); } } } static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) { List<Integer> remainingElements = new ArrayList<>(); for (Integer number : list) { if (!Objects.equals(number, element)) { remainingElements.add(number);
} } return remainingElements; } static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) { List<Integer> remainingElements = new ArrayList<>(); for (Integer number : list) { if (!Objects.equals(number, element)) { remainingElements.add(number); } } list.clear(); list.addAll(remainingElements); } static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) { return list.stream() .filter(e -> !Objects.equals(e, element)) .collect(Collectors.toList()); } static void removeWithRemoveIf(List<Integer> list, Integer element) { list.removeIf(n -> Objects.equals(n, element)); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\removeall\RemoveAll.java
1
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (requiresLogout(request, response)) { Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication(); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Logging out [%s]", auth)); } this.handler.logout(request, response, auth); this.logoutSuccessHandler.onLogoutSuccess(request, response, auth); return; } chain.doFilter(request, response); } /** * Allow subclasses to modify when a logout should take place. * @param request the request * @param response the response * @return <code>true</code> if logout should occur, <code>false</code> otherwise */ protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) { if (this.logoutRequestMatcher.matches(request)) { return true; } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Did not match request to %s", this.logoutRequestMatcher)); }
return false; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); this.logoutRequestMatcher = logoutRequestMatcher; } public void setFilterProcessesUrl(String filterProcessesUrl) { this.logoutRequestMatcher = pathPattern(filterProcessesUrl); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\logout\LogoutFilter.java
1
请完成以下Java代码
public class ProductionSimulationView extends AbstractCustomView<ProductionSimulationRow> implements IEditableView { private final PostMaterialEventService postMaterialEventService = SpringContextHolder.instance.getBean(PostMaterialEventService.class); @Builder public ProductionSimulationView( @NonNull final ViewId viewId, @Nullable final ITranslatableString description, @NonNull final ProductionSimulationRows rows) { super(viewId, description, rows, NullDocumentFilterDescriptorsProvider.instance); } @Nullable @Override public String getTableNameOrNull(@Nullable final DocumentId documentId) { return null; }
@Override public void close(final ViewCloseAction closeAction) { postMaterialEventService.enqueueEventNow(DeactivateAllSimulatedCandidatesEvent.builder() .eventDescriptor(EventDescriptor.ofClientAndOrg(Env.getClientAndOrgId())) .build()); } @Override protected ProductionSimulationRows getRowsData() { return ProductionSimulationRows.cast(super.getRowsData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationView.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getSourceActivityId() { return sourceActivityId; } public void setSourceActivityId(String sourceActivityId) { this.sourceActivityId = sourceActivityId; } @Override public String getSourceActivityName() { return sourceActivityName; } public void setSourceActivityName(String sourceActivityName) { this.sourceActivityName = sourceActivityName; } @Override public String getSourceActivityType() { return sourceActivityType; } public void setSourceActivityType(String sourceActivityType) { this.sourceActivityType = sourceActivityType; } @Override public String getTargetActivityId() { return targetActivityId; } public void setTargetActivityId(String targetActivityId) { this.targetActivityId = targetActivityId; }
@Override public String getTargetActivityName() { return targetActivityName; } public void setTargetActivityName(String targetActivityName) { this.targetActivityName = targetActivityName; } @Override public String getTargetActivityType() { return targetActivityType; } public void setTargetActivityType(String targetActivityType) { this.targetActivityType = targetActivityType; } @Override public String getSourceActivityBehaviorClass() { return sourceActivityBehaviorClass; } public void setSourceActivityBehaviorClass(String sourceActivityBehaviorClass) { this.sourceActivityBehaviorClass = sourceActivityBehaviorClass; } @Override public String getTargetActivityBehaviorClass() { return targetActivityBehaviorClass; } public void setTargetActivityBehaviorClass(String targetActivityBehaviorClass) { this.targetActivityBehaviorClass = targetActivityBehaviorClass; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\event\impl\FlowableSequenceFlowTakenEventImpl.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Max. Value. @param ValueMax Maximum Value for a field */ public void setValueMax (String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Value. @return Maximum Value for a field */ public String getValueMax () { return (String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Value. @param ValueMin Minimum Value for a field */
public void setValueMin (String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Value. @return Minimum Value for a field */ public String getValueMin () { return (String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public void setVFormat (String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public String getVFormat () { return (String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute.java
1