instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public boolean compileFromString(String className, String sourceCode) { JavaFileObject sourceObject = new InMemoryJavaFile(className, sourceCode); return compile(Collections.singletonList(sourceObject)); } private boolean compile(Iterable<? extends JavaFileObject> compilationUnits) { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); JavaCompiler.CompilationTask task = compiler.getTask( null, standardFileManager, diagnostics, null, null, compilationUnits ); boolean success = task.call(); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { logger.debug(diagnostic.getMessage(null));
} return success; } public void runClass(String className, String... args) throws Exception { try (URLClassLoader classLoader = new URLClassLoader(new URL[]{outputDirectory.toUri().toURL()})) { Class<?> loadedClass = classLoader.loadClass(className); loadedClass.getMethod("main", String[].class).invoke(null, (Object) args); } } public Path getOutputDirectory() { return outputDirectory; } }
repos\tutorials-master\core-java-modules\core-java-compiler\src\main\java\com\baeldung\compilerapi\JavaCompilerUtils.java
1
请完成以下Java代码
public class SimpleContext extends ELContext { static class Functions extends FunctionMapper { Map<String, Method> map = Collections.emptyMap(); @Override public Method resolveFunction(String prefix, String localName) { return map.get(prefix + ":" + localName); } public void setFunction(String prefix, String localName, Method method) { if (map.isEmpty()) { map = new HashMap<String, Method>(); } map.put(prefix + ":" + localName, method); } } static class Variables extends VariableMapper { Map<String, ValueExpression> map = Collections.emptyMap(); @Override public ValueExpression resolveVariable(String variable) { return map.get(variable); } @Override public ValueExpression setVariable(String variable, ValueExpression expression) { if (map.isEmpty()) { map = new HashMap<String, ValueExpression>(); } return map.put(variable, expression); } } private Functions functions; private Variables variables; private ELResolver resolver; /** * Create a context. */ public SimpleContext() { this(null); } /** * Create a context, use the specified resolver. */ public SimpleContext(ELResolver resolver) { this.resolver = resolver; } /** * Define a function. */ public void setFunction(String prefix, String localName, Method method) { if (functions == null) { functions = new Functions(); } functions.setFunction(prefix, localName, method); } /** * Define a variable. */ public ValueExpression setVariable(String name, ValueExpression expression) { if (variables == null) { variables = new Variables(); }
return variables.setVariable(name, expression); } /** * Get our function mapper. */ @Override public FunctionMapper getFunctionMapper() { if (functions == null) { functions = new Functions(); } return functions; } /** * Get our variable mapper. */ @Override public VariableMapper getVariableMapper() { if (variables == null) { variables = new Variables(); } return variables; } /** * Get our resolver. Lazy initialize to a {@link SimpleResolver} if necessary. */ @Override public ELResolver getELResolver() { if (resolver == null) { resolver = new SimpleResolver(); } return resolver; } /** * Set our resolver. * * @param resolver */ public void setELResolver(ELResolver resolver) { this.resolver = resolver; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\SimpleContext.java
1
请完成以下Java代码
public boolean isSavedOrDeleted() { return isSaved() || isDeleted(); } public DocumentSaveStatus throwIfError() { if (!error) { return this; } if (exception != null) { throw AdempiereException.wrapIfNeeded(exception); } else { throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Error")); }
} public void throwIfNotSavedNorDelete() { if (isSavedOrDeleted()) { return; } if (exception != null) { throw AdempiereException.wrapIfNeeded(exception); } else { throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Not saved")); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentSaveStatus.java
1
请完成以下Java代码
protected void setJobRetriesByJobId(String jobId, CommandContext commandContext) { JobEntity job = commandContext .getJobManager() .findJobById(jobId); if (job != null) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateRetriesJob(job); } if (job.isInInconsistentLockState()) { job.resetLock(); } List<PropertyChange> propertyChanges = new ArrayList<>(); int oldRetries = job.getRetries(); job.setRetries(retries); propertyChanges.add(new PropertyChange(RETRIES, oldRetries, job.getRetries())); if (isDueDateSet) { Date oldDueDate = job.getDuedate(); job.setDuedate(dueDate); propertyChanges.add(new PropertyChange(DUE_DATE, oldDueDate, job.getDuedate())); } commandContext.getOperationLogManager().logJobOperation(getLogEntryOperation(), job.getId(), job.getJobDefinitionId(), job.getProcessInstanceId(), job.getProcessDefinitionId(), job.getProcessDefinitionKey(), propertyChanges); } else { throw LOG.exceptionNoJobFoundForId(jobId); } } protected void setJobRetriesByJobDefinitionId(CommandContext commandContext) {
JobDefinitionManager jobDefinitionManager = commandContext.getJobDefinitionManager(); JobDefinitionEntity jobDefinition = jobDefinitionManager.findById(jobDefinitionId); if (jobDefinition != null) { String processDefinitionId = jobDefinition.getProcessDefinitionId(); for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateRetriesProcessInstanceByProcessDefinitionId(processDefinitionId); } } commandContext .getJobManager() .updateFailedJobRetriesByJobDefinitionId(jobDefinitionId, retries, dueDate, isDueDateSet); List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange(RETRIES, null, retries)); if (isDueDateSet) { propertyChanges.add(new PropertyChange(DUE_DATE, null, dueDate)); } commandContext.getOperationLogManager().logJobOperation(getLogEntryOperation(), null, jobDefinitionId, null, null, null, propertyChanges); } protected String getLogEntryOperation() { return UserOperationLogEntry.OPERATION_TYPE_SET_JOB_RETRIES; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetJobRetriesCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class GraphQLDataFetchers { private static List<Map<String, String>> books = Arrays.asList( ImmutableMap.of("id", "book-1", "name", "Harry Potter and the Philosopher's Stone", "pageCount", "223", "authorId", "author-1"), ImmutableMap.of("id", "book-2", "name", "Moby Dick", "pageCount", "635", "authorId", "author-2"), ImmutableMap.of("id", "book-3", "name", "Interview with the vampire", "pageCount", "371", "authorId", "author-3") ); private static List<Map<String, String>> authors = Arrays.asList( ImmutableMap.of("id", "author-1", "firstName", "Joanne", "lastName", "Rowling"), ImmutableMap.of("id", "author-2", "firstName", "Herman", "lastName", "Melville"), ImmutableMap.of("id", "author-3", "firstName", "Anne", "lastName", "Rice") ); public DataFetcher getBookByIdDataFetcher() { return dataFetchingEnvironment -> {
String bookId = dataFetchingEnvironment.getArgument("id"); return books .stream() .filter(book -> book.get("id").equals(bookId)) .findFirst() .orElse(null); }; } public DataFetcher getAuthorDataFetcher() { return dataFetchingEnvironment -> { Map<String, String> book = dataFetchingEnvironment.getSource(); String authorId = book.get("authorId"); return authors .stream() .filter(author -> author.get("id").equals(authorId)) .findFirst() .orElse(null); }; } }
repos\spring-boot-quick-master\quick-graphQL\src\main\java\com\quick\graphql\service\GraphQLDataFetchers.java
2
请完成以下Java代码
public <R> R forProcessInstanceReadonly(final DocumentId pinstanceId, @NonNull final Function<IProcessInstanceController, R> processor) { try (final IAutoCloseable ignored = getInstance(pinstanceId).lockForReading()) { final HUReportProcessInstance processInstance = getInstance(pinstanceId) .copyReadonly(); return processor.apply(processInstance); } } @Override public <R> R forProcessInstanceWritable(final DocumentId pinstanceId, final IDocumentChangesCollector changesCollector, @NonNull final Function<IProcessInstanceController, R> processor) { try (final IAutoCloseable ignored = getInstance(pinstanceId).lockForWriting()) { final HUReportProcessInstance processInstance = getInstance(pinstanceId) .copyReadWrite(changesCollector); final R result = processor.apply(processInstance); putInstance(processInstance); return result; } } @Override public void cacheReset() { processDescriptors.reset(); instances.cleanUp(); } private DocumentId nextPInstanceId() { return DocumentId.ofString(UUID.randomUUID().toString()); } private static final class IndexedWebuiHUProcessDescriptors {
private final ImmutableMap<ProcessId, WebuiHUProcessDescriptor> descriptorsByProcessId; private IndexedWebuiHUProcessDescriptors(final List<WebuiHUProcessDescriptor> descriptors) { descriptorsByProcessId = Maps.uniqueIndex(descriptors, WebuiHUProcessDescriptor::getProcessId); } public WebuiHUProcessDescriptor getByProcessId(final ProcessId processId) { final WebuiHUProcessDescriptor descriptor = descriptorsByProcessId.get(processId); if (descriptor == null) { throw new EntityNotFoundException("No HU process descriptor found for " + processId); } return descriptor; } public Collection<WebuiHUProcessDescriptor> getAll() { return descriptorsByProcessId.values(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\HUReportProcessInstancesRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class GroovyTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider { private static final String REQUIRED_CLASS_NAME = "groovy.text.TemplateEngine"; public GroovyTemplateAvailabilityProvider() { super(REQUIRED_CLASS_NAME, GroovyTemplateAvailabilityProperties.class, "spring.groovy.template"); } protected static final class GroovyTemplateAvailabilityProperties extends TemplateAvailabilityProperties { private List<String> resourceLoaderPath = new ArrayList<>( Arrays.asList(GroovyTemplateProperties.DEFAULT_RESOURCE_LOADER_PATH)); GroovyTemplateAvailabilityProperties() { super(GroovyTemplateProperties.DEFAULT_PREFIX, GroovyTemplateProperties.DEFAULT_SUFFIX); } @Override protected List<String> getLoaderPath() { return this.resourceLoaderPath; } public List<String> getResourceLoaderPath() { return this.resourceLoaderPath; } public void setResourceLoaderPath(List<String> resourceLoaderPath) { this.resourceLoaderPath = resourceLoaderPath;
} } static class GroovyTemplateAvailabilityRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { if (ClassUtils.isPresent(REQUIRED_CLASS_NAME, classLoader)) { BindableRuntimeHintsRegistrar.forTypes(GroovyTemplateAvailabilityProperties.class) .registerHints(hints, classLoader); } } } }
repos\spring-boot-4.0.1\module\spring-boot-groovy-templates\src\main\java\org\springframework\boot\groovy\template\autoconfigure\GroovyTemplateAvailabilityProvider.java
2
请在Spring Boot框架中完成以下Java代码
public class BankAccountAspect { @Before(value = "@annotation(com.baeldung.method.info.AccountOperation)") public void getAccountOperationInfo(JoinPoint joinPoint) { // Method Information MethodSignature signature = (MethodSignature) joinPoint.getSignature(); System.out.println("full method description: " + signature.getMethod()); System.out.println("method name: " + signature.getMethod().getName()); System.out.println("declaring type: " + signature.getDeclaringType()); // Method args System.out.println("Method args names:"); Arrays.stream(signature.getParameterNames()) .forEach(s -> System.out.println("arg name: " + s)); System.out.println("Method args types:"); Arrays.stream(signature.getParameterTypes()) .forEach(s -> System.out.println("arg type: " + s));
System.out.println("Method args values:"); Arrays.stream(joinPoint.getArgs()) .forEach(o -> System.out.println("arg value: " + o.toString())); // Additional Information System.out.println("returning type: " + signature.getReturnType()); System.out.println("method modifier: " + Modifier.toString(signature.getModifiers())); Arrays.stream(signature.getExceptionTypes()) .forEach(aClass -> System.out.println("exception type: " + aClass)); // Method annotation Method method = signature.getMethod(); AccountOperation accountOperation = method.getAnnotation(AccountOperation.class); System.out.println("Account operation annotation: " + accountOperation); System.out.println("Account operation value: " + accountOperation.operation()); } }
repos\tutorials-master\spring-aop-2\src\main\java\com\baeldung\method\info\BankAccountAspect.java
2
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getRegTime() { return regTime; }
public void setRegTime(Date regTime) { this.regTime = regTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\entity\UserEntity.java
1
请在Spring Boot框架中完成以下Java代码
public static BPartnerPrintFormatMap ofList(@NonNull final List<BPartnerPrintFormat> list) { return !list.isEmpty() ? new BPartnerPrintFormatMap(list) : EMPTY; } private static BPartnerPrintFormatMap EMPTY = new BPartnerPrintFormatMap(ImmutableList.of()); private final ImmutableMap<DocTypeId, BPartnerPrintFormat> byDocTypeId; private BPartnerPrintFormatMap(@NonNull final List<BPartnerPrintFormat> list) { byDocTypeId = Maps.uniqueIndex(list, BPartnerPrintFormat::getDocTypeId); } public Optional<PrintFormatId> getPrintFormatIdByDocTypeId(@NonNull final DocTypeId docTypeId)
{ return Optional.ofNullable(byDocTypeId.get(docTypeId)) .map(BPartnerPrintFormat::getPrintFormatId); } public Optional<PrintFormatId> getFirstByTableId(@NonNull final AdTableId tableId) { return byDocTypeId.values() .stream() .filter(item -> AdTableId.equals(item.getAdTableId(), tableId)) .findFirst() .map(BPartnerPrintFormat::getPrintFormatId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerPrintFormatMap.java
2
请在Spring Boot框架中完成以下Java代码
public void create(@NonNull final InvoicePayScheduleCreateRequest request) { request.getLines().forEach(line -> createLine(line, request.getInvoiceId())); } private void createLine(@NonNull final InvoicePayScheduleCreateRequest.Line request, @NonNull final InvoiceId invoiceId) { final I_C_InvoicePaySchedule record = newInstance(I_C_InvoicePaySchedule.class); record.setC_Invoice_ID(invoiceId.getRepoId()); InvoicePayScheduleConverter.updateRecord(record, request); saveRecord(record); } public void deleteByInvoiceId(@NonNull final InvoiceId invoiceId) { queryBL.createQueryBuilder(I_C_InvoicePaySchedule.class) .addEqualsFilter(I_C_InvoicePaySchedule.COLUMNNAME_C_Invoice_ID, invoiceId) .create() .delete();
} public void updateById(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater) { newLoaderAndSaver().updateById(invoiceId, updater); } public void updateByIds(@NonNull final Set<InvoiceId> invoiceIds, @NonNull final Consumer<InvoicePaySchedule> updater) { newLoaderAndSaver().updateByIds(invoiceIds, updater); } public Optional<InvoicePaySchedule> getByInvoiceId(@NonNull final InvoiceId invoiceId) { return newLoaderAndSaver().loadByInvoiceId(invoiceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\repository\InvoicePayScheduleRepository.java
2
请完成以下Java代码
public void allocatePOLineToSOLine( @NonNull final OrderLineId purchaseOrderLineId, @NonNull final OrderLineId salesOrderLineId) { final I_C_PO_OrderLine_Alloc poLineAllocation = InterfaceWrapperHelper.newInstance(I_C_PO_OrderLine_Alloc.class); poLineAllocation.setC_PO_OrderLine_ID(purchaseOrderLineId.getRepoId()); poLineAllocation.setC_SO_OrderLine_ID(salesOrderLineId.getRepoId()); InterfaceWrapperHelper.save(poLineAllocation); } @NonNull public List<OrderId> getUnprocessedIdsBy(@NonNull final ProductId productId) { return queryBL.createQueryBuilder(I_C_OrderLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_OrderLine.COLUMNNAME_M_Product_ID, productId) .addEqualsFilter(I_C_OrderLine.COLUMNNAME_Processed, false) .create() .listDistinct(I_C_OrderLine.COLUMNNAME_C_Order_ID, OrderId.class); } @Override public Optional<PPCostCollectorId> getPPCostCollectorId(@NonNull final OrderLineId orderLineId) { final String sql = "SELECT " + org.compiere.model.I_C_OrderLine.COLUMNNAME_PP_Cost_Collector_ID + " FROM C_OrderLine WHERE C_OrderLine_ID=? AND PP_Cost_Collector_ID IS NOT NULL"; return Optional.ofNullable(PPCostCollectorId.ofRepoIdOrNull(DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, orderLineId))); } public boolean hasDeliveredItems(@NonNull final OrderId orderId) { return queryBL.createQueryBuilder(I_C_OrderLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId) .addCompareFilter(I_C_OrderLine.COLUMNNAME_QtyDelivered, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .create() .anyMatch(); } @NonNull private Optional<I_C_Order> getOrderByExternalId(@NonNull final OrderQuery orderQuery) { final OrgId orgId = assumeNotNull(orderQuery.getOrgId(), "Param query needs to have a non-null orgId; query={}", orderQuery); final ExternalId externalId = assumeNotNull(orderQuery.getExternalId(), "Param query needs to have a non-null externalId; query={}", orderQuery); final IQueryBuilder<I_C_Order> queryBuilder = createQueryBuilder() .addEqualsFilter(I_C_Order.COLUMNNAME_AD_Org_ID, orgId) .addEqualsFilter(I_C_Order.COLUMNNAME_ExternalId, externalId.getValue());
final InputDataSourceId dataSourceId = orderQuery.getInputDataSourceId(); if (dataSourceId != null) { queryBuilder.addEqualsFilter(I_C_Order.COLUMNNAME_AD_InputDataSource_ID, dataSourceId); } final ExternalSystemId externalSystemId = orderQuery.getExternalSystemId(); if (externalSystemId != null) { queryBuilder.addEqualsFilter(I_C_Order.COLUMNNAME_ExternalSystem_ID, externalSystemId); } return queryBuilder .create() .firstOnlyOptional(); } public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter) { return queryBL.createQueryBuilder(I_C_Order.class) .filter(queryFilter) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\AbstractOrderDAO.java
1
请完成以下Java代码
public void add(AuditEvent event) { Assert.notNull(event, "'event' must not be null"); synchronized (this.monitor) { this.tail = (this.tail + 1) % this.events.length; this.events[this.tail] = event; } } @Override public List<AuditEvent> find(@Nullable String principal, @Nullable Instant after, @Nullable String type) { LinkedList<AuditEvent> events = new LinkedList<>(); synchronized (this.monitor) { for (int i = 0; i < this.events.length; i++) { AuditEvent event = resolveTailEvent(i); if (event != null && isMatch(principal, after, type, event)) { events.addFirst(event); } } } return events; }
private boolean isMatch(@Nullable String principal, @Nullable Instant after, @Nullable String type, AuditEvent event) { boolean match = true; match = match && (principal == null || event.getPrincipal().equals(principal)); match = match && (after == null || event.getTimestamp().isAfter(after)); match = match && (type == null || event.getType().equals(type)); return match; } private AuditEvent resolveTailEvent(int offset) { int index = ((this.tail + this.events.length - offset) % this.events.length); return this.events[index]; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\audit\InMemoryAuditEventRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class ExcelController { private String fileLocation; @Resource(name = "excelPOIHelper") private ExcelPOIHelper excelPOIHelper; @RequestMapping(method = RequestMethod.GET, value = "/excelProcessing") public String getExcelProcessingPage() { return "excel"; } @RequestMapping(method = RequestMethod.POST, value = "/uploadExcelFile") public String uploadFile(Model model, MultipartFile file) throws IOException { InputStream in = file.getInputStream(); File currDir = new File("."); String path = currDir.getAbsolutePath(); fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename(); FileOutputStream f = new FileOutputStream(fileLocation); int ch = 0; while ((ch = in.read()) != -1) { f.write(ch); } f.flush(); f.close(); model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!"); return "excel"; }
@RequestMapping(method = RequestMethod.GET, value = "/readPOI") public String readPOI(Model model) throws IOException { if (fileLocation != null) { if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) { Map<Integer, List<MyCell>> data = excelPOIHelper.readExcel(fileLocation); model.addAttribute("data", data); } else { model.addAttribute("message", "Not a valid excel file!"); } } else { model.addAttribute("message", "File missing! Please upload an excel file."); } return "excel"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\excel\ExcelController.java
2
请完成以下Java代码
public class PrivilegeMappingEntityImpl extends AbstractIdmEngineEntity implements PrivilegeMappingEntity { protected String privilegeId; protected String userId; protected String groupId; @Override public Object getPersistentState() { // Privilege mapping is immutable return PrivilegeMappingEntityImpl.class; } @Override public String getPrivilegeId() { return privilegeId; } @Override public void setPrivilegeId(String privilegeId) { this.privilegeId = privilegeId; } @Override public String getUserId() { return userId;
} @Override public void setUserId(String userId) { this.userId = userId; } @Override public String getGroupId() { return groupId; } @Override public void setGroupId(String groupId) { this.groupId = groupId; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\PrivilegeMappingEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public EventSubscriptionDataManager getEventSubscriptionDataManager() { return eventSubscriptionDataManager; } public EventSubscriptionServiceConfiguration setEventSubscriptionDataManager(EventSubscriptionDataManager eventSubscriptionDataManager) { this.eventSubscriptionDataManager = eventSubscriptionDataManager; return this; } public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return eventSubscriptionEntityManager; } public EventSubscriptionServiceConfiguration setEventSubscriptionEntityManager(EventSubscriptionEntityManager eventSubscriptionEntityManager) { this.eventSubscriptionEntityManager = eventSubscriptionEntityManager; return this; } @Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public EventSubscriptionServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; }
public Duration getEventSubscriptionLockTime() { return eventSubscriptionLockTime; } public EventSubscriptionServiceConfiguration setEventSubscriptionLockTime(Duration eventSubscriptionLockTime) { this.eventSubscriptionLockTime = eventSubscriptionLockTime; return this; } public String getLockOwner() { return lockOwner; } public EventSubscriptionServiceConfiguration setLockOwner(String lockOwner) { this.lockOwner = lockOwner; return this; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\EventSubscriptionServiceConfiguration.java
2
请完成以下Java代码
public void setIsDeliveryStop (final boolean IsDeliveryStop) { set_Value (COLUMNNAME_IsDeliveryStop, IsDeliveryStop); } @Override public boolean isDeliveryStop() { return get_ValueAsBoolean(COLUMNNAME_IsDeliveryStop); } @Override public void setIsPaid (final boolean IsPaid) { throw new IllegalArgumentException ("IsPaid is virtual column"); } @Override public boolean isPaid() { return get_ValueAsBoolean(COLUMNNAME_IsPaid); } @Override public void setM_Shipment_Constraint_ID (final int M_Shipment_Constraint_ID) { if (M_Shipment_Constraint_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, M_Shipment_Constraint_ID); } @Override public int getM_Shipment_Constraint_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipment_Constraint_ID); } @Override
public void setSourceDoc_Record_ID (final int SourceDoc_Record_ID) { if (SourceDoc_Record_ID < 1) set_Value (COLUMNNAME_SourceDoc_Record_ID, null); else set_Value (COLUMNNAME_SourceDoc_Record_ID, SourceDoc_Record_ID); } @Override public int getSourceDoc_Record_ID() { return get_ValueAsInt(COLUMNNAME_SourceDoc_Record_ID); } @Override public void setSourceDoc_Table_ID (final int SourceDoc_Table_ID) { if (SourceDoc_Table_ID < 1) set_Value (COLUMNNAME_SourceDoc_Table_ID, null); else set_Value (COLUMNNAME_SourceDoc_Table_ID, SourceDoc_Table_ID); } @Override public int getSourceDoc_Table_ID() { return get_ValueAsInt(COLUMNNAME_SourceDoc_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Shipment_Constraint.java
1
请完成以下Java代码
public void validateDocTypeIsInSync(@NonNull final I_C_Payment payment) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(payment.getC_DocType_ID()); if (docTypeId == null) { return; } final I_C_DocType docType = docTypeBL.getById(docTypeId); // Invoice final I_C_Invoice invoice = InvoiceId.optionalOfRepoId(payment.getC_Invoice_ID()) .map(invoiceBL::getById) .orElse(null); if (invoice != null && invoice.isSOTrx() != docType.isSOTrx()) { // task: 07564 the SOtrx flags don't match, but that's OK *if* the invoice i a credit memo (either for the vendor or customer side) if (!invoiceBL.isCreditMemo(invoice)) { throw new AdempiereException(MSG_PaymentDocTypeInvoiceInconsistent); } } // globalqss - Allow prepayment to Purchase Orders // Order Waiting Payment (can only be SO)
// if (C_Order_ID != 0 && dt != null && !dt.isSOTrx()) // return "PaymentDocTypeInvoiceInconsistent"; // Order final OrderId orderId = OrderId.ofRepoIdOrNull(payment.getC_Order_ID()); if (orderId == null) { return; } final I_C_Order order = orderDAO.getById(orderId); if (order.isSOTrx() != docType.isSOTrx()) { throw new AdempiereException(MSG_PaymentDocTypeInvoiceInconsistent); } } @Override public void reversePaymentById(@NonNull final PaymentId paymentId) { final I_C_Payment payment = getById(paymentId); payment.setDocAction(IDocument.ACTION_Reverse_Correct); documentBL.processEx(payment, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PaymentBL.java
1
请完成以下Java代码
public static int dateDiff(Date one, Date two) throws ServiceException { if (one == null || two == null) { throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR); } long diff = Math.abs((one.getTime() - two.getTime()) / (1000 * 3600 * 24)); return new Long(diff).intValue(); } /** * 计算几天前的时间 * * @param date 当前时间 * @param day 几天前 * @return */ public static Date getDateBefore(Date date, int day) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, now.get(Calendar.DATE) - day); return now.getTime(); } /** * 获取当前月第一天 * * @return Date * @throws ParseException
*/ public static Date getFirstAndLastOfMonth() { LocalDate today = LocalDate.now(); LocalDate firstDay = LocalDate.of(today.getYear(),today.getMonth(),1); ZoneId zone = ZoneId.systemDefault(); Instant instant = firstDay.atStartOfDay().atZone(zone).toInstant(); return Date.from(instant); } /** * 获取当前周第一天 * * @return Date * @throws ParseException */ public static Date getWeekFirstDate(){ Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date date = cal.getTime(); return date; } }
repos\springBoot-master\abel-util\src\main\java\cn\abel\utils\DateTimeUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class DemoController { @GetMapping("/echo") public String echo() { return "echo"; } @GetMapping("/test") public String test() { return "test"; } @GetMapping("/sleep") public String sleep() throws InterruptedException { Thread.sleep(100L); return "sleep"; } // 测试热点参数限流 @GetMapping("/product_info") @SentinelResource("demo_product_info_hot") public String productInfo(Integer id) { return "商品编号:" + id; } // 手动使用 Sentinel 客户端 API @GetMapping("/entry_demo") public String entryDemo() { Entry entry = null; try { // 访问资源 entry = SphU.entry("entry_demo"); // ... 执行业务逻辑 return "执行成功"; } catch (BlockException ex) { return "被拒绝"; } finally {
// 释放资源 if (entry != null) { entry.exit(); } } } // 测试 @SentinelResource 注解 @GetMapping("/annotations_demo") @SentinelResource(value = "annotations_demo_resource", blockHandler = "blockHandler", fallback = "fallback") public String annotationsDemo(@RequestParam(required = false) Integer id) throws InterruptedException { if (id == null) { throw new IllegalArgumentException("id 参数不允许为空"); } return "success..."; } // BlockHandler 处理函数,参数最后多一个 BlockException,其余与原函数一致. public String blockHandler(Integer id, BlockException ex) { return "block:" + ex.getClass().getSimpleName(); } // Fallback 处理函数,函数签名与原函数一致或加一个 Throwable 类型的参数. public String fallback(Integer id, Throwable throwable) { return "fallback:" + throwable.getMessage(); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\controller\DemoController.java
2
请完成以下Java代码
public ActivityImpl getInitial() { return initial; } public void setInitial(ActivityImpl initial) { this.initial = initial; } @Override public String toString() { return "ProcessDefinition("+id+")"; } public String getDescription() { return (String) getProperty("documentation"); } /** * @return all lane-sets defined on this process-instance. Returns an empty list if none are defined. */ public List<LaneSet> getLaneSets() { if(laneSets == null) { laneSets = new ArrayList<LaneSet>(); } return laneSets; } public void setParticipantProcess(ParticipantProcess participantProcess) { this.participantProcess = participantProcess; } public ParticipantProcess getParticipantProcess() { return participantProcess; } public boolean isScope() { return true; }
public PvmScope getEventScope() { return null; } public ScopeImpl getFlowScope() { return null; } public PvmScope getLevelOfSubprocessScope() { return null; } @Override public boolean isSubProcessScope() { return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ProcessDefinitionImpl.java
1
请完成以下Java代码
public BigDecimal getF_SHARE() { return F_SHARE; } public void setF_SHARE(BigDecimal f_SHARE) { F_SHARE = f_SHARE; } public String getF_ISRATION() { return F_ISRATION; } public void setF_ISRATION(String f_ISRATION) { F_ISRATION = f_ISRATION; } public String getF_INCANTONID() { return F_INCANTONID; } public void setF_INCANTONID(String f_INCANTONID) { F_INCANTONID = f_INCANTONID; } public String getF_INOFFICEID() { return F_INOFFICEID; } public void setF_INOFFICEID(String f_INOFFICEID) { F_INOFFICEID = f_INOFFICEID; } public Integer getF_INACCOUNTTYPE() { return F_INACCOUNTTYPE; } public void setF_INACCOUNTTYPE(Integer f_INACCOUNTTYPE) { F_INACCOUNTTYPE = f_INACCOUNTTYPE; } public String getF_INACCOUNTID() { return F_INACCOUNTID; } public void setF_INACCOUNTID(String f_INACCOUNTID) { F_INACCOUNTID = f_INACCOUNTID; } public String getF_STARTDATE() { return F_STARTDATE; } public void setF_STARTDATE(String f_STARTDATE) { F_STARTDATE = f_STARTDATE; } public String getF_ENDDATE() { return F_ENDDATE; } public void setF_ENDDATE(String f_ENDDATE) { F_ENDDATE = f_ENDDATE; } public String getF_MEMO() { return F_MEMO; }
public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; } public String getF_AUDITTIME() { return F_AUDITTIME; } public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_VERSION() { return F_VERSION; } public void setF_VERSION(String f_VERSION) { F_VERSION = f_VERSION; } public String getF_BUDGETCODE() { return F_BUDGETCODE; } public void setF_BUDGETCODE(String f_BUDGETCODE) { F_BUDGETCODE = f_BUDGETCODE; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollSpecialShare.java
1
请完成以下Java代码
public String getImplementationType() { return implementationType; } public void setImplementationType(String implementationType) { this.implementationType = implementationType; } public String getImplementation() { return implementation; } public void setImplementation(String implementation) { this.implementation = implementation; } public List<FieldExtension> getFieldExtensions() { return fieldExtensions; } public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public String getOnTransaction() { return onTransaction; } public void setOnTransaction(String onTransaction) { this.onTransaction = onTransaction; } /** * Return the script info, if present. * <p> * ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when * implementationType is 'script'. * </p> */ public ScriptInfo getScriptInfo() { return scriptInfo; } /** * Sets the script info * * @see #getScriptInfo() */ public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo;
} public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } @Override public FlowableListener clone() { FlowableListener clone = new FlowableListener(); clone.setValues(this); return clone; } public void setValues(FlowableListener otherListener) { super.setValues(otherListener); setEvent(otherListener.getEvent()); setSourceState(otherListener.getSourceState()); setTargetState(otherListener.getTargetState()); setImplementation(otherListener.getImplementation()); setImplementationType(otherListener.getImplementationType()); setOnTransaction(otherListener.getOnTransaction()); Optional.ofNullable(otherListener.getScriptInfo()).map(ScriptInfo::clone).ifPresent(this::setScriptInfo); fieldExtensions = new ArrayList<>(); if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherListener.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\FlowableListener.java
1
请在Spring Boot框架中完成以下Java代码
private ResultSet executeStatement(SimpleStatement statement, String keyspace) { if (keyspace != null) { statement.setKeyspace(CqlIdentifier.fromCql(keyspace)); } return session.execute(statement); } private BoundStatement getProductVariantInsertStatement(Product product,UUID productId) { String insertQuery = new StringBuilder("").append("INSERT INTO ").append(PRODUCT_TABLE_NAME) .append("(product_id,variant_id,product_name,description,price) ").append("VALUES (").append(":product_id") .append(", ").append(":variant_id").append(", ").append(":product_name").append(", ") .append(":description").append(", ").append(":price").append(");").toString(); PreparedStatement preparedStatement = session.prepare(insertQuery); return preparedStatement.bind(productId, UUID.randomUUID(), product.getProductName(), product.getDescription(),
product.getPrice()); } private BoundStatement getProductInsertStatement(Product product,UUID productId,String productTableName) { String cqlQuery1 = new StringBuilder("").append("INSERT INTO ").append(productTableName) .append("(product_id,product_name,description,price) ").append("VALUES (").append(":product_id") .append(", ").append(":product_name").append(", ").append(":description").append(", ") .append(":price").append(");").toString(); PreparedStatement preparedStatement = session.prepare(cqlQuery1); return preparedStatement.bind(productId, product.getProductName(), product.getDescription(), product.getPrice()); } }
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\batch\repository\ProductRepository.java
2
请完成以下Java代码
public final List<IHUDocument> createHUDocuments(final Properties ctx, final String tableName, final int recordId) { assumeTableName(tableName); final T model = InterfaceWrapperHelper.create(ctx, recordId, modelClass, ITrx.TRXNAME_None); final HUDocumentsCollector documentsCollector = new HUDocumentsCollector(); createHUDocumentsFromTypedModel(documentsCollector, model); return documentsCollector.getHUDocuments(); } @Override public final <IT> List<IHUDocument> createHUDocuments(final Properties ctx, final Class<IT> modelClass, final Iterator<IT> records) { final HUDocumentsCollector documentsCollector = new HUDocumentsCollector(); createHUDocuments(documentsCollector, modelClass, records); return documentsCollector.getHUDocuments(); } protected <IT> void createHUDocuments(final HUDocumentsCollector documentsCollector, final Class<IT> modelClass, final Iterator<IT> records) { assumeTableName(InterfaceWrapperHelper.getTableName(modelClass)); while (records.hasNext()) { final IT record = records.next(); final T model = InterfaceWrapperHelper.create(record, this.modelClass); try { createHUDocumentsFromTypedModel(documentsCollector, model); } catch (final Exception e) { logger.warn("Error while creating source from " + model + ". Skipping.", e); } } } @Override public final List<IHUDocument> createHUDocuments(final ProcessInfo pi) { final HUDocumentsCollector documentsCollector = new HUDocumentsCollector(); createHUDocuments(documentsCollector, pi); return documentsCollector.getHUDocuments(); }
protected final void createHUDocuments(final HUDocumentsCollector documentsCollector, final ProcessInfo pi) { Check.assumeNotNull(pi, "process info not null"); final String tableName = pi.getTableNameOrNull(); assumeTableName(tableName); final Iterator<T> models = retrieveModelsFromProcessInfo(pi); createHUDocuments(documentsCollector, modelClass, models); } /** * Method used to retrieve relevant models from given ProcessInfo. * * @param pi * @return */ protected Iterator<T> retrieveModelsFromProcessInfo(final ProcessInfo pi) { final Properties ctx = pi.getCtx(); final int recordId = pi.getRecord_ID(); Check.assume(recordId > 0, "No Record_ID found in {}", pi); final T model = InterfaceWrapperHelper.create(ctx, recordId, modelClass, ITrx.TRXNAME_None); return new SingletonIterator<>(model); } @Override public final List<IHUDocument> createHUDocumentsFromModel(final Object modelObj) { final HUDocumentsCollector documentsCollector = new HUDocumentsCollector(); final T model = InterfaceWrapperHelper.create(modelObj, modelClass); createHUDocumentsFromTypedModel(documentsCollector, model); return documentsCollector.getHUDocuments(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentFactory.java
1
请完成以下Java代码
public LocatorId getPickFromLocatorId() {return getPickFromLocator().getId();} public WarehouseId getPickFromWarehouseId() {return getPickFromLocatorId().getWarehouseId();} public Optional<Quantity> getQtyPicked() { return Optional.ofNullable(pickedTo != null ? pickedTo.getQtyPicked() : null); } public Optional<Quantity> getQtyRejected() { if (pickedTo == null) { return Optional.empty(); } final QtyRejectedWithReason qtyRejected = pickedTo.getQtyRejected(); if (qtyRejected == null) { return Optional.empty(); } return Optional.of(qtyRejected.toQuantity()); } public HuId getPickFromHUId() {return getPickFromHU().getId();} public boolean isPicked() {return pickedTo != null;} public boolean isNotPicked() {return pickedTo == null;}
public void assertPicked() { if (!isPicked()) { throw new AdempiereException("PickFrom was not picked: " + this); } } public PickingJobStepPickFrom assertNotPicked() { if (isPicked()) { throw new AdempiereException("PickFrom already picked: " + this); } return this; } public PickingJobStepPickFrom withPickedEvent(@NonNull final PickingJobStepPickedTo pickedTo) { return withPickedTo(pickedTo); } public PickingJobStepPickFrom withUnPickedEvent(@NonNull PickingJobStepUnpickInfo unpickEvent) { return withPickedTo(pickedTo != null ? pickedTo.removing(unpickEvent.getUnpickedHUs()) : null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFrom.java
1
请完成以下Java代码
public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", parentId=").append(parentId); sb.append(", name=").append(name); sb.append(", level=").append(level); sb.append(", productCount=").append(productCount); sb.append(", productUnit=").append(productUnit); sb.append(", navStatus=").append(navStatus); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", icon=").append(icon); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategory.java
1
请完成以下Java代码
public void invalidateMatchingInvoiceCandidatesAfterCommit(@NonNull final I_C_Flatrate_Term flatrateTerm) { if (isNoRefundTerm(flatrateTerm)) { return; // this MI only deals with "refund" terms } final IQuery<I_C_Invoice_Candidate> query = createInvoiceCandidatesToInvalidQuery(flatrateTerm); Services.get(ITrxManager.class) .getCurrentTrxListenerManagerOrAutoCommit() .newEventListener(TrxEventTiming.AFTER_COMMIT) .registerHandlingMethod(trx -> Services.get(IInvoiceCandDAO.class).invalidateCandsFor(query)); } private IQuery<I_C_Invoice_Candidate> createInvoiceCandidatesToInvalidQuery( @NonNull final I_C_Flatrate_Term flatrateTerm) { final IQueryFilter<I_C_Invoice_Candidate> dateToInvoiceEffectiveFilter = invoiceCandidateRepository .createDateToInvoiceEffectiveFilter( flatrateTerm.getStartDate(),
flatrateTerm.getEndDate()); return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, false) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID, flatrateTerm.getM_Product_ID()) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID, flatrateTerm.getBill_BPartner_ID()) .filter(dateToInvoiceEffectiveFilter) .create(); } private boolean isNoRefundTerm(@NonNull final I_C_Flatrate_Term flatrateTerm) { return !X_C_Flatrate_Term.TYPE_CONDITIONS_Refund.equals(flatrateTerm.getType_Conditions()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\interceptor\C_Flatrate_Term.java
1
请完成以下Java代码
public boolean containsKey(Object key) { return getDelegate().containsKey(key); } @Override public Object get(Object key) { return getDelegate().get(key); } @Override public void load(InputStream inStream) throws IOException { getDelegate().load(inStream); } @Override public Object put(Object key, Object value) { return getDelegate().put(key, value); } @Override public Object remove(Object key) { return getDelegate().remove(key); } @Override public void putAll(Map<? extends Object, ? extends Object> t) { getDelegate().putAll(t); } @Override public void clear() { getDelegate().clear(); } @Override public Object clone() { return getDelegate().clone(); } @Override public String toString() { return getDelegate().toString(); } @Override public Set<Object> keySet() { return getDelegate().keySet(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { return getDelegate().entrySet(); } @Override public Collection<Object> values() { return getDelegate().values(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); } @SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override
public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public FlowRule toRule() { FlowRule flowRule = new FlowRule(); flowRule.setCount(this.count); flowRule.setGrade(this.grade); flowRule.setResource(this.resource);
flowRule.setLimitApp(this.limitApp); flowRule.setRefResource(this.refResource); flowRule.setStrategy(this.strategy); if (this.controlBehavior != null) { flowRule.setControlBehavior(controlBehavior); } if (this.warmUpPeriodSec != null) { flowRule.setWarmUpPeriodSec(warmUpPeriodSec); } if (this.maxQueueingTimeMs != null) { flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); } flowRule.setClusterMode(clusterMode); flowRule.setClusterConfig(clusterConfig); return flowRule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java
1
请完成以下Java代码
public OrderProductPK getPk() { return pk; } public void setPk(OrderProductPK pk) { this.pk = pk; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((pk == null) ? 0 : pk.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; }
if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } OrderProduct other = (OrderProduct) obj; if (pk == null) { if (other.pk != null) { return false; } } else if (!pk.equals(other.pk)) { return false; } return true; } }
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\OrderProduct.java
1
请完成以下Java代码
public int shiftOperators(int number) { int length = 0; long temp = 1; while(temp <= number) { length++; temp = (temp << 3) + (temp << 1); } return length; } public int dividingWithPowersOf2(int number) { int length = 1; if (number >= 100000000) { length += 8; number /= 100000000; } if (number >= 10000) { length += 4; number /= 10000; } if (number >= 100) { length += 2; number /= 100; } if (number >= 10) { length += 1; } return length; } public int divideAndConquer(int number) { if (number < 100000){ // 5 digits or less if (number < 100){ // 1 or 2 if (number < 10) return 1; else return 2; }else{ // 3 to 5 digits if (number < 1000) return 3; else{
// 4 or 5 digits if (number < 10000) return 4; else return 5; } } } else { // 6 digits or more if (number < 10000000) { // 6 or 7 digits if (number < 1000000) return 6; else return 7; } else { // 8 to 10 digits if (number < 100000000) return 8; else { // 9 or 10 digits if (number < 1000000000) return 9; else return 10; } } } } }
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\numberofdigits\NumberOfDigits.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getBatchSize() { return this.batchSize; } public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } public Duration getMeterTimeToLive() { return this.meterTimeToLive; } public void setMeterTimeToLive(Duration meterTimeToLive) { this.meterTimeToLive = meterTimeToLive; } public boolean isLwcEnabled() { return this.lwcEnabled; } public void setLwcEnabled(boolean lwcEnabled) { this.lwcEnabled = lwcEnabled; } public Duration getLwcStep() { return this.lwcStep; } public void setLwcStep(Duration lwcStep) { this.lwcStep = lwcStep; } public boolean isLwcIgnorePublishStep() { return this.lwcIgnorePublishStep; } public void setLwcIgnorePublishStep(boolean lwcIgnorePublishStep) { this.lwcIgnorePublishStep = lwcIgnorePublishStep; } public Duration getConfigRefreshFrequency() { return this.configRefreshFrequency; } public void setConfigRefreshFrequency(Duration configRefreshFrequency) { this.configRefreshFrequency = configRefreshFrequency;
} public Duration getConfigTimeToLive() { return this.configTimeToLive; } public void setConfigTimeToLive(Duration configTimeToLive) { this.configTimeToLive = configTimeToLive; } public String getConfigUri() { return this.configUri; } public void setConfigUri(String configUri) { this.configUri = configUri; } public String getEvalUri() { return this.evalUri; } public void setEvalUri(String evalUri) { this.evalUri = evalUri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
2
请完成以下Java代码
public static EventDescriptor ofClientOrgUserIdAndTraceId( @NonNull final ClientAndOrgId clientAndOrgId, @NonNull final UserId userId, @Nullable final String traceId) { return builder() .eventId(newEventId()) .clientAndOrgId(clientAndOrgId) .userId(userId) .traceId(traceId) .build(); } private static String newEventId() { return UUID.randomUUID().toString(); } public ClientId getClientId() { return getClientAndOrgId().getClientId(); }
public OrgId getOrgId() { return getClientAndOrgId().getOrgId(); } @NonNull public EventDescriptor withNewEventId() { return toBuilder() .eventId(newEventId()) .build(); } @NonNull public EventDescriptor withClientAndOrg(@NonNull final ClientAndOrgId clientAndOrgId) { return toBuilder() .clientAndOrgId(clientAndOrgId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\EventDescriptor.java
1
请完成以下Java代码
private String generateRandomResult() { // // Randomly throw exception if (throwRandomException && random.nextInt(10) == 0) { throw new RuntimeException("Randomly generated exception"); } // // Generate and return a random weight final BigDecimal weight = BigDecimal.valueOf(random.nextInt(1000000)).divide(new BigDecimal("1000"), 3, RoundingMode.HALF_UP); final String resultString = createWeightString(weight); return resultString; } /** * Returns a number of predefined results in a round-robin fashion. * The result will be one of <code>450, 460, ... , 490, 450, ...</code> <b>plus</b> an instance-specific offset (e.g. for the 2nd instance, it will be <code>451, 461, ...</code>) * * @return */ private String generateSequenceResult() { synchronized (MockedEndpoint.class) { weightSequenceIdx++; if (weightSequenceIdx >= weightSequence.length) { weightSequenceIdx = 0; } final BigDecimal weighFromArray = weightSequence[weightSequenceIdx]; final BigDecimal weightToUse = weighFromArray.add(new BigDecimal(mockedEndpointInstanceNumber));
final String returnString = createWeightString(weightToUse); return returnString; } } public static String createWeightString(final BigDecimal weight) { final DecimalFormat weightFormat = new DecimalFormat("#########.000"); String weightStr = weightFormat.format(weight); while (weightStr.length() < 11) { weightStr = " " + weightStr; } final String resultString = "S S " + weightStr + " kg"; return resultString; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\endpoint\MockedEndpoint.java
1
请完成以下Java代码
public List<HistoricIncidentEntity> getCompletedHistoricIncidents(Date finishedAfter, Date finishedAt, int maxResults) { checkIsAuthorizedToReadHistoryAndTenants(); Map<String, Object> params = new HashMap<>(); params.put("finishedAfter", finishedAfter); params.put("finishedAt", finishedAt); params.put("maxResults", maxResults); return getDbEntityManager().selectList("selectCompletedHistoricIncidentsPage", params); } @SuppressWarnings("unchecked") public List<HistoricIncidentEntity> getOpenHistoricIncidents(Date createdAfter, Date createdAt, int maxResults) { checkIsAuthorizedToReadHistoryAndTenants(); Map<String, Object> params = new HashMap<>(); params.put("createdAfter", createdAfter); params.put("createdAt", createdAt); params.put("maxResults", maxResults); return getDbEntityManager().selectList("selectOpenHistoricIncidentsPage", params); } @SuppressWarnings("unchecked") public List<HistoricDecisionInstance> getHistoricDecisionInstances(Date evaluatedAfter, Date evaluatedAt, int maxResults) { checkIsAuthorizedToReadHistoryAndTenants(); Map<String, Object> params = new HashMap<>(); params.put("evaluatedAfter", evaluatedAfter); params.put("evaluatedAt", evaluatedAt); params.put("maxResults", maxResults); List<HistoricDecisionInstance> decisionInstances = getDbEntityManager().selectList("selectHistoricDecisionInstancePage", params); HistoricDecisionInstanceQueryImpl query = (HistoricDecisionInstanceQueryImpl) new HistoricDecisionInstanceQueryImpl()
.disableBinaryFetching() .disableCustomObjectDeserialization() .includeInputs() .includeOutputs(); List<List<HistoricDecisionInstance>> partitions = CollectionUtil.partition(decisionInstances, DbSqlSessionFactory.MAXIMUM_NUMBER_PARAMS); for (List<HistoricDecisionInstance> partition : partitions) { getHistoricDecisionInstanceManager() .enrichHistoricDecisionsWithInputsAndOutputs(query, partition); } return decisionInstances; } private void checkIsAuthorizedToReadHistoryAndTenants() { CompositePermissionCheck necessaryPermissionsForOptimize = new PermissionCheckBuilder() .conjunctive() .atomicCheckForResourceId(PROCESS_DEFINITION, ANY, READ_HISTORY) .atomicCheckForResourceId(DECISION_DEFINITION, ANY, READ_HISTORY) .atomicCheckForResourceId(TENANT, ANY, READ) .build(); getAuthorizationManager().checkAuthorization(necessaryPermissionsForOptimize); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\optimize\OptimizeManager.java
1
请在Spring Boot框架中完成以下Java代码
public class Child { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public Child(){} public Child(Integer id, String name){ this.id = id; this.name = name; } }
repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringMysqlhiber\src\main\java\spring\mysqlhiber\domain\Child.java
2
请完成以下Java代码
public static FacetAwareItem ofList(final Set<PickingJobFacet> facets) { if (facets.isEmpty()) { return EMPTY; } return new FacetAwareItem(facets); } public boolean hasFacets() {return !facetsByGroup.isEmpty();} public boolean isMatching(@NonNull final PickingJobQuery.Facets query) { return isMatching(customerIds, query.getCustomerIds()) && isMatching(deliveryDays, query.getDeliveryDays()) && isMatching(handoverLocationIds, query.getHandoverLocationIds()); }
private static <T> boolean isMatching(final Set<T> values, final Set<T> requiredValues) { if (requiredValues.isEmpty()) { return true; } return values.stream().anyMatch(requiredValues::contains); } public ImmutableSet<PickingJobFacet> getFacets(@NonNull final PickingJobFacetGroup group) { return facetsByGroup.get(group); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\facets\PickingJobFacetsAccumulator.java
1
请完成以下Java代码
public int getDerivedVersion() { return derivedVersion; } @Override public void setDerivedVersion(int derivedVersion) { this.derivedVersion = derivedVersion; } @Override public String getEngineVersion() { return engineVersion; } @Override public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion; } public IOSpecification getIoSpecification() { return ioSpecification; } public void setIoSpecification(IOSpecification ioSpecification) { this.ioSpecification = ioSpecification; } @Override public String toString() { return "ProcessDefinitionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java
1
请完成以下Java代码
public void setPayBankFee_Acct (final int PayBankFee_Acct) { set_Value (COLUMNNAME_PayBankFee_Acct, PayBankFee_Acct); } @Override public int getPayBankFee_Acct() { return get_ValueAsInt(COLUMNNAME_PayBankFee_Acct); } @Override public org.compiere.model.I_C_ValidCombination getPayment_WriteOff_A() { return get_ValueAsPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPayment_WriteOff_A(final org.compiere.model.I_C_ValidCombination Payment_WriteOff_A) { set_ValueFromPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, Payment_WriteOff_A); } @Override public void setPayment_WriteOff_Acct (final int Payment_WriteOff_Acct) { set_Value (COLUMNNAME_Payment_WriteOff_Acct, Payment_WriteOff_Acct); } @Override public int getPayment_WriteOff_Acct() { return get_ValueAsInt(COLUMNNAME_Payment_WriteOff_Acct); } @Override public org.compiere.model.I_C_ValidCombination getRealizedGain_A() { return get_ValueAsPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setRealizedGain_A(final org.compiere.model.I_C_ValidCombination RealizedGain_A) { set_ValueFromPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedGain_A); }
@Override public void setRealizedGain_Acct (final int RealizedGain_Acct) { set_Value (COLUMNNAME_RealizedGain_Acct, RealizedGain_Acct); } @Override public int getRealizedGain_Acct() { return get_ValueAsInt(COLUMNNAME_RealizedGain_Acct); } @Override public org.compiere.model.I_C_ValidCombination getRealizedLoss_A() { return get_ValueAsPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setRealizedLoss_A(final org.compiere.model.I_C_ValidCombination RealizedLoss_A) { set_ValueFromPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedLoss_A); } @Override public void setRealizedLoss_Acct (final int RealizedLoss_Acct) { set_Value (COLUMNNAME_RealizedLoss_Acct, RealizedLoss_Acct); } @Override public int getRealizedLoss_Acct() { return get_ValueAsInt(COLUMNNAME_RealizedLoss_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_Acct.java
1
请完成以下Java代码
public class MdcThreadPoolTaskExecutor extends ThreadPoolTaskExecutor { /** * 所有线程都会委托给这个execute方法,在这个方法中我们把父线程的MDC内容赋值给子线程 * https://logback.qos.ch/manual/mdc.html#managedThreads * * @param runnable */ @Override public void execute(Runnable runnable) { // 获取父线程MDC中的内容,必须在run方法之前,否则等异步线程执行的时候有可能MDC里面的值已经被清空了,这个时候就会返回null Map<String, String> context = MDC.getCopyOfContextMap(); super.execute(() -> run(runnable, context)); } /** * 子线程委托的执行方法 * * @param runnable {@link Runnable} * @param context 父线程MDC内容
*/ private void run(Runnable runnable, Map<String, String> context) { // 将父线程的MDC内容传给子线程 if (context != null) { try { MDC.setContextMap(context); } catch (Exception e) { logger.error(e.getMessage(), e); } } try { // 执行异步操作 runnable.run(); } finally { // 清空MDC内容 MDC.clear(); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\utils\MdcThreadPoolTaskExecutor.java
1
请在Spring Boot框架中完成以下Java代码
private static ExternalSystemConfigQRCode fromJson(@NonNull final JsonPayload json) { final ExternalSystemType externalSystemType = ExternalSystemType.ofValue(json.getExternalSystemType()); final int repoId = json.getChildConfigId(); return ExternalSystemConfigQRCode.builder() .childConfigId(toExternalSystemChildConfigId(externalSystemType, repoId)) .build(); } private static IExternalSystemChildConfigId toExternalSystemChildConfigId(final ExternalSystemType externalSystemType, final int repoId) { if (externalSystemType.isAlberta()) { return ExternalSystemAlbertaConfigId.ofRepoId(repoId); } else if (externalSystemType.isShopware6()) { return ExternalSystemShopware6ConfigId.ofRepoId(repoId); } // else if (externalSystemType.isOther()) // { // return ExternalSystemOtherConfigId.ofRepoId(repoId); // } else if (externalSystemType.isRabbitMQ()) { return ExternalSystemRabbitMQConfigId.ofRepoId(repoId); } else if (externalSystemType.isWOO()) { return ExternalSystemWooCommerceConfigId.ofRepoId(repoId);
} else if (externalSystemType.isGRSSignum()) { return ExternalSystemGRSSignumConfigId.ofRepoId(repoId); } else if (externalSystemType.isLeichUndMehl()) { return ExternalSystemLeichMehlConfigId.ofRepoId(repoId); } throw new AdempiereException("Unsupported externalSystemType: " + externalSystemType); } // // // @Value @Builder @Jacksonized public static class JsonPayload { @NonNull String externalSystemType; int childConfigId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\config\qrcode\v1\JsonConverterV1.java
2
请完成以下Java代码
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> cars) { for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) { // Notify car } } private static int sendOneTimeNotification() { System.out.println("Sending one time notification!"); return 1; } static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) { var x = cars.poll(); var y = cars.poll(); var z = cars.poll(); return x; } static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) { var car = cars.poll(); var _ = cars.poll(); var _ = cars.poll(); return car; } static void handleCarExceptionWithNamedVariables(Car<?> car) { try { someOperationThatFails(car); } catch (IllegalStateException ex) { System.out.println("Got an illegal state exception for: " + car.name()); } catch (RuntimeException ex) { System.out.println("Got a runtime exception!"); } } static void handleCarExceptionWithUnnamedVariables(Car<?> car) { try { someOperationThatFails(car); } catch (IllegalStateException | NumberFormatException _) { System.out.println("Got an illegal state exception for: " + car.name()); } catch (RuntimeException _) { System.out.println("Got a runtime exception!"); } } static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) { try (var transaction = new Transaction()) { updateCar(car); } }
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) { try (var _ = new Transaction()) { updateCar(car); } } static void updateCar(Car<?> car) { // Some update logic System.out.println("Car updated!"); } static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) { Map<String, List<Car<?>>> carMap = new HashMap<>(); cars.forEach(car -> carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car) ); return carMap; } static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) { Map<String, List<Car<?>>> carMap = new HashMap<>(); cars.forEach(car -> carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car) ); return carMap; } private static void someOperationThatFails(Car<?> car) { throw new IllegalStateException("Triggered exception for: " + car.name()); } }
repos\tutorials-master\core-java-modules\core-java-21\src\main\java\com\baeldung\unnamed\variables\UnnamedVariables.java
1
请完成以下Java代码
public void setTimes(String times) { this.times = times; } public String getTempleNumber() { return TempleNumber; } public void setTempleNumber(String templeNumber) { TempleNumber = templeNumber; } public String getPosthumousTitle() { return posthumousTitle; } public void setPosthumousTitle(String posthumousTitle) { this.posthumousTitle = posthumousTitle; } public String getSon() { return son; }
public void setSon(String son) { this.son = son; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public King getKing() { return king; } public void setKing(King king) { this.king = king; } }
repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\Queen.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Relative URL. @param RelativeURL Contains the relative URL for the container */ public void setRelativeURL (String RelativeURL) { set_Value (COLUMNNAME_RelativeURL, RelativeURL); } /** Get Relative URL. @return Contains the relative URL for the container */ public String getRelativeURL () { return (String)get_Value(COLUMNNAME_RelativeURL); } /** Set StructureXML. @param StructureXML Autogenerated Containerdefinition as XML Code */ public void setStructureXML (String StructureXML) { set_Value (COLUMNNAME_StructureXML, StructureXML); }
/** Get StructureXML. @return Autogenerated Containerdefinition as XML Code */ public String getStructureXML () { return (String)get_Value(COLUMNNAME_StructureXML); } /** Set Title. @param Title Name this entity is referred to as */ public void setTitle (String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Title. @return Name this entity is referred to as */ public String getTitle () { return (String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_CStage.java
1
请完成以下Java代码
public boolean process(final I_ESR_ImportLine line, final String message) { Check.assumeNotNull(line.getESR_Payment_Action(), "@" + ESRConstants.ERR_ESR_LINE_WITH_NO_PAYMENT_ACTION + "@"); // 08500: allocate when process final I_C_Invoice invoice = line.getC_Invoice(); final PaymentId paymentId = PaymentId.ofRepoIdOrNull(line.getC_Payment_ID()); final I_C_Payment payment = paymentId == null ? null : paymentDAO.getById(paymentId); if (invoice != null && payment != null) { if (!payment.isAllocated() && !invoice.isPaid()) { payment.setC_Invoice_ID(invoice.getC_Invoice_ID());
final BigDecimal invoiceOpenAmt = Services.get(IInvoiceDAO.class).retrieveOpenAmt(invoice); if (payment.getPayAmt().compareTo(invoiceOpenAmt) != 0) { final BigDecimal overUnderAmt = payment.getPayAmt().subtract(invoiceOpenAmt); payment.setOverUnderAmt(overUnderAmt); } InterfaceWrapperHelper.save(payment); Services.get(IESRImportBL.class).linkInvoiceToPayment(line); } } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\actionhandler\impl\AbstractESRActionHandler.java
1
请完成以下Java代码
protected abstract class AbstractPropertySourceLoggingFunction implements Function<PropertySource<?>, PropertySource<?>> { protected void logProperties(@NonNull Iterable<String> propertyNames, @NonNull Function<String, Object> propertyValueFunction) { log("Properties ["); for (String propertyName : CollectionUtils.nullSafeIterable(propertyNames)) { log("\t%1$s = %2$s", propertyName, propertyValueFunction.apply(propertyName)); } log("]"); } } protected class EnumerablePropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction { @Override public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) { if (propertySource instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource; String[] propertyNames = enumerablePropertySource.getPropertyNames(); Arrays.sort(propertyNames); logProperties(Arrays.asList(propertyNames), enumerablePropertySource::getProperty);
} return propertySource; } } // The PropertySource may not be enumerable but may use a Map as its source. protected class MapPropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction { @Override @SuppressWarnings("unchecked") public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) { if (!(propertySource instanceof EnumerablePropertySource)) { Object source = propertySource != null ? propertySource.getSource() : null; if (source instanceof Map) { Map<String, Object> map = new TreeMap<>((Map<String, Object>) source); logProperties(map.keySet(), map::get); } } return propertySource; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\logging\EnvironmentLoggingApplicationListener.java
1
请完成以下Java代码
private final boolean isValueDisplayed() { return !isValueToColumn || isValueToColumn && isValueToEnabled; } @Override public boolean isCellEditable(final EventObject e) { return true; } @Override public boolean shouldSelectCell(final EventObject e) { return isValueDisplayed(); } private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex) { final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel(); final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex); return model.getRow(modelRowIndex); } /** * Destroy existing editor. * * Very important to be called because this will also unregister the listeners from editor to underlying lookup (if any). */ private final void destroyEditor() { if (editor == null) { return; } editor.dispose(); editor = null; }
@Override public boolean stopCellEditing() { if (!super.stopCellEditing()) { return false; } destroyEditor(); return true; } @Override public void cancelCellEditing() { super.cancelCellEditing(); destroyEditor(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindValueEditor.java
1
请完成以下Java代码
public final class InvoiceCandidateGenerateResult { public static InvoiceCandidateGenerateResult of( @NonNull final IInvoiceCandidateHandler handler, @NonNull final List<? extends I_C_Invoice_Candidate> invoiceCandidates) { return new InvoiceCandidateGenerateResult(handler, invoiceCandidates); } public static InvoiceCandidateGenerateResult of( @NonNull final IInvoiceCandidateHandler handler, @Nullable final I_C_Invoice_Candidate invoiceCandidate) { if (invoiceCandidate == null) { final List<I_C_Invoice_Candidate> invoiceCandidates = ImmutableList.of(); return new InvoiceCandidateGenerateResult(handler, invoiceCandidates); } return new InvoiceCandidateGenerateResult(handler, ImmutableList.of(invoiceCandidate)); } public static InvoiceCandidateGenerateResult of(@NonNull final IInvoiceCandidateHandler handler) { final List<I_C_Invoice_Candidate> invoiceCandidates = ImmutableList.of(); return new InvoiceCandidateGenerateResult(handler, invoiceCandidates); } private final IInvoiceCandidateHandler handler; private final List<I_C_Invoice_Candidate> invoiceCandidates; private InvoiceCandidateGenerateResult( @NonNull final IInvoiceCandidateHandler handler, @NonNull final List<? extends I_C_Invoice_Candidate> invoiceCandidates)
{ this.handler = handler; this.invoiceCandidates = ImmutableList.copyOf(invoiceCandidates); } public IInvoiceCandidateHandler getHandler() { return handler; } public List<I_C_Invoice_Candidate> getC_Invoice_Candidates() { return invoiceCandidates; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\InvoiceCandidateGenerateResult.java
1
请完成以下Java代码
void removeFileSystem(NestedFileSystem fileSystem) { synchronized (this.fileSystems) { this.fileSystems.remove(fileSystem.getJarPath()); } } @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { NestedPath nestedPath = NestedPath.cast(path); return new NestedByteChannel(nestedPath.getJarPath(), nestedPath.getNestedEntryName()); } @Override public DirectoryStream<Path> newDirectoryStream(Path dir, Filter<? super Path> filter) throws IOException { throw new NotDirectoryException(NestedPath.cast(dir).toString()); } @Override public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException { throw new ReadOnlyFileSystemException(); } @Override public void delete(Path path) throws IOException { throw new ReadOnlyFileSystemException(); } @Override public void copy(Path source, Path target, CopyOption... options) throws IOException { throw new ReadOnlyFileSystemException(); } @Override public void move(Path source, Path target, CopyOption... options) throws IOException { throw new ReadOnlyFileSystemException(); } @Override public boolean isSameFile(Path path, Path path2) throws IOException { return path.equals(path2); } @Override public boolean isHidden(Path path) throws IOException { return false; } @Override public FileStore getFileStore(Path path) throws IOException {
NestedPath nestedPath = NestedPath.cast(path); nestedPath.assertExists(); return new NestedFileStore(nestedPath.getFileSystem()); } @Override public void checkAccess(Path path, AccessMode... modes) throws IOException { Path jarPath = getJarPath(path); jarPath.getFileSystem().provider().checkAccess(jarPath, modes); } @Override public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { Path jarPath = getJarPath(path); return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options); } @Override public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException { Path jarPath = getJarPath(path); return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options); } @Override public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException { Path jarPath = getJarPath(path); return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options); } protected Path getJarPath(Path path) { return NestedPath.cast(path).getJarPath(); } @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { throw new ReadOnlyFileSystemException(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java
1
请完成以下Java代码
public class MiniTableModel extends DefaultTableModel { /** * */ private static final long serialVersionUID = 1672846860594628976L; public MiniTableModel() { super(); } /** * Same as {@link DefaultTableModel#setValueAt(Object, int, int)} but is firing the event ONLY if the value was really changed. * * In case exception is thrown in firing, the value is reverted. */ @SuppressWarnings("unchecked") @Override public void setValueAt(Object aValue, int row, int column) { @SuppressWarnings("rawtypes") final Vector rowVector = (Vector)dataVector.elementAt(row); // Check if value was really changed. If not, do nothing final Object valueOld = rowVector.get(column); if (Check.equals(valueOld, aValue)) { return; }
boolean valueSet = false; try { rowVector.setElementAt(aValue, column); fireTableCellUpdated(row, column); valueSet = true; } finally { // Rollback changes if (!valueSet) { rowVector.setElementAt(valueOld, column); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\minigrid\MiniTableModel.java
1
请在Spring Boot框架中完成以下Java代码
private BeanMetadataElement extracted(Element element, ParserContext pc, NamespaceHandlerResolver resolver, Element providerElement) { String ref = providerElement.getAttribute(ATT_REF); if (!StringUtils.hasText(ref)) { BeanDefinition provider = resolver.resolve(providerElement.getNamespaceURI()).parse(providerElement, pc); Assert.notNull(provider, () -> "Parser for " + providerElement.getNodeName() + " returned a null bean definition"); String providerId = pc.getReaderContext().generateBeanName(provider); pc.registerBeanComponent(new BeanComponentDefinition(provider, providerId)); return new RuntimeBeanReference(providerId); } if (providerElement.getAttributes().getLength() > 1) { pc.getReaderContext() .error("authentication-provider element cannot be used with other attributes " + "when using 'ref' attribute", pc.extractSource(element)); } NodeList providerChildren = providerElement.getChildNodes(); for (int i = 0; i < providerChildren.getLength(); i++) { if (providerChildren.item(i) instanceof Element) { pc.getReaderContext() .error("authentication-provider element cannot have child elements when used " + "with 'ref' attribute", pc.extractSource(element)); } } return new RuntimeBeanReference(ref); } /** * Provider which doesn't provide any service. Only used to prevent a configuration * exception if the provider list is empty (usually because a child ProviderManager
* from the &lt;http&gt; namespace, such as OpenID, is expected to handle the * request). */ public static final class NullAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { return null; } @Override public boolean supports(Class<?> authentication) { return false; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\authentication\AuthenticationManagerBeanDefinitionParser.java
2
请完成以下Java代码
public void setM_IolCandHandler_Log_ID (final int M_IolCandHandler_Log_ID) { if (M_IolCandHandler_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_Log_ID, M_IolCandHandler_Log_ID); } @Override public int getM_IolCandHandler_Log_ID() { return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_Log_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID()
{ return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setStatus (final @Nullable java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_IolCandHandler_Log.java
1
请完成以下Java代码
public static LookupValuesPage allValues(@NonNull final LookupValuesList values) { return builder() .totalRows(OptionalInt.of(values.size())) // N/A .firstRow(0) // N/A .values(values) .hasMoreResults(OptionalBoolean.FALSE) .build(); } public static LookupValuesPage ofNullable(@Nullable final LookupValue lookupValue) { if (lookupValue == null) { return EMPTY;
} return allValues(LookupValuesList.fromNullable(lookupValue)); } public <T> T transform(@NonNull final Function<LookupValuesPage, T> transformation) { return transformation.apply(this); } public boolean isEmpty() { return values.isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValuesPage.java
1
请在Spring Boot框架中完成以下Java代码
public class NettyConfig { /** * 定义全局单利channel组 管理所有channel */ private static volatile ChannelGroup channelGroup = null; /** * 存放请求ID与channel的对应关系 */ private static volatile ConcurrentHashMap<String, Channel> channelMap = null; /** * 定义两把锁 */ private static final Object lock1 = new Object(); private static final Object lock2 = new Object(); public static ChannelGroup getChannelGroup() { if (null == channelGroup) { synchronized (lock1) { if (null == channelGroup) { channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); } } }
return channelGroup; } public static ConcurrentHashMap<String, Channel> getChannelMap() { if (null == channelMap) { synchronized (lock2) { if (null == channelMap) { channelMap = new ConcurrentHashMap<>(); } } } return channelMap; } public static Channel getChannel(String userId) { if (null == channelMap) { return getChannelMap().get(userId); } return channelMap.get(userId); } }
repos\springboot-demo-master\netty\src\main\java\com\et\netty\config\NettyConfig.java
2
请完成以下Spring Boot application配置
spring.datasource.url= jdbc:mysql://localhost:3306/springboot_demo?useSSL=false spring.datasource.username= root spring.datasource.password= root ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto = update ## Hibernate Logging logging.level.org.hibernate.SQL= DEBUG ## MULTIPART (MultipartProperties) # Enable multipart uploads spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk. spring.servlet.multipart.file-size-threshold=2KB # Max file size. spring.servlet.multipart.max-file-size=200MB # Max Request Size spring.servlet.multipart.max-request-size=215MB
repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-database\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderDeliveryAddress orderDeliveryAddress = (OrderDeliveryAddress) o; return Objects.equals(this.gender, orderDeliveryAddress.gender) && Objects.equals(this.title, orderDeliveryAddress.title) && Objects.equals(this.name, orderDeliveryAddress.name) && Objects.equals(this.address, orderDeliveryAddress.address) && Objects.equals(this.additionalAddress, orderDeliveryAddress.additionalAddress) && Objects.equals(this.additionalAddress2, orderDeliveryAddress.additionalAddress2) && Objects.equals(this.postalCode, orderDeliveryAddress.postalCode) && Objects.equals(this.city, orderDeliveryAddress.city); } @Override public int hashCode() { return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderDeliveryAddress {\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n"); sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java
2
请完成以下Java代码
public void deleteDeployment(String deploymentId) { getHistoricDecisionExecutionEntityManager().deleteHistoricDecisionExecutionsByDeploymentId(deploymentId); getDecisionTableEntityManager().deleteDecisionsByDeploymentId(deploymentId); getResourceEntityManager().deleteResourcesByDeploymentId(deploymentId); delete(findById(deploymentId)); } protected DecisionEntity findLatestDefinition(DmnDecision definition) { DecisionEntity latestDefinition = null; if (definition.getTenantId() != null && !DmnEngineConfiguration.NO_TENANT_ID.equals(definition.getTenantId())) { latestDefinition = getDecisionTableEntityManager() .findLatestDecisionByKeyAndTenantId(definition.getKey(), definition.getTenantId()); } else { latestDefinition = getDecisionTableEntityManager().findLatestDecisionByKey(definition.getKey()); } return latestDefinition; } @Override public long findDeploymentCountByQueryCriteria(DmnDeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentCountByQueryCriteria(deploymentQuery); } @Override public List<DmnDeployment> findDeploymentsByQueryCriteria(DmnDeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentsByQueryCriteria(deploymentQuery); } @Override public List<String> getDeploymentResourceNames(String deploymentId) {
return dataManager.getDeploymentResourceNames(deploymentId); } @Override public List<DmnDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentsByNativeQuery(parameterMap); } @Override public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentCountByNativeQuery(parameterMap); } protected DmnResourceEntityManager getResourceEntityManager() { return engineConfiguration.getResourceEntityManager(); } protected HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager() { return engineConfiguration.getHistoricDecisionExecutionEntityManager(); } protected DecisionEntityManager getDecisionTableEntityManager() { return engineConfiguration.getDecisionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DmnDeploymentEntityManagerImpl.java
1
请完成以下Java代码
public class FinishedGoodsReceiveLineId { public static final FinishedGoodsReceiveLineId FINISHED_GOODS = new FinishedGoodsReceiveLineId("finishedGoods"); public static FinishedGoodsReceiveLineId ofCOProductBOMLineId(@NonNull final PPOrderBOMLineId coProductBOMLineId) {return new FinishedGoodsReceiveLineId(PREFIX_CO_PRODUCT + coProductBOMLineId.getRepoId());} @JsonCreator public static FinishedGoodsReceiveLineId ofString(@NonNull final String string) { if (string.equals(FINISHED_GOODS.string)) { return FINISHED_GOODS; } else if (string.startsWith(PREFIX_CO_PRODUCT)) { return new FinishedGoodsReceiveLineId(string); } else { throw new AdempiereException("Invalid ID: " + string); } } private static final String PREFIX_CO_PRODUCT = "coProduct-"; private final String string;
private FinishedGoodsReceiveLineId(@NonNull final String string) { this.string = string; } @Override @Deprecated public String toString() {return toJson();} @JsonValue public String toJson() {return string;} public static boolean equals(@Nullable final FinishedGoodsReceiveLineId id1, @Nullable final FinishedGoodsReceiveLineId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\FinishedGoodsReceiveLineId.java
1
请在Spring Boot框架中完成以下Java代码
public class ShippingHeaderTypesProperties { private String headerName; private String international; private String domestic; public String getHeaderName() { return headerName; } public void setHeaderName(String headerName) { this.headerName = headerName; } public String getInternational() {
return international; } public void setInternational(String international) { this.international = international; } public String getDomestic() { return domestic; } public void setDomestic(String domestic) { this.domestic = domestic; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\conversion\configuration\ShippingHeaderTypesProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class PersonServiceImpl implements PersonService { @Autowired PersonRepository personRepository; @Autowired RedisTemplate redisTemplate; @Override @CachePut(value = "people", key = "#person.id") public Person save(Person person) { Person p = personRepository.save(person); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); return p; } @Override @CacheEvict(value = "people")//2 public void remove(Long id) { System.out.println("删除了id、key为" + id + "的数据缓存"); //这里不做实际删除操作 } /** * Cacheable * value:缓存key的前缀。 * key:缓存key的后缀。 * sync:设置如果缓存过期是不是只放一个请求去请求数据库,其他请求阻塞,默认是false。 */
@Override @Cacheable(value = "people#${select.cache.timeout:1800}#${select.cache.refresh:600}", key = "#person.id", sync = true) //3 public Person findOne(Person person, String a, String[] b, List<Long> c) { Person p = personRepository.findOne(person.getId()); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); System.out.println(redisTemplate); return p; } @Override @Cacheable(value = "people#120#120")//3 public Person findOne1() { Person p = personRepository.findOne(2L); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); return p; } @Override @Cacheable(value = "people2")//3 public Person findOne2(Person person) { Person p = personRepository.findOne(person.getId()); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); return p; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java
2
请完成以下Java代码
protected void executeSynchronous(FlowNode flowNode) { // Execution listener if (CollectionUtil.isNotEmpty(flowNode.getExecutionListeners())) { executeExecutionListeners(flowNode, ExecutionListener.EVENTNAME_START); } commandContext.getHistoryManager().recordActivityStart(execution); // Execute actual behavior ActivityBehavior activityBehavior = (ActivityBehavior) flowNode.getBehavior(); if (activityBehavior != null) { logger.debug( "Executing activityBehavior {} on activity '{}' with execution {}", activityBehavior.getClass(), flowNode.getId(), execution.getId() ); if ( Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled() ) { Context.getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createActivityEvent( ActivitiEventType.ACTIVITY_STARTED, execution, flowNode ) ); } try { activityBehavior.execute(execution); } catch (BpmnError error) { // re-throw business fault so that it can be caught by an Error Intermediate Event or Error Event Sub-Process in the process
ErrorPropagation.propagateError(error, execution); } catch (RuntimeException e) { if (LogMDC.isMDCEnabled()) { LogMDC.putMDCExecution(execution); } throw e; } } else { logger.debug("No activityBehavior on activity '{}' with execution {}", flowNode.getId(), execution.getId()); } } protected void executeAsynchronous(FlowNode flowNode) { JobEntity job = commandContext.getJobManager().createAsyncJob(execution, flowNode.isExclusive()); commandContext.getJobManager().scheduleAsyncJob(job); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\ContinueMultiInstanceOperation.java
1
请完成以下Java代码
public List<Passenger> addPassenger(Passenger passenger) { passengers.add(passenger); return passengers; } public List<Passenger> removePassenger(Passenger passenger) { passengers.remove(passenger); return passengers; } public List<Passenger> getPassengersBySource(String source) { return passengers.stream() .filter(it -> it.getSource().equals(source)) .collect(Collectors.toList()); } public List<Passenger> getPassengersByDestination(String destination) { return passengers.stream() .filter(it -> it.getDestination().equals(destination)) .collect(Collectors.toList()); }
public long getKidsCount(List<Passenger> passengerList) { return passengerList.stream() .filter(it -> (it.getAge() <= 10)) .count(); } public List<Passenger> getFinalPassengersList() { return Collections.unmodifiableList(passengers); } public List<String> getServicedCountries() { return Stream.of(Locale.getISOCountries()) .collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\listvsarraylist\ListDemo.java
1
请完成以下Java代码
public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public List<PrintPackageInfo> getPrintPackageInfos() { if (printPackageInfos == null) { return Collections.emptyList(); } return printPackageInfos; } public void setPrintPackageInfos(List<PrintPackageInfo> printPackageInfos) { this.printPackageInfos = printPackageInfos; } public String getPrintJobInstructionsID() { return printJobInstructionsID; } public void setPrintJobInstructionsID(String printJobInstructionsID) { this.printJobInstructionsID = printJobInstructionsID; } public int getCopies() { return copies; } public void setCopies(final int copies) { this.copies = copies; } @Override public String toString() { return String.format("PrintPackage [transactionId=%s, printPackageId=%s, pageCount=%s, copies=%s, format=%s, printPackageInfos=%s, printJobInstructionsID=%s]", transactionId, printPackageId, pageCount, copies, format, printPackageInfos, printJobInstructionsID); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + copies; result = prime * result + ((format == null) ? 0 : format.hashCode()); result = prime * result + pageCount; result = prime * result + ((printJobInstructionsID == null) ? 0 : printJobInstructionsID.hashCode()); result = prime * result + ((printPackageId == null) ? 0 : printPackageId.hashCode()); result = prime * result + ((printPackageInfos == null) ? 0 : printPackageInfos.hashCode()); result = prime * result + ((transactionId == null) ? 0 : transactionId.hashCode()); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrintPackage other = (PrintPackage)obj; if (copies != other.copies) return false; if (format == null) { if (other.format != null) return false; } else if (!format.equals(other.format)) return false; if (pageCount != other.pageCount) return false; if (printJobInstructionsID == null) { if (other.printJobInstructionsID != null) return false; } else if (!printJobInstructionsID.equals(other.printJobInstructionsID)) return false; if (printPackageId == null) { if (other.printPackageId != null) return false; } else if (!printPackageId.equals(other.printPackageId)) return false; if (printPackageInfos == null) { if (other.printPackageInfos != null) return false; } else if (!printPackageInfos.equals(other.printPackageInfos)) return false; if (transactionId == null) { if (other.transactionId != null) return false; } else if (!transactionId.equals(other.transactionId)) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackage.java
1
请完成以下Java代码
public LwM2mClient get(String endpoint) { try (var connection = connectionFactory.getConnection()) { byte[] data = connection.get(getKey(endpoint)); if (data == null) { return null; } else { try { return deserialize(data); } catch (Exception e) { log.warn("[{}] Failed to deserialize client from data: {}", endpoint, Hex.encodeHexString(data), e); return null; } } } } @Override public Set<LwM2mClient> getAll() { try (var connection = connectionFactory.getConnection()) { Set<LwM2mClient> clients = new HashSet<>(); ScanOptions scanOptions = ScanOptions.scanOptions().count(100).match(CLIENT_EP + "*").build(); List<Cursor<byte[]>> scans = new ArrayList<>(); if (connection instanceof RedisClusterConnection) { ((RedisClusterConnection) connection).clusterGetNodes().forEach(node -> { scans.add(((RedisClusterConnection) connection).scan(node, scanOptions)); }); } else { scans.add(connection.scan(scanOptions)); } scans.forEach(scan -> { scan.forEachRemaining(key -> { byte[] element = connection.get(key); if (element != null) { try { clients.add(deserialize(element)); } catch (Exception e) { log.warn("[{}] Failed to deserialize client from data: {}", Hex.encodeHexString(key), Hex.encodeHexString(element), e); }
} }); }); return clients; } } @Override public void put(LwM2mClient client) { if (client.getState().equals(LwM2MClientState.UNREGISTERED)) { log.error("[{}] Client is in invalid state: {}!", client.getEndpoint(), client.getState(), new Exception()); } else { try { byte[] clientSerialized = serialize(client); try (var connection = connectionFactory.getConnection()) { connection.getSet(getKey(client.getEndpoint()), clientSerialized); } } catch (Exception e) { log.warn("Failed to serialize client: {}", client, e); } } } @Override public void remove(String endpoint) { try (var connection = connectionFactory.getConnection()) { connection.del(getKey(endpoint)); } } private byte[] getKey(String endpoint) { return (CLIENT_EP + endpoint).getBytes(); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbRedisLwM2MClientStore.java
1
请完成以下Java代码
public Optional<StockQtyAndUOMQty> getQtyShipped(final I_C_OLCand olCand) { if (InterfaceWrapperHelper.isNull(olCand, I_C_OLCand.COLUMNNAME_QtyShipped)) { return Optional.empty(); } final Quantity qtyShipped = Quantity.of(olCand.getQtyShipped(), getC_UOM_Effective(olCand)); final ProductId productId = ProductId.ofRepoId(olCand.getM_Product_ID()); final Quantity qtyShippedProductUOM = uomConversionBL.convertToProductUOM(qtyShipped, productId); final StockQtyAndUOMQty.StockQtyAndUOMQtyBuilder builder = StockQtyAndUOMQty.builder() .productId(productId) .stockQty(qtyShippedProductUOM); final UomId catchWeightUomId = UomId.ofRepoIdOrNull(olCand.getQtyShipped_CatchWeight_UOM_ID()); if (catchWeightUomId != null) {
final Quantity catchWeight = Quantity.of(olCand.getQtyShipped_CatchWeight(), uomDAO.getById(catchWeightUomId)); builder.uomQty(catchWeight); } return Optional.of(builder.build()); } @Override public Optional<BigDecimal> getManualQtyInPriceUOM(final @NonNull I_C_OLCand record) { return !InterfaceWrapperHelper.isNull(record, I_C_OLCand.COLUMNNAME_ManualQtyInPriceUOM) ? Optional.of(record.getManualQtyInPriceUOM()) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\impl\OLCandEffectiveValuesBL.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { return http .authorizeExchange(exchanges -> exchanges .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") .anyExchange().authenticated()) .formLogin(formLogin -> formLogin .loginPage("/login")) .csrf(csrf -> csrf.disable()) .build(); } @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User .withUsername("user") .password(passwordEncoder().encode("password"))
.roles("USER") .build(); UserDetails admin = User .withUsername("admin") .password(passwordEncoder().encode("password")) .roles("ADMIN") .build(); return new MapReactiveUserDetailsService(user, admin); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\security\SecurityConfig.java
2
请完成以下Java代码
public PrintingQueueProcessingInfo getProcessingInfo() { return printingQueueProcessingInfo; } /** * Iterate {@link I_C_Printing_Queue}s which are not processed yet. * * IMPORTANT: items are returned in FIFO order (ordered by {@link I_C_Printing_Queue#COLUMNNAME_C_Printing_Queue_ID}) */ @Override public Iterator<I_C_Printing_Queue> createItemsIterator() { return createPrintingQueueIterator(ctx, printingQueueQuery, ITrx.TRXNAME_None); } /** * Similar to {@link #createItemsIterator()}, but retrieves an iterator about all items have the same * <ul> * <li><code>AD_Client_ID</code> * <li><code>AD_Org_ID</code> * <li><code>Copies</code> * </ul> * as the given item, but excluding the given item itself. */ @Override public Iterator<I_C_Printing_Queue> createRelatedItemsIterator(@NonNull final I_C_Printing_Queue item) { final IPrintingQueueQuery queryRelated = printingQueueQuery.copy(); queryRelated.setAD_Client_ID(item.getAD_Client_ID()); queryRelated.setAD_Org_ID(item.getAD_Org_ID()); queryRelated.setIgnoreC_Printing_Queue_ID(item.getC_Printing_Queue_ID()); queryRelated.setCopies(item.getCopies()); // 08958 return createPrintingQueueIterator(ctx, queryRelated, ITrx.TRXNAME_None); } private Iterator<I_C_Printing_Queue> createPrintingQueueIterator(final Properties ctx, final IPrintingQueueQuery queueQuery,
final String trxName) { final IQuery<I_C_Printing_Queue> query = Services.get(IPrintingDAO.class).createQuery(ctx, queueQuery, trxName); // IMPORTANT: we need to query only one item at time (BufferSize=1) because else // it could happen that we re-process again an item which was already processed but it was cached in the buffer. query.setOption(IQuery.OPTION_IteratorBufferSize, 1); final Iterator<I_C_Printing_Queue> it = query.iterate(I_C_Printing_Queue.class); return it; } @Override public String getTrxName() { // mass processing of not printed queue items shall be out of transaction return ITrx.TRXNAME_None; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\DefaultPrintingQueueSource.java
1
请完成以下Java代码
protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state, @NonNull final I_I_Pharma_Product importRecord, final boolean isInsertOnly) throws Exception { final org.compiere.model.I_M_Product existentProduct = productDAO.retrieveProductByValue(importRecord.getA00PZN()); final String operationCode = importRecord.getA00SSATZ(); if (DEACTIVATE_OPERATION_CODE.equals(operationCode) && existentProduct != null) { IFAProductImportHelper.deactivateProduct(existentProduct); return ImportRecordResult.Updated; } else if (!DEACTIVATE_OPERATION_CODE.equals(operationCode)) { final I_M_Product product; final boolean newProduct = existentProduct == null || importRecord.getM_Product_ID() <= 0; if (!newProduct && isInsertOnly) { // #4994 do not update entries return ImportRecordResult.Nothing; } if (newProduct) { product = IFAProductImportHelper.createProduct(importRecord); } else
{ product = IFAProductImportHelper.updateProduct(importRecord, existentProduct); } importRecord.setM_Product_ID(product.getM_Product_ID()); ModelValidationEngine.get().fireImportValidate(this, importRecord, importRecord.getM_Product(), IImportInterceptor.TIMING_AFTER_IMPORT); IFAProductImportHelper.importPrices(importRecord, true); return newProduct ? ImportRecordResult.Inserted : ImportRecordResult.Updated; } return ImportRecordResult.Nothing; } @Override protected void markImported(@NonNull final I_I_Pharma_Product importRecord) { //set this to Yes because in initial import we don't want the prices to be copied importRecord.setIsPriceCopied(true); importRecord.setI_IsImported(X_I_Pharma_Product.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\IFAInitialImportProcess2.java
1
请在Spring Boot框架中完成以下Java代码
public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public int getInitialSize() { return initialSize; } public void setInitialSize(int initialSize) { this.initialSize = initialSize; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public int getMaxWait() { return maxWait; } public void setMaxWait(int maxWait) { this.maxWait = maxWait; } public int getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public long getMaxEvictableIdleTimeMillis() { return maxEvictableIdleTimeMillis; } public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) { this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle;
} public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public boolean isPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } public String getConnectionProperties() { return connectionProperties; } public void setConnectionProperties(String connectionProperties) { this.connectionProperties = connectionProperties; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidConfig.java
2
请完成以下Java代码
public class CacheAwareCmmnHistoryEventProducer extends DefaultCmmnHistoryEventProducer { @Override protected HistoricCaseInstanceEventEntity loadCaseInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { final String caseInstanceId = caseExecutionEntity.getCaseInstanceId(); HistoricCaseInstanceEventEntity cachedEntity = findInCache(HistoricCaseInstanceEventEntity.class, caseInstanceId); if (cachedEntity != null) { return cachedEntity; } else { return newCaseInstanceEventEntity(caseExecutionEntity); } } @Override protected HistoricCaseActivityInstanceEventEntity loadCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { final String caseActivityInstanceId = caseExecutionEntity.getId(); HistoricCaseActivityInstanceEventEntity cachedEntity = findInCache(HistoricCaseActivityInstanceEventEntity.class, caseActivityInstanceId);
if (cachedEntity != null) { return cachedEntity; } else { return newCaseActivityInstanceEventEntity(caseExecutionEntity); } } /** find a cached entity by primary key */ protected <T extends HistoryEvent> T findInCache(Class<T> type, String id) { return Context.getCommandContext() .getDbEntityManager() .getCachedEntity(type, id); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\CacheAwareCmmnHistoryEventProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } @Override public boolean equals(Object obj) { if (this == obj) { return true;
} if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOneToManyUnidirectional\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, @Nullable final ViewProfileId profileId) { return ViewLayout.builder() .setWindowId(PickingConstants.WINDOWID_PickingView) .setCaption("Picking") // .setIncludedViewLayout(IncludedViewLayout.builder() .openOnSelect(true) .build()) // .addElementsFromViewRowClass(PackageableRow.class, viewDataType) // .build(); } /** * @param request its {@code windowId} has to me {@link PickingConstants#WINDOWID_PickingView} */ @Override public IView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = request.getViewId(); if (!PickingConstants.WINDOWID_PickingView.equals(viewId.getWindowId())) { throw new IllegalArgumentException("Invalid request's windowId: " + request); } final Set<ShipmentScheduleId> shipmentScheduleIds = extractShipmentScheduleIds(request); final PackageableRowsData rowsData = pickingViewRepo.createRowsData(viewId, shipmentScheduleIds); return PackageableView.builder() .viewId(viewId) .rowsData(rowsData)
.pickingCandidateService(pickingCandidateService) .barcodeFilterData(extractProductBarcodeFilterData(request).orElse(null)) .build(); } @Builder(builderMethodName = "createViewRequest", builderClassName = "$CreateViewRequestBuilder") private static CreateViewRequest createCreateViewRequest( @NonNull final List<ShipmentScheduleId> shipmentScheduleIds, @Nullable final ProductBarcodeFilterData barcodeFilterData) { Check.assumeNotEmpty(shipmentScheduleIds, "shipmentScheduleIds"); return CreateViewRequest.builder(PickingConstants.WINDOWID_PickingView) .setFilterOnlyIds(RepoIdAwares.asRepoIds(shipmentScheduleIds)) .setParameter(VIEWPARAM_ProductBarcodeFilterData, barcodeFilterData) .build(); } private static Set<ShipmentScheduleId> extractShipmentScheduleIds(@NonNull final CreateViewRequest request) { return request.getFilterOnlyIds() .stream() .map(ShipmentScheduleId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } private static Optional<ProductBarcodeFilterData> extractProductBarcodeFilterData(@NonNull final CreateViewRequest request) { return Optional.ofNullable(request.getParameterAs(VIEWPARAM_ProductBarcodeFilterData, ProductBarcodeFilterData.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
static class LazyTracingSpanContext implements SpanContext { private final SingletonSupplier<Tracer> tracer; LazyTracingSpanContext(ObjectProvider<Tracer> tracerProvider) { this.tracer = SingletonSupplier.of(tracerProvider::getObject); } @Override public @Nullable String getCurrentTraceId() { Span currentSpan = currentSpan(); return (currentSpan != null) ? currentSpan.context().traceId() : null; } @Override public @Nullable String getCurrentSpanId() { Span currentSpan = currentSpan(); return (currentSpan != null) ? currentSpan.context().spanId() : null; } @Override public boolean isCurrentSpanSampled() { Span currentSpan = currentSpan(); if (currentSpan == null) {
return false; } Boolean sampled = currentSpan.context().sampled(); return sampled != null && sampled; } @Override public void markCurrentSpanAsExemplar() { } private @Nullable Span currentSpan() { return this.tracer.obtain().currentSpan(); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\prometheus\PrometheusExemplarsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public final class WebMvcObservationAutoConfiguration { @Bean @ConditionalOnMissingFilterBean FilterRegistrationBean<ServerHttpObservationFilter> webMvcObservationFilter(ObservationRegistry registry, ObjectProvider<ServerRequestObservationConvention> customConvention, ObservationProperties observationProperties) { String name = observationProperties.getHttp().getServer().getRequests().getName(); ServerRequestObservationConvention convention = customConvention .getIfAvailable(() -> new DefaultServerRequestObservationConvention(name)); ServerHttpObservationFilter filter = new ServerHttpObservationFilter(registry, convention); FilterRegistrationBean<ServerHttpObservationFilter> registration = new FilterRegistrationBean<>(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC); return registration; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(MeterRegistry.class)
@ConditionalOnBean(MeterRegistry.class) static class MeterFilterConfiguration { @Bean @Order(0) MaximumAllowableTagsMeterFilter metricsHttpServerUriTagFilter(ObservationProperties observationProperties, MetricsProperties metricsProperties) { String meterNamePrefix = observationProperties.getHttp().getServer().getRequests().getName(); int maxUriTags = metricsProperties.getWeb().getServer().getMaxUriTags(); return new MaximumAllowableTagsMeterFilter(meterNamePrefix, "uri", maxUriTags); } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\WebMvcObservationAutoConfiguration.java
2
请完成以下Java代码
public int assignAsyncBatchForProcessing(@NonNull final AsyncBatchId asyncBatchId) { return dao.assignAsyncBatchForProcessing(getQueuePackageProcessorIds(), asyncBatchId); } @NonNull private Optional<IQuery<I_C_Queue_WorkPackage>> createQuery(final Properties workPackageCtx) { return createQuery(workPackageCtx, QueryLimit.NO_LIMIT); } /** * Gets the priority to be used for new workpackages.<br> * If there is a thread inherited priority available, then that one is returned (task 06283). Otherwise, the given <code>defaultPrio</code> is returned. * * @return default priority; never returns null */ private String getPriorityForNewWorkpackage(final IWorkpackagePrioStrategy defaultPrio) { // // Use the one from thread context (if any) final String priority = contextFactory.getThreadInheritedPriority(); if (!Check.isEmpty(priority, true)) { return priority; } // // No priority set => return automatic priority return defaultPrio.getPrioriy(this); } @Override public String getEnquingPackageProcessorInternalName() { Check.errorIf(Check.isEmpty(enquingPackageProcessorInternalName, true), UnsupportedOperationException.class, "Queue {} has no EnqueuingProcessorInternalName. It was problably not intended for enqueuing, but for queue processing", this); return enquingPackageProcessorInternalName; } @Override public IWorkPackageBuilder newWorkPackage()
{ return newWorkPackage(ctx); } @Override public IWorkPackageBuilder newWorkPackage(final Properties context) { if (enquingPackageProcessorId == null) { throw new IllegalStateException("Enquing not allowed"); } return new WorkPackageBuilder(context, this, enquingPackageProcessorId); } @NonNull public Set<QueuePackageProcessorId> getQueuePackageProcessorIds() { return packageProcessorIds; } @Override public QueueProcessorId getQueueProcessorId() { return queueProcessorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQueue.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { dispose(); } // actionPerformed /** * Add change log menu item * * @param l * @param popupMenu * @return CMenuItem */ public static CMenuItem addMenu(ActionListener l, JPopupMenu popupMenu) { CMenuItem mi = new CMenuItem(Msg.getElement(Env.getCtx(), "AD_ChangeLog_ID"), s_icon); mi.setActionCommand(CHANGE_LOG_COMMAND); mi.addActionListener(l);
popupMenu.add(mi); return mi; } // addMenu /** * Open field record info dialog * * @param mField */ public static void start(GridField mField) { int WindowNo = mField.getWindowNo(); Frame frame = Env.getWindow(WindowNo); new FieldRecordInfo(frame, mField.getColumnName(), mField.getGridTab().getAD_Table_ID(), mField.getAD_Column_ID(), mField.getGridTab().getRecord_ID()); } } // FieldRecordInfo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\FieldRecordInfo.java
1
请完成以下Java代码
public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace) { set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace); } @Override public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_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 setIsModifyPrice (final boolean IsModifyPrice) { set_Value (COLUMNNAME_IsModifyPrice, IsModifyPrice); } @Override public boolean isModifyPrice() { return get_ValueAsBoolean(COLUMNNAME_IsModifyPrice); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override
public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_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); } /** * POSPaymentProcessor AD_Reference_ID=541896 * Reference name: POSPaymentProcessor */ public static final int POSPAYMENTPROCESSOR_AD_Reference_ID=541896; /** SumUp = sumup */ public static final String POSPAYMENTPROCESSOR_SumUp = "sumup"; @Override public void setPOSPaymentProcessor (final @Nullable java.lang.String POSPaymentProcessor) { set_Value (COLUMNNAME_POSPaymentProcessor, POSPaymentProcessor); } @Override public java.lang.String getPOSPaymentProcessor() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessor); } @Override public void setPrinterName (final @Nullable java.lang.String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } @Override public java.lang.String getPrinterName() { return get_ValueAsString(COLUMNNAME_PrinterName); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POS.java
1
请在Spring Boot框架中完成以下Java代码
public CommandLineRunner commandLineRunner() { return useJdbcClient(); } private CommandLineRunner useJdbcTemplate() { return (args) -> { log.info("using JdbcTemplate..."); BeanPropertyRowMapper<UserDO> rowMapper = new BeanPropertyRowMapper<>(UserDO.class); UserDO userDO = jdbcTemplate.queryForObject("select * from t_user where id = 2", rowMapper); log.info("user info : {}", userDO); List<UserDO> userDOList = jdbcTemplate.query("select * from t_user", rowMapper); log.info("user list: {}", userDOList); // 测试事务回滚 // userDao.update(); }; }
private CommandLineRunner useJdbcClient() { return (args) -> { log.info("using JdbcClient..."); UserDO userDO = jdbcClient.sql("select username from t_user where id = ?") .param(2L) .query(UserDO.class) .single(); log.info("user info : {}", userDO); List<UserDO> userDOList = jdbcClient.sql("select * from t_user") .query(UserDO.class) .list(); log.info("user list: {}", userDOList); }; } }
repos\spring-boot-best-practice-master\spring-boot-datasource\src\main\java\cn\javastack\springboot\ds\Application.java
2
请完成以下Java代码
protected Map<String, Long> reportMetrics() { Map<String, Long> reports = new HashMap<>(); DbOperation deleteOperationProcessInstance = deleteOperations.get(HistoricProcessInstanceEntity.class); if (deleteOperationProcessInstance != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_PROCESS_INSTANCES, (long) deleteOperationProcessInstance.getRowsAffected()); } DbOperation deleteOperationDecisionInstance = deleteOperations.get(HistoricDecisionInstanceEntity.class); if (deleteOperationDecisionInstance != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_DECISION_INSTANCES, (long) deleteOperationDecisionInstance.getRowsAffected()); } DbOperation deleteOperationBatch = deleteOperations.get(HistoricBatchEntity.class); if (deleteOperationBatch != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_BATCH_OPERATIONS, (long) deleteOperationBatch.getRowsAffected()); } DbOperation deleteOperationTaskMetric = deleteOperations.get(TaskMeterLogEntity.class); if (deleteOperationTaskMetric != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_TASK_METRICS, (long) deleteOperationTaskMetric.getRowsAffected()); } return reports; } protected boolean isDmnEnabled() { return Context .getProcessEngineConfiguration() .isDmnEnabled(); } protected Integer getTaskMetricsTimeToLive() { return Context .getProcessEngineConfiguration() .getParsedTaskMetricsTimeToLive();
} protected boolean shouldRescheduleNow() { int batchSize = getBatchSize(); for (DbOperation deleteOperation : deleteOperations.values()) { if (deleteOperation.getRowsAffected() == batchSize) { return true; } } return false; } public int getBatchSize() { return Context .getProcessEngineConfiguration() .getHistoryCleanupBatchSize(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupRemovalTime.java
1
请在Spring Boot框架中完成以下Java代码
public ConcurrentKafkaListenerContainerFactory<String, String> filterKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = kafkaListenerContainerFactory("filter"); factory.setRecordFilterStrategy(record -> record.value() .contains("World")); return factory; } public ConsumerFactory<String, Greeting> greetingConsumerFactory() { Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.GROUP_ID_CONFIG, "greeting"); return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(Greeting.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Greeting> greetingKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Greeting> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(greetingConsumerFactory()); return factory; } @Bean public RecordMessageConverter multiTypeConverter() { StringJsonMessageConverter converter = new StringJsonMessageConverter(); DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper(); typeMapper.setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence.TYPE_ID); typeMapper.addTrustedPackages("com.baeldung.spring.kafka"); Map<String, Class<?>> mappings = new HashMap<>(); mappings.put("greeting", Greeting.class); mappings.put("farewell", Farewell.class); typeMapper.setIdClassMapping(mappings); converter.setTypeMapper(typeMapper); return converter; } @Bean
public ConsumerFactory<String, Object> multiTypeConsumerFactory() { HashMap<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Object> multiTypeKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(multiTypeConsumerFactory()); factory.setRecordMessageConverter(multiTypeConverter()); return factory; } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\spring\kafka\KafkaConsumerConfig.java
2
请完成以下Java代码
public OrderCost execute() { final ImmutableList<OrderCostDetail> details = createOrderCostDetails(); final OrderCostType costType = costTypeRepository.getById(request.getCostTypeId()); final OrderId orderId = request.getOrderId(); final I_C_Order order = orderBL.getById(orderId); final OrderCost orderCost = OrderCost.builder() .orderId(orderId) .soTrx(SOTrx.ofBoolean(order.isSOTrx())) .orgId(OrgId.ofRepoId(order.getAD_Org_ID())) .bpartnerId(request.getBpartnerId()) .costElementId(costType.getCostElementId()) .costTypeId(costType.getId()) .calculationMethod(costType.getCalculationMethod()) .calculationMethodParams(request.getCostCalculationMethodParams()) .distributionMethod(costType.getDistributionMethod()) .details(details) .build(); orderCost.updateCostAmount(moneyService::getStdPrecision, uomConverter); createOrderLineIfNeeded(order, orderCost); orderCostRepository.save(orderCost); return orderCost; } private ImmutableList<OrderCostDetail> createOrderCostDetails() { final ImmutableSet<OrderAndLineId> orderAndLineIds = request.getOrderAndLineIds(); if (orderAndLineIds.isEmpty()) { throw new AdempiereException("No order lines provided"); } // Make sure all lines are from a single order CollectionUtils.extractSingleElement(orderAndLineIds, OrderAndLineId::getOrderId); // Do not allow order lines created by other costs // Maybe in future we will support it, but now, that's the simplest way to avoid recursion. final ImmutableSet<OrderLineId> orderLineIds = orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet()); if (orderCostRepository.hasCostsByCreatedOrderLineIds(orderLineIds)) { throw new AdempiereException("Cannot use order lines which were created by other costs");
} return orderBL.getLinesByIds(orderAndLineIds) .values() .stream() .sorted(Comparator.comparing(I_C_OrderLine::getLine)) .map(OrderCostCreateCommand::toOrderCostDetail) .collect(ImmutableList.toImmutableList()); } private static OrderCostDetail toOrderCostDetail(final I_C_OrderLine orderLine) { return OrderCostDetail.builder() .orderLineInfo(OrderCostDetailOrderLinePart.ofOrderLine(orderLine)) .build(); } public void createOrderLineIfNeeded(final I_C_Order order, final OrderCost orderCost) { final OrderCostCreateRequest.OrderLine addOrderLineRequest = request.getAddOrderLine(); if (addOrderLineRequest == null) { return; } final OrderAndLineId createdOrderAndLineId = CreateOrUpdateOrderLineFromOrderCostCommand.builder() .orderBL(orderBL) .moneyService(moneyService) .orderCost(orderCost) .productId(addOrderLineRequest.getProductId()) .loadedOrder(order) .build() .execute(); orderCost.setCreatedOrderLineId(createdOrderAndLineId.getOrderLineId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostCreateCommand.java
1
请完成以下Java代码
public void setIsRemitTo (final boolean IsRemitTo) { set_Value (COLUMNNAME_IsRemitTo, IsRemitTo); } @Override public boolean isRemitTo() { return get_ValueAsBoolean(COLUMNNAME_IsRemitTo); } @Override public void setIsReplicationLookupDefault (final boolean IsReplicationLookupDefault) { set_Value (COLUMNNAME_IsReplicationLookupDefault, IsReplicationLookupDefault); } @Override public boolean isReplicationLookupDefault() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationLookupDefault); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setIsShipToDefault (final boolean IsShipToDefault) { set_Value (COLUMNNAME_IsShipToDefault, IsShipToDefault); } @Override public boolean isShipToDefault() { return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault); } @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 setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone);
} @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java
1
请完成以下Java代码
public void validateBankAccountCurrency(final I_C_PaySelection paySelection) { final I_C_BP_BankAccount bankAccount = InterfaceWrapperHelper.create(paySelection.getC_BP_BankAccount(), I_C_BP_BankAccount.class); final List<I_C_PaySelectionLine> paySelectionLines = Services.get(IPaySelectionDAO.class).retrievePaySelectionLines(paySelection); if (paySelectionLines.isEmpty()) { return; } for (final I_C_PaySelectionLine paySelectionLine : paySelectionLines) { final I_C_Invoice invoice = paySelectionLine.getC_Invoice(); // // Match currency if (invoice.getC_Currency_ID() == bankAccount.getC_Currency_ID()) { continue; } final CurrencyCode invoiceCurrencyCode = getCurrencyCodeById(invoice.getC_Currency_ID()); final CurrencyCode bankAccountCurrencyCode = getCurrencyCodeById(bankAccount.getC_Currency_ID()); throw new AdempiereException(MSG_PaySelection_CannotChangeBPBankAccount_InvalidCurrency, new Object[] { paySelection.getName(), // name of the record we deal with bankAccountCurrencyCode.toThreeLetterCode(), // BPBA Actual Currency (actual) invoiceCurrencyCode.toThreeLetterCode() }); // Invoice Currency (expected) } } private CurrencyCode getCurrencyCodeById(final int currencyRepoId) { final ICurrencyDAO currenciesRepo = Services.get(ICurrencyDAO.class); return currenciesRepo.getCurrencyCodeById(CurrencyId.ofRepoId(currencyRepoId)); } /** * Updates the pay selection's name if paydate or the bank account are changed. the name is set to be <PayDate>_<Bank>_<Currency>. * * @param paySelection * @task 08267 */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_PaySelection.COLUMNNAME_C_BP_BankAccount_ID, I_C_PaySelection.COLUMNNAME_PayDate }) public void updateNameIfNotSet(final I_C_PaySelection paySelection) { final StringBuilder name = new StringBuilder(); if (paySelection.getPayDate() != null) { final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final String formattedDate = dateFormat.format(paySelection.getPayDate()); name.append(formattedDate); } if (name.length() > 0) { name.append("_"); } final BankAccountId bankAccountId = BankAccountId.ofRepoIdOrNull(paySelection.getC_BP_BankAccount_ID()); if (bankAccountId != null) { final String bankAccountName = bankAccountService.createBankAccountName(bankAccountId); name.append(bankAccountName); } if (name.length() > 0 && !paySelection.getName().startsWith(name.toString())) { paySelection.setName(name.toString()); } } // TODO: Fix this in the followup https://github.com/metasfresh/metasfresh/issues/2841 // @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) // public void createPayments(final I_C_PaySelection paySelection) // { // Services.get(IPaySelectionBL.class).createPayments(paySelection); // } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_PaySelection.java
1
请完成以下Java代码
public class TimerCancelledListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNTimerCancelledEvent>> processRuntimeEventListeners; private ToTimerCancelledConverter converter; public TimerCancelledListenerDelegate( List<BPMNElementEventListener<BPMNTimerCancelledEvent>> processRuntimeEventListeners, ToTimerCancelledConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override
public void onEvent(ActivitiEvent event) { converter .from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerCancelledEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TimerCancelledListenerDelegate.java
1
请完成以下Java代码
public final class ALoginRes_da extends ListResourceBundle { // TODO Run native2ascii to convert to plain ASCII !! /** Translation Content */ static final Object[][] contents = new String[][] { { "Connection", "Forbindelse" }, { "Defaults", "Basis" }, { "Login", "ADempiere: Log på" }, { "File", "Fil" }, { "Exit", "Afslut" }, { "Help", "Hjælp" }, { "About", "Om" }, { "Host", "Vært" }, { "Database", "Database" }, { "User", "Bruger-ID" }, { "EnterUser", "Angiv bruger-ID til program" }, { "Password", "Adgangskode" }, { "EnterPassword", "Angiv adgangskode til program" }, { "Language", "Sprog" }, { "SelectLanguage", "Vælg sprog" }, { "Role", "Rolle" }, { "Client", "Firma" }, { "Organization", "Organisation" }, { "Date", "Dato" }, { "Warehouse", "Lager" }, { "Printer", "Printer" }, { "Connected", "Forbindelse OK" },
{ "NotConnected", "Ingen forbindelse" }, { "DatabaseNotFound", "Database blev ikke fundet" }, { "UserPwdError", "Forkert bruger til adgangskode" }, { "RoleNotFound", "Rolle blev ikke fundet/afsluttet" }, { "Authorized", "Tilladelse OK" }, { "Ok", "OK" }, { "Cancel", "Annullér" }, { "VersionConflict", "Konflikt:" }, { "VersionInfo", "Server <> Klient" }, { "PleaseUpgrade", "Kør opdateringsprogram" } }; /** * Get Contents * @return context */ public Object[][] getContents() { return contents; } // getContents } // ALoginRes_da // ALoginRes-da
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_da.java
1
请完成以下Java代码
public static boolean isOldValues(final Object model) { final POWrapper wrapper = getPOWrapperOrNull(model); return wrapper != null && wrapper.useOldValues; } @Nullable public static IModelInternalAccessor getModelInternalAccessor(@NonNull final Object model) { if (model instanceof PO) { final PO po = (PO)model; return new POModelInternalAccessor(po); } final POWrapper wrapper = getPOWrapperOrNull(model); if (wrapper != null) { return wrapper.modelInternalAccessor; } return null; } /** * {@link POWrapper} internal accessor implementation */ private final IModelInternalAccessor modelInternalAccessor = new IModelInternalAccessor() { @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { POWrapper.this.setValueFromPO(idColumnName, parameterType, value); } @Override public boolean setValue(final String columnName, final Object value) { return POWrapper.this.setValue(columnName, value); } @Override public boolean setValueNoCheck(final String columnName, final Object value) { return POWrapper.this.setValueNoCheck(columnName, value); } ; @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { return POWrapper.this.invokeParent(method, methodArgs); } @Override public boolean invokeEquals(final Object[] methodArgs) { return POWrapper.this.invokeEquals(methodArgs); } @Override public Object getValue(final String columnName, final int idx, final Class<?> returnType) { return POWrapper.this.getValue(columnName, idx, returnType); } @Override public Object getValue(final String columnName, final Class<?> returnType) {
final int columnIndex = POWrapper.this.getColumnIndex(columnName); return POWrapper.this.getValue(columnName, columnIndex, returnType); } @Override public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception { return POWrapper.this.getReferencedObject(columnName, interfaceMethod); } @Override public Set<String> getColumnNames() { return POWrapper.this.getColumnNames(); } @Override public int getColumnIndex(final String columnName) { return POWrapper.this.getColumnIndex(columnName); } @Override public boolean isVirtualColumn(final String columnName) { return POWrapper.this.isVirtualColumn(columnName); } @Override public boolean isKeyColumnName(final String columnName) { return POWrapper.this.isKeyColumnName(columnName); } ; @Override public boolean isCalculated(final String columnName) { return POWrapper.this.isCalculated(columnName); } @Override public boolean hasColumnName(final String columnName) { return POWrapper.this.hasColumnName(columnName); } }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\POWrapper.java
1
请完成以下Java代码
public final void setNString(final int parameterIndex, final String value) throws SQLException { traceSqlParam(parameterIndex, value); delegate.setNString(parameterIndex, value); } @Override public final ResultSet executeQuery() throws SQLException { return trace(() -> delegate.executeQuery()); } @Override public ResultSet executeQueryAndLogMigationScripts() throws SQLException { return trace(() -> delegate.executeQueryAndLogMigationScripts()); } @Override public final int executeUpdate() throws SQLException { return trace(() -> delegate.executeUpdate()); } @Override public final void clearParameters() throws SQLException { delegate.clearParameters(); } @Override
public final boolean execute() throws SQLException { return trace(() -> delegate.execute()); } @Override public final void addBatch() throws SQLException { trace(() -> { delegate.addBatch(); return null; }); } @Override public final ResultSetMetaData getMetaData() throws SQLException { return delegate.getMetaData(); } @Override public final ParameterMetaData getParameterMetaData() throws SQLException { return delegate.getParameterMetaData(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingPreparedStatement.java
1
请完成以下Java代码
public int characteristics() { return Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.CONCURRENT; } } /** * Returns a {@link Spliterator} over the elements in this queue. * * <p>The returned spliterator is * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT}, * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}. * * @return a {@code Spliterator} over the elements in this queue * @implNote The {@code Spliterator} implements {@code trySplit} to permit limited * parallelism. * @since 1.8 */ @Override public Spliterator<E> spliterator() { return new CLQSpliterator<E>(this); } /** * Throws NullPointerException if argument is null. * * @param v the element */ private static void checkNotNull(Object v) { if (v == null) throw new NullPointerException(); } private boolean casTail(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); } private boolean casHead(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); }
// Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long headOffset; private static final long tailOffset; static { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); UNSAFE = (Unsafe) f.get(null); Class<?> k = ConcurrentLinkedQueue.class; headOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("head")); tailOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("tail")); } catch (Exception e) { throw new Error(e); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ConcurrentLinkedQueue.java
1
请在Spring Boot框架中完成以下Java代码
CsrfRequestDataValueProcessor requestDataValueProcessor() { return new CsrfRequestDataValueProcessor(); } @Bean static RsaKeyConversionServicePostProcessor conversionServicePostProcessor() { return new RsaKeyConversionServicePostProcessor(); } private List<SecurityWebFilterChain> getSecurityWebFilterChains() { List<SecurityWebFilterChain> result = this.securityWebFilterChains; if (ObjectUtils.isEmpty(result)) { return Arrays.asList(springSecurityFilterChain()); } return result; } private SecurityWebFilterChain springSecurityFilterChain() { ServerHttpSecurity http = this.context.getBean(ServerHttpSecurity.class); return springSecurityFilterChain(http); } /** * The default {@link ServerHttpSecurity} configuration. * @param http * @return */ private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated()); if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) { OAuth2ClasspathGuard.configure(this.context, http); } else { http.httpBasic(withDefaults()); http.formLogin(withDefaults()); }
SecurityWebFilterChain result = http.build(); return result; } private static class OAuth2ClasspathGuard { static void configure(ApplicationContext context, ServerHttpSecurity http) { http.oauth2Login(withDefaults()); http.oauth2Client(withDefaults()); } static boolean shouldConfigure(ApplicationContext context) { ClassLoader loader = context.getClassLoader(); Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\WebFluxSecurityConfiguration.java
2
请完成以下Java代码
public class MCharge extends X_C_Charge { /** * */ private static final long serialVersionUID = 630271473830196435L; /** * Get Charge Account * @param C_Charge_ID charge * @param as account schema * @param amount amount for expense(+)/revenue(-) * @return Charge Account or null */ public static MAccount getAccount (int C_Charge_ID, AcctSchemaId acctSchemaId, BigDecimal amount) { if (C_Charge_ID == 0 || acctSchemaId == null) return null; String acctName = X_C_Charge_Acct.COLUMNNAME_Ch_Expense_Acct; // Expense (positive amt) if (amount != null && amount.signum() < 0) acctName = X_C_Charge_Acct.COLUMNNAME_Ch_Revenue_Acct; // Revenue (negative amt) String sql = "SELECT "+acctName+" FROM C_Charge_Acct WHERE C_Charge_ID=? AND C_AcctSchema_ID=?"; int Account_ID = DB.getSQLValueEx(null, sql, C_Charge_ID, acctSchemaId); // No account if (Account_ID <= 0) { s_log.error("NO account for C_Charge_ID=" + C_Charge_ID); return null; } // Return Account MAccount acct = Services.get(IAccountDAO.class).getById(Account_ID); return acct; } // getAccount /** * Get MCharge from Cache * @param ctx context * @param C_Charge_ID id * @return MCharge */ public static MCharge get (Properties ctx, int C_Charge_ID) { Integer key = new Integer (C_Charge_ID); MCharge retValue = s_cache.get (key); if (retValue != null) return retValue; retValue = new MCharge (ctx, C_Charge_ID, null); if (retValue.get_ID() != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MCharge> s_cache = new CCache<> ("C_Charge", 10); /** Static Logger */ private static Logger s_log = LogManager.getLogger(MCharge.class); /**************************************************************************
* Standard Constructor * @param ctx context * @param C_Charge_ID id * @param trxName transaction */ public MCharge (Properties ctx, int C_Charge_ID, String trxName) { super (ctx, C_Charge_ID, trxName); if (C_Charge_ID == 0) { setChargeAmt (Env.ZERO); setIsSameCurrency (false); setIsSameTax (false); setIsTaxIncluded (false); // N // setName (null); // setC_TaxCategory_ID (0); } } // MCharge /** * Load Constructor * @param ctx ctx * @param rs result set * @param trxName transaction */ public MCharge (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MCharge /** * After Save * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave (boolean newRecord, boolean success) { if (newRecord && success) insert_Accounting("C_Charge_Acct", "C_AcctSchema_Default", null); return success; } // afterSave /** * Before Delete * @return true */ @Override protected boolean beforeDelete () { return delete_Accounting("C_Charge_Acct"); } // beforeDelete } // MCharge
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MCharge.java
1
请完成以下Java代码
private List<ImmutableAttributeSet.Builder> recurse( final int currendAttributeIdIdx, @NonNull final List<AttributeId> attributeIds, @NonNull final MultiValueMap<AttributeId, AttributeListValue> attributeId2Values, @NonNull final ImmutableAttributeSet.Builder builder) { final LinkedList<ImmutableAttributeSet.Builder> result = new LinkedList<>(); final AttributeId currentAttributeId = attributeIds.get(currendAttributeIdIdx); final List<AttributeListValue> valuesForCurrentAttribute = attributeId2Values.get(currentAttributeId); for (final AttributeListValue attributeListValue : valuesForCurrentAttribute) { final ImmutableAttributeSet.Builder copy = builder.createCopy(); copy.attributeValue(attributeListValue); final int nextAttributeIdIdx = currendAttributeIdIdx + 1;
final boolean listContainsMore = attributeIds.size() > nextAttributeIdIdx; if (listContainsMore) { result.addAll(recurse(nextAttributeIdIdx, attributeIds, attributeId2Values, copy)); } else { result.add(copy); } } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\CreateAllAttributeSetsCommand.java
1
请在Spring Boot框架中完成以下Java代码
public XMLGregorianCalendar getStartDate() { return startDate; } /** * Sets the value of the startDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setStartDate(XMLGregorianCalendar value) { this.startDate = value; } /** * Gets the value of the endDate property. * * @return * possible object is * {@link XMLGregorianCalendar }
* */ public XMLGregorianCalendar getEndDate() { return endDate; } /** * Sets the value of the endDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setEndDate(XMLGregorianCalendar value) { this.endDate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ExtendedPeriodType.java
2
请完成以下Java代码
protected final I_C_Queue_WorkPackage getC_Queue_WorkPackage() { Check.assumeNotNull(workpackage, "workpackage not null"); return this.workpackage; } @NonNull protected final QueueWorkPackageId getQueueWorkPackageId() { Check.assumeNotNull(workpackage, "workpackage not null"); return QueueWorkPackageId.ofRepoId(this.workpackage.getC_Queue_WorkPackage_ID()); } /** * @return <code>true</code>, i.e. ask the executor to run this processor in transaction (backward compatibility) */ @Override public boolean isRunInTransaction() { return true; } @Override public boolean isAllowRetryOnError() { return true; } @Override public final Optional<ILock> getElementsLock() { final String elementsLockOwnerName = getParameters().getParameterAsString(PARAMETERNAME_ElementsLockOwner); if (Check.isBlank(elementsLockOwnerName)) { return Optional.empty(); // no lock was created for this workpackage } final LockOwner elementsLockOwner = LockOwner.forOwnerName(elementsLockOwnerName); try { final ILock existingLockForOwner = Services.get(ILockManager.class).getExistingLockForOwner(elementsLockOwner); return Optional.of(existingLockForOwner); }
catch (final LockFailedException e) { // this can happen, if e.g. there was a restart, or if the WP was flagged as error once Loggables.addLog("Missing lock for ownerName={}; was probably cleaned up meanwhile", elementsLockOwnerName); return Optional.empty(); } } /** * Returns the {@link NullLatchStrategy}. */ @Override public ILatchStragegy getLatchStrategy() { return NullLatchStrategy.INSTANCE; } public final <T> List<T> retrieveItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(getC_Queue_WorkPackage(), modelType); } /** * Retrieves all active POs, even the ones that are caught in other packages */ public final <T> List<T> retrieveAllItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItems(getC_Queue_WorkPackage(), modelType); } public final List<I_C_Queue_Element> retrieveQueueElements(final boolean skipAlreadyScheduledItems) { return Services.get(IQueueDAO.class).retrieveQueueElements(getC_Queue_WorkPackage(), skipAlreadyScheduledItems); } /** * retrieves all active PO's IDs, even the ones that are caught in other packages */ public final Set<Integer> retrieveAllItemIds() { return Services.get(IQueueDAO.class).retrieveAllItemIds(getC_Queue_WorkPackage()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackageProcessorAdapter.java
1
请完成以下Java代码
public void updateLockTime(String caseInstanceId, Date lockDate, String lockOwner, Date expirationTime) { HashMap<String, Object> params = new HashMap<>(); params.put("id", caseInstanceId); params.put("lockTime", lockDate); params.put("expirationTime", expirationTime); params.put("lockOwner", lockOwner); int result = getDbSqlSession().directUpdate("updateCaseInstanceLockTime", params); if (result == 0) { throw new FlowableOptimisticLockingException("Could not lock case instance"); } } @Override public void clearLockTime(String caseInstanceId) { HashMap<String, Object> params = new HashMap<>(); params.put("id", caseInstanceId); getDbSqlSession().directUpdate("clearCaseInstanceLockTime", params); } @Override public void clearAllLockTimes(String lockOwner) { HashMap<String, Object> params = new HashMap<>(); params.put("lockOwner", lockOwner); getDbSqlSession().directUpdate("clearAllCaseInstanceLockTimes", params); }
protected void setSafeInValueLists(CaseInstanceQueryImpl caseInstanceQuery) { if (caseInstanceQuery.getCaseInstanceIds() != null) { caseInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(caseInstanceQuery.getCaseInstanceIds())); } if (caseInstanceQuery.getInvolvedGroups() != null) { caseInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(caseInstanceQuery.getInvolvedGroups())); } if (caseInstanceQuery.getOrQueryObjects() != null && !caseInstanceQuery.getOrQueryObjects().isEmpty()) { for (CaseInstanceQueryImpl orCaseInstanceQuery : caseInstanceQuery.getOrQueryObjects()) { setSafeInValueLists(orCaseInstanceQuery); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisCaseInstanceDataManagerImpl.java
1
请完成以下Java代码
public class Bestellen { @XmlElement(namespace = "", required = true) protected String clientSoftwareKennung; @XmlElement(namespace = "", required = true) protected Bestellung bestellung; /** * Gets the value of the clientSoftwareKennung property. * * @return * possible object is * {@link String } * */ public String getClientSoftwareKennung() { return clientSoftwareKennung; } /** * Sets the value of the clientSoftwareKennung property. * * @param value * allowed object is * {@link String } * */ public void setClientSoftwareKennung(String value) { this.clientSoftwareKennung = value; } /** * Gets the value of the bestellung property. * * @return * possible object is
* {@link Bestellung } * */ public Bestellung getBestellung() { return bestellung; } /** * Sets the value of the bestellung property. * * @param value * allowed object is * {@link Bestellung } * */ public void setBestellung(Bestellung value) { this.bestellung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\Bestellen.java
1
请完成以下Spring Boot application配置
spring: application: name: dubbo-registry-nacos-consumer-sample demo: service: version: 1.0.0 nacos: host: 127.0.0.1 port: 8848 username: nacos password: nacos dubbo: registry: address
: nacos://${nacos.host}:${nacos.port}/?username=${nacos.username}&password=${nacos.password}
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-samples\registry-samples\nacos-samples\consumer-sample\src\main\resources\application.yml
2
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Product_TaxCategory_ID (final int M_Product_TaxCategory_ID) { if (M_Product_TaxCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, M_Product_TaxCategory_ID); } @Override public int getM_Product_TaxCategory_ID() {
return get_ValueAsInt(COLUMNNAME_M_Product_TaxCategory_ID); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_TaxCategory.java
1
请完成以下Java代码
public class ExcelCreator { public static HSSFWorkbook createSampleWorkbook() { HSSFWorkbook workbook = new HSSFWorkbook(); final String SHEET_NAME = "Employees"; final String[] COLUMN_HEADERS = { "ID", "Name", "Department" }; Object[][] data = { { 101, "John Doe", "Finance" }, { 102, "Jane Smith", "HR" }, { 103, "Michael Clark", "IT" } }; Sheet sheet = workbook.createSheet(SHEET_NAME); HSSFFont font = workbook.createFont(); font.setBold(true); HSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFont(font); Row header = sheet.createRow(0); for (int i = 0; i < COLUMN_HEADERS.length; i++) { Cell cell = header.createCell(i); cell.setCellValue(COLUMN_HEADERS[i]); cell.setCellStyle(headerStyle); } int rowNum = 1; for (Object[] rowData : data) { Row row = sheet.createRow(rowNum++);
for (int i = 0; i < rowData.length; i++) { Cell cell = row.createCell(i); Object value = rowData[i]; if (value instanceof Integer) { cell.setCellValue(((Integer) value).doubleValue()); } else if (value instanceof Double) { cell.setCellValue((Double) value); } else if (value != null) { cell.setCellValue(value.toString()); } } } for (int i = 0; i < COLUMN_HEADERS.length; i++) { sheet.autoSizeColumn(i); } return workbook; } }
repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\hssfworkbook\ExcelCreator.java
1
请完成以下Java代码
public void sendAndCancel() { sendRequests(Lists.newArrayList( "http://www.baidu.com", "http://www.163.com", "http://www.sina.com.cn")); client.cancel(this.tag); } public void sendRequests(List<String> urls) { for (String item : urls) { client.newCall(new Request.Builder() .url(item) .tag(this.tag) .build()) .enqueue(new SimpleCallback()); } }
private static class SimpleCallback implements Callback { public void onFailure(Request request, IOException e) { e.printStackTrace(); } public void onResponse(Response response) throws IOException { System.out.println(response.body().string()); } } public static void main(String[] args) throws IOException { new CancelRequest().sendAndCancel(); } }
repos\spring-boot-quick-master\quick-okhttp\src\main\java\com\quick\okhttp\CancelRequest.java
1