instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void newAuthors() { Author a1 = new Author(); a1.setName("Mark Janel"); a1.setGenre("Anthology"); a1.setId(1L); a1.setAge(23); Author a2 = new Author(); a2.setName("Olivia Goy"); a2.setGenre("Anthology"); a2.setId(2L); a2.setAge(43); Author a3 = new Author(); a3.setName("Quartis Young"); a3.setGenre("Anthology");
a3.setId(3L); a3.setAge(51); Author a4 = new Author(); a4.setName("Joana Nimar"); a4.setGenre("History"); a4.setId(4L); a4.setAge(34); authorRepository.save(a1); authorRepository.save(a2); authorRepository.save(a3); authorRepository.save(a4); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalInRepository\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<PhoneNumJson> getPhoneNumList() { return phoneNumList; } public void setPhoneNumList(List<PhoneNumJson> phoneNumList) { this.phoneNumList = phoneNumList; } }
repos\springboot-demo-master\protobuf\src\main\java\com\et\protobuf\StudentJson.java
1
请完成以下Java代码
public R<String> filePath(@RequestParam String fileName) { return R.data(qiniuTemplate.filePath(fileName)); } /** * 获取文件外链 * * @param fileName 存储桶对象名称 * @return String */ @SneakyThrows @GetMapping("/file-link") public R<String> fileLink(@RequestParam String fileName) { return R.data(qiniuTemplate.fileLink(fileName)); } /** * 上传文件 * * @param file 文件 * @return ObjectStat */ @SneakyThrows @PostMapping("/put-file") public R<BladeFile> putFile(@RequestParam MultipartFile file) { BladeFile bladeFile = qiniuTemplate.putFile(file.getOriginalFilename(), file.getInputStream()); return R.data(bladeFile); } /** * 上传文件 * * @param fileName 存储桶对象名称 * @param file 文件 * @return ObjectStat */
@SneakyThrows @PostMapping("/put-file-by-name") public R<BladeFile> putFile(@RequestParam String fileName, @RequestParam MultipartFile file) { BladeFile bladeFile = qiniuTemplate.putFile(fileName, file.getInputStream()); return R.data(bladeFile); } /** * 删除文件 * * @param fileName 存储桶对象名称 * @return R */ @SneakyThrows @PostMapping("/remove-file") public R removeFile(@RequestParam String fileName) { qiniuTemplate.removeFile(fileName); return R.success("操作成功"); } /** * 批量删除文件 * * @param fileNames 存储桶对象名称集合 * @return R */ @SneakyThrows @PostMapping("/remove-files") public R removeFiles(@RequestParam String fileNames) { qiniuTemplate.removeFiles(Func.toStrList(fileNames)); return R.success("操作成功"); } }
repos\SpringBlade-master\blade-ops\blade-resource\src\main\java\org\springblade\resource\endpoint\OssEndpoint.java
1
请在Spring Boot框架中完成以下Java代码
static class WebSecurityConfiguration { @Bean @ConditionalOnBean(ReactiveJwtDecoder.class) SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ReactiveJwtDecoder jwtDecoder) { http.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated()); http.oauth2ResourceServer((server) -> customDecoder(server, jwtDecoder)); return http.build(); } private void customDecoder(OAuth2ResourceServerSpec server, ReactiveJwtDecoder decoder) { server.jwt((jwt) -> jwt.jwtDecoder(decoder)); } } private static class JwtConverterPropertiesCondition extends AnyNestedCondition { JwtConverterPropertiesCondition() { super(ConfigurationPhase.REGISTER_BEAN);
} @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authority-prefix") static class OnAuthorityPrefix { } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.principal-claim-name") static class OnPrincipalClaimName { } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-name") static class OnAuthoritiesClaimName { } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\reactive\ReactiveOAuth2ResourceServerJwkConfiguration.java
2
请完成以下Java代码
public void setDataEntry_Record_ID (int DataEntry_Record_ID) { if (DataEntry_Record_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_Record_ID, Integer.valueOf(DataEntry_Record_ID)); } /** Get DataEntry_Record. @return DataEntry_Record */ @Override public int getDataEntry_Record_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DataEntry_RecordData. @param DataEntry_RecordData Holds the (JSON-)data of all fields for a data entry. The json is supposed to be rendered into the respective fields, the column is not intended for actual display */ @Override public void setDataEntry_RecordData (java.lang.String DataEntry_RecordData) { set_Value (COLUMNNAME_DataEntry_RecordData, DataEntry_RecordData); } /** Get DataEntry_RecordData. @return Holds the (JSON-)data of all fields for a data entry. The json is supposed to be rendered into the respective fields, the column is not intended for actual display */ @Override public java.lang.String getDataEntry_RecordData () { return (java.lang.String)get_Value(COLUMNNAME_DataEntry_RecordData); } @Override public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class); } @Override public void setDataEntry_SubTab(de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab) { set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab); } /** Set Unterregister. @param DataEntry_SubTab_ID Unterregister */ @Override public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID)); }
/** Get Unterregister. @return Unterregister */ @Override public int getDataEntry_SubTab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java
1
请完成以下Java代码
public BoundaryCancelEventActivityBehavior createBoundaryCancelEventActivityBehavior(CancelEventDefinition cancelEventDefinition) { return new BoundaryCancelEventActivityBehavior(); } @Override public BoundaryCompensateEventActivityBehavior createBoundaryCompensateEventActivityBehavior(BoundaryEvent boundaryEvent, CompensateEventDefinition compensateEventDefinition, boolean interrupting) { return new BoundaryCompensateEventActivityBehavior(compensateEventDefinition, interrupting); } @Override public BoundaryConditionalEventActivityBehavior createBoundaryConditionalEventActivityBehavior(BoundaryEvent boundaryEvent, ConditionalEventDefinition conditionalEventDefinition, String conditionExpression, String conditionLanguage, boolean interrupting) { return new BoundaryConditionalEventActivityBehavior(conditionalEventDefinition, conditionExpression, conditionLanguage, interrupting); } @Override public BoundaryTimerEventActivityBehavior createBoundaryTimerEventActivityBehavior(BoundaryEvent boundaryEvent, TimerEventDefinition timerEventDefinition, boolean interrupting) { return new BoundaryTimerEventActivityBehavior(timerEventDefinition, interrupting); } @Override
public BoundarySignalEventActivityBehavior createBoundarySignalEventActivityBehavior(BoundaryEvent boundaryEvent, SignalEventDefinition signalEventDefinition, Signal signal, boolean interrupting) { return new BoundarySignalEventActivityBehavior(signalEventDefinition, signal, interrupting); } @Override public BoundaryMessageEventActivityBehavior createBoundaryMessageEventActivityBehavior(BoundaryEvent boundaryEvent, MessageEventDefinition messageEventDefinition, boolean interrupting) { return new BoundaryMessageEventActivityBehavior(messageEventDefinition, interrupting); } @Override public BoundaryEscalationEventActivityBehavior createBoundaryEscalationEventActivityBehavior(BoundaryEvent boundaryEvent, EscalationEventDefinition escalationEventDefinition, Escalation escalation, boolean interrupting) { return new BoundaryEscalationEventActivityBehavior(escalationEventDefinition, escalation, interrupting); } @Override public BoundaryEventRegistryEventActivityBehavior createBoundaryEventRegistryEventActivityBehavior(BoundaryEvent boundaryEvent, String eventDefinitionKey, boolean interrupting) { return new BoundaryEventRegistryEventActivityBehavior(eventDefinitionKey, interrupting); } @Override public BoundaryVariableListenerEventActivityBehavior createBoundaryVariableListenerEventActivityBehavior(BoundaryEvent boundaryEvent, VariableListenerEventDefinition variableListenerEventDefinition, boolean interrupting) { return new BoundaryVariableListenerEventActivityBehavior(variableListenerEventDefinition, interrupting); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
1
请在Spring Boot框架中完成以下Java代码
class ServletContextInitializerConfiguration extends AbstractConfiguration { private final ServletContextInitializers initializers; /** * Create a new {@link ServletContextInitializerConfiguration}. * @param initializers the initializers that should be invoked */ ServletContextInitializerConfiguration(ServletContextInitializers initializers) { super(new AbstractConfiguration.Builder()); Assert.notNull(initializers, "'initializers' must not be null"); this.initializers = initializers; } @Override public void configure(WebAppContext context) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(context.getClassLoader()); try {
callInitializers(context); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } private void callInitializers(WebAppContext context) throws ServletException { try { context.getContext().setExtendedListenerTypes(true); for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(context.getServletContext()); } } finally { context.getContext().setExtendedListenerTypes(false); } } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\ServletContextInitializerConfiguration.java
2
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driverClassName=com.p6spy.engine.spy.P6SpyDriver spring.jpa.hibernate.ddl-auto=create spring.jpa.s
how-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.open-in-view=false
repos\Hibernate-SpringBoot-master\HibernateSpringBootP6spy\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
private User importUserNoSave(final BPartner bpartner, final SyncUser syncUser, User user) { final String uuid = syncUser.getUuid(); if (user != null && !Objects.equals(uuid, user.getUuid())) { user = null; } if (user == null) { user = new User(); user.setUuid(uuid); user.setBpartner(bpartner); } user.markNotDeleted(); user.setEmail(syncUser.getEmail().trim()); // only sync the PW if not already set, e.g. by the forgot-password feature if (user.getPassword() == null || user.getPassword().trim().isEmpty()) { user.setPassword(syncUser.getPassword());
} user.setLanguage(syncUser.getLanguage()); // usersRepo.save(user); // don't save it logger.debug("Imported: {} -> {}", syncUser, user); return user; } private void deleteUser(final User user) { if (user.isDeleted()) { return; } user.markDeleted(); usersRepo.save(user); logger.debug("Deleted: {}", user); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncUserImportService.java
2
请完成以下Java代码
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(loadKeyStore(), null); return kmf; } private KeyStore loadKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (redisSslCredentials.getUserCertFile().isBlank() || redisSslCredentials.getUserKeyFile().isBlank()) { return null; } List<X509Certificate> certificates = SslUtil.readCertFileByPath(redisSslCredentials.getCertFile()); PrivateKey privateKey = SslUtil.readPrivateKeyByFilePath(redisSslCredentials.getUserKeyFile(), null); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null);
List<X509Certificate> unique = certificates.stream().distinct().toList(); for (X509Certificate cert : unique) { keyStore.setCertificateEntry("redis-cert" + cert.getSubjectX500Principal().getName(), cert); } if (privateKey != null) { CertificateFactory factory = CertificateFactory.getInstance("X.509"); CertPath certPath = factory.generateCertPath(certificates); List<? extends Certificate> path = certPath.getCertificates(); Certificate[] x509Certificates = path.toArray(new Certificate[0]); keyStore.setKeyEntry("redis-private-key", privateKey, null, x509Certificates); } return keyStore; } }
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\TBRedisCacheConfiguration.java
1
请完成以下Java代码
public Tax getC_Tax() { return tax; } @Override public void setC_Tax(final Tax tax) { this.tax = tax; } @Override public boolean isPrinted() { return printed; } @Override public void setPrinted(final boolean printed) { this.printed = printed; } @Override public int getLineNo() { return lineNo; } @Override public void setLineNo(final int lineNo) { this.lineNo = lineNo; } @Override public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes); } @Override public List<IInvoiceLineAttribute> getInvoiceLineAttributes()
{ return invoiceLineAttributes; } @Override public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate() { return iciolsToUpdate; } @Override public int getC_PaymentTerm_ID() { return C_PaymentTerm_ID; } @Override public void setC_PaymentTerm_ID(final int paymentTermId) { C_PaymentTerm_ID = paymentTermId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java
1
请完成以下Java代码
public class XxlJobProps { /** * 调度中心配置 */ private XxlJobAdminProps admin; /** * 执行器配置 */ private XxlJobExecutorProps executor; /** * 与调度中心交互的accessToken */ private String accessToken; @Data public static class XxlJobAdminProps { /** * 调度中心地址 */ private String address; } @Data public static class XxlJobExecutorProps { /** * 执行器名称 */ private String appName; /** * 执行器 IP */ private String ip;
/** * 执行器端口 */ private int port; /** * 执行器日志 */ private String logPath; /** * 执行器日志保留天数,-1 */ private int logRetentionDays; } }
repos\spring-boot-demo-master\demo-task-xxl-job\src\main\java\com\xkcoding\task\xxl\job\config\props\XxlJobProps.java
1
请完成以下Java代码
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return inoutLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { inoutLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return inoutLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { inoutLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return inoutLine.getQtyEnteredTU(); }
@Override public void setQtyTU(final BigDecimal qtyPacks) { inoutLine.setQtyEnteredTU(qtyPacks); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public boolean isInDispute() { return inoutLine.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { inoutLine.setIsInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InOutLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public class HADDI1 { @XmlElement(name = "DOCUMENTID", required = true) protected String documentid; @XmlElement(name = "ADDINFO", required = true) protected String addinfo; /** * Gets the value of the documentid property. * * @return * possible object is * {@link String } * */ public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the addinfo property. * * @return * possible object is * {@link String } * */
public String getADDINFO() { return addinfo; } /** * Sets the value of the addinfo property. * * @param value * allowed object is * {@link String } * */ public void setADDINFO(String value) { this.addinfo = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HADDI1.java
2
请完成以下Java代码
public void setOutMessageRef(String outMessageRef) { this.outMessageRef = outMessageRef; } public List<String> getErrorMessageRef() { return errorMessageRef; } public void setErrorMessageRef(List<String> errorMessageRef) { this.errorMessageRef = errorMessageRef; } public Operation clone() { Operation clone = new Operation(); clone.setValues(this); return clone;
} public void setValues(Operation otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setImplementationRef(otherElement.getImplementationRef()); setInMessageRef(otherElement.getInMessageRef()); setOutMessageRef(otherElement.getOutMessageRef()); errorMessageRef = new ArrayList<String>(); if (otherElement.getErrorMessageRef() != null && !otherElement.getErrorMessageRef().isEmpty()) { errorMessageRef.addAll(otherElement.getErrorMessageRef()); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Operation.java
1
请完成以下Java代码
public Warehouse getByIdNotNull(@NonNull final WarehouseId id) { return warehouseDAO.getOptionalById(id) .orElseThrow(() -> new AdempiereException("No warehouse found for ID !") .appendParametersToMessage() .setParameter("WarehouseId", id)); } public void save(@NonNull final Warehouse warehouse) { warehouseDAO.save(warehouse); } @NonNull public Warehouse createWarehouse(@NonNull final CreateWarehouseRequest request) { return warehouseDAO.createWarehouse(request); } @Override public Optional<LocationId> getLocationIdByLocatorRepoId(final int locatorRepoId) { final WarehouseId warehouseId = getIdByLocatorRepoId(locatorRepoId); final I_M_Warehouse warehouse = getById(warehouseId); return Optional.ofNullable(LocationId.ofRepoIdOrNull(warehouse.getC_Location_ID())); } @Override public OrgId getOrgIdByLocatorRepoId(final int locatorId) { return warehouseDAO.retrieveOrgIdByLocatorId(locatorId); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIdsOfTheSamePickingGroup(@NonNull final WarehouseId warehouseId) { final Set<WarehouseId> pickFromWarehouseIds = warehouseDAO.getWarehouseIdsOfSamePickingGroup(warehouseId); return warehouseDAO.getLocatorIdsByWarehouseIds(pickFromWarehouseIds); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds) { return warehouseDAO.getLocatorIdsByRepoId(locatorIds); } @Override public LocatorQRCode getLocatorQRCode(@NonNull final LocatorId locatorId) { final I_M_Locator locator = warehouseDAO.getLocatorById(locatorId); return LocatorQRCode.ofLocator(locator); }
@Override @NonNull public ExplainedOptional<LocatorQRCode> getLocatorQRCodeByValue(@NonNull String locatorValue) { final List<I_M_Locator> locators = getActiveLocatorsByValue(locatorValue); if (locators.isEmpty()) { return ExplainedOptional.emptyBecause(AdempiereException.MSG_NotFound); } else if (locators.size() > 1) { return ExplainedOptional.emptyBecause(DBMoreThanOneRecordsFoundException.MSG_QueryMoreThanOneRecordsFound); } else { final I_M_Locator locator = locators.get(0); return ExplainedOptional.of(LocatorQRCode.ofLocator(locator)); } } @Override public List<I_M_Locator> getActiveLocatorsByValue(final @NotNull String locatorValue) { return warehouseDAO.retrieveActiveLocatorsByValue(locatorValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseBL.java
1
请在Spring Boot框架中完成以下Java代码
private String getCellValueAsString(final Cell cell) { final Object value = getCellValue(cell); return value == null ? null : value.toString(); } public enum RowType { TableHeader("H"), TableRow("R"), NameValuePair("V"); private final String code; RowType(final String code) { this.code = code; } public String getCode() { return code; } @Nullable public static RowType forCodeOrNull(@Nullable final String code) { if (code == null) { return null; } for (final RowType d : values()) { if (d.getCode().equals(code)) { return d; } } return null; } } public static class Builder { @Nullable private String noNameHeaderPrefix = DEFAULT_UnknownHeaderPrefix; private boolean considerNullStringAsNull = false; private boolean considerEmptyStringAsNull = false; private String rowNumberMapKey = null; private boolean discardRepeatingHeaders = false; private boolean useTypeColumn = true; private Builder() { super(); } public ExcelToMapListConverter build() { return new ExcelToMapListConverter(this); } /** * Sets the header prefix to be used if the header columns is null or black. * * Set it to <code>null</code> to turn it off and get rid of columns without header. * * @see #setDiscardNoNameHeaders() */ public Builder setNoNameHeaderPrefix(@Nullable final String noNameHeaderPrefix) { this.noNameHeaderPrefix = noNameHeaderPrefix; return this; } public Builder setDiscardNoNameHeaders() {
setNoNameHeaderPrefix(null); return this; } /** * Sets if a cell value which is a null string (i.e. {@link ExcelToMapListConverter#NULLStringMarker}) shall be considered as <code>null</code>. */ public Builder setConsiderNullStringAsNull(final boolean considerNullStringAsNull) { this.considerNullStringAsNull = considerNullStringAsNull; return this; } public Builder setConsiderEmptyStringAsNull(final boolean considerEmptyStringAsNull) { this.considerEmptyStringAsNull = considerEmptyStringAsNull; return this; } public Builder setRowNumberMapKey(final String rowNumberMapKey) { this.rowNumberMapKey = rowNumberMapKey; return this; } /** * Sets if we shall detect repeating headers and discard them. */ public Builder setDiscardRepeatingHeaders(final boolean discardRepeatingHeaders) { this.discardRepeatingHeaders = discardRepeatingHeaders; return this; } /** * If enabled, the XLS converter will look for first not null column and it will expect to have one of the codes from {@link RowType}. * If no row type would be found, the row would be ignored entirely. * * task 09045 */ public Builder setUseRowTypeColumn(final boolean useTypeColumn) { this.useTypeColumn = useTypeColumn; return this; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelToMapListConverter.java
2
请完成以下Java代码
public ProcessEngine buildProcessEngine(ProcessEngineConfigurationImpl v6Configuration) { org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl v5Configuration = null; if (v6Configuration instanceof SpringProcessEngineConfiguration) { v5Configuration = new org.activiti.spring.SpringProcessEngineConfiguration(); super.copyConfigItems(v6Configuration, v5Configuration); copySpringConfigItems((SpringProcessEngineConfiguration) v6Configuration, (org.activiti.spring.SpringProcessEngineConfiguration) v5Configuration); return v5Configuration.buildProcessEngine(); } else { return super.buildProcessEngine(v6Configuration); } }
protected void copySpringConfigItems(SpringProcessEngineConfiguration v6Configuration, org.activiti.spring.SpringProcessEngineConfiguration v5Configuration) { v5Configuration.setApplicationContext(v6Configuration.getApplicationContext()); v5Configuration.setTransactionManager(v6Configuration.getTransactionManager()); Map<Object, Object> beans = v6Configuration.getBeans(); if (!(beans instanceof org.flowable.common.engine.impl.cfg.SpringBeanFactoryProxyMap)) { v5Configuration.setBeans(new SpringBeanFactoryProxyMap(v6Configuration.getApplicationContext())); } if (v5Configuration.getExpressionManager() == null) { v5Configuration.setExpressionManager(new SpringExpressionManager(v6Configuration.getApplicationContext(), v6Configuration.getBeans())); } } }
repos\flowable-engine-main\modules\flowable5-spring-compatibility\src\main\java\org\activiti\compatibility\spring\DefaultSpringProcessEngineFactory.java
1
请完成以下Java代码
public int getPageNumber() { throw unsupportedOperation(); } @Override public int getPageSize() { return limit; } @Override public long getOffset() { return offset; } @Override public Sort getSort() { return sort; } @Override public Pageable next() { throw unsupportedOperation(); } @Override public Pageable previousOrFirst() { throw unsupportedOperation(); } @Override
public Pageable first() { throw unsupportedOperation(); } @Override public Pageable withPage(int pageNumber) { throw unsupportedOperation(); } @Override public boolean hasPrevious() { throw unsupportedOperation(); } private UnsupportedOperationException unsupportedOperation() { return new UnsupportedOperationException("OffsetBasedPageable has no pages. Contains only offset and page size"); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\lib\OffsetBasedPageable.java
1
请在Spring Boot框架中完成以下Java代码
public R<DataScope> detail(DataScope dataScope) { DataScope detail = dataScopeService.getOne(Condition.getQueryWrapper(dataScope)); return R.data(detail); } /** * 分页 */ @GetMapping("/list") @ApiOperationSupport(order = 2) @Operation(summary = "分页", description = "传入dataScope") public R<IPage<DataScopeVO>> list(DataScope dataScope, Query query) { IPage<DataScope> pages = dataScopeService.page(Condition.getPage(query), Condition.getQueryWrapper(dataScope)); return R.data(DataScopeWrapper.build().pageVO(pages)); } /** * 新增 */ @PostMapping("/save") @ApiOperationSupport(order = 3) @Operation(summary = "新增", description = "传入dataScope") public R save(@Valid @RequestBody DataScope dataScope) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.save(dataScope)); } /** * 修改 */ @PostMapping("/update") @ApiOperationSupport(order = 4) @Operation(summary = "修改", description = "传入dataScope") public R update(@Valid @RequestBody DataScope dataScope) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.updateById(dataScope)); } /**
* 新增或修改 */ @PostMapping("/submit") @ApiOperationSupport(order = 5) @Operation(summary = "新增或修改", description = "传入dataScope") public R submit(@Valid @RequestBody DataScope dataScope) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.saveOrUpdate(dataScope)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 6) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.deleteLogic(Func.toLongList(ids))); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\DataScopeController.java
2
请完成以下Java代码
public void parseText(String text, AhoCorasickDoubleArrayTrie.IHit<V> processor) { Searcher searcher = getSearcher(text, 0); while (searcher.next()) { processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value); } } public LongestSearcher getLongestSearcher(String text, int offset) { return getLongestSearcher(text.toCharArray(), offset); } public LongestSearcher getLongestSearcher(char[] text, int offset) { return new LongestSearcher(offset, text); } /** * 最长匹配 * * @param text 文本 * @param processor 处理器 */ public void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<V> processor) { LongestSearcher searcher = getLongestSearcher(text, 0); while (searcher.next()) { processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value); } } /** * 转移状态 * * @param current * @param c * @return */ protected int transition(int current, char c) { int b = base[current]; int p; p = b + c + 1; if (b == check[p]) b = base[p]; else return -1; p = b; return p; } /** * 更新某个键对应的值 * * @param key 键 * @param value 值 * @return 是否成功(失败的原因是没有这个键) */
public boolean set(String key, V value) { int index = exactMatchSearch(key); if (index >= 0) { v[index] = value; return true; } return false; } /** * 从值数组中提取下标为index的值<br> * 注意为了效率,此处不进行参数校验 * * @param index 下标 * @return 值 */ public V get(int index) { return v[index]; } /** * 释放空闲的内存 */ private void shrink() { // if (HanLP.Config.DEBUG) // { // System.err.printf("释放内存 %d bytes\n", base.length - size - 65535); // } int nbase[] = new int[size + 65535]; System.arraycopy(base, 0, nbase, 0, size); base = nbase; int ncheck[] = new int[size + 65535]; System.arraycopy(check, 0, ncheck, 0, size); check = ncheck; } /** * 打印统计信息 */ // public void report() // { // System.out.println("size: " + size); // int nonZeroIndex = 0; // for (int i = 0; i < base.length; i++) // { // if (base[i] != 0) nonZeroIndex = i; // } // System.out.println("BaseUsed: " + nonZeroIndex); // nonZeroIndex = 0; // for (int i = 0; i < check.length; i++) // { // if (check[i] != 0) nonZeroIndex = i; // } // System.out.println("CheckUsed: " + nonZeroIndex); // } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\DoubleArrayTrie.java
1
请完成以下Java代码
public OrderCheckupBuilder setPlantId(ResourceId plantId) { this._plantId = plantId; return this; } private ResourceId getPlantId() { return _plantId; } public OrderCheckupBuilder setReponsibleUserId(UserId reponsibleUserId) { this._reponsibleUserId = reponsibleUserId; return this; }
private UserId getReponsibleUserId() { return _reponsibleUserId; } public OrderCheckupBuilder setDocumentType(String documentType) { this._documentType = documentType; return this; } private String getDocumentType() { Check.assumeNotEmpty(_documentType, "documentType not empty"); return _documentType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\impl\OrderCheckupBuilder.java
1
请完成以下Java代码
class WebServerManager { private final ReactiveWebServerApplicationContext applicationContext; private final DelayedInitializationHttpHandler handler; private final WebServer webServer; WebServerManager(ReactiveWebServerApplicationContext applicationContext, ReactiveWebServerFactory factory, Supplier<HttpHandler> handlerSupplier, boolean lazyInit) { this.applicationContext = applicationContext; Assert.notNull(factory, "'factory' must not be null"); this.handler = new DelayedInitializationHttpHandler(handlerSupplier, lazyInit); this.webServer = factory.getWebServer(this.handler); } void start() { this.handler.initializeHandler(); this.webServer.start(); this.applicationContext .publishEvent(new ReactiveWebServerInitializedEvent(this.webServer, this.applicationContext)); } void shutDownGracefully(GracefulShutdownCallback callback) { this.webServer.shutDownGracefully(callback); } void stop() { this.webServer.stop(); } WebServer getWebServer() { return this.webServer; } HttpHandler getHandler() { return this.handler; } /** * A delayed {@link HttpHandler} that doesn't initialize things too early. */ static final class DelayedInitializationHttpHandler implements HttpHandler { private final Supplier<HttpHandler> handlerSupplier; private final boolean lazyInit;
private volatile HttpHandler delegate = this::handleUninitialized; private DelayedInitializationHttpHandler(Supplier<HttpHandler> handlerSupplier, boolean lazyInit) { this.handlerSupplier = handlerSupplier; this.lazyInit = lazyInit; } private Mono<Void> handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) { throw new IllegalStateException("The HttpHandler has not yet been initialized"); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.handle(request, response); } void initializeHandler() { this.delegate = this.lazyInit ? new LazyHttpHandler(this.handlerSupplier) : this.handlerSupplier.get(); } HttpHandler getHandler() { return this.delegate; } } /** * {@link HttpHandler} that initializes its delegate on first request. */ private static final class LazyHttpHandler implements HttpHandler { private final Mono<HttpHandler> delegate; private LazyHttpHandler(Supplier<HttpHandler> handlerSupplier) { this.delegate = Mono.fromSupplier(handlerSupplier); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.flatMap((handler) -> handler.handle(request, response)); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerManager.java
1
请完成以下Java代码
public void updateProcessDefinitionInfo(ProcessDefinitionInfoEntity updatedProcessDefinitionInfo) { CommandContext commandContext = Context.getCommandContext(); DbSqlSession dbSqlSession = commandContext.getDbSqlSession(); dbSqlSession.update(updatedProcessDefinitionInfo); if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, updatedProcessDefinitionInfo), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } public void deleteProcessDefinitionInfo(String processDefinitionId) { ProcessDefinitionInfoEntity processDefinitionInfo = findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); if (processDefinitionInfo != null) { getDbSqlSession().delete(processDefinitionInfo); deleteInfoJson(processDefinitionInfo); if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, processDefinitionInfo), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } } public void updateInfoJson(String id, byte[] json) { ProcessDefinitionInfoEntity processDefinitionInfo = getDbSqlSession().selectById(ProcessDefinitionInfoEntity.class, id); if (processDefinitionInfo != null) {
ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId()); ref.setValue("json", json); if (processDefinitionInfo.getInfoJsonId() == null) { processDefinitionInfo.setInfoJsonId(ref.getId()); updateProcessDefinitionInfo(processDefinitionInfo); } } } public void deleteInfoJson(ProcessDefinitionInfoEntity processDefinitionInfo) { if (processDefinitionInfo.getInfoJsonId() != null) { ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId()); ref.delete(); } } public ProcessDefinitionInfoEntity findProcessDefinitionInfoById(String id) { return (ProcessDefinitionInfoEntity) getDbSqlSession().selectOne("selectProcessDefinitionInfo", id); } public ProcessDefinitionInfoEntity findProcessDefinitionInfoByProcessDefinitionId(String processDefinitionId) { return (ProcessDefinitionInfoEntity) getDbSqlSession().selectOne("selectProcessDefinitionInfoByProcessDefinitionId", processDefinitionId); } public byte[] findInfoJsonById(String infoJsonId) { ByteArrayRef ref = new ByteArrayRef(infoJsonId); return ref.getBytes(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionInfoEntityManager.java
1
请完成以下Java代码
public int getOverallNumberOfInvoicings() { return numberOfInspections; } @Override public BigDecimal getWithholdingPercent() { return Env.ONEHUNDRED.divide(BigDecimal.valueOf(numberOfInspections), 2, RoundingMode.HALF_UP); } @Override public Currency getCurrency() { return currency; } @Override public I_M_Product getRegularPPOrderProduct()
{ return regularPPOrderProduct; } @Override public String toString() { return ObjectUtils.toString(this); } @Override public Timestamp getValidToDate() { return validToDate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\RecordBackedQualityBasedConfig.java
1
请完成以下Java代码
public URI getWebhookUrl() { return this.webhookUrl; } public void setWebhookUrl(URI webhookUrl) { this.webhookUrl = webhookUrl; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public boolean isAtAll() { return atAll; } public void setAtAll(boolean atAll) { this.atAll = atAll; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public MessageType getMessageType() { return messageType; } public void setMessageType(MessageType messageType) { this.messageType = messageType; } public Card getCard() { return card; }
public void setCard(Card card) { this.card = card; } public enum MessageType { text, interactive } public static class Card { /** * This is header title. */ private String title = "Codecentric's Spring Boot Admin notice"; private String themeColor = "red"; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getThemeColor() { return themeColor; } public void setThemeColor(String themeColor) { this.themeColor = themeColor; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\FeiShuNotifier.java
1
请在Spring Boot框架中完成以下Java代码
public class StatusUpdateTrigger extends AbstractEventHandler<InstanceEvent> { private static final Logger log = LoggerFactory.getLogger(StatusUpdateTrigger.class); private final StatusUpdater statusUpdater; private final IntervalCheck intervalCheck; public StatusUpdateTrigger(StatusUpdater statusUpdater, Publisher<InstanceEvent> publisher, Duration updateInterval, Duration statusLifetime, Duration maxBackoff) { super(publisher, InstanceEvent.class); this.statusUpdater = statusUpdater; this.intervalCheck = new IntervalCheck("status", this::updateStatus, updateInterval, statusLifetime, maxBackoff); } @Override protected Publisher<Void> handle(Flux<InstanceEvent> publisher) { return publisher .filter((event) -> event instanceof InstanceRegisteredEvent || event instanceof InstanceRegistrationUpdatedEvent) .flatMap((event) -> updateStatus(event.getInstance())); } protected Mono<Void> updateStatus(InstanceId instanceId) { return this.statusUpdater.timeout(this.intervalCheck.getInterval()) .updateStatus(instanceId) .onErrorResume((e) -> { log.warn("Unexpected error while updating status for {}", instanceId, e); return Mono.empty(); }) .doFinally((s) -> this.intervalCheck.markAsChecked(instanceId)); } @Override
public void start() { super.start(); this.intervalCheck.start(); } @Override public void stop() { super.stop(); this.intervalCheck.stop(); } public void setInterval(Duration updateInterval) { this.intervalCheck.setInterval(updateInterval); } public void setLifetime(Duration statusLifetime) { this.intervalCheck.setMinRetention(statusLifetime); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\StatusUpdateTrigger.java
2
请完成以下Java代码
public static void main(String[] args) { double maxPricePerUniqueSong = 2.5; SpringsteenProblem springsteen = new SpringsteenProblem( ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")), new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")), new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))), maxPricePerUniqueSong); Engine<BitGene, Double> engine = Engine.builder(springsteen) .build(); ISeq<SpringsteenRecord> result = springsteen.codec() .decoder() .apply(engine.stream() .limit(10) .collect(EvolutionResult.toBestGenotype())); double cost = result.stream() .mapToDouble(r -> r.price) .sum(); int uniqueSongCount = result.stream()
.flatMap(r -> r.songs.stream()) .collect(Collectors.toSet()) .size(); double pricePerUniqueSong = cost / uniqueSongCount; System.out.println("Overall cost: " + cost); System.out.println("Unique songs: " + uniqueSongCount); System.out.println("Cost per song: " + pricePerUniqueSong); System.out.println("Records: " + result.map(r -> r.name) .toString(", ")); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\jenetics\SpringsteenProblem.java
1
请完成以下Java代码
public void setValue (int key) { setValue(String.valueOf(key)); } // setValue @Override public NamePair getSelectedItem() { return (NamePair)super.getSelectedItem(); } /** * Get Value * @return key as Integer or String value */ @Override public Object getValue() { final NamePair p = getSelectedItem(); if (p == null) { return null; } // if (p instanceof KeyNamePair) { if (p.getID() == null) // -1 return null return null; return new Integer(((KeyNamePair)p).getID()); } return p.getID(); } // getValue /** * Get Display * @return displayed string */ @Override public String getDisplay() { if (getSelectedIndex() == -1) { return ""; } // final NamePair p = getSelectedItem(); if (p == null) { return ""; }
return p.getName(); } // getDisplay @Override public boolean isSelectionNone() { final Object selectedItem = getSelectedItem(); if (selectedItem == null) { return true; } else if (KeyNamePair.EMPTY.equals(selectedItem)) { return true; } else if (ValueNamePair.EMPTY.equals(selectedItem)) { return true; } else { return super.isSelectionNone(); } } } // VComboBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VComboBox.java
1
请完成以下Java代码
public void registerCallout() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }) public void beforeSave(final I_S_ExternalReference record) { final IExternalReferenceType externalReferenceType = externalReferenceTypes.ofCode(record.getType()).orElse(null); if (externalReferenceType instanceof ExternalUserReferenceType) { switch (ExternalUserReferenceType.cast(externalReferenceType)) { case USER_ID: validateUserId(UserId.ofRepoId(record.getRecord_ID())); break; default: throw new AdempiereException("There is no validation in place for ExternalReferenceType: " + externalReferenceType.getCode()); } } else { logger.debug("Ignore unrelated IExternalReferenceType={}", externalReferenceType.getCode()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_S_ExternalReference.COLUMNNAME_Record_ID }) @CalloutMethod(columnNames = { I_S_ExternalReference.COLUMNNAME_Record_ID }) public void updateReferenced_Record_ID(final I_S_ExternalReference record) { record.setReferenced_Record_ID(record.getRecord_ID()); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_S_ExternalReference.COLUMNNAME_Type }) @CalloutMethod(columnNames = { I_S_ExternalReference.COLUMNNAME_Type })
public void updateReferenced_Table_ID(final I_S_ExternalReference record) { final IExternalReferenceType externalReferenceType = externalReferenceTypes.ofCode(record.getType()) .orElseThrow(() -> new AdempiereException("Unsupported S_ExternalReference.Type=" + record.getType()) .appendParametersToMessage() .setParameter("S_ExternalReference", record)); record.setReferenced_AD_Table_ID(adTableDAO.retrieveTableId(externalReferenceType.getTableName())); } private void validateUserId(@NonNull final UserId userId) { try { userDAO.getByIdInTrx(userId); } catch (final AdempiereException ex) { throw new AdempiereException("No user found for the given recordId! ", ex) .appendParametersToMessage() .setParameter("recordId", userId.getRepoId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\user\S_ExternalReference.java
1
请完成以下Java代码
public GuavaSession getSession() { if (!isInstall()) { return session; } else { if (session == null) { initSession(); } return session; } } public String getKeyspaceName() { return keyspaceName; } private boolean isInstall() { return environment.acceptsProfiles(Profiles.of("install")); } private void initSession() { if (this.keyspaceName != null) { this.sessionBuilder.withKeyspace(this.keyspaceName); } this.sessionBuilder.withLocalDatacenter(localDatacenter); if (StringUtils.isNotBlank(cloudSecureConnectBundlePath)) { this.sessionBuilder.withCloudSecureConnectBundle(Paths.get(cloudSecureConnectBundlePath)); this.sessionBuilder.withAuthCredentials(cloudClientId, cloudClientSecret); } session = sessionBuilder.build(); if (this.metrics && this.jmx) {
MetricRegistry registry = session.getMetrics().orElseThrow( () -> new IllegalStateException("Metrics are disabled")) .getRegistry(); this.reporter = JmxReporter.forRegistry(registry) .inDomain("com.datastax.oss.driver") .build(); this.reporter.start(); } } @PreDestroy public void close() { if (reporter != null) { reporter.stop(); } if (session != null) { session.close(); } } public ConsistencyLevel getDefaultReadConsistencyLevel() { return driverOptions.getDefaultReadConsistencyLevel(); } public ConsistencyLevel getDefaultWriteConsistencyLevel() { return driverOptions.getDefaultWriteConsistencyLevel(); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\AbstractCassandraCluster.java
1
请完成以下Java代码
public PrivilegeQuery groupIds(List<String> groupIds) { this.groupIds = groupIds; return this; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getIds() { return ids; } public void setIds(List<String> ids) { this.ids = ids; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId;
} public void setGroupId(String groupId) { this.groupId = groupId; } public List<String> getGroupIds() { return groupIds; } public void setGroupIds(List<String> groupIds) { this.groupIds = groupIds; } @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getPrivilegeEntityManager(commandContext).findPrivilegeCountByQueryCriteria(this); } @Override public List<Privilege> executeList(CommandContext commandContext) { return CommandContextUtil.getPrivilegeEntityManager(commandContext).findPrivilegeByQueryCriteria(this); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\PrivilegeQueryImpl.java
1
请完成以下Java代码
public void setC_Tax_ID (final int C_Tax_ID) { if (C_Tax_ID < 1) set_Value (COLUMNNAME_C_Tax_ID, null); else set_Value (COLUMNNAME_C_Tax_ID, C_Tax_ID); } @Override public int getC_Tax_ID() { return get_ValueAsInt(COLUMNNAME_C_Tax_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 setDocument_Currency_ID (final int Document_Currency_ID) { if (Document_Currency_ID < 1) set_Value (COLUMNNAME_Document_Currency_ID, null); else set_Value (COLUMNNAME_Document_Currency_ID, Document_Currency_ID); } @Override public int getDocument_Currency_ID() { return get_ValueAsInt(COLUMNNAME_Document_Currency_ID); } @Override public void setFact_Acct_UserChange_ID (final int Fact_Acct_UserChange_ID) { if (Fact_Acct_UserChange_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_UserChange_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_UserChange_ID, Fact_Acct_UserChange_ID); } @Override public int getFact_Acct_UserChange_ID() { return get_ValueAsInt(COLUMNNAME_Fact_Acct_UserChange_ID); } @Override public void setLocal_Currency_ID (final int Local_Currency_ID) { if (Local_Currency_ID < 1) set_Value (COLUMNNAME_Local_Currency_ID, null); else set_Value (COLUMNNAME_Local_Currency_ID, Local_Currency_ID); } @Override public int getLocal_Currency_ID() { return get_ValueAsInt(COLUMNNAME_Local_Currency_ID); } @Override public void setMatchKey (final @Nullable java.lang.String MatchKey) { set_Value (COLUMNNAME_MatchKey, MatchKey);
} @Override public java.lang.String getMatchKey() { return get_ValueAsString(COLUMNNAME_MatchKey); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } /** * PostingSign AD_Reference_ID=541699 * Reference name: PostingSign */ public static final int POSTINGSIGN_AD_Reference_ID=541699; /** DR = D */ public static final String POSTINGSIGN_DR = "D"; /** CR = C */ public static final String POSTINGSIGN_CR = "C"; @Override public void setPostingSign (final java.lang.String PostingSign) { set_Value (COLUMNNAME_PostingSign, PostingSign); } @Override public java.lang.String getPostingSign() { return get_ValueAsString(COLUMNNAME_PostingSign); } @Override public void setUserElementString1 (final @Nullable java.lang.String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public java.lang.String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_UserChange.java
1
请完成以下Java代码
public List<T> findRoute(T from, T to) { Map<T, RouteNode<T>> allNodes = new HashMap<>(); Queue<RouteNode> openSet = new PriorityQueue<>(); RouteNode<T> start = new RouteNode<>(from, null, 0d, targetScorer.computeCost(from, to)); allNodes.put(from, start); openSet.add(start); while (!openSet.isEmpty()) { log.debug("Open Set contains: " + openSet.stream().map(RouteNode::getCurrent).collect(Collectors.toSet())); RouteNode<T> next = openSet.poll(); log.debug("Looking at node: " + next); if (next.getCurrent().equals(to)) { log.debug("Found our destination!"); List<T> route = new ArrayList<>(); RouteNode<T> current = next; do { route.add(0, current.getCurrent()); current = allNodes.get(current.getPrevious()); } while (current != null); log.debug("Route: " + route); return route; } graph.getConnections(next.getCurrent()).forEach(connection -> {
double newScore = next.getRouteScore() + nextNodeScorer.computeCost(next.getCurrent(), connection); RouteNode<T> nextNode = allNodes.getOrDefault(connection, new RouteNode<>(connection)); allNodes.put(connection, nextNode); if (nextNode.getRouteScore() > newScore) { nextNode.setPrevious(next.getCurrent()); nextNode.setRouteScore(newScore); nextNode.setEstimatedScore(newScore + targetScorer.computeCost(connection, to)); openSet.add(nextNode); log.debug("Found a better route to node: " + nextNode); } }); } throw new IllegalStateException("No route found"); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\astar\RouteFinder.java
1
请在Spring Boot框架中完成以下Java代码
protected IgnoreCsrfProtectionRegistry chainRequestMatchers(List<RequestMatcher> requestMatchers) { CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(requestMatchers); return this; } } private static final class SpaCsrfTokenRequestHandler implements CsrfTokenRequestHandler { private final CsrfTokenRequestAttributeHandler plain = new CsrfTokenRequestAttributeHandler(); private final CsrfTokenRequestAttributeHandler xor = new XorCsrfTokenRequestAttributeHandler(); SpaCsrfTokenRequestHandler() { this.xor.setCsrfRequestAttributeName(null);
} @Override public void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> csrfToken) { this.xor.handle(request, response, csrfToken); } @Override public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) { String headerValue = request.getHeader(csrfToken.getHeaderName()); return (StringUtils.hasText(headerValue) ? this.plain : this.xor).resolveCsrfTokenValue(request, csrfToken); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\CsrfConfigurer.java
2
请完成以下Java代码
public int getLogoReport_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LogoReport_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Image getLogoWeb() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_LogoWeb_ID, org.compiere.model.I_AD_Image.class); } @Override public void setLogoWeb(org.compiere.model.I_AD_Image LogoWeb) { set_ValueFromPO(COLUMNNAME_LogoWeb_ID, org.compiere.model.I_AD_Image.class, LogoWeb); } /** Set Logo Web. @param LogoWeb_ID Logo Web */ @Override public void setLogoWeb_ID (int LogoWeb_ID) { if (LogoWeb_ID < 1) set_Value (COLUMNNAME_LogoWeb_ID, null); else set_Value (COLUMNNAME_LogoWeb_ID, Integer.valueOf(LogoWeb_ID)); } /** Get Logo Web. @return Logo Web */ @Override public int getLogoWeb_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LogoWeb_ID); if (ii == null) return 0; return ii.intValue(); } @Override
public org.compiere.model.I_M_Product getM_ProductFreight() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_ProductFreight(org.compiere.model.I_M_Product M_ProductFreight) { set_ValueFromPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class, M_ProductFreight); } /** Set Produkt für Fracht. @param M_ProductFreight_ID Produkt für Fracht */ @Override public void setM_ProductFreight_ID (int M_ProductFreight_ID) { if (M_ProductFreight_ID < 1) set_Value (COLUMNNAME_M_ProductFreight_ID, null); else set_Value (COLUMNNAME_M_ProductFreight_ID, Integer.valueOf(M_ProductFreight_ID)); } /** Get Produkt für Fracht. @return Produkt für Fracht */ @Override public int getM_ProductFreight_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductFreight_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_AD_ClientInfo.java
1
请完成以下Java代码
public Builder additionalParameters(Map<String, Object> additionalParameters) { this.additionalParameters = additionalParameters; return this; } /** * Builds a new {@link OAuth2DeviceAuthorizationResponse}. * @return a {@link OAuth2DeviceAuthorizationResponse} */ public OAuth2DeviceAuthorizationResponse build() { Assert.hasText(this.verificationUri, "verificationUri cannot be empty"); Assert.isTrue(this.expiresIn > 0, "expiresIn must be greater than zero"); Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(this.expiresIn); OAuth2DeviceCode deviceCode = new OAuth2DeviceCode(this.deviceCode, issuedAt, expiresAt); OAuth2UserCode userCode = new OAuth2UserCode(this.userCode, issuedAt, expiresAt);
OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = new OAuth2DeviceAuthorizationResponse(); deviceAuthorizationResponse.deviceCode = deviceCode; deviceAuthorizationResponse.userCode = userCode; deviceAuthorizationResponse.verificationUri = this.verificationUri; deviceAuthorizationResponse.verificationUriComplete = this.verificationUriComplete; deviceAuthorizationResponse.interval = this.interval; deviceAuthorizationResponse.additionalParameters = Collections .unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap() : this.additionalParameters); return deviceAuthorizationResponse; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2DeviceAuthorizationResponse.java
1
请完成以下Java代码
public void setTenderType (final java.lang.String TenderType) { set_Value (COLUMNNAME_TenderType, TenderType); } @Override public java.lang.String getTenderType() { return get_ValueAsString(COLUMNNAME_TenderType); } /** * TrxType AD_Reference_ID=215 * Reference name: C_Payment Trx Type */ public static final int TRXTYPE_AD_Reference_ID=215; /** Sales = S */ public static final String TRXTYPE_Sales = "S"; /** DelayedCapture = D */ public static final String TRXTYPE_DelayedCapture = "D"; /** CreditPayment = C */ public static final String TRXTYPE_CreditPayment = "C"; /** VoiceAuthorization = F */ public static final String TRXTYPE_VoiceAuthorization = "F"; /** Authorization = A */ public static final String TRXTYPE_Authorization = "A"; /** Void = V */ public static final String TRXTYPE_Void = "V"; /** Rückzahlung = R */ public static final String TRXTYPE_Rueckzahlung = "R"; @Override public void setTrxType (final java.lang.String TrxType) { set_Value (COLUMNNAME_TrxType, TrxType); } @Override public java.lang.String getTrxType() { return get_ValueAsString(COLUMNNAME_TrxType); } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
} @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } @Override public void setVoiceAuthCode (final @Nullable java.lang.String VoiceAuthCode) { set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode); } @Override public java.lang.String getVoiceAuthCode() { return get_ValueAsString(COLUMNNAME_VoiceAuthCode); } @Override public void setWriteOffAmt (final @Nullable BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } @Override public BigDecimal getWriteOffAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WriteOffAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment.java
1
请完成以下Java代码
public abstract class AlarmCondition { @NotNull @Valid private AlarmConditionExpression expression; @Valid private AlarmConditionValue<AlarmSchedule> schedule; @JsonIgnore public boolean hasSchedule() { return schedule != null && !(schedule.getStaticValue() instanceof AnyTimeSchedule); } @JsonIgnore public boolean requiresScheduledReevaluation() {
return hasSchedule() || expression.requiresScheduledReevaluation(); } @JsonIgnore @AssertTrue(message = "Expressions requiring scheduled reevaluation can only be used with simple alarm conditions") public boolean isValid() { if (getType() != AlarmConditionType.SIMPLE && expression.requiresScheduledReevaluation()) { return false; } return true; } @JsonIgnore public abstract AlarmConditionType getType(); }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\rule\condition\AlarmCondition.java
1
请完成以下Java代码
public MemberSuspectEvent withReason(String reason) { this.reason = reason; return this; } /** * Builder method used to configure the {@link DistributedMember peer member} that is the subject of the suspicion * {@link MembershipEvent}. * * @param suspectMember {@link DistributedMember peer member} that is being suspected; may be {@literal null}. * @return this {@link MemberSuspectEvent}. * @see #getSuspectMember() */
public MemberSuspectEvent withSuspect(DistributedMember suspectMember) { this.suspectMember = suspectMember; return this; } /** * @inheritDoc */ @Override public final Type getType() { return Type.MEMBER_SUSPECT; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\support\MemberSuspectEvent.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<BigDecimal> asBigDecimalAbs(@Nullable final MonetaryAmountType monetaryAmountType) { return asBigDecimal(monetaryAmountType); } @NonNull private Optional<BigDecimal> asBigDecimal(@Nullable final MonetaryAmountType monetaryAmountType) { if (monetaryAmountType == null) { return Optional.empty(); } return Optional.of(monetaryAmountType.getAmount()); } @VisibleForTesting Optional<BigDecimal> getServiceFeeVATRate(@NonNull final REMADVListLineItemExtensionType.MonetaryAmounts monetaryAmounts) { if (CollectionUtils.isEmpty(monetaryAmounts.getAdjustment())) { logger.log(Level.INFO, "No adjustments found on line! Line:" + remadvLineItemExtension); return Optional.empty(); } final List<String> targetAdjustmentCodes = Arrays.asList(ADJUSTMENT_CODE_67, ADJUSTMENT_CODE_90); final ImmutableSet<BigDecimal> vatTaxRateSet = monetaryAmounts.getAdjustment() .stream() .filter(adjustmentType -> targetAdjustmentCodes.contains(adjustmentType.getReasonCode())) .map(AdjustmentType::getTax)
.filter(Objects::nonNull) .map(TaxType::getVAT) .filter(Objects::nonNull) .map(VATType::getItem) .flatMap(List::stream) .map(ItemType::getTaxRate) .collect(ImmutableSet.toImmutableSet()); if (vatTaxRateSet.size() > 1) { throw new RuntimeException("Multiple vatTax rates found on the line! TaxRates: " + vatTaxRateSet); } else if (vatTaxRateSet.isEmpty()) { logger.log(Level.INFO, "No vat tax rates found on line! Line:" + remadvLineItemExtension); return Optional.empty(); } else { return vatTaxRateSet.stream().findFirst(); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\remadvimport\ecosio\JsonRemittanceAdviceLineProducer.java
2
请在Spring Boot框架中完成以下Java代码
public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请完成以下Java代码
public void setDealPric(ActiveOrHistoricCurrencyAndAmount value) { this.dealPric = value; } /** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryPrice2 } * * */ public List<ProprietaryPrice2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryPrice2>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionPrice2Choice.java
1
请在Spring Boot框架中完成以下Java代码
public String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } @ApiModelProperty(example = "12345") public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @ApiModelProperty(example = "oneMilestoneCase%3A1%3A4") public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId;
} @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-milestone-instances/5") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345") public String getHistoricCaseInstanceUrl() { return historicCaseInstanceUrl; } public void setHistoricCaseInstanceUrl(String historicCaseInstanceUrl) { this.historicCaseInstanceUrl = historicCaseInstanceUrl; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/oneMilestoneCase%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\milestone\HistoricMilestoneInstanceResponse.java
2
请完成以下Java代码
private static void assertSameOrg(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { Check.assumeEquals(d1.getOrgId(), d2.getOrgId(), "Dates have the same org: {}, {}", d1, d2); } public Instant toInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atStartOfDay().atZone(orgMapper.apply(orgId)).toInstant(); } public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant(); } public LocalDate toLocalDate() { return localDate; } public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) { return Timestamp.from(toInstant(orgMapper)); } @Override public int compareTo(final @Nullable LocalDateAndOrgId o) { return compareToByLocalDate(o); }
/** * In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes. * A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?" * That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s. * * @see #compareTo(LocalDateAndOrgId) */ private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o) { if (o == null) { return 1; } return this.localDate.compareTo(o.localDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
1
请在Spring Boot框架中完成以下Java代码
public void setMaxQueueSize(@Nullable Integer maxQueueSize) { this.maxQueueSize = maxQueueSize; } public @Nullable Integer getMaxConcurrentRequests() { return this.maxConcurrentRequests; } public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) { this.maxConcurrentRequests = maxConcurrentRequests; } public @Nullable Integer getMaxRequestsPerSecond() { return this.maxRequestsPerSecond; } public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) { this.maxRequestsPerSecond = maxRequestsPerSecond; } public @Nullable Duration getDrainInterval() { return this.drainInterval; } public void setDrainInterval(@Nullable Duration drainInterval) { this.drainInterval = drainInterval; } } /** * Name of the algorithm used to compress protocol frames. */ public enum Compression { /** * Requires 'net.jpountz.lz4:lz4'. */ LZ4, /** * Requires org.xerial.snappy:snappy-java. */ SNAPPY, /** * No compression. */ NONE
} public enum ThrottlerType { /** * Limit the number of requests that can be executed in parallel. */ CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"), /** * Limits the request rate per second. */ RATE_LIMITING("RateLimitingRequestThrottler"), /** * No request throttling. */ NONE("PassThroughRequestThrottler"); private final String type; ThrottlerType(String type) { this.type = type; } public String type() { return this.type; } } }
repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java
2
请完成以下Java代码
public List<Association> getOutgoingAssociations() { return outgoingAssociations; } @Override public void setOutgoingAssociations(List<Association> outgoingAssociations) { this.outgoingAssociations = outgoingAssociations; } public Object getBehavior() { return behavior; } public void setBehavior(Object behavior) { this.behavior = behavior; } public List<PlanItem> getEntryDependencies() { return entryDependencies; } public void setEntryDependencies(List<PlanItem> entryDependencies) { this.entryDependencies = entryDependencies; } public List<PlanItem> getExitDependencies() { return exitDependencies; } public void setExitDependencies(List<PlanItem> exitDependencies) { this.exitDependencies = exitDependencies; } public List<PlanItem> getEntryDependentPlanItems() { return entryDependentPlanItems; } public void setEntryDependentPlanItems(List<PlanItem> entryDependentPlanItems) { this.entryDependentPlanItems = entryDependentPlanItems; } public void addEntryDependentPlanItem(PlanItem planItem) { Optional<PlanItem> planItemWithSameId = entryDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst(); if (!planItemWithSameId.isPresent()) { entryDependentPlanItems.add(planItem); } } public List<PlanItem> getExitDependentPlanItems() { return exitDependentPlanItems; } public void setExitDependentPlanItems(List<PlanItem> exitDependentPlanItems) { this.exitDependentPlanItems = exitDependentPlanItems; }
public void addExitDependentPlanItem(PlanItem planItem) { Optional<PlanItem> planItemWithSameId = exitDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst(); if (!planItemWithSameId.isPresent()) { exitDependentPlanItems.add(planItem); } } public List<PlanItem> getAllDependentPlanItems() { List<PlanItem> allDependentPlanItems = new ArrayList<>(entryDependentPlanItems.size() + exitDependentPlanItems.size()); allDependentPlanItems.addAll(entryDependentPlanItems); allDependentPlanItems.addAll(exitDependentPlanItems); return allDependentPlanItems; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("PlanItem"); if (getName() != null) { stringBuilder.append(" '").append(getName()).append("'"); } stringBuilder.append(" (id: "); stringBuilder.append(getId()); if (getPlanItemDefinition() != null) { stringBuilder.append(", definitionId: ").append(getPlanItemDefinition().getId()); } stringBuilder.append(")"); return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItem.java
1
请在Spring Boot框架中完成以下Java代码
public DataResponse<ExternalWorkerJobResponse> listExternalWorkerJobs(@ModelAttribute ExternalWorkerJobQueryRequest request) { ExternalWorkerJobQuery query = createExternalWorkerJobQuery(); if (request.getId() != null) { query.jobId(request.getId()); } if (request.getProcessInstanceId() != null) { query.processInstanceId(request.getProcessInstanceId()); } if (request.isWithoutProcessInstanceId()) { query.withoutProcessInstanceId(); } if (request.getExecutionId() != null) { query.executionId(request.getExecutionId()); } if (request.getProcessDefinitionId() != null) { query.processDefinitionId(request.getProcessDefinitionId()); } if (request.getScopeId() != null) { query.scopeId(request.getScopeId()); } if (request.isWithoutScopeId()) { query.withoutScopeId(); } if (request.getSubScopeId() != null) { query.subScopeId(request.getSubScopeId()); } if (request.getScopeDefinitionId() != null) { query.scopeDefinitionId(request.getScopeDefinitionId()); } if (request.getScopeType() != null) { query.scopeType(request.getScopeType()); } if (request.getElementId() != null) { query.elementId(request.getElementId()); } if (request.getElementName() != null) { query.elementName(request.getElementName()); } if (request.isWithException()) { query.withException(); } if (request.getExceptionMessage() != null) { query.exceptionMessage(request.getExceptionMessage()); } if (request.getTenantId() != null) { query.jobTenantId(request.getTenantId()); }
if (request.getTenantIdLike() != null) { query.jobTenantIdLike(request.getTenantIdLike()); } if (request.isWithoutTenantId()) { query.jobWithoutTenantId(); } if (request.isLocked()) { query.locked(); } if (request.isUnlocked()) { query.unlocked(); } if (request.isWithoutScopeType()) { query.withoutScopeType(); } if (restApiInterceptor != null) { restApiInterceptor.accessExternalWorkerJobInfoWithQuery(query, request); } return PaginateListUtil.paginateList(request, query, "id", PROPERTIES, restResponseFactory::createExternalWorkerJobResponseList); } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobCollectionResource.java
2
请完成以下Java代码
public BranchAndFinancialInstitutionIdentification4 getPty() { return pty; } /** * Sets the value of the pty property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification4 } * */ public void setPty(BranchAndFinancialInstitutionIdentification4 value) { this.pty = value; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxCharges2 } * */ public TaxCharges2 getTax() {
return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxCharges2 } * */ public void setTax(TaxCharges2 value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ChargesInformation6.java
1
请完成以下Java代码
public class GregorianCalendarExample { public Date setMonth(GregorianCalendar calendar, int amount) { calendar.set(Calendar.MONTH, amount); return calendar.getTime(); } public Date rollAdd(GregorianCalendar calendar, int amount) { calendar.roll(GregorianCalendar.MONTH, amount); return calendar.getTime(); } public boolean isLeapYearExample(int year) { GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); return cal.isLeapYear(year); } public Date subtractDays(GregorianCalendar calendar, int daysToSubtract) { GregorianCalendar cal = calendar; cal.add(Calendar.DATE, -daysToSubtract); return cal.getTime(); } public Date addDays(GregorianCalendar calendar, int daysToAdd) { GregorianCalendar cal = calendar; cal.add(Calendar.DATE, daysToAdd); return cal.getTime(); } public XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) throws DatatypeConfigurationException { DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); return datatypeFactory.newXMLGregorianCalendar(calendar);
} public Date toDate(XMLGregorianCalendar calendar) { return calendar.toGregorianCalendar() .getTime(); } public int compareDates(GregorianCalendar firstDate, GregorianCalendar secondDate) { return firstDate.compareTo(secondDate); } public String formatDate(GregorianCalendar calendar) { return calendar.toZonedDateTime() .format(DateTimeFormatter.ofPattern("d MMM uuuu")); } }
repos\tutorials-master\core-java-modules\core-java-date-operations-4\src\main\java\com\baeldung\gregorian\calendar\GregorianCalendarExample.java
1
请完成以下Java代码
public WorkflowLaunchersFacet toWorkflowLaunchersFacet(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds) { final WorkflowLaunchersFacetId facetId = this.facetId.toWorkflowLaunchersFacetId(); return WorkflowLaunchersFacet.builder() .facetId(facetId) .caption(caption) .isActive(activeFacetIds != null && activeFacetIds.contains(facetId)) .build(); } } @EqualsAndHashCode @ToString public static class FacetsCollection implements Iterable<Facet> { private static final FacetsCollection EMPTY = new FacetsCollection(ImmutableSet.of()); private final ImmutableSet<Facet> set; private FacetsCollection(@NonNull final ImmutableSet<Facet> set) { this.set = set; } public static FacetsCollection ofCollection(final Collection<Facet> collection) { return !collection.isEmpty() ? new FacetsCollection(ImmutableSet.copyOf(collection)) : EMPTY; } @Override @NonNull public Iterator<Facet> iterator() {return set.iterator();} public boolean isEmpty() {return set.isEmpty();} public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds) { if (isEmpty()) {
return WorkflowLaunchersFacetGroupList.EMPTY; } final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>(); for (final ManufacturingJobFacets.Facet manufacturingFacet : set) { final WorkflowLaunchersFacet facet = manufacturingFacet.toWorkflowLaunchersFacet(activeFacetIds); groupBuilders.computeIfAbsent(facet.getGroupId(), k -> manufacturingFacet.newWorkflowLaunchersFacetGroupBuilder()) .facet(facet); } final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values() .stream() .map(WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder::build) .collect(ImmutableList.toImmutableList()); return WorkflowLaunchersFacetGroupList.ofList(groups); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobFacets.java
1
请完成以下Java代码
public String getNotificationsWhereClause() { if (this.notificationsWhereClause == null) { final Accessor accessor = new Accessor() { @Override public Object getValue(Object o) { return ((I_AD_Note)o).getAD_Note_ID(); } }; this.notificationsWhereClause = buildSqlInArrayWhereClause( I_AD_Note.COLUMNNAME_AD_Note_ID, this.notifications, accessor, null // params ); } return this.notificationsWhereClause; } private String buildSqlInArrayWhereClause(String columnName, List<?> values, Accessor accessor, List<Object> params) { if (values == null || values.isEmpty()) return ""; boolean hasNull = false; StringBuffer whereClause = new StringBuffer(); StringBuffer whereClauseCurrent = new StringBuffer(); int count = 0; for (Object v : values) { final Object value; if (accessor != null) value = accessor.getValue(v); else value = v; if (value == null) { hasNull = true; continue; } if (whereClauseCurrent.length() > 0) whereClauseCurrent.append(","); if (params == null) { whereClauseCurrent.append(value); } else { whereClauseCurrent.append("?"); params.add(value); } if (count >= 30) { if (whereClause.length() > 0) whereClause.append(" OR "); whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")"); whereClauseCurrent = new StringBuffer(); count = 0; } } if (whereClauseCurrent.length() > 0) { if (whereClause.length() > 0) whereClause.append(" OR "); whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")");
whereClauseCurrent = null; } if (hasNull) { if (whereClause.length() > 0) whereClause.append(" OR "); whereClause.append(columnName).append(" IS NULL"); } if (whereClause.length() > 0) whereClause.insert(0, "(").append(")"); return whereClause.toString(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("InvoiceGenerateResult ["); sb.append("invoiceCount=").append(getInvoiceCount()); if (storeInvoices) { sb.append(", invoices=").append(invoices); } if (notifications != null && !notifications.isEmpty()) { sb.append(", notifications=").append(notifications); } sb.append("]"); return sb.toString(); } @Override public String getSummary(final Properties ctx) { return Services.get(IMsgBL.class).getMsg(ctx, MSG_Summary, new Object[] { getInvoiceCount(), getNotificationCount() }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceGenerateResult.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email;
} public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
repos\tutorials-master\spring-reactive-modules\spring-reactor\src\main\java\com\baeldung\reactorbus\domain\NotificationData.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> updateDefIndex( @RequestParam("url") String url, @RequestParam("component") String component, @RequestParam("isRoute") Boolean isRoute ) { boolean success = sysRoleIndexService.updateDefaultIndex(url, component, isRoute); if (success) { return Result.OK("设置成功"); } else { return Result.error("设置失败"); } } /** * 切换默认门户 * * @param sysRoleIndex * @return */ @PostMapping(value = "/changeDefHome") public Result<?> changeDefHome(@RequestBody SysRoleIndex sysRoleIndex,HttpServletRequest request) { String username = JwtUtil.getUserNameByToken(request); sysRoleIndex.setRoleCode(username); sysRoleIndexService.changeDefHome(sysRoleIndex); // 代码逻辑说明: 切换完成后的homePath获取 String version = request.getHeader(CommonConstant.VERSION); String homePath = null; SysRoleIndex defIndexCfg = sysUserService.getDynamicIndexByUserRole(username, version); if (defIndexCfg == null) { defIndexCfg = sysRoleIndexService.initDefaultIndex(); } if (oConvertUtils.isNotEmpty(version) && defIndexCfg != null && oConvertUtils.isNotEmpty(defIndexCfg.getUrl())) { homePath = defIndexCfg.getUrl(); if (!homePath.startsWith(SymbolConstant.SINGLE_SLASH)) { homePath = SymbolConstant.SINGLE_SLASH + homePath; } }
return Result.OK(homePath); } /** * 获取门户类型 * * @return */ @GetMapping(value = "/getCurrentHome") public Result<?> getCurrentHome(HttpServletRequest request) { String username = JwtUtil.getUserNameByToken(request); Object homeType = redisUtil.get(DefIndexConst.CACHE_TYPE + username); return Result.OK(oConvertUtils.getString(homeType,DefIndexConst.HOME_TYPE_MENU)); } /** * 清除缓存 * * @return */ @RequestMapping(value = "/cleanDefaultIndexCache") public Result<?> cleanDefaultIndexCache(HttpServletRequest request) { sysRoleIndexService.cleanDefaultIndexCache(); return Result.OK(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysRoleIndexController.java
2
请完成以下Java代码
public class DeleteIdentityLinkForProcessDefinitionCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected String userId; protected String groupId; public DeleteIdentityLinkForProcessDefinitionCmd(String processDefinitionId, String userId, String groupId) { validateParams(userId, groupId, processDefinitionId); this.processDefinitionId = processDefinitionId; this.userId = userId; this.groupId = groupId; } protected void validateParams(String userId, String groupId, String processDefinitionId) { if (processDefinitionId == null) { throw new FlowableIllegalArgumentException("processDefinitionId is null"); } if (userId == null && groupId == null) { throw new FlowableIllegalArgumentException("userId and groupId cannot both be null"); } }
@Override public Void execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ProcessDefinitionEntity processDefinition = processEngineConfiguration.getProcessDefinitionEntityManager().findById(processDefinitionId); if (processDefinition == null) { throw new FlowableObjectNotFoundException("Cannot find process definition with id " + processDefinitionId, ProcessDefinition.class); } if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.deleteCandidateStarter(processDefinitionId, userId, groupId); return null; } processEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService() .deleteProcessDefinitionIdentityLink(processDefinition.getId(), userId, groupId); return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\DeleteIdentityLinkForProcessDefinitionCmd.java
1
请完成以下Java代码
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; }
@Override public String getScopeType() { return ScopeTypes.BPMN; } @Override public String getScopeId() { return processInstanceId; } @Override public String getSubScopeId() { return executionId; } @Override public String getScopeDefinitionId() { return processDefinitionId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventImpl.java
1
请完成以下Java代码
public boolean isShipConfirm() { return get_ValueAsBoolean(COLUMNNAME_IsShipConfirm); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setIsSplitWhenDifference (final boolean IsSplitWhenDifference) { set_Value (COLUMNNAME_IsSplitWhenDifference, IsSplitWhenDifference); } @Override public boolean isSplitWhenDifference() { return get_ValueAsBoolean(COLUMNNAME_IsSplitWhenDifference); } @Override public org.compiere.model.I_AD_Sequence getLotNo_Sequence() { return get_ValueAsPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setLotNo_Sequence(final org.compiere.model.I_AD_Sequence LotNo_Sequence) { set_ValueFromPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, LotNo_Sequence); } @Override public void setLotNo_Sequence_ID (final int LotNo_Sequence_ID) { if (LotNo_Sequence_ID < 1) set_Value (COLUMNNAME_LotNo_Sequence_ID, null); else set_Value (COLUMNNAME_LotNo_Sequence_ID, LotNo_Sequence_ID); } @Override public int getLotNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_LotNo_Sequence_ID); }
@Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintName (final java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } @Override public java.lang.String getPrintName() { return get_ValueAsString(COLUMNNAME_PrintName); } @Override public org.compiere.model.I_R_RequestType getR_RequestType() { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); } @Override public void setR_RequestType_ID (final int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID); } @Override public int getR_RequestType_ID() { return get_ValueAsInt(COLUMNNAME_R_RequestType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
1
请完成以下Java代码
public class R_MailText_Test extends JavaProcess { // services private final transient IADTableDAO tableDAO = Services.get(IADTableDAO.class); private final transient IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); private final transient IUserDAO userDAO = Services.get(IUserDAO.class); private final transient MailService mailService = SpringContextHolder.instance.getBean(MailService.class); @Param(parameterName = "C_BPartner_ID") private int p_C_BPartner_ID; @Param(parameterName = "AD_User_ID") private int p_AD_User_ID = -1; @Param(parameterName = "AD_Table_ID") private int p_AD_Table_ID = -1; @Param(parameterName = "Record_ID") private int p_Record_ID = -1; @Override protected String doIt() { final MailText mailText = createMailText(); addLog("@Result@ ---------------------------------"); addLog("Using @AD_Language@: {}", mailText.getAdLanguage()); addLog("@MailHeader@: {}", mailText.getMailHeader()); addLog("@MailText@ (full): {}", mailText.getFullMailText()); return MSG_OK; } private MailText createMailText() { final MailTemplateId mailTemplateId = MailTemplateId.ofRepoId(getRecord_ID()); final MailTextBuilder mailTextBuilder = mailService.newMailTextBuilder(mailTemplateId); Object record = null; if (p_AD_Table_ID > 0 && p_Record_ID >= 0) { final String tableName = tableDAO.retrieveTableName(p_AD_Table_ID); record = InterfaceWrapperHelper.create(getCtx(), tableName, p_Record_ID, Object.class, getTrxName()); if (record != null) { mailTextBuilder.recordAndUpdateBPartnerAndContact(record); }
} I_C_BPartner bpartner = null; if (p_C_BPartner_ID > 0) { bpartner = bpartnerDAO.getById(p_C_BPartner_ID); mailTextBuilder.bpartner(bpartner); } I_AD_User contact = null; if (p_AD_User_ID >= 0) { contact = userDAO.getById(UserId.ofRepoId(p_AD_User_ID)); mailTextBuilder.bpartnerContact(contact); } // // Display configuration addLog("Using @R_MailText_ID@: {}", mailTemplateId); addLog("Using @C_BPartner_ID@: {}", bpartner); addLog("Using @AD_User_ID@: {}", contact); addLog("Using @Record_ID@: {}", record); return mailTextBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\process\R_MailText_Test.java
1
请在Spring Boot框架中完成以下Java代码
public class GlobalQRCodeService { private static final AdProcessId default_qrCodeProcessId = AdProcessId.ofRepoId(584977); // hard coded process id private final IMassPrintingService massPrintingService; public GlobalQRCodeService(@NonNull final IMassPrintingService massPrintingService) {this.massPrintingService = massPrintingService;} public QRCodePDFResource createPDF(@NonNull final PrintableQRCode qrCode) { return createPDF(ImmutableList.of(qrCode), null, default_qrCodeProcessId); } public QRCodePDFResource createPDF(@NonNull final PrintableQRCode qrCode, @NonNull final AdProcessId qrCodeProcessId) { return createPDF(ImmutableList.of(qrCode), null, qrCodeProcessId); } public QRCodePDFResource createPDF(@NonNull final List<PrintableQRCode> qrCodes) { return createPDF(qrCodes, null, default_qrCodeProcessId); } public QRCodePDFResource createPDF(@NonNull final List<PrintableQRCode> qrCodes, @Nullable final PInstanceId pInstanceId, @Nullable final AdProcessId qrCodeProcessId) { return CreatePDFCommand.builder() .qrCodes(qrCodes) .pInstanceId(pInstanceId) .qrCodeProcessId(qrCodeProcessId != null ? qrCodeProcessId : default_qrCodeProcessId) .build() .execute();
} public void print(@NonNull final QRCodePDFResource pdf) { print(pdf, PrintCopies.ONE); } public void print(@NonNull final QRCodePDFResource pdf, @NonNull final PrintCopies copies) { final TableRecordReference recordRef = TableRecordReference.of(I_AD_PInstance.Table_Name, pdf.getPinstanceId().getRepoId()); final ArchiveInfo archiveInfo = new ArchiveInfo(pdf.getFilename(), recordRef); archiveInfo.setProcessId(pdf.getProcessId()); archiveInfo.setPInstanceId(pdf.getPinstanceId()); archiveInfo.setCopies(copies); massPrintingService.print(pdf, archiveInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.services\src\main\java\de\metas\global_qrcodes\service\GlobalQRCodeService.java
2
请在Spring Boot框架中完成以下Java代码
public static class Pool { /** * Maximum allowed number of threads. Doesn't have an effect if virtual threads * are enabled. */ private int size = 1; public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } } public static class Simple { /** * Set the maximum number of parallel accesses allowed. -1 indicates no * concurrency limit at all. */ private @Nullable Integer concurrencyLimit; public @Nullable Integer getConcurrencyLimit() { return this.concurrencyLimit; } public void setConcurrencyLimit(@Nullable Integer concurrencyLimit) { this.concurrencyLimit = concurrencyLimit; } } public static class Shutdown { /** * Whether the executor should wait for scheduled tasks to complete on shutdown. */ private boolean awaitTermination; /**
* Maximum time the executor should wait for remaining tasks to complete. */ private @Nullable Duration awaitTerminationPeriod; public boolean isAwaitTermination() { return this.awaitTermination; } public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; } public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingProperties.java
2
请完成以下Java代码
default Mono<Object> handleConnectionInitialization( WebSocketSessionInfo sessionInfo, Map<String, Object> connectionInitPayload) { return Mono.empty(); } /** * Handle the {@code "complete"} message that a client sends to stop a * subscription stream. The underlying {@link org.reactivestreams.Publisher} * for the subscription is automatically cancelled. This callback is for any * additional, or more centralized handling across subscriptions. * @param sessionInfo information about the underlying WebSocket session * @param subscriptionId the unique id for the subscription; correlates to the * {@link WebGraphQlRequest#getId() requestId} from the {@code "subscribe"} * message that started the subscription stream * @return {@code Mono} for the completion of handling
*/ default Mono<Void> handleCancelledSubscription(WebSocketSessionInfo sessionInfo, String subscriptionId) { return Mono.empty(); } /** * Invoked when the WebSocket session is closed, from either side. * @param sessionInfo information about the underlying WebSocket session * @param statusCode the WebSocket "close" status code * @param connectionInitPayload the payload from the {@code "connect_init"} * message received at the start of the connection */ default void handleConnectionClosed( WebSocketSessionInfo sessionInfo, int statusCode, Map<String, Object> connectionInitPayload) { } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\WebSocketGraphQlInterceptor.java
1
请完成以下Java代码
private static boolean matchesIdToken(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OidcIdToken> idToken = authorization.getToken(OidcIdToken.class); return idToken != null && idToken.getToken().getTokenValue().equals(token); } private static boolean matchesDeviceCode(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OAuth2DeviceCode> deviceCode = authorization.getToken(OAuth2DeviceCode.class); return deviceCode != null && deviceCode.getToken().getTokenValue().equals(token); } private static boolean matchesUserCode(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OAuth2UserCode> userCode = authorization.getToken(OAuth2UserCode.class); return userCode != null && userCode.getToken().getTokenValue().equals(token); } private static final class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> {
private final int maxSize; private MaxSizeHashMap(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > this.maxSize; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\InMemoryOAuth2AuthorizationService.java
1
请在Spring Boot框架中完成以下Java代码
public class LoginController { @Autowired private LoginService loginService; /** * 登录 */ @PostMapping("/auth") public JSONObject authLogin(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "username,password"); return loginService.authLogin(requestJson); } /**
* 查询当前登录用户的信息 */ @PostMapping("/getInfo") public JSONObject getInfo() { return loginService.getInfo(); } /** * 登出 */ @PostMapping("/logout") public JSONObject logout() { return loginService.logout(); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\controller\LoginController.java
2
请在Spring Boot框架中完成以下Java代码
public MSV3ServerConfig getServerConfig() { return serverConfigCache.getOrLoad(0, this::retrieveServerConfig); } private MSV3ServerConfig retrieveServerConfig() { final MSV3ServerConfigBuilder serverConfigBuilder = MSV3ServerConfig.builder(); final I_MSV3_Server serverConfigRecord = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_MSV3_Server.class) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_MSV3_Server.class); if (serverConfigRecord != null) { final int fixedQtyAvailableToPromise = serverConfigRecord.getFixedQtyAvailableToPromise(); serverConfigBuilder.fixedQtyAvailableToPromise(fixedQtyAvailableToPromise);
final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); final WarehousePickingGroupId warehousePickingGroupId = WarehousePickingGroupId.ofRepoId(serverConfigRecord.getM_Warehouse_PickingGroup_ID()); // note that the DAO method invoked by this supplier is cached serverConfigBuilder.warehousePickingGroupSupplier(() -> warehouseDAO.getWarehousePickingGroupById(warehousePickingGroupId)); } Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_MSV3_Server_Product_Category.class) .addOnlyActiveRecordsFilter() .create() .list(I_MSV3_Server_Product_Category.class) .forEach(productCategoryRecord -> serverConfigBuilder.productCategoryId(ProductCategoryId.ofRepoId(productCategoryRecord.getM_Product_Category_ID()))); return serverConfigBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3ServerConfigRepository.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("internalName", internalName) .add("elementGroups-count", elementGroupsBuilders.size()) .toString(); } public DocumentLayoutColumnDescriptor build() { final DocumentLayoutColumnDescriptor result = new DocumentLayoutColumnDescriptor(this); logger.trace("Built {} for {}", result, this); return result; } private List<DocumentLayoutElementGroupDescriptor> buildElementGroups() { return elementGroupsBuilders .stream() .map(DocumentLayoutElementGroupDescriptor.Builder::build) .filter(this::checkValid) .collect(GuavaCollectors.toImmutableList()); } private boolean checkValid(final DocumentLayoutElementGroupDescriptor elementGroup) { if(!elementGroup.hasElementLines()) { logger.trace("Skip adding {} to {} because it does not have element line", elementGroup, this); return false; } return true; } public Builder setInternalName(String internalName) {
this.internalName = internalName; return this; } public Builder addElementGroups(@NonNull final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupBuilders) { elementGroupsBuilders.addAll(elementGroupBuilders); return this; } public Builder addElementGroup(@NonNull final DocumentLayoutElementGroupDescriptor.Builder elementGroupBuilder) { elementGroupsBuilders.add(elementGroupBuilder); return this; } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementGroupsBuilders.stream().flatMap(DocumentLayoutElementGroupDescriptor.Builder::streamElementBuilders); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutColumnDescriptor.java
1
请完成以下Java代码
public Rectangle getRectangleBounds() { return new Rectangle(x, y, width, height); } public Area getEllipseAreaBounds() { Ellipse2D.Double coll = new Ellipse2D.Double(x, y, width, height); return new Area(coll); } public Ellipse2D getCircleBounds() { return new Ellipse2D.Double(x, y, 200, 200); } public Area getPolygonBounds() { for (int i = 0; i < xOffsets.length; i++) { this.xPoints[i] = x + xOffsets[i]; this.yPoints[i] = y + yOffsets[i]; } Polygon p = new Polygon(xPoints, yPoints, xOffsets.length); return new Area(p); } public boolean collidesWith(GameObject other) { int top = Math.max(y, other.y);
int bottom = Math.min(y + height, other.y + other.height); int left = Math.max(x, other.x); int right = Math.min(x + width, other.x + other.height); if (right <= left || bottom <= top) return false; for (int i = top; i < bottom; i++) { for (int j = left; j < right; j++) { int pixel1 = image.getRGB(j - x, i - y); int pixel2 = other.image.getRGB(j - other.x, i - other.y); if (((pixel1 >> 24) & 0xff) > 0 && ((pixel2 >> 24) & 0xff) > 0) { return true; } } } return false; } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imagecollision\GameObject.java
1
请完成以下Java代码
private void copyASI(final IHUPackingAware to) { final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(from.getM_AttributeSetInstance_ID()); if (asiId.isNone()) { return; } if (asiCopyMode == ASICopyMode.Clone) { final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); final AttributeSetInstanceId asiIdCopy = asiBL.copy(asiId); to.setM_AttributeSetInstance_ID(asiIdCopy.getRepoId()); } else if (asiCopyMode == ASICopyMode.CopyID) { to.setM_AttributeSetInstance_ID(asiId.getRepoId()); } else { throw new IllegalStateException("Unknown asiCopyMode: " + asiCopyMode); } } private void copyBPartner(final IHUPackingAware to) { // 08276 // do not modify the partner in the orderline if it was already set if (to.getC_BPartner_ID() <= 0 || overridePartner) { to.setC_BPartner_ID(from.getC_BPartner_ID()); } }
/** * @param overridePartner if true, the BPartner will be copied, even if "to" record already has a partner set */ public HUPackingAwareCopy overridePartner(final boolean overridePartner) { this.overridePartner = overridePartner; return this; } public HUPackingAwareCopy asiCopyMode(@NonNull final ASICopyMode asiCopyMode) { this.asiCopyMode = asiCopyMode; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\HUPackingAwareCopy.java
1
请在Spring Boot框架中完成以下Java代码
public static class AllCookieClearingLogoutConfiguration { @Bean public SecurityFilterChain filterChainAllCookieClearing(HttpSecurity http) throws Exception { http.securityMatcher("/cookies/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/cookies/cookielogout") .addLogoutHandler(new SecurityContextLogoutHandler()) .addLogoutHandler((request, response, auth) -> { for (Cookie cookie : request.getCookies()) { String cookieName = cookie.getName(); Cookie cookieToDelete = new Cookie(cookieName, null); cookieToDelete.setMaxAge(0); response.addCookie(cookieToDelete); } })); return http.build(); } } @Order(1) @Configuration
public static class ClearSiteDataHeaderLogoutConfiguration { private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS }; @Bean public SecurityFilterChain filterChainClearSiteDataHeader(HttpSecurity http) throws Exception { http.securityMatcher("/csd/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/csd/csdlogout") .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)))); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\manuallogout\SimpleSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class BPGroupDAO implements IBPGroupDAO { private static final Logger logger = LogManager.getLogger(BPGroupDAO.class); @Override public I_C_BP_Group getById(@NonNull final BPGroupId bpGroupId) { return loadOutOfTrx(bpGroupId, I_C_BP_Group.class); } @Override public I_C_BP_Group getByIdInInheritedTrx(@NonNull final BPGroupId bpGroupId) { return load(bpGroupId, I_C_BP_Group.class); } @Override public I_C_BP_Group getByBPartnerId(@NonNull final BPartnerId bpartnerId) { final I_C_BPartner bpartnerRecord = Services.get(IBPartnerDAO.class).getById(bpartnerId); final BPGroupId bpGroupId = BPGroupId.ofRepoId(bpartnerRecord.getC_BP_Group_ID()); return getById(bpGroupId); } @Override public BPGroupId getBPGroupByBPartnerId(@NonNull final BPartnerId bpartnerId) { return BPGroupId.ofRepoId(getByBPartnerId(bpartnerId).getC_BP_Group_ID()); } @Override @Nullable public I_C_BP_Group getDefaultByClientOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { final BPGroupId bpGroupId = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_BP_Group.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_Group.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId()) .addInArrayFilter(I_C_BP_Group.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId(), OrgId.ANY) .addEqualsFilter(I_C_BP_Group.COLUMNNAME_IsDefault, true) .orderByDescending(I_C_BP_Group.COLUMNNAME_AD_Org_ID) .create() .firstId(BPGroupId::ofRepoIdOrNull); if (bpGroupId == null) { logger.warn("No default BP group found for {}", clientAndOrgId); return null; } return getById(bpGroupId); } @Override public BPartnerNameAndGreetingStrategyId getBPartnerNameAndGreetingStrategyId(@NonNull final BPGroupId bpGroupId) { final I_C_BP_Group bpGroup = getById(bpGroupId); return StringUtils.trimBlankToOptional(bpGroup.getBPNameAndGreetingStrategy()) .map(BPartnerNameAndGreetingStrategyId::ofString) .orElse(DoNothingBPartnerNameAndGreetingStrategy.ID); } @Override public void save(@NonNull final I_C_BP_Group bpGroup) { InterfaceWrapperHelper.saveRecord(bpGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPGroupDAO.java
2
请完成以下Java代码
public HistoricPlanItemInstanceEntity create(PlanItemInstance planItemInstance) { return dataManager.create(planItemInstance); } @Override public HistoricPlanItemInstanceQuery createHistoricPlanItemInstanceQuery() { return new HistoricPlanItemInstanceQueryImpl(engineConfiguration.getCommandExecutor()); } @Override public List<HistoricPlanItemInstance> findByCaseDefinitionId(String caseDefinitionId) { return dataManager.findByCaseDefinitionId(caseDefinitionId); } @Override public List<HistoricPlanItemInstance> findByCriteria(HistoricPlanItemInstanceQuery query) { return dataManager.findByCriteria((HistoricPlanItemInstanceQueryImpl) query); } @Override public long countByCriteria(HistoricPlanItemInstanceQuery query) {
return dataManager.countByCriteria((HistoricPlanItemInstanceQueryImpl) query); } @Override public void bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(Collection<String> caseInstanceIds) { dataManager.bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(caseInstanceIds); } @Override public void deleteHistoricPlanItemInstancesForNonExistingCaseInstances() { dataManager.deleteHistoricPlanItemInstancesForNonExistingCaseInstances(); } @Override public List<HistoricPlanItemInstance> findWithVariablesByCriteria(HistoricPlanItemInstanceQueryImpl historicPlanItemInstanceQuery) { return dataManager.findWithVariablesByCriteria(historicPlanItemInstanceQuery); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricPlanItemInstanceEntityManagerImpl.java
1
请完成以下Java代码
protected void internalDbSchemaCreate() { executeMandatorySchemaResource("create", schemaComponent); } @Override public void schemaDrop() { try { executeMandatorySchemaResource("drop", schemaComponent); } catch (Exception e) { logger.info("Error dropping {} tables", schemaComponent, e); } } @Override public String schemaUpdate() { return schemaUpdate(null); } @Override public String schemaUpdate(String engineDbVersion) { String feedback = null; if (isUpdateNeeded()) { String dbVersion = getSchemaVersion(); String compareWithVersion = null; if (dbVersion == null) { compareWithVersion = "6.1.2.0"; // last version before services were separated. Start upgrading from this point. } else { compareWithVersion = dbVersion; } int matchingVersionIndex = FlowableVersions.getFlowableVersionIndexForDbVersion(compareWithVersion); boolean isUpgradeNeeded = (matchingVersionIndex != (FlowableVersions.FLOWABLE_VERSIONS.size() - 1)); if (isUpgradeNeeded) { dbSchemaUpgrade(schemaComponent, matchingVersionIndex, engineDbVersion); } feedback = "upgraded from " + compareWithVersion + " to " + FlowableVersions.CURRENT_VERSION; } else { schemaCreate(); } return feedback;
} @Override public void schemaCheckVersion() { String dbVersion = getSchemaVersion(); if (!FlowableVersions.CURRENT_VERSION.equals(dbVersion)) { throw new FlowableWrongDbException(FlowableVersions.CURRENT_VERSION, dbVersion); } } protected boolean isUpdateNeeded() { return isTablePresent(table); } protected String getSchemaVersion() { if (schemaVersionProperty == null) { throw new FlowableException("Schema version property is not set"); } String dbVersion = getProperty(schemaVersionProperty); if (dbVersion == null) { return getUpgradeStartVersion(); } return dbVersion; } protected String getUpgradeStartVersion() { return "6.1.2.0"; // last version before most services were separated. Start upgrading from this point. } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\ServiceSqlScriptBasedDbSchemaManager.java
1
请完成以下Java代码
public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setShipper_BPartner_ID (final int Shipper_BPartner_ID) { if (Shipper_BPartner_ID < 1) set_Value (COLUMNNAME_Shipper_BPartner_ID, null); else set_Value (COLUMNNAME_Shipper_BPartner_ID, Shipper_BPartner_ID); } @Override public int getShipper_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_BPartner_ID); } @Override public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID()
{ return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID() { return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public class MoveTimerToExecutableJobCmd implements Command<JobEntity>, Serializable { private static final long serialVersionUID = 1L; private static Logger log = LoggerFactory.getLogger(MoveTimerToExecutableJobCmd.class); protected String jobId; public MoveTimerToExecutableJobCmd(String jobId) { this.jobId = jobId; } public JobEntity execute(CommandContext commandContext) { if (jobId == null) { throw new ActivitiIllegalArgumentException("jobId and job is null"); }
TimerJobEntity timerJob = commandContext.getTimerJobEntityManager().findById(jobId); if (timerJob == null) { throw new JobNotFoundException(jobId); } if (log.isDebugEnabled()) { log.debug("Executing timer job {}", timerJob.getId()); } return commandContext.getJobManager().moveTimerJobToExecutableJob(timerJob); } public String getJobId() { return jobId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\MoveTimerToExecutableJobCmd.java
1
请在Spring Boot框架中完成以下Java代码
static class GeodeLocatorManagerConfiguration { } // end::locator-manager-configuration[] // tag::gateway-configuration[] // tag::gateway-receiver-configuration[] @Configuration @Profile("gateway-receiver") static class GeodeGatewayReceiverConfiguration { @Bean GatewayReceiverFactoryBean gatewayReceiver(Cache cache) { GatewayReceiverFactoryBean gatewayReceiver = new GatewayReceiverFactoryBean(cache); gatewayReceiver.setHostnameForSenders(GATEWAY_RECEIVER_HOSTNAME_FOR_SENDERS); gatewayReceiver.setStartPort(GATEWAY_RECEIVER_START_PORT); gatewayReceiver.setEndPort(GATEWAY_RECEIVER_END_PORT); return gatewayReceiver; } } // end::gateway-receiver-configuration[] // tag::gateway-sender-configuration[] @Configuration @Profile("gateway-sender") static class GeodeGatewaySenderConfiguration { @Bean GatewaySenderFactoryBean customersByNameGatewaySender(Cache cache, @Value("${geode.distributed-system.remote.id:1}") int remoteDistributedSystemId) {
GatewaySenderFactoryBean gatewaySender = new GatewaySenderFactoryBean(cache); gatewaySender.setPersistent(PERSISTENT); gatewaySender.setRemoteDistributedSystemId(remoteDistributedSystemId); return gatewaySender; } @Bean RegionConfigurer customersByNameConfigurer(GatewaySender gatewaySender) { return new RegionConfigurer() { @Override public void configure(String beanName, PeerRegionFactoryBean<?, ?> regionBean) { if (CUSTOMERS_BY_NAME_REGION.equals(beanName)) { regionBean.setGatewaySenders(ArrayUtils.asArray(gatewaySender)); } } }; } } // end::gateway-sender-configuration[] // end::gateway-configuration[] } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\server\BootGeodeMultiSiteCachingServerApplication.java
2
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = -1205226416664488559L; private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() {
return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\SpringBootLearning-master\sharding-jdbc-example\sharding-jdbc-master-slave\src\main\java\com\forezp\shardingjdbcmasterslave\entity\User.java
1
请在Spring Boot框架中完成以下Java代码
public class DemoService { private Logger logger = LoggerFactory.getLogger(getClass()); // public void task01() { // long now = System.currentTimeMillis(); // logger.info("[task01][开始执行]"); // // execute01(); // execute02(); // // logger.info("[task01][结束执行,消耗时长 {} 毫秒]", System.currentTimeMillis() - now); // } // // public void task02() { // long now = System.currentTimeMillis(); // logger.info("[task02][开始执行]"); // // execute01Async(); // execute02Async(); // // logger.info("[task02][结束执行,消耗时长 {} 毫秒]", System.currentTimeMillis() - now); // } // // public void task03() throws ExecutionException, InterruptedException { // long now = System.currentTimeMillis(); // logger.info("[task03][开始执行]"); // // // 执行任务 // Future<Integer> execute01Result = execute01AsyncWithFuture(); // Future<Integer> execute02Result = execute02AsyncWithFuture(); // // 阻塞等待结果 // execute01Result.get(); // execute02Result.get(); // // logger.info("[task03][结束执行,消耗时长 {} 毫秒]", System.currentTimeMillis() - now); // } @Async public Integer execute01Async() { return this.execute01(); } @Async public Integer execute02Async() { return this.execute02(); } @Async public Future<Integer> execute01AsyncWithFuture() { return AsyncResult.forValue(this.execute01()); } @Async
public Future<Integer> execute02AsyncWithFuture() { return AsyncResult.forValue(this.execute02()); } @Async public ListenableFuture<Integer> execute01AsyncWithListenableFuture() { try { return AsyncResult.forValue(this.execute02()); } catch (Throwable ex) { return AsyncResult.forExecutionException(ex); } } public Integer execute01() { logger.info("[execute01]"); sleep(10); return 1; } public Integer execute02() { logger.info("[execute02]"); sleep(5); return 2; } private static void sleep(int seconds) { try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Async public Integer zhaoDaoNvPengYou(Integer a, Integer b) { throw new RuntimeException("程序员不需要女朋友"); } }
repos\SpringBoot-Labs-master\lab-29\lab-29-async-demo\src\main\java\cn\iocoder\springboot\lab29\asynctask\service\DemoService.java
2
请完成以下Java代码
public void setEMail_Cc (final @Nullable java.lang.String EMail_Cc) { set_ValueNoCheck (COLUMNNAME_EMail_Cc, EMail_Cc); } @Override public java.lang.String getEMail_Cc() { return get_ValueAsString(COLUMNNAME_EMail_Cc); } @Override public void setEMail_From (final @Nullable java.lang.String EMail_From) { set_ValueNoCheck (COLUMNNAME_EMail_From, EMail_From); } @Override public java.lang.String getEMail_From() { return get_ValueAsString(COLUMNNAME_EMail_From); } @Override public void setEMail_To (final @Nullable java.lang.String EMail_To) { set_ValueNoCheck (COLUMNNAME_EMail_To, EMail_To); } @Override public java.lang.String getEMail_To() { return get_ValueAsString(COLUMNNAME_EMail_To); } @Override public void setPrinterName (final @Nullable java.lang.String PrinterName) { set_ValueNoCheck (COLUMNNAME_PrinterName, PrinterName); } @Override public java.lang.String getPrinterName() { return get_ValueAsString(COLUMNNAME_PrinterName); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } /** * Status AD_Reference_ID=542015 * Reference name: OutboundLogLineStatus */ public static final int STATUS_AD_Reference_ID=542015; /** Print_Success = Print_Success */ public static final String STATUS_Print_Success = "Print_Success"; /** Print_Failure = Print_Failure */ public static final String STATUS_Print_Failure = "Print_Failure"; /** Email_Success = Email_Success */ public static final String STATUS_Email_Success = "Email_Success"; /** Email_Failure = Email_Failure */ public static final String STATUS_Email_Failure = "Email_Failure"; @Override public void setStatus (final @Nullable java.lang.String Status) { set_ValueNoCheck (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } @Override public void setStoreURI (final @Nullable java.lang.String StoreURI) { set_Value (COLUMNNAME_StoreURI, StoreURI); } @Override public java.lang.String getStoreURI() { return get_ValueAsString(COLUMNNAME_StoreURI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Log_Line.java
1
请完成以下Java代码
public void onBeforeDelete(BeforeDeleteEvent<Object> event) { LOGGER.info("onBeforeDelete: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterDelete(org.springframework.data.cassandra.core.mapping.event.AfterDeleteEvent) */ @Override public void onAfterDelete(AfterDeleteEvent<Object> event) { LOGGER.info("onAfterDelete: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterLoad(org.springframework.data.cassandra.core.mapping.event.AfterLoadEvent)
*/ @Override public void onAfterLoad(AfterLoadEvent<Object> event) { LOGGER.info("onAfterLoad: {}", event.getSource()); } /* * (non-Javadoc) * @see org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener#onAfterConvert(org.springframework.data.cassandra.core.mapping.event.AfterConvertEvent) */ @Override public void onAfterConvert(AfterConvertEvent<Object> event) { LOGGER.info("onAfterConvert: {}", event.getSource()); } }
repos\spring-data-examples-main\cassandra\example\src\main\java\example\springdata\cassandra\events\LoggingEventListener.java
1
请完成以下Java代码
public void setC_Invoice_Candidate_Assignment_ID (int C_Invoice_Candidate_Assignment_ID) { if (C_Invoice_Candidate_Assignment_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Assignment_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Assignment_ID, Integer.valueOf(C_Invoice_Candidate_Assignment_ID)); } /** Get C_Invoice_Candidate_Assignment. @return C_Invoice_Candidate_Assignment */ @Override public int getC_Invoice_Candidate_Assignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Assignment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) { if (C_Invoice_Candidate_Term_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Zugeordnete Menge wird in Summe einbez.. @param IsAssignedQuantityIncludedInSum Zugeordnete Menge wird in Summe einbez. */ @Override public void setIsAssignedQuantityIncludedInSum (boolean IsAssignedQuantityIncludedInSum) { set_Value (COLUMNNAME_IsAssignedQuantityIncludedInSum, Boolean.valueOf(IsAssignedQuantityIncludedInSum)); } /** Get Zugeordnete Menge wird in Summe einbez.. @return Zugeordnete Menge wird in Summe einbez. */ @Override public boolean isAssignedQuantityIncludedInSum () { Object oo = get_Value(COLUMNNAME_IsAssignedQuantityIncludedInSum); 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.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment.java
1
请完成以下Java代码
public String getLocale() { return locale; } public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(ProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); } public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_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 setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() {
return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Department.java
1
请完成以下Java代码
public int getAD_BusinessRule_Precondition_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Precondition_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 org.compiere.model.I_AD_Val_Rule getPrecondition_Rule() { return get_ValueAsPO(COLUMNNAME_Precondition_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setPrecondition_Rule(final org.compiere.model.I_AD_Val_Rule Precondition_Rule) { set_ValueFromPO(COLUMNNAME_Precondition_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Precondition_Rule); } @Override public void setPrecondition_Rule_ID (final int Precondition_Rule_ID) { if (Precondition_Rule_ID < 1) set_Value (COLUMNNAME_Precondition_Rule_ID, null); else set_Value (COLUMNNAME_Precondition_Rule_ID, Precondition_Rule_ID); } @Override public int getPrecondition_Rule_ID()
{ return get_ValueAsInt(COLUMNNAME_Precondition_Rule_ID); } @Override public void setPreconditionSQL (final @Nullable java.lang.String PreconditionSQL) { set_Value (COLUMNNAME_PreconditionSQL, PreconditionSQL); } @Override public java.lang.String getPreconditionSQL() { return get_ValueAsString(COLUMNNAME_PreconditionSQL); } /** * PreconditionType AD_Reference_ID=541912 * Reference name: PreconditionType */ public static final int PRECONDITIONTYPE_AD_Reference_ID=541912; /** SQL = S */ public static final String PRECONDITIONTYPE_SQL = "S"; /** Validation Rule = R */ public static final String PRECONDITIONTYPE_ValidationRule = "R"; @Override public void setPreconditionType (final java.lang.String PreconditionType) { set_Value (COLUMNNAME_PreconditionType, PreconditionType); } @Override public java.lang.String getPreconditionType() { return get_ValueAsString(COLUMNNAME_PreconditionType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Precondition.java
1
请完成以下Java代码
public void assertNotStarted() { Check.assume(status == DDOrderMoveScheduleStatus.NOT_STARTED, "Expected status NOT_STARTED but was {}", status); } public void assertPickedFrom() { if (!isPickedFrom()) {throw new AdempiereException("Pick from required first");} } public void assertInTransit() { assertNotDroppedTo(); assertPickedFrom(); } public void removePickedHUs() { this.pickedHUs = null; this.qtyNotPickedReason = null; updateStatus(); } public void markAsPickedFrom( @Nullable final QtyRejectedReasonCode qtyNotPickedReason, @NonNull final DDOrderMoveSchedulePickedHUs pickedHUs) { assertNotPickedFrom(); final Quantity qtyPicked = pickedHUs.getQtyPicked(); Quantity.assertSameUOM(this.qtyToPick, qtyPicked); if (qtyPicked.signum() <= 0) { throw new AdempiereException("QtyPicked must be greater than zero"); } if (!this.qtyToPick.qtyAndUomCompareToEquals(qtyPicked)) { if (qtyNotPickedReason == null) { throw new AdempiereException("Reason must be provided when not picking the whole scheduled qty"); } this.qtyNotPickedReason = qtyNotPickedReason; } else { this.qtyNotPickedReason = null; } this.pickedHUs = pickedHUs; updateStatus(); } public boolean isDropTo() { return pickedHUs != null && pickedHUs.isDroppedTo(); } public void assertNotDroppedTo() { if (isDropTo()) { throw new AdempiereException("Already Dropped To"); } } public void markAsDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId) { assertInTransit();
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this); pickedHUs.setDroppedTo(dropToLocatorId, dropToMovementId); updateStatus(); } private void updateStatus() { this.status = computeStatus(); } private DDOrderMoveScheduleStatus computeStatus() { if (isDropTo()) { return DDOrderMoveScheduleStatus.COMPLETED; } else if (isPickedFrom()) { return DDOrderMoveScheduleStatus.IN_PROGRESS; } else { return DDOrderMoveScheduleStatus.NOT_STARTED; } } @NonNull public ExplainedOptional<LocatorId> getInTransitLocatorId() { if (pickedHUs == null) { return ExplainedOptional.emptyBecause("Schedule is not picked yet"); } return pickedHUs.getInTransitLocatorId(); } @NonNull public ImmutableSet<HuId> getPickedHUIds() { final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this); return pickedHUs.getActualHUIdsPicked(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java
1
请完成以下Java代码
public Builder entityId(EntityId entityId) { this.entityId = entityId; return this; } public Builder scope(AttributeScope scope) { this.scope = scope; return this; } @Deprecated public Builder scope(String scope) { try { this.scope = AttributeScope.valueOf(scope); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid attribute scope '" + scope + "'"); } return this; } public Builder keys(List<String> keys) { this.keys = keys; return this; } public Builder notifyDevice(boolean notifyDevice) { this.notifyDevice = notifyDevice; return this; } public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = previousCalculatedFieldIds; return this; } public Builder tbMsgId(UUID tbMsgId) { this.tbMsgId = tbMsgId; return this; }
public Builder tbMsgType(TbMsgType tbMsgType) { this.tbMsgType = tbMsgType; return this; } public Builder callback(FutureCallback<Void> callback) { this.callback = callback; return this; } public Builder future(SettableFuture<Void> future) { return callback(new FutureCallback<>() { @Override public void onSuccess(Void result) { future.set(result); } @Override public void onFailure(Throwable t) { future.setException(t); } }); } public AttributesDeleteRequest build() { return new AttributesDeleteRequest( tenantId, entityId, scope, keys, notifyDevice, previousCalculatedFieldIds, tbMsgId, tbMsgType, requireNonNullElse(callback, NoOpFutureCallback.instance()) ); } } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\AttributesDeleteRequest.java
1
请完成以下Java代码
public void numberingTagTemplate() { List<String> list = new ArrayList<String>(); list.add("Plug-in grammar"); list.add("Supports word text, pictures, table..."); list.add("Not just templates"); NumberingBuilder builder = Numberings.of(NumberingFormat.DECIMAL); for (String s : list) { builder.addItem(s); } NumberingRenderData renderData = builder.create(); this.templateData.put("list", renderData); } public void sectionTemplate() { Map<String, Object> students = new LinkedHashMap<String, Object>(); students.put("name", "John"); students.put("name", "Mary"); students.put("name", "Disarray"); this.templateData.put("students", students); } public void nestingTemplate() { List<Address> subData = new ArrayList<>(); subData.add(new Address("Florida,USA")); subData.add(new Address("Texas,USA"));
this.templateData.put("nested", Includes.ofStream(WordDocumentFromTemplate.class.getClassLoader() .getResourceAsStream("nested.docx")) .setRenderModel(subData) .create()); } public void refrenceTags() { ChartMultiSeriesRenderData chart = Charts.ofMultiSeries("ChartTitle", new String[] { "Title", "English" }) .addSeries("countries", new Double[] { 15.0, 6.0 }) .addSeries("speakers", new Double[] { 223.0, 119.0 }) .create(); this.templateData.put("barChart", chart); } public void usingPlugins() { this.templateData.put("sample", "custom-plugin"); } }
repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\wordtemplate\WordDocumentFromTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public InternalTaskAssignmentManager getInternalTaskAssignmentManager() { return internalTaskAssignmentManager; } public void setInternalTaskAssignmentManager(InternalTaskAssignmentManager internalTaskAssignmentManager) { this.internalTaskAssignmentManager = internalTaskAssignmentManager; } public boolean isEnableTaskRelationshipCounts() { return enableTaskRelationshipCounts; } public TaskServiceConfiguration setEnableTaskRelationshipCounts(boolean enableTaskRelationshipCounts) { this.enableTaskRelationshipCounts = enableTaskRelationshipCounts; return this; } public boolean isEnableLocalization() { return enableLocalization; } public TaskServiceConfiguration setEnableLocalization(boolean enableLocalization) { this.enableLocalization = enableLocalization; return this; } public TaskQueryInterceptor getTaskQueryInterceptor() { return taskQueryInterceptor; } public TaskServiceConfiguration setTaskQueryInterceptor(TaskQueryInterceptor taskQueryInterceptor) { this.taskQueryInterceptor = taskQueryInterceptor; return this; } public HistoricTaskQueryInterceptor getHistoricTaskQueryInterceptor() { return historicTaskQueryInterceptor; } public TaskServiceConfiguration setHistoricTaskQueryInterceptor(HistoricTaskQueryInterceptor historicTaskQueryInterceptor) { this.historicTaskQueryInterceptor = historicTaskQueryInterceptor; return this; } public boolean isEnableHistoricTaskLogging() { return enableHistoricTaskLogging; }
public TaskServiceConfiguration setEnableHistoricTaskLogging(boolean enableHistoricTaskLogging) { this.enableHistoricTaskLogging = enableHistoricTaskLogging; return this; } @Override public TaskServiceConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) { this.enableEventDispatcher = enableEventDispatcher; return this; } @Override public TaskServiceConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; return this; } @Override public TaskServiceConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { this.eventListeners = eventListeners; return this; } @Override public TaskServiceConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } public TaskPostProcessor getTaskPostProcessor() { return taskPostProcessor; } public TaskServiceConfiguration setTaskPostProcessor(TaskPostProcessor processor) { this.taskPostProcessor = processor; return this; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\TaskServiceConfiguration.java
2
请完成以下Java代码
public void setPMM_Product_ID (int PMM_Product_ID) { if (PMM_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_PMM_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_PMM_Product_ID, Integer.valueOf(PMM_Product_ID)); } /** Get Lieferprodukt. @return Lieferprodukt */ @Override public int getPMM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Produktname. @param ProductName Name des Produktes */ @Override public void setProductName (java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } /** Get Produktname. @return Name des Produktes */ @Override public java.lang.String getProductName () { return (java.lang.String)get_Value(COLUMNNAME_ProductName); } /** Set Produktschlüssel. @param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { throw new IllegalArgumentException ("ProductValue is virtual column"); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Product.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** RecurringType AD_Reference_ID=282 */ public static final int RECURRINGTYPE_AD_Reference_ID=282; /** Invoice = I */ public static final String RECURRINGTYPE_Invoice = "I"; /** Order = O */ public static final String RECURRINGTYPE_Order = "O"; /** GL Journal = G */ public static final String RECURRINGTYPE_GLJournal = "G"; /** Project = J */ public static final String RECURRINGTYPE_Project = "J"; /** Set Recurring Type. @param RecurringType Type of Recurring Document */ public void setRecurringType (String RecurringType) { set_Value (COLUMNNAME_RecurringType, RecurringType); } /** Get Recurring Type. @return Type of Recurring Document */ public String getRecurringType () { return (String)get_Value(COLUMNNAME_RecurringType); } /** Set Maximum Runs.
@param RunsMax Number of recurring runs */ public void setRunsMax (int RunsMax) { set_Value (COLUMNNAME_RunsMax, Integer.valueOf(RunsMax)); } /** Get Maximum Runs. @return Number of recurring runs */ public int getRunsMax () { Integer ii = (Integer)get_Value(COLUMNNAME_RunsMax); if (ii == null) return 0; return ii.intValue(); } /** Set Remaining Runs. @param RunsRemaining Number of recurring runs remaining */ public void setRunsRemaining (int RunsRemaining) { set_ValueNoCheck (COLUMNNAME_RunsRemaining, Integer.valueOf(RunsRemaining)); } /** Get Remaining Runs. @return Number of recurring runs remaining */ public int getRunsRemaining () { Integer ii = (Integer)get_Value(COLUMNNAME_RunsRemaining); 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_Recurring.java
1
请完成以下Java代码
public class UpdateInvalidShipmentSchedulesWorkpackageProcessorScheduler extends WorkpackagesOnCommitSchedulerTemplate<ShipmentSchedulesUpdateSchedulerRequest> implements IShipmentSchedulesUpdateScheduler { public UpdateInvalidShipmentSchedulesWorkpackageProcessorScheduler(final boolean createOneWorkpackagePerAsyncBatch) { super(UpdateInvalidShipmentSchedulesWorkpackageProcessor.class); super.setCreateOneWorkpackagePerAsyncBatch(createOneWorkpackagePerAsyncBatch); } @Override protected Properties extractCtxFromItem(@NonNull final ShipmentSchedulesUpdateSchedulerRequest item) { return item.getCtx(); } @Override protected String extractTrxNameFromItem(@NonNull final ShipmentSchedulesUpdateSchedulerRequest item) { return item.getTrxName(); }
@Override protected Object extractModelToEnqueueFromItem(final Collector collector, final ShipmentSchedulesUpdateSchedulerRequest item) { return null; // there is no actual model to be collected } @Override protected boolean isEnqueueWorkpackageWhenNoModelsEnqueued() { return true; } @Override public Optional<AsyncBatchId> extractAsyncBatchFromItem(@NonNull final Collector collector, @NonNull final ShipmentSchedulesUpdateSchedulerRequest request) { return Optional.ofNullable(request.getAsyncBatchId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\async\UpdateInvalidShipmentSchedulesWorkpackageProcessorScheduler.java
1
请在Spring Boot框架中完成以下Java代码
public String saveUser(@Valid @BeanParam User user) { if (bindingResult.isFailed()) { models.put("errors", bindingResult.getAllErrors()); return "user.jsp"; } String id = UUID.randomUUID().toString(); user.setId(id); users.add(user); return "redirect:users/success"; } /** * Handles a redirect view * @return The view name */ @GET @Controller @Path("success") public String saveUserSuccess() {
return "success.jsp"; } /** * The REST API that returns all the user details in the JSON format * @return The list of users that are saved. The List<User> is converted into Json Array. * If no user is present a empty array is returned */ @GET @Produces(MediaType.APPLICATION_JSON) public List<User> getUsers() { return users; } }
repos\tutorials-master\web-modules\jakarta-ee\src\main\java\com\baeldung\eclipse\krazo\UserController.java
2
请完成以下Java代码
protected List<DmnDecision> getDecisionsFromModel(Case caseModel, CaseDefinition caseDefinition) { Set<String> decisionKeys = new HashSet<>(); List<DmnDecision> decisions = new ArrayList<>(); List<DecisionTask> decisionTasks = caseModel.getPlanModel().findPlanItemDefinitionsOfType(DecisionTask.class, true); for (DecisionTask decisionTask : decisionTasks) { if (decisionTask.getFieldExtensions() != null && decisionTask.getFieldExtensions().size() > 0) { for (FieldExtension fieldExtension : decisionTask.getFieldExtensions()) { if ("decisionTableReferenceKey".equals(fieldExtension.getFieldName())) { String decisionReferenceKey = fieldExtension.getStringValue(); if (!decisionKeys.contains(decisionReferenceKey)) { addDecisionToCollection(decisions, decisionReferenceKey, caseDefinition); decisionKeys.add(decisionReferenceKey); } break; } } } } return decisions; } protected void addDecisionToCollection(List<DmnDecision> decisions, String decisionKey, CaseDefinition caseDefinition) { DmnDecisionQuery definitionQuery = dmnRepositoryService.createDecisionQuery().decisionKey(decisionKey); CmmnDeployment deployment = CommandContextUtil.getCmmnDeploymentEntityManager().findById(caseDefinition.getDeploymentId()); if (deployment.getParentDeploymentId() != null) { List<DmnDeployment> dmnDeployments = dmnRepositoryService.createDeploymentQuery().parentDeploymentId(deployment.getParentDeploymentId()).list(); if (dmnDeployments != null && dmnDeployments.size() > 0) { definitionQuery.deploymentId(dmnDeployments.get(0).getId());
} else { definitionQuery.latestVersion(); } } else { definitionQuery.latestVersion(); } DmnDecision decision = definitionQuery.singleResult(); if (decision != null) { decisions.add(decision); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetDecisionsForCaseDefinitionCmd.java
1
请完成以下Java代码
public Collection<Class<? extends SupplyRequiredEvent>> getHandledEventType() { return ImmutableList.of(SupplyRequiredEvent.class); } @Override public void handleEvent(@NonNull final SupplyRequiredEvent event) { handleSupplyRequiredEvent(event.getSupplyRequiredDescriptor()); } private void handleSupplyRequiredEvent(@NonNull final SupplyRequiredDescriptor descriptor) { final ArrayList<MaterialEvent> events = new ArrayList<>(); final MaterialPlanningContext context = helper.createContextOrNull(descriptor); if (context != null) { for (final SupplyRequiredAdvisor advisor : supplyRequiredAdvisors)
{ events.addAll(advisor.createAdvisedEvents(descriptor, context)); } } if (events.isEmpty()) { final NoSupplyAdviceEvent noSupplyAdviceEvent = NoSupplyAdviceEvent.of(descriptor.withNewEventId()); Loggables.addLog("No advice events were created. Firing {}", noSupplyAdviceEvent); postMaterialEventService.enqueueEventNow(noSupplyAdviceEvent); } else { events.forEach(postMaterialEventService::enqueueEventNow); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandler.java
1
请完成以下Java代码
final class CompositeDocumentLocationAdapterFactory { private final ImmutableList<DocumentLocationAdapterFactory> factories; public CompositeDocumentLocationAdapterFactory(@NonNull final List<DocumentLocationAdapterFactory> factories) { this.factories = ImmutableList.copyOf(factories); } public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(final Object record) { for (final DocumentLocationAdapterFactory factory : factories) { final Optional<IDocumentLocationAdapter> adapter = factory.getDocumentLocationAdapterIfHandled(record); if (adapter.isPresent()) { return adapter; } } return Optional.empty(); } public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record) { for (final DocumentLocationAdapterFactory factory : factories) { final Optional<IDocumentBillLocationAdapter> adapter = factory.getDocumentBillLocationAdapterIfHandled(record); if (adapter.isPresent()) { return adapter; } } return Optional.empty(); } public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record) { for (final DocumentLocationAdapterFactory factory : factories) { final Optional<IDocumentDeliveryLocationAdapter> adapter = factory.getDocumentDeliveryLocationAdapter(record);
if (adapter.isPresent()) { return adapter; } } return Optional.empty(); } public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record) { for (final DocumentLocationAdapterFactory factory : factories) { final Optional<IDocumentHandOverLocationAdapter> adapter = factory.getDocumentHandOverLocationAdapter(record); if (adapter.isPresent()) { return adapter; } } return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\adapter\CompositeDocumentLocationAdapterFactory.java
1
请完成以下Java代码
public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) @ResponseBody public ApiResponse handlerException(Exception e) { if (e instanceof NoHandlerFoundException) { log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod()); return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND); } else if (e instanceof HttpRequestMethodNotSupportedException) { log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods())); return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD); } else if (e instanceof MethodArgumentNotValidException) { log.error("【全局异常拦截】MethodArgumentNotValidException", e); return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().get(0).getDefaultMessage(), null); } else if (e instanceof ConstraintViolationException) { log.error("【全局异常拦截】ConstraintViolationException", e); return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations()).getMessage(), null); } else if (e instanceof MethodArgumentTypeMismatchException) { log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage()); return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
} else if (e instanceof HttpMessageNotReadableException) { log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage()); return ApiResponse.ofStatus(Status.PARAM_NOT_NULL); } else if (e instanceof BadCredentialsException) { log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage()); return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR); } else if (e instanceof DisabledException) { log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage()); return ApiResponse.ofStatus(Status.USER_DISABLED); } else if (e instanceof BaseException) { log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage()); return ApiResponse.ofException((BaseException) e); } log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage()); return ApiResponse.ofStatus(Status.ERROR); } }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\exception\handler\GlobalExceptionHandler.java
1
请完成以下Java代码
class PostgresR2dbcDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<R2dbcConnectionDetails> { PostgresR2dbcDockerComposeConnectionDetailsFactory() { super("postgres", "io.r2dbc.spi.ConnectionFactoryOptions"); } @Override protected R2dbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new PostgresDbR2dbcDockerComposeConnectionDetails(source.getRunningService(), source.getEnvironment()); } /** * {@link R2dbcConnectionDetails} backed by a {@code postgres} {@link RunningService}. */ static class PostgresDbR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements R2dbcConnectionDetails { private static final Option<String> APPLICATION_NAME = Option.valueOf("applicationName"); private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder( "postgresql", 5432); private final ConnectionFactoryOptions connectionFactoryOptions; PostgresDbR2dbcDockerComposeConnectionDetails(RunningService service, Environment environment) { super(service); this.connectionFactoryOptions = getConnectionFactoryOptions(service, environment); }
@Override public ConnectionFactoryOptions getConnectionFactoryOptions() { return this.connectionFactoryOptions; } private static ConnectionFactoryOptions getConnectionFactoryOptions(RunningService service, Environment environment) { PostgresEnvironment env = new PostgresEnvironment(service.env()); ConnectionFactoryOptions connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, env.getDatabase(), env.getUsername(), env.getPassword()); return addApplicationNameIfNecessary(connectionFactoryOptions, environment); } private static ConnectionFactoryOptions addApplicationNameIfNecessary( ConnectionFactoryOptions connectionFactoryOptions, Environment environment) { if (connectionFactoryOptions.hasOption(APPLICATION_NAME)) { return connectionFactoryOptions; } String applicationName = environment.getProperty("spring.application.name"); if (!StringUtils.hasText(applicationName)) { return connectionFactoryOptions; } return connectionFactoryOptions.mutate().option(APPLICATION_NAME, applicationName).build(); } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\PostgresR2dbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public class SetLocalVariableAsyncCmd extends AbstractSetVariableAsyncCmd implements Command<Void> { protected String planItemInstanceId; protected String variableName; protected Object variableValue; public SetLocalVariableAsyncCmd(String planItemInstanceId, String variableName, Object variableValue) { this.planItemInstanceId = planItemInstanceId; this.variableName = variableName; this.variableValue = variableValue; } @Override public Void execute(CommandContext commandContext) { if (planItemInstanceId == null) { throw new FlowableIllegalArgumentException("planItemInstanceId is null"); }
if (variableName == null) { throw new FlowableIllegalArgumentException("variable name is null"); } CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); PlanItemInstanceEntity planItemInstanceEntity = cmmnEngineConfiguration.getPlanItemInstanceEntityManager().findById(planItemInstanceId); if (planItemInstanceEntity == null) { throw new FlowableObjectNotFoundException("No plan item instance found for id " + planItemInstanceId, PlanItemInstanceEntity.class); } addVariable(true, planItemInstanceEntity.getCaseInstanceId(), planItemInstanceEntity.getId(), variableName, variableValue, planItemInstanceEntity.getTenantId(), cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableService()); createSetAsyncVariablesJob(planItemInstanceEntity, cmmnEngineConfiguration); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SetLocalVariableAsyncCmd.java
1
请完成以下Java代码
public class StartupEndpoint { private final BufferingApplicationStartup applicationStartup; /** * Creates a new {@code StartupEndpoint} that will describe the timeline of buffered * application startup events. * @param applicationStartup the application startup */ public StartupEndpoint(BufferingApplicationStartup applicationStartup) { this.applicationStartup = applicationStartup; } @ReadOperation public StartupDescriptor startupSnapshot() { StartupTimeline startupTimeline = this.applicationStartup.getBufferedTimeline(); return new StartupDescriptor(startupTimeline); } @WriteOperation public StartupDescriptor startup() { StartupTimeline startupTimeline = this.applicationStartup.drainBufferedTimeline(); return new StartupDescriptor(startupTimeline); } /** * Description of an application startup. */ public static final class StartupDescriptor implements OperationResponseBody { private final String springBootVersion; private final StartupTimeline timeline; private StartupDescriptor(StartupTimeline timeline) { this.timeline = timeline; this.springBootVersion = SpringBootVersion.getVersion(); } public String getSpringBootVersion() { return this.springBootVersion; } public StartupTimeline getTimeline() { return this.timeline; } }
static class StartupEndpointRuntimeHints implements RuntimeHintsRegistrar { private static final TypeReference DEFAULT_TAG = TypeReference .of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep$DefaultTag"); private static final TypeReference BUFFERED_STARTUP_STEP = TypeReference .of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep"); private static final TypeReference FLIGHT_RECORDER_TAG = TypeReference .of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep$FlightRecorderTag"); private static final TypeReference FLIGHT_RECORDER_STARTUP_STEP = TypeReference .of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep"); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection() .registerType(DEFAULT_TAG, (typeHint) -> typeHint.onReachableType(BUFFERED_STARTUP_STEP) .withMembers(MemberCategory.INVOKE_PUBLIC_METHODS)); hints.reflection() .registerType(FLIGHT_RECORDER_TAG, (typeHint) -> typeHint.onReachableType(FLIGHT_RECORDER_STARTUP_STEP) .withMembers(MemberCategory.INVOKE_PUBLIC_METHODS)); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\startup\StartupEndpoint.java
1
请完成以下Java代码
public class AccessingAllClassesInPackage { private static final Logger LOG = LoggerFactory.getLogger(AccessingAllClassesInPackage.class); public Set<Class> findAllClassesUsingClassLoader(String packageName) { InputStream stream = ClassLoader.getSystemClassLoader() .getResourceAsStream(packageName.replaceAll("[.]", "/")); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); return reader.lines() .filter(line -> line.endsWith(".class")) .map(line -> getClass(line, packageName)) .collect(Collectors.toSet()); } private Class getClass(String className, String packageName) { try { return Class.forName(packageName + "." + className.substring(0, className.lastIndexOf('.'))); } catch (ClassNotFoundException e) { LOG.error("<<Class not found>>"); }
return null; } public Set<Class> findAllClassesUsingReflectionsLibrary(String packageName) { Reflections reflections = new Reflections(packageName, new SubTypesScanner(false)); return reflections.getSubTypesOf(Object.class) .stream() .collect(Collectors.toSet()); } public Set<Class> findAllClassesUsingGoogleGuice(String packageName) throws IOException { return ClassPath.from(ClassLoader.getSystemClassLoader()) .getAllClasses() .stream() .filter(clazz -> clazz.getPackageName() .equalsIgnoreCase(packageName)) .map(clazz -> clazz.load()) .collect(Collectors.toSet()); } }
repos\tutorials-master\core-java-modules\core-java-reflection\src\main\java\com\baeldung\reflection\access\packages\AccessingAllClassesInPackage.java
1
请完成以下Java代码
public static boolean isPermutationWithOneCounter(String s1, String s2) { if (s1.length() != s2.length()) { return false; } int[] counter = new int[256]; for (int i = 0; i < s1.length(); i++) { counter[s1.charAt(i)]++; counter[s2.charAt(i)]--; } for (int count : counter) { if (count != 0) { return false; } } return true; } public static boolean isPermutationWithTwoCounters(String s1, String s2) { if (s1.length() != s2.length()) { return false; } int[] counter1 = new int[256]; int[] counter2 = new int[256]; for (int i = 0; i < s1.length(); i++) { counter1[s1.charAt(i)]++; } for (int i = 0; i < s2.length(); i++) { counter2[s2.charAt(i)]++; } return Arrays.equals(counter1, counter2); } public static boolean isPermutationWithMap(String s1, String s2) { if (s1.length() != s2.length()) { return false; } Map<Character, Integer> charsMap = new HashMap<>(); for (int i = 0; i < s1.length(); i++) {
charsMap.merge(s1.charAt(i), 1, Integer::sum); } for (int i = 0; i < s2.length(); i++) { if (!charsMap.containsKey(s2.charAt(i)) || charsMap.get(s2.charAt(i)) == 0) { return false; } charsMap.merge(s2.charAt(i), -1, Integer::sum); } return true; } public static boolean isPermutationInclusion(String s1, String s2) { int ns1 = s1.length(), ns2 = s2.length(); if (ns1 < ns2) { return false; } int[] s1Count = new int[26]; int[] s2Count = new int[26]; for (char ch : s2.toCharArray()) { s2Count[ch - 'a']++; } for (int i = 0; i < ns1; ++i) { s1Count[s1.charAt(i) - 'a']++; if (i >= ns2) { s1Count[s1.charAt(i - ns2) - 'a']--; } if (Arrays.equals(s2Count, s1Count)) { return true; } } return false; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-9\src\main\java\com\baeldung\algorithms\permutation\StringPermutation.java
1
请完成以下Java代码
public void setCM_Chat(org.compiere.model.I_CM_Chat CM_Chat) { set_ValueFromPO(COLUMNNAME_CM_Chat_ID, org.compiere.model.I_CM_Chat.class, CM_Chat); } /** Set Chat. @param CM_Chat_ID Chat or discussion thread */ @Override public void setCM_Chat_ID (int CM_Chat_ID) { if (CM_Chat_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, Integer.valueOf(CM_Chat_ID)); } /** Get Chat. @return Chat or discussion thread */ @Override public int getCM_Chat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Chat_ID); if (ii == null) return 0; return ii.intValue(); } /** * ConfidentialType AD_Reference_ID=340 * Reference name: R_Request Confidential */ public static final int CONFIDENTIALTYPE_AD_Reference_ID=340; /** Public Information = A */ public static final String CONFIDENTIALTYPE_PublicInformation = "A"; /** Partner Confidential = C */ public static final String CONFIDENTIALTYPE_PartnerConfidential = "C"; /** Internal = I */ public static final String CONFIDENTIALTYPE_Internal = "I"; /** Private Information = P */ public static final String CONFIDENTIALTYPE_PrivateInformation = "P"; /** Set Vertraulichkeit. @param ConfidentialType Type of Confidentiality */ @Override public void setConfidentialType (java.lang.String ConfidentialType) { set_Value (COLUMNNAME_ConfidentialType, ConfidentialType); } /** Get Vertraulichkeit. @return Type of Confidentiality */ @Override public java.lang.String getConfidentialType () { return (java.lang.String)get_Value(COLUMNNAME_ConfidentialType); } /** * ModeratorStatus AD_Reference_ID=396 * Reference name: CM_ChatEntry ModeratorStatus */ public static final int MODERATORSTATUS_AD_Reference_ID=396; /** Nicht angezeigt = N */ public static final String MODERATORSTATUS_NichtAngezeigt = "N"; /** Veröffentlicht = P */ public static final String MODERATORSTATUS_Veroeffentlicht = "P"; /** To be reviewed = R */ public static final String MODERATORSTATUS_ToBeReviewed = "R"; /** Verdächtig = S */ public static final String MODERATORSTATUS_Verdaechtig = "S"; /** Set Moderation Status. @param ModeratorStatus
Status of Moderation */ @Override public void setModeratorStatus (java.lang.String ModeratorStatus) { set_Value (COLUMNNAME_ModeratorStatus, ModeratorStatus); } /** Get Moderation Status. @return Status of Moderation */ @Override public java.lang.String getModeratorStatus () { return (java.lang.String)get_Value(COLUMNNAME_ModeratorStatus); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatEntry.java
1