instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected Properties childValue(final Properties ctx) { final Properties childCtx = new Properties(ctx); listener.onChildContextCreated(ctx, childCtx); return childCtx; } @Override public Properties get() { final Properties ctx = super.get(); listener.onContextCheckOut(ctx); return ctx; }; @Override public void set(final Properties ctx) { final Properties ctxOld = super.get(); super.set(ctx); listener.onContextCheckIn(ctx, ctxOld); }; }; @Override protected Properties getDelegate() { return threadLocalContext.get(); } public ThreadLocalServerContext() { super(); } /** * Temporarily switches the context in the current thread. */ public IAutoCloseable switchContext(final Properties ctx) { Check.assumeNotNull(ctx, "ctx not null"); // Avoid StackOverflowException caused by setting the same context if (ctx == this) { return NullAutoCloseable.instance; } final long threadIdOnSet = Thread.currentThread().getId(); final Properties ctxOld = threadLocalContext.get(); threadLocalContext.set(ctx); return new IAutoCloseable()
{ private boolean closed = false; @Override public void close() { // Do nothing if already closed if (closed) { return; } // Assert we are restoring the ctx in same thread. // Because else, we would set the context "back" in another thread which would lead to huge inconsistencies. if (Thread.currentThread().getId() != threadIdOnSet) { throw new IllegalStateException("Error: setting back the context shall be done in the same thread as it was set initially"); } threadLocalContext.set(ctxOld); closed = true; } }; } /** * Dispose the context from current thread */ public void dispose() { final Properties ctx = threadLocalContext.get(); ctx.clear(); threadLocalContext.remove(); } public void setListener(@NonNull final IContextProviderListener listener) { this.listener = listener; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\ThreadLocalServerContext.java
1
请完成以下Java代码
public Mono<Authentication> authenticate(Authentication authentication) { // @formatter:off return Mono.justOrEmpty(authentication) .filter(BearerTokenAuthenticationToken.class::isInstance) .cast(BearerTokenAuthenticationToken.class) .map(BearerTokenAuthenticationToken::getToken) .flatMap(this::authenticate); // @formatter:on } private Mono<Authentication> authenticate(String token) { // @formatter:off return this.introspector.introspect(token) .flatMap((principal) -> this.authenticationConverter.convert(token, principal)) .onErrorMap(OAuth2IntrospectionException.class, this::onError); // @formatter:on } private AuthenticationException onError(OAuth2IntrospectionException ex) { if (ex instanceof BadOpaqueTokenException) { return new InvalidBearerTokenException(ex.getMessage(), ex); } return new AuthenticationServiceException(ex.getMessage(), ex); } /** * Default {@link ReactiveOpaqueTokenAuthenticationConverter}. * @param introspectedToken the bearer string that was successfully introspected
* @param authenticatedPrincipal the successful introspection output * @return an async wrapper of default {@link OpaqueTokenAuthenticationConverter} * result */ static Mono<Authentication> convert(String introspectedToken, OAuth2AuthenticatedPrincipal authenticatedPrincipal) { return Mono.just(OpaqueTokenAuthenticationProvider.convert(introspectedToken, authenticatedPrincipal)); } /** * Provide with a custom bean to turn successful introspection result into an * {@link Authentication} instance of your choice. By default, * {@link BearerTokenAuthentication} will be built. * @param authenticationConverter the converter to use * @since 5.8 */ public void setAuthenticationConverter(ReactiveOpaqueTokenAuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenReactiveAuthenticationManager.java
1
请在Spring Boot框架中完成以下Java代码
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) { this.objectPostProcessor = objectPostProcessor; } @Autowired(required = false) public void setMethodSecurityExpressionHandler(List<MethodSecurityExpressionHandler> handlers) { if (handlers.size() != 1) { logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got " + handlers); return; } this.expressionHandler = handlers.get(0); } @Autowired(required = false) void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.context = beanFactory; } private AuthenticationConfiguration getAuthenticationConfiguration() { return this.context.getBean(AuthenticationConfiguration.class); } private boolean prePostEnabled() { return enableMethodSecurity().getBoolean("prePostEnabled"); }
private boolean securedEnabled() { return enableMethodSecurity().getBoolean("securedEnabled"); } private boolean jsr250Enabled() { return enableMethodSecurity().getBoolean("jsr250Enabled"); } private boolean isAspectJ() { return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ; } private AnnotationAttributes enableMethodSecurity() { if (this.enableMethodSecurity == null) { // if it is null look at this instance (i.e. a subclass was used) EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(), EnableGlobalMethodSecurity.class); Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required"); Map<String, Object> methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation); this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs); } return this.enableMethodSecurity; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecurityConfiguration.java
2
请完成以下Java代码
public boolean isPrinted() { return printed; } @Override public void setPrinted(final boolean printed) { this.printed = printed; } @Override public int getLineNo() { return lineNo; } @Override public void setLineNo(final int lineNo) { this.lineNo = lineNo; } @Override public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes); }
@Override public List<IInvoiceLineAttribute> getInvoiceLineAttributes() { return invoiceLineAttributes; } @Override public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate() { return iciolsToUpdate; } @Override public int getC_PaymentTerm_ID() { return C_PaymentTerm_ID; } @Override public void setC_PaymentTerm_ID(final int paymentTermId) { C_PaymentTerm_ID = paymentTermId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java
1
请在Spring Boot框架中完成以下Java代码
public TypeAProcessor typeAProcessor() { return new TypeAProcessor(); } @Bean public TypeBProcessor typeBProcessor() { return new TypeBProcessor(); } @Bean public CustomerProcessorRouter processorRouter(TypeAProcessor typeAProcessor, TypeBProcessor typeBProcessor) { return new CustomerProcessorRouter(typeAProcessor, typeBProcessor); } @Bean public JpaItemWriter<Customer> jpaDBWriter(EntityManagerFactory entityManagerFactory) { JpaItemWriter<Customer> writer = new JpaItemWriter<>(); writer.setEntityManagerFactory(entityManagerFactory); return writer; } @Bean public FlatFileItemWriter<Customer> fileWriter() { return new FlatFileItemWriterBuilder<Customer>().name("customerItemWriter") .resource(new FileSystemResource("output/processed_customers.txt")) .delimited() .delimiter(",") .names("id", "name", "email", "type")
.build(); } @Bean public CompositeItemWriter<Customer> compositeWriter(JpaItemWriter<Customer> jpaDBWriter, FlatFileItemWriter<Customer> fileWriter) { return new CompositeItemWriterBuilder<Customer>().delegates(List.of(jpaDBWriter, fileWriter)) .build(); } @Bean public Step processCustomersStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, FlatFileItemReader<Customer> reader, CustomerProcessorRouter processorRouter, CompositeItemWriter<Customer> compositeWriter) { return new StepBuilder("processCustomersStep", jobRepository).<Customer, Customer> chunk(10, transactionManager) .reader(reader) .processor(processorRouter) .writer(compositeWriter) .build(); } @Bean public Job processCustomersJob(JobRepository jobRepository, Step processCustomersStep) { return new JobBuilder("customerProcessingJob", jobRepository).start(processCustomersStep) .build(); } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\multiprocessorandwriter\config\BatchConfig.java
2
请完成以下Java代码
protected ITranslatableString buildMessage() { String msg = super.getMessage(); StringBuffer sb = new StringBuffer(msg); // if (this.order != null) { final String info; if (order instanceof IDocument) { info = ((IDocument)order).getSummary(); } else { info = "" + order.getDocumentNo() + "/" + order.getDatePromised(); }
sb.append(" @PP_Order_ID@:").append(info); } if (this.orderActivity != null) { sb.append(" @PP_Order_Node_ID@:").append(orderActivity); } if (this.resource != null) { sb.append(" @S_Resource_ID@:").append(resource.getValue()).append("_").append(resource.getName()); } // return TranslatableStrings.parse(sb.toString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\exceptions\CRPException.java
1
请完成以下Java代码
public static BPartnerCompositeLookupKey ofExternalId(@NonNull final ExternalId externalId) { return ofJsonExternalId(JsonExternalIds.of(externalId)); } public static BPartnerCompositeLookupKey ofCode(@NonNull final String code) { assumeNotEmpty(code, "Given parameter 'code' may not be empty"); return new BPartnerCompositeLookupKey(null, null, code.trim(), null, null); } public static BPartnerCompositeLookupKey ofGln(@NonNull final GLN gln) { return new BPartnerCompositeLookupKey(null, null, null, gln, null); } public static BPartnerCompositeLookupKey ofGlnWithLabel(@NonNull final GlnWithLabel glnWithLabel) { return new BPartnerCompositeLookupKey(null, null, null, null, glnWithLabel); } public static BPartnerCompositeLookupKey ofIdentifierString(@NonNull final IdentifierString bpartnerIdentifier) { switch (bpartnerIdentifier.getType()) { case EXTERNAL_ID: return BPartnerCompositeLookupKey.ofJsonExternalId(bpartnerIdentifier.asJsonExternalId()); case VALUE: return BPartnerCompositeLookupKey.ofCode(bpartnerIdentifier.asValue()); case GLN: return BPartnerCompositeLookupKey.ofGln(bpartnerIdentifier.asGLN()); case GLN_WITH_LABEL: return BPartnerCompositeLookupKey.ofGlnWithLabel(bpartnerIdentifier.asGlnWithLabel()); case METASFRESH_ID: return BPartnerCompositeLookupKey.ofMetasfreshId(bpartnerIdentifier.asMetasfreshId()); default: throw new AdempiereException("Unexpected type=" + bpartnerIdentifier.getType()); } } MetasfreshId metasfreshId; JsonExternalId jsonExternalId;
String code; GLN gln; GlnWithLabel glnWithLabel; private BPartnerCompositeLookupKey( @Nullable final MetasfreshId metasfreshId, @Nullable final JsonExternalId jsonExternalId, @Nullable final String code, @Nullable final GLN gln, @Nullable final GlnWithLabel glnWithLabel) { this.metasfreshId = metasfreshId; this.jsonExternalId = jsonExternalId; this.code = code; this.gln = gln; this.glnWithLabel = glnWithLabel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerCompositeLookupKey.java
1
请完成以下Java代码
public CalculatedFieldId getId() { return super.getId(); } @Schema(description = "Timestamp of the calculated field creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } // Getter is ignored for serialization @JsonIgnore public boolean isDebugMode() { return debugMode; } // Setter is annotated for deserialization @JsonSetter public void setDebugMode(boolean debugMode) { this.debugMode = debugMode; }
@Override public String toString() { return new StringBuilder() .append("CalculatedField[") .append("tenantId=").append(tenantId) .append(", entityId=").append(entityId) .append(", type='").append(type) .append(", name='").append(name) .append(", configurationVersion=").append(configurationVersion) .append(", configuration=").append(configuration) .append(", version=").append(version) .append(", createdTime=").append(createdTime) .append(", id=").append(id).append(']') .toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\CalculatedField.java
1
请完成以下Java代码
public static AttributeId ofRepoId(final int repoId) { return new AttributeId(repoId); } public static AttributeId ofRepoIdObj(@NonNull final Object repoIdObj) { if (repoIdObj instanceof AttributeId) { return (AttributeId)repoIdObj; } else if (repoIdObj instanceof Integer) { return ofRepoId((int)repoIdObj); } else { try { final int repoId = Integer.parseInt(repoIdObj.toString()); return ofRepoId(repoId); } catch (final Exception ex) { throw new AdempiereException("Failed converting '" + repoIdObj + "' (" + repoIdObj.getClass() + ") to " + AttributeId.class, ex); } } } public static AttributeId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; }
public static int toRepoId(final AttributeId attributeId) { return attributeId != null ? attributeId.getRepoId() : -1; } private AttributeId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(final AttributeId id1, final AttributeId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeId.java
1
请完成以下Java代码
public Result afterHU(final I_M_HU hu) { final int huId = hu.getM_HU_ID(); final List<IHUDocumentLine> documentLines = huId2documentLines.remove(huId); // allow empty documents because it's more obvious for user // if (documentLines.isEmpty()) // { // return Result.CONTINUE; // } final IHUDocument doc = createHUDocument(hu, documentLines); documentsCollector.getHUDocuments().add(doc); return Result.CONTINUE; } /** * Create a document line for each IProductStorage. */ @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorageMutable) { final int huId = itemStorageMutable.getValue().getM_HU_Item().getM_HU_ID(); final List<IHUDocumentLine> documentLines = huId2documentLines.get(huId); final IHUItemStorage itemStorage = itemStorageMutable.getValue(); final I_M_HU_Item item = iterator.getCurrentHUItem(); final List<IProductStorage> productStorages = itemStorage.getProductStorages(iterator.getDate()); for (final IProductStorage productStorage : productStorages) { final HandlingUnitHUDocumentLine documentLine = createHUDocumentLine(item, productStorage); documentLines.add(documentLine);
} return Result.SKIP_DOWNSTREAM; } }); iterator.iterate(hu); } protected IHUDocument createHUDocument(final I_M_HU hu, final List<IHUDocumentLine> documentLines) { final I_M_HU innerHU = getInnerHU(hu); return new HandlingUnitHUDocument(hu, innerHU, documentLines); } protected I_M_HU getInnerHU(final I_M_HU hu) { // If HU has no parent (i.e. it's a top level HU) then there is nothing to take out if (hu.getM_HU_Item_Parent_ID() <= 0) { return null; } else { return hu; } } protected HandlingUnitHUDocumentLine createHUDocumentLine(final I_M_HU_Item item, final IProductStorage productStorage) { return new HandlingUnitHUDocumentLine(item, productStorage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\HandlingUnitHUDocumentFactory.java
1
请完成以下Java代码
public void exceptionWhileUnregisteringDeploymentsWithJobExecutor(Exception e) { logError( "020", "Exceptions while unregistering deployments with job executor", e); } public void registrationSummary(String string) { logInfo( "021", string); } public void exceptionWhileLoggingRegistrationSummary(Throwable e) { logError( "022", "Exception while logging registration summary", e); } public boolean isContextSwitchLoggable() { return isDebugEnabled(); }
public void debugNoTargetProcessApplicationFound(ExecutionEntity execution, ProcessApplicationManager processApplicationManager) { logDebug("023", "No target process application found for Execution[{}], ProcessDefinition[{}], Deployment[{}] Registrations[{}]", execution.getId(), execution.getProcessDefinitionId(), execution.getProcessDefinition().getDeploymentId(), processApplicationManager.getRegistrationSummary()); } public void debugNoTargetProcessApplicationFoundForCaseExecution(CaseExecutionEntity execution, ProcessApplicationManager processApplicationManager) { logDebug("024", "No target process application found for CaseExecution[{}], CaseDefinition[{}], Deployment[{}] Registrations[{}]", execution.getId(), execution.getCaseDefinitionId(), ((CaseDefinitionEntity)execution.getCaseDefinition()).getDeploymentId(), processApplicationManager.getRegistrationSummary()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\ProcessApplicationLogger.java
1
请完成以下Java代码
public void setCountry(String country) { this.country = country; } public String getCounty() { return country; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", cls='" + cls + '\'' + ", country='" + country + '\'' + '}';
} public Student (String name, String cls, String country){ super(); this.name = name; this.cls = cls; this.country = country; } public String getName() { return name; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringSwagger2Project\src\main\java\spring\swagger2\Student.java
1
请完成以下Java代码
public void setPostgREST_ResultDirectory (final String PostgREST_ResultDirectory) { set_Value (COLUMNNAME_PostgREST_ResultDirectory, PostgREST_ResultDirectory); } @Override public String getPostgREST_ResultDirectory() { return get_ValueAsString(COLUMNNAME_PostgREST_ResultDirectory); } @Override public void setRead_timeout (final int Read_timeout) { set_Value (COLUMNNAME_Read_timeout, Read_timeout); } @Override public int getRead_timeout() { return get_ValueAsInt(COLUMNNAME_Read_timeout); }
@Override public void setS_PostgREST_Config_ID (final int S_PostgREST_Config_ID) { if (S_PostgREST_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_S_PostgREST_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_S_PostgREST_Config_ID, S_PostgREST_Config_ID); } @Override public int getS_PostgREST_Config_ID() { return get_ValueAsInt(COLUMNNAME_S_PostgREST_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_PostgREST_Config.java
1
请完成以下Java代码
public void read(LineHandler handler, int size) throws Exception { File rootFile = new File(root); File[] files; if (rootFile.isDirectory()) { files = rootFile.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && !pathname.getName().endsWith(".bin"); } }); if (files == null) { if (rootFile.isFile()) files = new File[]{rootFile}; else return; } } else { files = new File[]{rootFile}; } int n = 0; int totalAddress = 0; long start = System.currentTimeMillis(); for (File file : files) { if (size-- == 0) break; if (file.isDirectory()) continue; if (verbose) System.out.printf("正在处理%s, %d / %d\n", file.getName(), ++n, files.length); IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(file.getAbsolutePath()); while (lineIterator.hasNext())
{ ++totalAddress; String line = lineIterator.next(); if (line.length() == 0) continue; handler.handle(line); } } handler.done(); if (verbose) System.out.printf("处理了 %.2f 万行,花费了 %.2f min\n", totalAddress / 10000.0, (System.currentTimeMillis() - start) / 1000.0 / 60.0); } /** * 读取 * @param handler 处理逻辑 * @throws Exception */ public void read(LineHandler handler) throws Exception { read(handler, Integer.MAX_VALUE); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\EasyReader.java
1
请完成以下Java代码
protected void compute() { if (Objects.isNull(file)) { return; } File[] files = file.listFiles(); List<EncryptionClassFileTask> fileTasks = new ArrayList<>(); if (Objects.nonNull(files)) { for (File f : files) { // 拆分任务 if (f.isDirectory()) { fileTasks.add(new EncryptionClassFileTask(f, packages, excludeClass, publicKey)); } else { if (f.getAbsolutePath().endsWith(".class")) { if (!CollectionUtils.isEmpty(excludeClass) && excludeClass.contains(f.getName().substring(0, f.getName().indexOf(".")))) { continue; } // 如果packages为空直接加密文件夹下所有文件 if (CollectionUtils.isEmpty(packages)) { encryptFile(f); return; } // 如果packages不为空则加密指定报名下面的文件 for (String packageName : packages) { if (f.getPath().contains(packageName.replace('.', File.separatorChar))) { encryptFile(f); return; } } } } } // 提交并执行任务
invokeAll(fileTasks); for (EncryptionClassFileTask fileTask : fileTasks) { // 等待任务执行完成 fileTask.join(); } } } private void encryptFile(File file) { try { logger.info("加密[{}] 文件 开始", file.getPath()); byte[] bytes = RSAUtil.encryptByPublicKey(RSAUtil.toByteArray(file), publicKey); try (FileChannel fc = new FileOutputStream(file.getPath()).getChannel()) { ByteBuffer bb = ByteBuffer.wrap(bytes); fc.write(bb); logger.info("加密[{}] 文件 结束", file.getPath()); } } catch (IOException e) { logger.error("加密文件 {} 异常:{}", file.getPath(), e.getMessage(), e); } } }
repos\spring-boot-student-master\spring-boot-student-jvm\src\main\java\com\xiaolyuh\utils\EncryptionClassFileTask.java
1
请完成以下Java代码
public List<IPricingAttribute> extractPricingAttributes(@NonNull final I_M_ProductPrice productPrice) { final I_M_AttributeSetInstance productPriceASI = productPrice.getM_AttributeSetInstance(); if (productPriceASI == null || productPriceASI.getM_AttributeSetInstance_ID() <= 0) { return ImmutableList.of(); } return asiBL.getAttributeInstances(productPriceASI) .stream() .map(this::createPricingAttribute) .collect(GuavaCollectors.toImmutableList()); } private PricingAttribute createPricingAttribute(final I_M_AttributeInstance instance) { final AttributeId attributeId = AttributeId.ofRepoId(instance.getM_Attribute_ID()); final AttributeValueId attributeValueId = AttributeValueId.ofRepoIdOrNull(instance.getM_AttributeValue_ID()); final AttributeListValue attributeValue = attributeValueId != null ? attributesRepo.retrieveAttributeValueOrNull(attributeId, attributeValueId) : null; return new PricingAttribute(attributeValue); } // task 08839 private final static ModelDynAttributeAccessor<IAttributeSetInstanceAware, IProductPriceAware> DYN_ATTR_IProductPriceAware = new ModelDynAttributeAccessor<>(IProductPriceAware.class); @Override public void setDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware, final Optional<IProductPriceAware> productPriceAware) { if (asiAware == null) { return; // nothing to do } DYN_ATTR_IProductPriceAware.setValue(asiAware, productPriceAware.orElse(null));
} @Override public void setDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware, final IProductPriceAware productPriceAware) { if (asiAware == null) { return; // nothing to do } DYN_ATTR_IProductPriceAware.setValue(asiAware, productPriceAware); } @Override public Optional<IProductPriceAware> getDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware) { return DYN_ATTR_IProductPriceAware.getValueIfExists(asiAware); } @Value private static class PricingAttribute implements IPricingAttribute { @Nullable AttributeListValue attributeValue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\attributebased\impl\AttributePricingBL.java
1
请完成以下Java代码
public class ErrorEventDefinition extends EventDefinition { protected String errorCode; protected String errorVariableName; protected Boolean errorVariableTransient; protected Boolean errorVariableLocalScope; public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorVariableName() { return errorVariableName; } public void setErrorVariableName(String errorVariableName) { this.errorVariableName = errorVariableName; } public Boolean getErrorVariableTransient() { return errorVariableTransient; } public void setErrorVariableTransient(Boolean errorVariableTransient) { this.errorVariableTransient = errorVariableTransient; } public Boolean getErrorVariableLocalScope() { return errorVariableLocalScope; }
public void setErrorVariableLocalScope(Boolean errorVariableLocalScope) { this.errorVariableLocalScope = errorVariableLocalScope; } @Override public ErrorEventDefinition clone() { ErrorEventDefinition clone = new ErrorEventDefinition(); clone.setValues(this); return clone; } public void setValues(ErrorEventDefinition otherDefinition) { super.setValues(otherDefinition); setErrorCode(otherDefinition.getErrorCode()); setErrorVariableName(otherDefinition.getErrorVariableName()); setErrorVariableLocalScope(otherDefinition.getErrorVariableLocalScope()); setErrorVariableTransient(otherDefinition.getErrorVariableTransient()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ErrorEventDefinition.java
1
请完成以下Java代码
void configureCopyWithDetailsSupport() { CopyRecordFactory.enableForTableName(I_C_RfQ.Table_Name); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void beforeSave(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateWorkDates(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DateWorkStart, skipIfCopying = true) public void onDateWorkStart(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkStart(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DateWorkComplete, skipIfCopying = true) public void onDateWorkComplete(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkComplete(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DeliveryDays, skipIfCopying = true)
public void onDeliveryDays(final I_C_RfQ rfq) { if (InterfaceWrapperHelper.isNull(rfq, I_C_RfQ.COLUMNNAME_DeliveryDays)) { return; } final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDeliveryDays(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_C_RfQ_Topic_ID, skipIfCopying = true) public void onC_RfQTopic(final I_C_RfQ rfq) { final I_C_RfQ_Topic rfqTopic = rfq.getC_RfQ_Topic(); if (rfqTopic == null) { return; } final String rfqTypeDefault = rfqTopic.getRfQType(); if (rfqTypeDefault != null) { rfq.setRfQType(rfqTypeDefault); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\model\interceptor\C_RfQ.java
1
请在Spring Boot框架中完成以下Java代码
public void saveRouting(final PPOrderRouting routing) { supportingServices.saveOrderRouting(routing); } public void saveHeader(@NonNull final ManufacturingJob job) { final I_PP_Order ppOrder = getPPOrderRecordById(job.getPpOrderId()); ppOrder.setCurrentScaleDeviceId(job.getCurrentScaleDeviceId() != null ? job.getCurrentScaleDeviceId().getAsString() : null); InterfaceWrapperHelper.saveRecord(ppOrder); } @NonNull private Optional<ManufacturingJobActivity> toValidateLocatorInfoActivity(final @NonNull PPOrderRoutingActivity from) { return Optional.of(supportingServices.getValidateSourceLocatorInfo(from.getOrderId())) .filter(ValidateLocatorInfo::hasAnySourceLocators)
.map(sourceLocatorInfo -> prepareJobActivity(from).sourceLocatorValidate(sourceLocatorInfo).build()); } @NonNull private Optional<ManufacturingJobActivity> toIssueOnlyWhatWasReceivedActivity(final @NonNull PPOrderRoutingActivity from) { if (!hasAnyIssueOnlyForReceivedLines(from.getOrderId())) { return Optional.empty(); } return Optional.of(prepareJobActivity(from) .issueOnlyWhatWasReceivedConfig(IssueOnlyWhatWasReceivedConfig.ofIssueStrategy(from.getRawMaterialsIssueStrategy())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaver.java
2
请完成以下Java代码
public class TsKvQueryCursor extends QueryCursor { @Getter private final List<TsKvEntry> data; @Getter private final String orderBy; private int partitionIndex; private int currentLimit; public TsKvQueryCursor(String entityType, UUID entityId, ReadTsKvQuery baseQuery, List<Long> partitions) { super(entityType, entityId, baseQuery, partitions); this.orderBy = baseQuery.getOrder(); this.partitionIndex = isDesc() ? partitions.size() - 1 : 0; this.data = new ArrayList<>(); this.currentLimit = baseQuery.getLimit(); } @Override public boolean hasNextPartition() { return isDesc() ? partitionIndex >= 0 : partitionIndex <= partitions.size() - 1; } public boolean isFull() { return currentLimit <= 0; }
@Override public long getNextPartition() { long partition = partitions.get(partitionIndex); if (isDesc()) { partitionIndex--; } else { partitionIndex++; } return partition; } public int getCurrentLimit() { return currentLimit; } public void addData(List<TsKvEntry> newData) { currentLimit -= newData.size(); data.addAll(newData); } private boolean isDesc() { return orderBy.equals(DESC_ORDER); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\TsKvQueryCursor.java
1
请完成以下Java代码
public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { final InputStream inputStream = getRequestBody(isBodyEmpty, requestBody); @Override public int read() throws IOException { return inputStream.read(); } @Override public int available() throws IOException { return inputStream.available(); } @Override public void close() throws IOException { inputStream.close(); } @Override public synchronized void mark(int readlimit) { inputStream.mark(readlimit); } @Override public synchronized void reset() throws IOException { inputStream.reset(); }
@Override public boolean markSupported() { return inputStream.markSupported(); } }; } @Override public BufferedReader getReader() throws IOException { return EmptyBodyFilter.this.getReader(this.getInputStream()); } }; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\filter\EmptyBodyFilter.java
1
请完成以下Java代码
private DocumentFilterDescriptor createFacetFilter(@NonNull final DocumentFieldDescriptor field, final int sortNo) { final FacetsFilterLookupDescriptor facetsLookupDescriptor = createFacetsFilterLookupDescriptor(field); return DocumentFilterDescriptor.builder() .setFilterId(facetsLookupDescriptor.getFilterId()) .setSortNo(DocumentFilterDescriptorsConstants.SORT_NO_FACETS_START + sortNo) .setFrequentUsed(true) .setParametersLayoutType(PanelLayoutType.Panel) .setDisplayName(field.getCaption()) .setFacetFilter(true) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(facetsLookupDescriptor.getFieldName()) .operator(Operator.IN_ARRAY) .displayName(field.getCaption()) .mandatory(true) .widgetType(DocumentFieldWidgetType.MultiValuesList) .lookupDescriptor(facetsLookupDescriptor)) .build(); } private FacetsFilterLookupDescriptor createFacetsFilterLookupDescriptor(final DocumentFieldDescriptor field) { final String columnName = field.getDataBinding() .orElseThrow(() -> new AdempiereException("No data binding defined for " + field)) .getColumnName(); final String filterId = FACET_FILTER_ID_PREFIX + columnName; final DocumentFieldDefaultFilterDescriptor fieldFilteringInfo = field.getDefaultFilterInfo(); final DocumentFieldWidgetType fieldWidgetType = extractFilterWidgetType(field); final LookupDescriptor fieldLookupDescriptor = field.getLookupDescriptorForFiltering().orElse(null); final boolean numericKey; if (fieldWidgetType.isLookup() && fieldLookupDescriptor != null) { numericKey = fieldLookupDescriptor.isNumericKey(); }
else { numericKey = fieldWidgetType.isNumeric(); } return FacetsFilterLookupDescriptor.builder() .viewsRepository(viewsRepository) .filterId(filterId) .fieldName(columnName) .fieldWidgetType(fieldWidgetType) .numericKey(numericKey) .maxFacetsToFetch(fieldFilteringInfo.getMaxFacetsToFetch().orElse(getMaxFacetsToFetch())) .fieldLookupDescriptor(fieldLookupDescriptor) .build(); } private int getMaxFacetsToFetch() { return sysConfigs.getIntValue(SYSCONFIG_MAX_FACETS_TO_FETCH, SYSCONFIG_FACETS_TO_FETCH_DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\standard\StandardDocumentFilterDescriptorsProviderFactory.java
1
请完成以下Java代码
public static String nullToEmpty(@Nullable final String in) { return in != null ? in : ""; } /** * Example: * <pre> * - string = `87whdhA7008S` (length 14) * - groupSeparator = "--" * - groupSize = 4 * * Results into `87wh--dhA7--008S` of length 18. * </pre> * * @param string the input string * @param groupSeparator the separator string * @param groupSize the size of each character group, after which a groupSeparator is inserted * @return the input string containing the groupSeparator */ @NonNull public static String insertSeparatorEveryNCharacters( @NonNull final String string, @NonNull final String groupSeparator, final int groupSize) { if (groupSize < 1) { return string; } final StringBuilder result = new StringBuilder(string); int insertPosition = groupSize; while (insertPosition < result.length()) { result.insert(insertPosition, groupSeparator); insertPosition += groupSize + groupSeparator.length(); } return result.toString(); } public static Map<String, String> parseURLQueryString(@Nullable final String query) { final String queryNorm = trimBlankToNull(query); if (queryNorm == null) { return ImmutableMap.of(); }
final HashMap<String, String> params = new HashMap<>(); for (final String param : queryNorm.split("&")) { final String key; final String value; final int idx = param.indexOf("="); if (idx < 0) { key = param; value = null; } else { key = param.substring(0, idx); value = param.substring(idx + 1); } params.put(key, value); } return params; } @Nullable public static String ucFirst(@Nullable final String str) { if (str == null || str.isEmpty()) { return str; } final char first = str.charAt(0); if (!Character.isLetter(first)) { return str; } final char capital = Character.toUpperCase(first); if(first == capital) { return str; } final StringBuilder sb = new StringBuilder(str); sb.setCharAt(0, capital); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\StringUtils.java
1
请完成以下Java代码
public void createNewDocument() { Tutorials tutorials = new Tutorials(); tutorials.setTutorial(new ArrayList<Tutorial>()); Tutorial tut = new Tutorial(); tut.setTutId("01"); tut.setType("XML"); tut.setTitle("XML with Jaxb"); tut.setDescription("XML Binding with Jaxb"); tut.setDate("04/02/2015"); tut.setAuthor("Jaxb author"); tutorials.getTutorial().add(tut); try { JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(tutorials, file);
} catch (JAXBException e) { e.printStackTrace(); } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\JaxbParser.java
1
请完成以下Java代码
public Iterator<I_M_InOut> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED) { return Collections.emptyIterator(); } @Override public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { throw new IllegalStateException("Not supported"); } @Override public void invalidateCandidatesFor(final Object model) { final I_M_InOut inout = InterfaceWrapperHelper.create(model, I_M_InOut.class); invalidateCandidatesForInOut(inout); invalidateFreightCostCandidateIfNeeded(inout); } private void invalidateFreightCostCandidateIfNeeded(final I_M_InOut inout) { final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); final OrderId orderId = OrderId.ofRepoIdOrNull(inout.getC_Order_ID()); if (orderId == null) { // nothing to do return; } invoiceCandDAO.invalidateUninvoicedFreightCostCandidate(orderId); } private void invalidateCandidatesForInOut(final I_M_InOut inout) { // // Retrieve inout line handlers final Properties ctx = InterfaceWrapperHelper.getCtx(inout); final List<IInvoiceCandidateHandler> inoutLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, org.compiere.model.I_M_InOutLine.Table_Name); for (final IInvoiceCandidateHandler handler : inoutLineHandlers) { for (final org.compiere.model.I_M_InOutLine line : inOutDAO.retrieveLines(inout)) { handler.invalidateCandidatesFor(line); } } } @Override public String getSourceTable() { return org.compiere.model.I_M_InOut.Table_Name;
} @Override public boolean isUserInChargeUserEditable() { return false; } @Override public void setOrderedData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic) { throw new UnsupportedOperationException(); } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOut_Handler.java
1
请完成以下Java代码
public static class StringTypeImpl extends PrimitiveValueTypeImpl { private static final long serialVersionUID = 1L; public StringTypeImpl() { super(String.class); } public StringValue createValue(Object value, Map<String, Object> valueInfo) { return Variables.stringValue((String) value, isTransient(valueInfo)); } } public static class NumberTypeImpl extends PrimitiveValueTypeImpl { private static final long serialVersionUID = 1L;
public NumberTypeImpl() { super(Number.class); } public NumberValue createValue(Object value, Map<String, Object> valueInfo) { return Variables.numberValue((Number) value, isTransient(valueInfo)); } @Override public boolean isAbstract() { return true; } } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\PrimitiveValueTypeImpl.java
1
请完成以下Java代码
private void startWorkflow( @NonNull final Workflow workflow, @NonNull final PO document) { final ProcessInfo pi = ProcessInfo.builder() .setCtx(document.getCtx()) .setAD_Process_ID(305) // FIXME HARDCODED .setAD_Client_ID(document.getAD_Client_ID()) .setTitle(workflow.getName().getDefaultValue()) .setRecord(document.get_Table_ID(), document.get_ID()) .build(); final WorkflowExecutionResult result = WorkflowExecutor.builder() .workflow(workflow) .clientId(pi.getClientId()) .adLanguage(Env.getADLanguageOrBaseLanguage()) .documentRef(pi.getRecordRefOrNull()) .userId(pi.getUserId()) .build() .start(); countStarted.incrementAndGet(); } /** * Test Start condition * * @return true if workflow should be started */ private boolean isSQLStartLogicMatches(final Workflow workflow, final PO document) { String logic = workflow.getDocValueWorkflowTriggerLogic(); logic = logic.substring(4); // "SQL=" // final String tableName = document.get_TableName(); final String[] keyColumns = document.get_KeyColumns(); if (keyColumns.length != 1) { log.error("Tables with more then one key column not supported - " + tableName + " = " + keyColumns.length); return false; } final String keyColumn = keyColumns[0]; final StringBuilder sql = new StringBuilder("SELECT ") .append(keyColumn).append(" FROM ").append(tableName) .append(" WHERE AD_Client_ID=? AND ") // #1 .append(keyColumn).append("=? AND ") // #2 .append(logic) // Duplicate Open Workflow test
.append(" AND NOT EXISTS (SELECT 1 FROM AD_WF_Process wfp ") .append("WHERE wfp.AD_Table_ID=? AND wfp.Record_ID=") // #3 .append(tableName).append(".").append(keyColumn) .append(" AND wfp.AD_Workflow_ID=?") // #4 .append(" AND SUBSTR(wfp.WFState,1,1)='O')"); final Object[] sqlParams = new Object[] { workflow.getClientId(), document.get_ID(), document.get_Table_ID(), workflow.getId() }; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.toString(), document.get_TrxName()); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); return rs.next(); } catch (final Exception ex) { throw new DBException(ex, sql, sqlParams); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\DocWorkflowManager.java
1
请完成以下Java代码
public List<HistoricCaseInstance> findHistoricCaseInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return getDbEntityManager().selectListWithRawParameter("selectHistoricCaseInstanceByNativeQuery", parameterMap, firstResult, maxResults); } public long findHistoricCaseInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbEntityManager().selectOne("selectHistoricCaseInstanceCountByNativeQuery", parameterMap); } protected void configureHistoricCaseInstanceQuery(HistoricCaseInstanceQueryImpl query) { getTenantManager().configureQuery(query); } @SuppressWarnings("unchecked") public List<String> findHistoricCaseInstanceIdsForCleanup(int batchSize, int minuteFrom, int minuteTo) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("currentTimestamp", ClockUtil.getCurrentTime()); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } ListQueryParameterObject parameterObject = new ListQueryParameterObject(parameters, 0, batchSize); return getDbEntityManager().selectList("selectHistoricCaseInstanceIdsForCleanup", parameterObject); }
@SuppressWarnings("unchecked") public List<CleanableHistoricCaseInstanceReportResult> findCleanableHistoricCaseInstancesReportByCriteria(CleanableHistoricCaseInstanceReportImpl query, Page page) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); getTenantManager().configureQuery(query); return getDbEntityManager().selectList("selectFinishedCaseInstancesReportEntities", query, page); } public long findCleanableHistoricCaseInstancesReportCountByCriteria(CleanableHistoricCaseInstanceReportImpl query) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); getTenantManager().configureQuery(query); return (Long) getDbEntityManager().selectOne("selectFinishedCaseInstancesReportEntitiesCount", query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricCaseInstanceManager.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getMetaInfo() { return metaInfo; } public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } public String getDeploymentId() { return deploymentId;
} public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getEditorSourceValueId() { return editorSourceValueId; } public void setEditorSourceValueId(String editorSourceValueId) { this.editorSourceValueId = editorSourceValueId; } public String getEditorSourceExtraValueId() { return editorSourceExtraValueId; } public void setEditorSourceExtraValueId(String editorSourceExtraValueId) { this.editorSourceExtraValueId = editorSourceExtraValueId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean hasEditorSource() { return this.editorSourceValueId != null; } public boolean hasEditorSourceExtra() { return this.editorSourceExtraValueId != null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityImpl.java
1
请完成以下Java代码
private void createFactsForInventoryLine(final Fact fact, final DocLine_Inventory line) { final AcctSchema as = fact.getAcctSchema(); final CostAmount costs = line.getCreateCosts(as); // // Inventory DR/CR fact.createLine() .setDocLine(line) .setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as)) .setAmtSourceDrOrCr(costs.toMoney()) .setQty(line.getQty()) .locatorId(line.getM_Locator_ID()) .buildAndAdd();
// // Charge/InventoryDiff CR/DR final Account invDiff = line.getInvDifferencesAccount(as, costs.toBigDecimal().negate()); final FactLine cr = fact.createLine() .setDocLine(line) .setAccount(invDiff) .setAmtSourceDrOrCr(costs.toMoney().negate()) .setQty(line.getQty().negate()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); if (line.getC_Charge_ID().isPresent()) // explicit overwrite for charge { cr.setAD_Org_ID(line.getOrgId()); } } } // Doc_Inventory
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Inventory.java
1
请完成以下Java代码
public void setBaseURL (final String BaseURL) { set_Value (COLUMNNAME_BaseURL, BaseURL); } @Override public String getBaseURL() { return get_ValueAsString(COLUMNNAME_BaseURL); } @Override public void setC_Root_BPartner_ID (final int C_Root_BPartner_ID) { if (C_Root_BPartner_ID < 1) set_Value (COLUMNNAME_C_Root_BPartner_ID, null); else set_Value (COLUMNNAME_C_Root_BPartner_ID, C_Root_BPartner_ID); } @Override public int getC_Root_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_Root_BPartner_ID); } @Override public void setExternalSystem_Config_Alberta_ID (final int ExternalSystem_Config_Alberta_ID) { if (ExternalSystem_Config_Alberta_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, ExternalSystem_Config_Alberta_ID); } @Override public int getExternalSystem_Config_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Alberta_ID); } @Override public I_ExternalSystem_Config getExternalSystem_Config() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class); } @Override public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
} @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setPharmacy_PriceList_ID (final int Pharmacy_PriceList_ID) { if (Pharmacy_PriceList_ID < 1) set_Value (COLUMNNAME_Pharmacy_PriceList_ID, null); else set_Value (COLUMNNAME_Pharmacy_PriceList_ID, Pharmacy_PriceList_ID); } @Override public int getPharmacy_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_Pharmacy_PriceList_ID); } @Override public void setTenant (final String Tenant) { set_Value (COLUMNNAME_Tenant, Tenant); } @Override public String getTenant() { return get_ValueAsString(COLUMNNAME_Tenant); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Alberta.java
1
请完成以下Java代码
public <NT> OldAndNewValues<NT> mapNonNulls(@NonNull final Function<T, NT> mapper) { final OldAndNewValues<NT> result = ofOldAndNewValues( oldValue != null ? mapper.apply(oldValue) : null, newValue != null ? mapper.apply(newValue) : null ); if (this.equals(result)) { //noinspection unchecked return (OldAndNewValues<NT>)this; } return result; } public <NT> OldAndNewValues<NT> map(@NonNull final Function<T, NT> mapper) {
final OldAndNewValues<NT> result = ofOldAndNewValues( mapper.apply(oldValue), mapper.apply(newValue) ); if (this.equals(result)) { //noinspection unchecked return (OldAndNewValues<NT>)this; } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\OldAndNewValues.java
1
请完成以下Java代码
private static Dictionary<String, String> props(String... args) { Dictionary<String, String> props = new Hashtable<>(); for (int i = 0; i < args.length / 2; i++) { props.put(args[2 * i], args[2 * i + 1]); } return props; } @SuppressWarnings({"rawtypes"}) private static class Service implements Runnable { private final ServiceRegistration registration; public Service(BundleContext context, String clazz, Object service, Dictionary props) { this.registration = context.registerService(clazz, service, props); } public Service(BundleContext context, String[] clazz, Object service, Dictionary props) { this.registration = context.registerService(clazz, service, props); } @Override public void run() { registration.unregister(); } }
private static class Tracker implements Runnable { private final Extender extender; private Tracker(Extender extender) { this.extender = extender; this.extender.open(); } @Override public void run() { extender.close(); } } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\Activator.java
1
请完成以下Java代码
public Object stringToObject(final I_AD_Column column, final String valueStr) { if (valueStr == null) { if (column.isMandatory()) { return VALUE_Unknown; } else { return null; } } final int displayType = column.getAD_Reference_ID(); if (DisplayType.isText(displayType)) { return valueStr; } else if (displayType == DisplayType.List) { return valueStr; } else if (DisplayType.isNumeric(displayType)) { return new BigDecimal(valueStr); } else if (DisplayType.isID(displayType)) { // TODO: hardcoded Table references with String Key if ("EntityType".equals(column.getColumnName()) || "AD_Language".equals(column.getColumnName())) { return valueStr; } return Integer.valueOf(valueStr); } else if (DisplayType.YesNo == displayType) { if ("true".equalsIgnoreCase(valueStr) || "Y".equals(valueStr)) { return true; } else if ("false".equalsIgnoreCase(valueStr) || "N".equals(valueStr)) { return false; } else { logger.warn("Invalid boolean value '" + valueStr + "' for column " + column + ". Returning false."); return false; } } else if (DisplayType.isDate(displayType)) { try { Date value = dateTimeFormat.parse(valueStr); return new Timestamp(value.getTime()); // convert it to Timestamp, as required by persistence API } catch (ParseException e) { throw new AdempiereException(e); } } // YesNo Button - metas, 02662 // e.g. AD_Column.IsEncrypted else if (DisplayType.Button == displayType
&& column.getColumnName().startsWith("Is")) { final boolean valueBoolean = "true".equalsIgnoreCase(valueStr) || "Y".equalsIgnoreCase(valueStr); return valueBoolean ? "Y" : "N"; // column value expected to be string } // // Binary, Radio, RowID, Image not supported else { return null; } } @Override public String objectToString(I_AD_Column column, Object value) { final int displayType = column.getAD_Reference_ID(); final boolean isMandatory = column.isMandatory(); return objectToString(value, displayType, isMandatory); } @Override public String objectToString(POInfoColumn columnInfo, Object value) { return objectToString(value, columnInfo.getDisplayType(), columnInfo.isMandatory()); } private String objectToString(final Object value, final int displayType, final boolean isMandatory) { if (value == null) { if (isMandatory) { logger.warn("Value is null even if is marked to be mandatory [Returning null]"); } return null; } // final String valueStr; if (DisplayType.isDate(displayType)) { valueStr = dateTimeFormat.format(value); } else if (DisplayType.YesNo == displayType) { if (value instanceof Boolean) { valueStr = ((Boolean)value) ? "true" : "false"; } else { valueStr = "Y".equals(value) ? "true" : "false"; } return valueStr; } else { valueStr = value.toString(); } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\util\DefaultDataConverter.java
1
请完成以下Java代码
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { int index = getIndex(row, column, n); coverBoard[index][hBase] = true; } } } return hBase; } private int checkRowConstraint(boolean[][] coverBoard, int hBase) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) { int index = getIndex(row, column, n); coverBoard[index][hBase] = true; } } } return hBase; } private int checkCellConstraint(boolean[][] coverBoard, int hBase) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) { int index = getIndex(row, column, n); coverBoard[index][hBase] = true; } }
} return hBase; } private boolean[][] initializeExactCoverBoard(int[][] board) { boolean[][] coverBoard = createExactCoverBoard(); for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) { int n = board[row - 1][column - 1]; if (n != NO_VALUE) { for (int num = MIN_VALUE; num <= MAX_VALUE; num++) { if (num != n) { Arrays.fill(coverBoard[getIndex(row, column, num)], false); } } } } } return coverBoard; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\DancingLinksAlgorithm.java
1
请完成以下Java代码
public void setLocode (java.lang.String Locode) { set_Value (COLUMNNAME_Locode, Locode); } /** Get Locode. @return Location code - UN/LOCODE */ @Override public java.lang.String getLocode () { return (java.lang.String)get_Value(COLUMNNAME_Locode); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set PLZ. @param Postal Postal code */ @Override public void setPostal (java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } /** Get PLZ. @return Postal code */ @Override public java.lang.String getPostal () { return (java.lang.String)get_Value(COLUMNNAME_Postal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_City.java
1
请完成以下Java代码
protected void onInit(final IModelValidationEngine engine, final I_AD_Client client) { engine.addModelChange(modelTableName, this); } @Override public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception { if (!changeType.isAfter()) { return; } // // Model was created on changed if (changeType.isNewOrChange()) { createOrUpdateAllocation(model); } // // Model was deleted else if (changeType.isDelete()) { deleteAllocation(model); } } private void createOrUpdateAllocation(final Object model) { final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class);
final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable); if (deliveryDayAlloc == null) { // Case: no delivery day allocation was found and no delivery day on which we could allocate was found return; } deliveryDayBL.getDeliveryDayHandlers() .updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable); InterfaceWrapperHelper.save(deliveryDayAlloc); } private void deleteAllocation(Object model) { final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayDAO.retrieveDeliveryDayAllocForModel(context, deliveryDayAllocable); if (deliveryDayAlloc != null) { InterfaceWrapperHelper.delete(deliveryDayAlloc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\DeliveryDayAllocableInterceptor.java
1
请完成以下Java代码
public List<DimensionSpec> retrieveForColumn(final I_AD_Column column) { final IQuery<I_DIM_Dimension_Spec_Assignment> assignmentQuery = createDimAssignmentQueryBuilderFor(column) .addOnlyActiveRecordsFilter() .create(); return Services.get(IQueryBL.class).createQueryBuilder(I_DIM_Dimension_Spec.class, column) .addInSubQueryFilter(I_DIM_Dimension_Spec.COLUMN_DIM_Dimension_Spec_ID, I_DIM_Dimension_Spec_Assignment.COLUMN_DIM_Dimension_Spec_ID, assignmentQuery) .create() .stream(I_DIM_Dimension_Spec.class) .map(DimensionSpec::ofRecord) .collect(ImmutableList.toImmutableList()); } @Override public DimensionSpec retrieveForInternalNameOrNull(final String internalName) { final I_DIM_Dimension_Spec record = Services.get(IQueryBL.class).createQueryBuilder(I_DIM_Dimension_Spec.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DIM_Dimension_Spec.COLUMN_InternalName, internalName) .create() .firstOnly(I_DIM_Dimension_Spec.class); if(record == null) { return null;
} return DimensionSpec.ofRecord(record); } @Override public List<String> retrieveAttributeValueForGroup(final String dimensionSpectInternalName, final String groupName, final IContextAware ctxAware) { final KeyNamePair[] keyNamePairs = DB.getKeyNamePairs("SELECT M_AttributeValue_ID, ValueName " + "FROM " + DimensionConstants.VIEW_DIM_Dimension_Spec_Attribute_AllValue + " WHERE InternalName=? AND GroupName=?", false, dimensionSpectInternalName, groupName); final List<String> result = new ArrayList<String>(keyNamePairs.length); for (final KeyNamePair keyNamePair : keyNamePairs) { result.add(keyNamePair.getName()); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\impl\DimensionspecDAO.java
1
请完成以下Java代码
public Builder addAllowedWriteOffType(final InvoiceWriteOffAmountType allowedWriteOffType) { Check.assumeNotNull(allowedWriteOffType, "allowedWriteOffType not null"); allowedWriteOffTypes.add(allowedWriteOffType); return this; } public Builder setWarningsConsumer(final IProcessor<Exception> warningsConsumer) { this.warningsConsumer = warningsConsumer; return this; } public Builder setDocumentIdsToIncludeWhenQuering(final Multimap<AllocableDocType, Integer> documentIds) { this.documentIds = documentIds; return this; } public Builder setFilter_Payment_ID(int filter_Payment_ID)
{ this.filterPaymentId = filter_Payment_ID; return this; } public Builder setFilter_POReference(String filterPOReference) { this.filterPOReference = filterPOReference; return this; } public Builder allowPurchaseSalesInvoiceCompensation(final boolean allowPurchaseSalesInvoiceCompensation) { this.allowPurchaseSalesInvoiceCompensation = allowPurchaseSalesInvoiceCompensation; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationContext.java
1
请完成以下Java代码
public MFColor setTextureTaintColor(final Color color) { if (!isTexture() || color == null) { return this; } return toBuilder().textureTaintColor(color).build(); } public MFColor setTextureCompositeAlpha(final float alpha) { if (!isTexture()) { return this; } return toBuilder().textureCompositeAlpha(alpha).build(); } public MFColor setLineColor(final Color color) { if (!isLine() || color == null) { return this; } return toBuilder().lineColor(color).build(); } public MFColor setLineBackColor(final Color color) { if (!isLine() || color == null) { return this; } return toBuilder().lineBackColor(color).build(); } public MFColor setLineWidth(final float width) { if (!isLine()) { return this; } return toBuilder().lineWidth(width).build(); } public MFColor setLineDistance(final int distance) { if (!isLine()) { return this; } return toBuilder().lineDistance(distance).build(); }
public MFColor toFlatColor() { switch (getType()) { case FLAT: return this; case GRADIENT: return ofFlatColor(getGradientUpperColor()); case LINES: return ofFlatColor(getLineBackColor()); case TEXTURE: return ofFlatColor(getTextureTaintColor()); default: throw new IllegalStateException("Type not supported: " + getType()); } } public String toHexString() { final Color awtColor = toFlatColor().getFlatColor(); return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } public static String toHexString(final int red, final int green, final int blue) { Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red); Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green); Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue); return String.format("#%02x%02x%02x", red, green, blue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java
1
请在Spring Boot框架中完成以下Java代码
public class FlowableIdmProperties { /** * Whether the idm engine needs to be started. */ private boolean enabled = true; /** * The type of the password encoder that needs to be used. */ private String passwordEncoder; /** * The servlet configuration for the IDM Rest API. */ @NestedConfigurationProperty private final FlowableServlet servlet = new FlowableServlet("/idm-api", "Flowable IDM Rest API"); public boolean isEnabled() {
return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPasswordEncoder() { return passwordEncoder; } public void setPasswordEncoder(String passwordEncoder) { this.passwordEncoder = passwordEncoder; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\idm\FlowableIdmProperties.java
2
请完成以下Java代码
public void init(TbActorCtx ctx) throws TbActorException { super.init(ctx); log.debug("[{}] Starting CF manager actor.", processor.tenantId); try { processor.init(ctx); log.debug("[{}] CF manager actor started.", processor.tenantId); } catch (Exception e) { log.warn("[{}] Unknown failure", processor.tenantId, e); throw new TbActorException("Failed to initialize manager actor", e); } } @Override public void destroy(TbActorStopReason stopReason, Throwable cause) throws TbActorException { log.debug("[{}] Stopping CF manager actor.", processor.tenantId); processor.stop(); } @Override protected boolean doProcessCfMsg(ToCalculatedFieldSystemMsg msg) throws CalculatedFieldException { switch (msg.getMsgType()) { case CF_PARTITIONS_CHANGE_MSG: processor.onPartitionChange((CalculatedFieldPartitionChangeMsg) msg); break; case CF_CACHE_INIT_MSG: processor.onCacheInitMsg((CalculatedFieldCacheInitMsg) msg); break; case CF_STATE_RESTORE_MSG: processor.onStateRestoreMsg((CalculatedFieldStateRestoreMsg) msg); break; case CF_STATE_PARTITION_RESTORE_MSG:
processor.onStatePartitionRestoreMsg((CalculatedFieldStatePartitionRestoreMsg) msg); break; case CF_ENTITY_LIFECYCLE_MSG: processor.onEntityLifecycleMsg((CalculatedFieldEntityLifecycleMsg) msg); break; case CF_ENTITY_ACTION_EVENT_MSG: processor.onEntityActionEventMsg((CalculatedFieldEntityActionEventMsg) msg); break; case CF_TELEMETRY_MSG: processor.onTelemetryMsg((CalculatedFieldTelemetryMsg) msg); break; case CF_LINKED_TELEMETRY_MSG: processor.onLinkedTelemetryMsg((CalculatedFieldLinkedTelemetryMsg) msg); break; default: return false; } return true; } @Override void logProcessingException(Exception e) { log.warn("[{}] Processing failure", tenantId, e); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\calculatedField\CalculatedFieldManagerActor.java
1
请完成以下Java代码
public class JpaUserSettingsDao implements UserSettingsDao, TenantEntityDao<UserSettings> { @Autowired private UserSettingsRepository userSettingsRepository; @Override public UserSettings save(TenantId tenantId, UserSettings userSettings) { log.trace("save [{}][{}]", tenantId, userSettings); return DaoUtil.getData(userSettingsRepository.save(new UserSettingsEntity(userSettings))); } @Override public UserSettings findById(TenantId tenantId, UserSettingsCompositeKey id) { return DaoUtil.getData(userSettingsRepository.findById(id)); } @Override public void removeById(TenantId tenantId, UserSettingsCompositeKey id) { userSettingsRepository.deleteById(id);
} @Override public void removeByUserId(TenantId tenantId, UserId userId) { userSettingsRepository.deleteByUserId(userId.getId()); } @Override public List<UserSettings> findByTypeAndPath(TenantId tenantId, UserSettingsType type, String... path) { log.trace("findByTypeAndPath [{}][{}][{}]", tenantId, type, path); return DaoUtil.convertDataList(userSettingsRepository.findByTypeAndPathExisting(type.name(), path)); } @Override public PageData<UserSettings> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(userSettingsRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserSettingsDao.java
1
请完成以下Java代码
private void onPharmaProductImported(@NonNull final I_I_Product iproduct, @NonNull final I_M_Product product ) { product.setIsPrescription(iproduct.isPrescription()); product.setIsNarcotic(iproduct.isNarcotic()); product.setIsColdChain(iproduct.isColdChain()); product.setIsTFG(iproduct.isTFG()); if (!Check.isEmpty(iproduct.getFAM_ZUB(), true)) { product.setFAM_ZUB(iproduct.getFAM_ZUB()); } if (iproduct.getM_DosageForm_ID() > 0) { product.setM_DosageForm_ID(iproduct.getM_DosageForm_ID()); } if (iproduct.getM_Indication_ID() > 0) { product.setM_Indication_ID(iproduct.getM_Indication_ID()); } if (iproduct.getM_PharmaProductCategory_ID() > 0) { product.setM_PharmaProductCategory_ID(iproduct.getM_PharmaProductCategory_ID()); } save(product); importPrices(iproduct); } private void importPrices(@NonNull final I_I_Product importRecord) { createAPU(importRecord); createAEP(importRecord); } private void createAPU(@NonNull final I_I_Product importRecord) {
final TaxCategoryQuery query = TaxCategoryQuery.builder() .type(VATType.RegularVAT) .countryId(Services.get(ICountryDAO.class).getDefaultCountryId()) .build(); final ProductPriceCreateRequest request = ProductPriceCreateRequest.builder() .price(importRecord.getA01APU()) .priceListId(importRecord.getAPU_Price_List_ID()) .productId(importRecord.getM_Product_ID()) .validDate(firstDayYear) .taxCategoryId(taxDAO.findTaxCategoryId(query)) .build(); final ProductPriceImporter command = new ProductPriceImporter(request); command.createProductPrice_And_PriceListVersionIfNeeded(); } private void createAEP(@NonNull final I_I_Product importRecord) { final TaxCategoryQuery query = TaxCategoryQuery.builder() .type(VATType.RegularVAT) .countryId(Services.get(ICountryDAO.class).getDefaultCountryId()) .build(); final ProductPriceCreateRequest request = ProductPriceCreateRequest.builder() .price(importRecord.getA01AEP()) .priceListId(importRecord.getAEP_Price_List_ID()) .productId(importRecord.getM_Product_ID()) .validDate(firstDayYear) .taxCategoryId(taxDAO.findTaxCategoryId(query)) .build(); final ProductPriceImporter command = new ProductPriceImporter(request); command.createProductPrice_And_PriceListVersionIfNeeded(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\PharmaImportProductInterceptor.java
1
请完成以下Java代码
public int getShipment_MailText_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Shipment_MailText_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_PrintFormat getShipment_PrintFormat() throws RuntimeException { return (I_AD_PrintFormat)MTable.get(getCtx(), I_AD_PrintFormat.Table_Name) .getPO(getShipment_PrintFormat_ID(), get_TrxName()); } /** Set Shipment Print Format. @param Shipment_PrintFormat_ID Print Format for Shipments, Receipts, Pick Lists */ public void setShipment_PrintFormat_ID (int Shipment_PrintFormat_ID) { if (Shipment_PrintFormat_ID < 1)
set_Value (COLUMNNAME_Shipment_PrintFormat_ID, null); else set_Value (COLUMNNAME_Shipment_PrintFormat_ID, Integer.valueOf(Shipment_PrintFormat_ID)); } /** Get Shipment Print Format. @return Print Format for Shipments, Receipts, Pick Lists */ public int getShipment_PrintFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Shipment_PrintFormat_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintForm.java
1
请完成以下Java代码
private Optional<PriceListVersion> getPriceListVersion( @NonNull final ExternalIdentifier priceListVersionIdentifier, @NonNull final String orgCode) { return getPriceListVersionId(priceListVersionIdentifier, orgCode) .map(priceListVersionRepository::getPriceListVersionById); } @NonNull public PriceListVersionId getNewestVersionId( @NonNull final String priceListIdentifier, @NonNull final OrgId orgId) { final String orgCode = orgDAO.retrieveOrgValue(orgId); final PriceListId priceListId = getPriceListId(priceListIdentifier, orgCode); return priceListDAO.retrieveNewestPriceListVersionId(priceListId) .orElseThrow(() -> new AdempiereException("No price list version found for price list identifier !") .appendParametersToMessage() .setParameter("priceListIdentifier", priceListIdentifier)); } private void handleNewPriceListVersionExternalReference( @NonNull final String orgCode, @NonNull final ExternalIdentifier externalPriceListVersionIdentifier,
@NonNull final PriceListVersionId priceListVersionId) { Check.assume(externalPriceListVersionIdentifier.getType().equals(ExternalIdentifier.Type.EXTERNAL_REFERENCE), "ExternalIdentifier must be of type external reference."); final ExternalReferenceValueAndSystem externalReferenceValueAndSystem = externalPriceListVersionIdentifier.asExternalValueAndSystem(); final JsonExternalReferenceLookupItem externalReferenceLookupItem = JsonExternalReferenceLookupItem.builder() .id(externalReferenceValueAndSystem.getValue()) .type(PriceListVersionExternalReferenceType.PRICE_LIST_VERSION.getCode()) .build(); final JsonMetasfreshId jsonPriceListVersionId = JsonMetasfreshId.of(priceListVersionId.getRepoId()); final JsonExternalReferenceItem externalReferenceItem = JsonExternalReferenceItem.of(externalReferenceLookupItem, jsonPriceListVersionId); final JsonExternalSystemName systemName = JsonExternalSystemName.of(externalReferenceValueAndSystem.getExternalSystem()); final JsonExternalReferenceCreateRequest externalReferenceCreateRequest = JsonExternalReferenceCreateRequest.builder() .systemName(systemName) .item(externalReferenceItem) .build(); externalReferenceRestControllerService.performInsert(orgCode, externalReferenceCreateRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\pricing\PriceListRestService.java
1
请完成以下Java代码
public class UndeployProcessArchiveStep extends DeploymentOperationStep { protected String processArchvieName; protected JmxManagedProcessApplication deployedProcessApplication; protected ProcessArchiveXml processArchive; protected String processEngineName; public UndeployProcessArchiveStep(JmxManagedProcessApplication deployedProcessApplication, ProcessArchiveXml processArchive, String processEngineName) { this.deployedProcessApplication = deployedProcessApplication; this.processArchive = processArchive; this.processEngineName = processEngineName; } public String getName() { return "Undeploying process archvie "+processArchvieName; } public void performOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
final Map<String, DeployedProcessArchive> processArchiveDeploymentMap = deployedProcessApplication.getProcessArchiveDeploymentMap(); final DeployedProcessArchive deployedProcessArchive = processArchiveDeploymentMap.get(processArchive.getName()); final ProcessEngine processEngine = serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, processEngineName); // unregrister with the process engine. processEngine.getManagementService().unregisterProcessApplication(deployedProcessArchive.getAllDeploymentIds(), true); // delete the deployment if not disabled if (PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_DELETE_UPON_UNDEPLOY, false)) { if (processEngine != null) { // always cascade & skip custom listeners deleteDeployment(deployedProcessArchive.getPrimaryDeploymentId(), processEngine.getRepositoryService()); } } } protected void deleteDeployment(String deploymentId, RepositoryService repositoryService) { repositoryService.deleteDeployment(deploymentId, true, true); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\UndeployProcessArchiveStep.java
1
请完成以下Java代码
public void add(@NonNull final PickFromHU pickFromHU) {list.add(pickFromHU);} public List<I_M_HU> toHUsList() {return list.stream().map(PickFromHU::toM_HU).collect(ImmutableList.toImmutableList());} public PickFromHU getSingleHU() {return CollectionUtils.singleElement(list);} public boolean isSingleHUAlreadyPacked( final boolean checkIfAlreadyPacked, @NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final HuPackingInstructionsId packingInstructionsId) { if (list.size() != 1) { return false; } final PickFromHU hu = list.get(0); // NOTE we check isGeneratedFromInventory because we want to avoid splitting an HU that we just generated it, even if checkIfAlreadyPacked=false if (checkIfAlreadyPacked || hu.isGeneratedFromInventory()) { return hu.isAlreadyPacked(productId, qty, packingInstructionsId); } else { return false; } } } // // // ------------------------------------ // // @Value(staticConstructor = "of") @EqualsAndHashCode(doNotUseGetters = true)
private static class HuPackingInstructionsIdAndCaptionAndCapacity { @NonNull HuPackingInstructionsId huPackingInstructionsId; @NonNull String caption; @Nullable Capacity capacity; @Nullable public Capacity getCapacityOrNull() {return capacity;} @SuppressWarnings("unused") @NonNull public Optional<Capacity> getCapacity() {return Optional.ofNullable(capacity);} public TUPickingTarget toTUPickingTarget() { return TUPickingTarget.ofPackingInstructions(huPackingInstructionsId, caption); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackToHUsProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class PInstanceId implements RepoIdAware { int repoId; @JsonCreator public static PInstanceId ofRepoId(final int repoId) { return new PInstanceId(repoId); } public static PInstanceId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PInstanceId(repoId) : null; } public static Optional<PInstanceId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final PInstanceId id) { return toRepoIdOr(id, -1); } public static int toRepoIdOr(@Nullable final PInstanceId id, final int defaultValue) { return id != null ? id.getRepoId() : defaultValue; }
private PInstanceId(final int adPInstanceId) { repoId = Check.assumeGreaterThanZero(adPInstanceId, "adPInstanceId"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(final PInstanceId o1, final PInstanceId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\PInstanceId.java
2
请完成以下Java代码
public void getFile(String remoteFile, String localTargetDirectory) { Connection conn = new Connection(ip, port); try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (!isAuthenticated) { System.err.println("authentication failed"); } SCPClient client = new SCPClient(conn); client.get(remoteFile, localTargetDirectory); } catch (IOException ex) { Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex); }finally{ conn.close(); } } public void putFile(String localFile, String remoteTargetDirectory) { putFile(localFile, null, remoteTargetDirectory); } public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) { putFile(localFile, remoteFileName, remoteTargetDirectory,null); } public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) { Connection conn = new Connection(ip, port); try {
conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (!isAuthenticated) { System.err.println("authentication failed"); } SCPClient client = new SCPClient(conn); if (StringUtils.isBlank(mode)) { mode = "0600"; } if (remoteFileName == null) { client.put(localFile, remoteTargetDirectory); } else { client.put(localFile, remoteFileName, remoteTargetDirectory, mode); } } catch (IOException ex) { Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex); }finally{ conn.close(); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\util\ScpClientUtil.java
1
请完成以下Java代码
private String getClientId(TbContext ctx) throws TbNodeException { String clientId = mqttNodeConfiguration.isAppendClientIdSuffix() ? mqttNodeConfiguration.getClientId() + "_" + ctx.getServiceId() : mqttNodeConfiguration.getClientId(); int maxLength = mqttNodeConfiguration.getProtocolVersion() == MqttVersion.MQTT_3_1 ? MQTT_3_MAX_CLIENT_ID_LENGTH : MQTT_5_MAX_CLIENT_ID_LENGTH; if (clientId.length() > maxLength) { throw new TbNodeException("The length of Client ID cannot be longer than " + maxLength + ", but current length is " + clientId.length() + ".", true); } return clientId; } MqttClient getMqttClient(TbContext ctx, MqttClientConfig config) { return MqttClient.create(config, null, ctx.getExternalCallExecutor()); } protected void prepareMqttClientConfig(MqttClientConfig config) { ClientCredentials credentials = mqttNodeConfiguration.getCredentials(); if (credentials.getType() == CredentialsType.BASIC) { BasicCredentials basicCredentials = (BasicCredentials) credentials; config.setUsername(basicCredentials.getUsername()); config.setPassword(basicCredentials.getPassword()); } } private SslContext getSslContext() throws SSLException { return mqttNodeConfiguration.isSsl() ? mqttNodeConfiguration.getCredentials().initSslContext() : null; } private String getData(TbMsg tbMsg, boolean parseToPlainText) { if (parseToPlainText) { return JacksonUtil.toPlainText(tbMsg.getData()); } return tbMsg.getData(); }
@Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: String parseToPlainText = "parseToPlainText"; if (!oldConfiguration.has(parseToPlainText)) { hasChanges = true; ((ObjectNode) oldConfiguration).put(parseToPlainText, false); } case 1: String protocolVersion = "protocolVersion"; if (!oldConfiguration.has(protocolVersion)) { hasChanges = true; ((ObjectNode) oldConfiguration).put(protocolVersion, MqttVersion.MQTT_3_1.name()); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mqtt\TbMqttNode.java
1
请在Spring Boot框架中完成以下Java代码
protected static class IntegrationRSocketConfiguration { /** * Check if either an {@link IntegrationRSocketEndpoint} or * {@link RSocketOutboundGateway} bean is available. */ static class AnyRSocketChannelAdapterAvailable extends AnyNestedCondition { AnyRSocketChannelAdapterAvailable() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnBean(IntegrationRSocketEndpoint.class) static class IntegrationRSocketEndpointAvailable { } @ConditionalOnBean(RSocketOutboundGateway.class) static class RSocketOutboundGatewayAvailable { } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(TcpServerTransport.class) protected static class IntegrationRSocketServerConfiguration { @Bean @ConditionalOnMissingBean(ServerRSocketMessageHandler.class) RSocketMessageHandler serverRSocketMessageHandler(RSocketStrategies rSocketStrategies, IntegrationProperties integrationProperties) { RSocketMessageHandler messageHandler = new ServerRSocketMessageHandler( integrationProperties.getRsocket().getServer().isMessageMappingEnabled()); messageHandler.setRSocketStrategies(rSocketStrategies); return messageHandler; } @Bean @ConditionalOnMissingBean ServerRSocketConnector serverRSocketConnector(ServerRSocketMessageHandler messageHandler) { return new ServerRSocketConnector(messageHandler); } } @Configuration(proxyBeanMethods = false) protected static class IntegrationRSocketClientConfiguration { @Bean @ConditionalOnMissingBean @Conditional(RemoteRSocketServerAddressConfigured.class) ClientRSocketConnector clientRSocketConnector(IntegrationProperties integrationProperties, RSocketStrategies rSocketStrategies) { IntegrationProperties.RSocket.Client client = integrationProperties.getRsocket().getClient(); ClientRSocketConnector clientRSocketConnector; if (client.getUri() != null) { clientRSocketConnector = new ClientRSocketConnector(client.getUri()); } else if (client.getHost() != null && client.getPort() != null) { clientRSocketConnector = new ClientRSocketConnector(client.getHost(), client.getPort());
} else { throw new IllegalStateException("Neither uri nor host and port is set"); } clientRSocketConnector.setRSocketStrategies(rSocketStrategies); return clientRSocketConnector; } /** * Check if a remote address is configured for the RSocket Integration client. */ static class RemoteRSocketServerAddressConfigured extends AnyNestedCondition { RemoteRSocketServerAddressConfigured() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty("spring.integration.rsocket.client.uri") static class WebSocketAddressConfigured { } @ConditionalOnProperty({ "spring.integration.rsocket.client.host", "spring.integration.rsocket.client.port" }) static class TcpAddressConfigured { } } } } }
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationAutoConfiguration.java
2
请完成以下Java代码
public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Document Type. @return Document type or rules */ public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** ReplicationType AD_Reference_ID=126 */ public static final int REPLICATIONTYPE_AD_Reference_ID=126; /** Local = L */ public static final String REPLICATIONTYPE_Local = "L"; /** Merge = M */ public static final String REPLICATIONTYPE_Merge = "M"; /** Reference = R */ public static final String REPLICATIONTYPE_Reference = "R";
/** Broadcast = B */ public static final String REPLICATIONTYPE_Broadcast = "B"; /** Set Replication Type. @param ReplicationType Type of Data Replication */ public void setReplicationType (String ReplicationType) { set_Value (COLUMNNAME_ReplicationType, ReplicationType); } /** Get Replication Type. @return Type of Data Replication */ public String getReplicationType () { return (String)get_Value(COLUMNNAME_ReplicationType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationDocument.java
1
请完成以下Java代码
private static Optional<DocumentLayoutElementDescriptor> getClearanceNoteLayoutElement(@NonNull final I_M_HU hu) { if (Check.isBlank(hu.getClearanceNote())) { return Optional.empty(); } final boolean isDisplayedClearanceStatus = Services.get(ISysConfigBL.class).getBooleanValue(SYS_CONFIG_CLEARANCE, true); if (!isDisplayedClearanceStatus) { return Optional.empty(); } return Optional.of(createClearanceNoteLayoutElement()); }
@NonNull private static DocumentLayoutElementDescriptor createClearanceNoteLayoutElement() { final ITranslatableString caption = Services.get(IMsgBL.class).translatable(I_M_HU.COLUMNNAME_ClearanceNote); return DocumentLayoutElementDescriptor.builder() .setCaption(caption) .setWidgetType(DocumentFieldWidgetType.Text) .addField(DocumentLayoutElementFieldDescriptor .builder(I_M_HU.COLUMNNAME_ClearanceNote) .setPublicField(true)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesHelper.java
1
请在Spring Boot框架中完成以下Java代码
public R<List<Kv>> authRoutes(BladeUser user) { if (Func.isEmpty(user) || user.getUserId() == 0L) { return null; } return R.data(menuService.authRoutes(user)); } /** * 顶部菜单数据 */ @GetMapping("/top-menu") @ApiOperationSupport(order = 13) @Operation(summary = "顶部菜单数据", description = "顶部菜单数据") public R<List<TopMenu>> topMenu(BladeUser user) { if (Func.isEmpty(user)) { return null; } List<TopMenu> list = topMenuService.list(Wrappers.<TopMenu>query().lambda().orderByAsc(TopMenu::getSort)); return R.data(list); } /** * 获取顶部菜单树形结构 */
@GetMapping("/grant-top-tree") @PreAuth(RoleConstant.HAS_ROLE_ADMIN) @ApiOperationSupport(order = 14) @Operation(summary = "顶部菜单树形结构", description = "顶部菜单树形结构") public R<GrantTreeVO> grantTopTree(BladeUser user) { GrantTreeVO vo = new GrantTreeVO(); vo.setMenu(menuService.grantTopTree(user)); return R.data(vo); } /** * 获取顶部菜单树形结构 */ @GetMapping("/top-tree-keys") @PreAuth(RoleConstant.HAS_ROLE_ADMIN) @ApiOperationSupport(order = 15) @Operation(summary = "顶部菜单所分配的树", description = "顶部菜单所分配的树") public R<CheckedTreeVO> topTreeKeys(String topMenuIds) { CheckedTreeVO vo = new CheckedTreeVO(); vo.setMenu(menuService.topTreeKeys(topMenuIds)); return R.data(vo); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\MenuController.java
2
请在Spring Boot框架中完成以下Java代码
public void setDetails(Object details) { this.delegate.setDetails(details); } @Override public Object getDetails() { return this.delegate.getDetails(); } @Override public void setAuthenticated(boolean authenticated) { this.delegate.setAuthenticated(authenticated); } @Override public boolean isAuthenticated() { return this.delegate.isAuthenticated(); } @Override public String getName() { return this.delegate.getName(); } @Override public Collection<GrantedAuthority> getAuthorities() { return this.delegate.getAuthorities(); } @Override public Map<String, Object> getTokenAttributes() { return this.delegate.getTokenAttributes(); } /** * Returns a JWT. It usually refers to a token string expressing with 'eyXXX.eyXXX.eyXXX' format.
* * @return the token value as a String */ public String tokenValue() { return delegate.getToken().getTokenValue(); } /** * Extract Subject from JWT. Here, Subject is the user ID in UUID format. * * @return the user ID as a UUID */ public UUID userId() { return UUID.fromString(delegate.getName()); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthToken.java
2
请完成以下Java代码
public void clearCookies(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { String domain = getCookieDomain(httpServletRequest); for (String cookieName : COOKIE_NAMES) { clearCookie(httpServletRequest, httpServletResponse, domain, cookieName); } } private void clearCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String domain, String cookieName) { Cookie cookie = new Cookie(cookieName, ""); setCookieProperties(cookie, httpServletRequest.isSecure(), domain); cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); log.debug("clearing cookie {}", cookie.getName()); } /** * Returns the top level domain of the server from the request. This is used to limit the Cookie * to the top domain instead of the full domain name. * <p> * A lot of times, individual gateways of the same domain get their own subdomain but authentication * shall work across all subdomains of the top level domain. * <p> * For example, when sending a request to <code>app1.domain.com</code>, * this returns <code>.domain.com</code>. * * @param request the HTTP request we received from the client. * @return the top level domain to set the cookies for. * Returns null if the domain is not under a public suffix (.com, .co.uk), e.g. for localhost. */ private String getCookieDomain(HttpServletRequest request) { String domain = oAuth2Properties.getWebClientConfiguration().getCookieDomain(); if (domain != null) { return domain; }
// if not explicitly defined, use top-level domain domain = request.getServerName().toLowerCase(); // strip off leading www. if (domain.startsWith("www.")) { domain = domain.substring(4); } // if it isn't an IP address if (!isIPv4Address(domain) && !isIPv6Address(domain)) { // strip off private subdomains, leaving public TLD only String suffix = suffixMatcher.getDomainRoot(domain); if (suffix != null && !suffix.equals(domain)) { // preserve leading dot return "." + suffix; } } // no top-level domain, stick with default domain return null; } /** * Strip our token cookies from the array. * * @param cookies the cookies we receive as input. * @return the new cookie array without our tokens. */ Cookie[] stripCookies(Cookie[] cookies) { CookieCollection cc = new CookieCollection(cookies); if (cc.removeAll(COOKIE_NAMES)) { return cc.toArray(); } return cookies; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\OAuth2CookieHelper.java
1
请完成以下Java代码
public String getPreferenceType() { return preferenceType; } /** * Show (Value) Preference Menu * * @return true if preference type is not {@link #NONE}. */ public boolean isShowPreference() { return !isNone(); } public boolean isNone() { return this == NONE; } public boolean isClient() { return this == CLIENT; }
public boolean isOrganization() { return this == ORGANIZATION; } public boolean isUser() { return this == USER; } /** * * @return true if this level allows user to view table record change log (i.e. this level is {@link #CLIENT}) */ public boolean canViewRecordChangeLog() { return isClient(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\UserPreferenceLevelConstraint.java
1
请完成以下Java代码
public boolean isAutoStartup() { return this.autoStartup; } /** * Specify the phase in which this component should be started * and stopped. The startup order proceeds from lowest to highest, and * the shutdown order is the reverse of that. By default this value is * Integer.MAX_VALUE meaning that this component starts as late * as possible and stops as soon as possible. */ public void setPhase(int phase) { this.phase = phase; } /** * Return the phase in which this component will be started and stopped. */ @Override public int getPhase() { return this.phase; } @Override public void start() { synchronized (this.lifeCycleMonitor) { if (!this.running) { logger.info("Starting..."); doStart(); this.running = true; logger.info("Started."); } } } @Override public void stop() {
synchronized (this.lifeCycleMonitor) { if (this.running) { logger.info("Stopping..."); doStop(); this.running = false; logger.info("Stopped."); } } } @Override public void stop(Runnable callback) { synchronized (this.lifeCycleMonitor) { stop(); callback.run(); } } @Override public boolean isRunning() { return this.running; } @Override public void destroy() { stop(); } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\AbstractActivitiSmartLifeCycle.java
1
请在Spring Boot框架中完成以下Java代码
public class DemoServiceImpl implements DemoService { @Override public String getOneResult(String methodName) { return String.format("%s invoker success", methodName); } @Override public List<String> getMultiResult(String methodName) { List<String> list = new ArrayList<>(3); for (int i = 0; i < 3; i++) { list.add(String.format("%s invoker success, %d ", methodName, i + 1)); } return list; } @Override public User addUser(User user) { user.setId(1L); return user; } @Override public List<User> findAllUser() {
List<User> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { int no = i + 1; list.add(new User((long) no, "USER_" + no, "PWD_" + no, 18 + no)); } return list; } @Override public User findUserById(Long id) { return new User(id, "USER_" + id, "PWD_" + id, 18); } }
repos\springboot-demo-master\webflux\src\main\java\com\et\webflux\DemoServiceImpl.java
2
请完成以下Java代码
private static Geometry buildPolygonFromCoordinates(List<Coordinate> coordinates) { if (coordinates.size() == 2) { Coordinate a = coordinates.get(0); Coordinate c = coordinates.get(1); coordinates.clear(); Coordinate b = new Coordinate(a.x, c.y); Coordinate d = new Coordinate(c.x, a.y); coordinates.addAll(List.of(a, b, c, d, a)); } CoordinateSequence coordinateSequence = jtsCtx .getShapeFactory() .getGeometryFactory() .getCoordinateSequenceFactory() .create(coordinates.toArray(new Coordinate[0])); return GeometryFixer.fix(jtsCtx.getShapeFactory().getGeometryFactory().createPolygon(coordinateSequence)); } private static List<Coordinate> parseCoordinates(JsonArray coordinatesJson) { List<Coordinate> result = new LinkedList<>(); for (JsonElement coords : coordinatesJson) { double x = coords.getAsJsonArray().get(0).getAsDouble(); double y = coords.getAsJsonArray().get(1).getAsDouble(); result.add(new Coordinate(x, y)); } if (result.size() >= 3) { result.add(result.get(0)); } return result; } private static boolean containsPrimitives(JsonArray array) {
for (JsonElement element : array) { return element.isJsonPrimitive(); } return false; } private static boolean containsArrayWithPrimitives(JsonArray array) { for (JsonElement element : array) { if (!containsPrimitives(element.getAsJsonArray())) { return false; } } return true; } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\geo\GeoUtil.java
1
请完成以下Java代码
public class CamundaScriptImpl extends BpmnModelElementInstanceImpl implements CamundaScript { protected static Attribute<String> camundaScriptFormatAttribute; protected static Attribute<String> camundaResourceAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaScript.class, CAMUNDA_ELEMENT_SCRIPT) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaScript>() { public CamundaScript newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaScriptImpl(instanceContext); } }); camundaScriptFormatAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_SCRIPT_FORMAT) .required() .build(); camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE) .build(); typeBuilder.build(); } public CamundaScriptImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext); } public String getCamundaScriptFormat() { return camundaScriptFormatAttribute.getValue(this); } public void setCamundaScriptFormat(String camundaScriptFormat) { camundaScriptFormatAttribute.setValue(this, camundaScriptFormat); } public String getCamundaResource() { return camundaResourceAttribute.getValue(this); } public void setCamundaResource(String camundaResource) { camundaResourceAttribute.setValue(this, camundaResource); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaScriptImpl.java
1
请完成以下Java代码
public void setAD_Reference_ID (final int AD_Reference_ID) { if (AD_Reference_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Reference_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Reference_ID, AD_Reference_ID); } @Override public int getAD_Reference_ID() { return get_ValueAsInt(COLUMNNAME_AD_Reference_ID); } @Override public void setAD_Ref_List_ID (final int AD_Ref_List_ID) { if (AD_Ref_List_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID); } @Override public int getAD_Ref_List_ID() { return get_ValueAsInt(COLUMNNAME_AD_Ref_List_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); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @Override public void 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 setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueName (final @Nullable java.lang.String ValueName) { set_ValueNoCheck (COLUMNNAME_ValueName, ValueName); } @Override public java.lang.String getValueName() { return get_ValueAsString(COLUMNNAME_ValueName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List.java
1
请完成以下Java代码
public class ConsumerPartitionPausedEvent extends KafkaEvent { private static final long serialVersionUID = 1L; private final TopicPartition partition; /** * Construct an instance with the provided source and partition. * @param source the container instance that generated the event. * @param container the container or the parent container if the container is a child. * @param partition the partition. * @since 2.7 */ public ConsumerPartitionPausedEvent(Object source, Object container, TopicPartition partition) { super(source, container); this.partition = partition; }
/** * Return the paused partition. * @return the partition. * @since 3.3 */ public TopicPartition getPartition() { return this.partition; } @Override public String toString() { return "ConsumerPartitionPausedEvent [partition=" + this.partition + "]"; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ConsumerPartitionPausedEvent.java
1
请完成以下Java代码
public JwkSourceReactiveJwtDecoderBuilder jwtProcessorCustomizer( Consumer<ConfigurableJWTProcessor<JWKSecurityContext>> jwtProcessorCustomizer) { Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null"); this.jwtProcessorCustomizer = jwtProcessorCustomizer; return this; } /** * Build the configured {@link NimbusReactiveJwtDecoder}. * @return the configured {@link NimbusReactiveJwtDecoder} */ public NimbusReactiveJwtDecoder build() { return new NimbusReactiveJwtDecoder(processor()); } Converter<JWT, Mono<JWTClaimsSet>> processor() { JWKSecurityContextJWKSet jwkSource = new JWKSecurityContextJWKSet(); JWSKeySelector<JWKSecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(this.jwsAlgorithm, jwkSource); DefaultJWTProcessor<JWKSecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector); jwtProcessor.setJWSTypeVerifier(this.typeVerifier); jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { });
this.jwtProcessorCustomizer.accept(jwtProcessor); return (jwt) -> { if (jwt instanceof SignedJWT) { return this.jwkSource.apply((SignedJWT) jwt) .onErrorMap((e) -> new IllegalStateException("Could not obtain the keys", e)) .collectList() .map((jwks) -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwks))); } throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm()); }; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoder.java
1
请在Spring Boot框架中完成以下Java代码
final class MethodSecuritySelector implements ImportSelector { private static final boolean isDataPresent = ClassUtils .isPresent("org.springframework.security.data.aot.hint.AuthorizeReturnObjectDataHintsRegistrar", null); private static final boolean isWebPresent = ClassUtils .isPresent("org.springframework.web.servlet.DispatcherServlet", null) && ClassUtils.isPresent("org.springframework.security.web.util.ThrowableAnalyzer", null); private static final boolean isObservabilityPresent = ClassUtils .isPresent("io.micrometer.observation.ObservationRegistry", null); private final ImportSelector autoProxy = new AutoProxyRegistrarSelector(); @Override public String[] selectImports(@NonNull AnnotationMetadata importMetadata) { if (!importMetadata.hasAnnotation(EnableMethodSecurity.class.getName()) && !importMetadata.hasMetaAnnotation(EnableMethodSecurity.class.getName())) { return new String[0]; } EnableMethodSecurity annotation = importMetadata.getAnnotations().get(EnableMethodSecurity.class).synthesize(); List<String> imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata))); if (annotation.prePostEnabled()) { imports.add(PrePostMethodSecurityConfiguration.class.getName()); } if (annotation.securedEnabled()) { imports.add(SecuredMethodSecurityConfiguration.class.getName()); } if (annotation.jsr250Enabled()) { imports.add(Jsr250MethodSecurityConfiguration.class.getName()); } imports.add(AuthorizationProxyConfiguration.class.getName()); if (isDataPresent) { imports.add(AuthorizationProxyDataConfiguration.class.getName()); } if (isWebPresent) { imports.add(AuthorizationProxyWebConfiguration.class.getName()); } if (isObservabilityPresent) { imports.add(MethodObservationConfiguration.class.getName());
} return imports.toArray(new String[0]); } private static final class AutoProxyRegistrarSelector extends AdviceModeImportSelector<EnableMethodSecurity> { private static final String[] IMPORTS = new String[] { AutoProxyRegistrar.class.getName(), MethodSecurityAdvisorRegistrar.class.getName() }; private static final String[] ASPECTJ_IMPORTS = new String[] { MethodSecurityAspectJAutoProxyRegistrar.class.getName() }; @Override protected String[] selectImports(@NonNull AdviceMode adviceMode) { if (adviceMode == AdviceMode.PROXY) { return IMPORTS; } if (adviceMode == AdviceMode.ASPECTJ) { return ASPECTJ_IMPORTS; } throw new IllegalStateException("AdviceMode '" + adviceMode + "' is not supported"); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodSecuritySelector.java
2
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Node_ID. @param Node_ID Node_ID */ @Override public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_Value (COLUMNNAME_Node_ID, null);
else set_Value (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ @Override public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeBar.java
1
请完成以下Java代码
public void updateFromDocType(final I_C_RemittanceAdvice remittanceAdviceRecord, final ICalloutField field) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(remittanceAdviceRecord.getC_DocType_ID()); if (docTypeId == null) { return; } final I_C_DocType docType = docTypeDAO.getById(docTypeId); final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(docType) .setOldDocumentNo(remittanceAdviceRecord.getDocumentNo()) .setDocumentModel(remittanceAdviceRecord) .buildOrNull(); if (documentNoInfo != null && documentNoInfo.isDocNoControlled()) { remittanceAdviceRecord.setDocumentNo(documentNoInfo.getDocumentNo()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = I_C_RemittanceAdvice.COLUMNNAME_C_Payment_Doctype_Target_ID) public void setIsSOTrxFromPaymentDocType(@NonNull final I_C_RemittanceAdvice record) { final I_C_DocType targetPaymentDocType = docTypeDAO.getById(record.getC_Payment_Doctype_Target_ID()); record.setIsSOTrx(targetPaymentDocType.isSOTrx()); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_NEW }, ifColumnsChanged = I_C_RemittanceAdvice.COLUMNNAME_Processed) public void setProcessedFlag(@NonNull final I_C_RemittanceAdvice record) {
final RemittanceAdviceId remittanceAdviceId = RemittanceAdviceId.ofRepoId(record.getC_RemittanceAdvice_ID()); final RemittanceAdvice remittanceAdvice = remittanceAdviceRepository.getRemittanceAdvice(remittanceAdviceId); remittanceAdvice.setProcessedFlag(record.isProcessed()); remittanceAdviceRepository.updateRemittanceAdvice(remittanceAdvice); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteLines(@NonNull final I_C_RemittanceAdvice record) { queryBL.createQueryBuilder(I_C_RemittanceAdvice_Line.class) .addEqualsFilter(I_C_RemittanceAdvice_Line.COLUMN_C_RemittanceAdvice_ID, record.getC_RemittanceAdvice_ID()) .create() .delete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\interceptor\C_RemittanceAdvice.java
1
请完成以下Java代码
private JsonCreateReceiptsResponse createReceipts_0(@NonNull final JsonCreateReceiptsRequest jsonCreateReceiptsRequest) { final List<InOutId> createdReceiptIds = jsonCreateReceiptsRequest.getJsonCreateReceiptInfoList().isEmpty() ? ImmutableList.of() : receiptService.updateReceiptCandidatesAndGenerateReceipts(jsonCreateReceiptsRequest); final List<InOutId> createdReturnIds = jsonCreateReceiptsRequest.getJsonCreateCustomerReturnInfoList().isEmpty() ? ImmutableList.of() : customerReturnRestService.handleReturns(jsonCreateReceiptsRequest.getJsonCreateCustomerReturnInfoList()); return toJsonCreateReceiptsResponse(createdReceiptIds, createdReturnIds); } @NonNull private JsonCreateReceiptsResponse toJsonCreateReceiptsResponse(@NonNull final List<InOutId> receiptIds, @NonNull final List<InOutId> returnIds) { final List<JsonMetasfreshId> jsonReceiptIds = receiptIds .stream()
.map(InOutId::getRepoId) .map(JsonMetasfreshId::of) .collect(ImmutableList.toImmutableList()); final List<JsonMetasfreshId> jsonReturnIds = returnIds .stream() .map(InOutId::getRepoId) .map(JsonMetasfreshId::of) .collect(ImmutableList.toImmutableList()); return JsonCreateReceiptsResponse.builder() .createdReceiptIdList(jsonReceiptIds) .createdReturnIdList(jsonReturnIds) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\ReceiptRestController.java
1
请完成以下Java代码
public String getPermsType() { return permsType; } public void setPermsType(String permsType) { this.permsType = permsType; } public java.lang.String getStatus() { return status; } public void setStatus(java.lang.String status) { this.status = status; } /*update_begin author:wuxianquan date:20190908 for:get set方法 */ public boolean isInternalOrExternal() { return internalOrExternal;
} public void setInternalOrExternal(boolean internalOrExternal) { this.internalOrExternal = internalOrExternal; } /*update_end author:wuxianquan date:20190908 for:get set 方法 */ public boolean isHideTab() { return hideTab; } public void setHideTab(boolean hideTab) { this.hideTab = hideTab; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
1
请完成以下Java代码
public void inefficientUsage() throws SQLException { for (int i = 0; i < 10000; i++) { PreparedStatement preparedStatement = connection.prepareStatement(SQL); preparedStatement.setInt(1, i); preparedStatement.setString(2, "firstname" + i); preparedStatement.setString(3, "secondname" + i); preparedStatement.executeUpdate(); preparedStatement.close(); } } public void betterUsage() { try (PreparedStatement preparedStatement = connection.prepareStatement(SQL)) { for (int i = 0; i < 10000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "firstname" + i); preparedStatement.setString(3, "secondname" + i); preparedStatement.executeUpdate(); } } catch (SQLException e) { throw new RuntimeException(e); } } public void bestUsage() { try (PreparedStatement preparedStatement = connection.prepareStatement(SQL)) { connection.setAutoCommit(false); for (int i = 0; i < 10000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "firstname" + i); preparedStatement.setString(3, "secondname" + i); preparedStatement.addBatch();
} preparedStatement.executeBatch(); try { connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } } catch (SQLException e) { throw new RuntimeException(e); } } public int checkRowCount() { try (PreparedStatement counter = connection.prepareStatement("SELECT COUNT(*) AS customers FROM CUSTOMER")) { ResultSet resultSet = counter.executeQuery(); resultSet.next(); int count = resultSet.getInt("customers"); resultSet.close(); return count; } catch (SQLException e) { return -1; } } }
repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\resusepreparedstatement\ReusePreparedStatement.java
1
请完成以下Java代码
public class TraditionalToHongKongChineseDictionary extends BaseChineseDictionary { static AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<String>(); static { long start = System.currentTimeMillis(); String datPath = HanLP.Config.tcDictionaryRoot + "t2hk"; if (!loadDat(datPath, trie)) { TreeMap<String, String> t2hk = new TreeMap<String, String>(); if (!load(t2hk, false, HanLP.Config.tcDictionaryRoot + "t2hk.txt")) { throw new IllegalArgumentException("繁体转香港繁体加载失败"); } trie.build(t2hk);
saveDat(datPath, trie, t2hk.entrySet()); } logger.info("繁体转香港繁体加载成功,耗时" + (System.currentTimeMillis() - start) + "ms"); } public static String convertToHongKongTraditionalChinese(String traditionalChineseString) { return segLongest(traditionalChineseString.toCharArray(), trie); } public static String convertToHongKongTraditionalChinese(char[] traditionalHongKongChineseString) { return segLongest(traditionalHongKongChineseString, trie); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\TraditionalToHongKongChineseDictionary.java
1
请完成以下Java代码
public int getM_InventoryLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID); } @Override public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); }
@Override public void setMD_Candidate_StockChange_Detail_ID (final int MD_Candidate_StockChange_Detail_ID) { if (MD_Candidate_StockChange_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, MD_Candidate_StockChange_Detail_ID); } @Override public int getMD_Candidate_StockChange_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_StockChange_Detail_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_StockChange_Detail.java
1
请完成以下Java代码
public final class PreAuthorizeReactiveAuthorizationManager implements ReactiveAuthorizationManager<MethodInvocation>, MethodAuthorizationDeniedHandler { private final PreAuthorizeExpressionAttributeRegistry registry = new PreAuthorizeExpressionAttributeRegistry(); public PreAuthorizeReactiveAuthorizationManager() { this(new DefaultMethodSecurityExpressionHandler()); } public PreAuthorizeReactiveAuthorizationManager(MethodSecurityExpressionHandler expressionHandler) { Assert.notNull(expressionHandler, "expressionHandler cannot be null"); this.registry.setExpressionHandler(expressionHandler); } /** * Configure pre/post-authorization template resolution * <p> * By default, this value is <code>null</code>, which indicates that templates should * not be resolved. * @param defaults - whether to resolve pre/post-authorization templates parameters * @since 6.4 */ public void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) { this.registry.setTemplateDefaults(defaults); } public void setApplicationContext(ApplicationContext context) { this.registry.setApplicationContext(context); } /** * Determines if an {@link Authentication} has access to the {@link MethodInvocation}
* by evaluating an expression from the {@link PreAuthorize} annotation. * @param authentication the {@link Mono} of the {@link Authentication} to check * @param mi the {@link MethodInvocation} to check * @return a {@link Mono} of the {@link AuthorizationResult} or an empty {@link Mono} * if the {@link PreAuthorize} annotation is not present */ @Override public Mono<AuthorizationResult> authorize(Mono<Authentication> authentication, MethodInvocation mi) { ExpressionAttribute attribute = this.registry.getAttribute(mi); if (attribute == null) { return Mono.empty(); } // @formatter:off return authentication .map((auth) -> this.registry.getExpressionHandler().createEvaluationContext(auth, mi)) .flatMap((ctx) -> ReactiveExpressionUtils.evaluate(attribute.getExpression(), ctx, authentication, mi)) .cast(AuthorizationResult.class); // @formatter:on } @Override public @Nullable Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) { ExpressionAttribute attribute = this.registry.getAttribute(methodInvocation); PreAuthorizeExpressionAttribute preAuthorizeAttribute = (PreAuthorizeExpressionAttribute) attribute; return preAuthorizeAttribute.getHandler().handleDeniedInvocation(methodInvocation, authorizationResult); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreAuthorizeReactiveAuthorizationManager.java
1
请在Spring Boot框架中完成以下Java代码
public class LogAspect { @Autowired private SysLogDao sysLogDao; @Pointcut("@annotation(com.springboot.annotation.Log)") public void pointcut() { } @Around("pointcut()") public void around(ProceedingJoinPoint point) { long beginTime = System.currentTimeMillis(); try { // 执行方法 point.proceed(); } catch (Throwable e) { e.printStackTrace(); } // 执行时长(毫秒) long time = System.currentTimeMillis() - beginTime; // 保存日志 saveLog(point, time); } private void saveLog(ProceedingJoinPoint joinPoint, long time) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLog sysLog = new SysLog(); Log logAnnotation = method.getAnnotation(Log.class); if (logAnnotation != null) { // 注解上的描述 sysLog.setOperation(logAnnotation.value()); } // 请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); // 请求的方法参数值 Object[] args = joinPoint.getArgs(); // 请求的方法参数名称
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] paramNames = u.getParameterNames(method); if (args != null && paramNames != null) { String params = ""; for (int i = 0; i < args.length; i++) { params += " " + paramNames[i] + ": " + args[i]; } sysLog.setParams(params); } // 获取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); // 设置IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); // 模拟一个用户名 sysLog.setUsername("mrbird"); sysLog.setTime((int) time); Date date = new Date(); sysLog.setCreateTime(date); // 保存系统日志 sysLogDao.saveSysLog(sysLog); } }
repos\SpringAll-master\07.Spring-Boot-AOP-Log\src\main\java\com\springboot\aspect\LogAspect.java
2
请完成以下Java代码
public static void doEvent(String path, Document obj) throws Exception { String[] pathArray = path.split("/"); if (pathArray.length != 4) { logger.info("path 格式不正确: {}", path); return; } Method method = handlerMap.get(path); Object schema = instanceMap.get(pathArray[1]); //查找不到映射Bean和Method不做处理 if (method == null || schema == null) { return; } try { long begin = System.currentTimeMillis(); logger.info("integrate data: {} , {}", path, obj); method.invoke(schema, new Object[]{obj}); logger.info("integrate data consume: {}ms ", System.currentTimeMillis() - begin); } catch (Exception e) { logger.error("调用组合逻辑异常", e); throw new Exception(e.getCause()); } } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean.
public static Object getBean(String name) { return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } //通过name,以及Clazz返回指定的Bean public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
repos\spring-boot-leaning-master\2.x_data\3-4 解决后期业务变动导致的数据结构不一致的问题\spring-boot-canal-mongodb-cascade\src\main\java\com\neo\util\SpringUtil.java
1
请完成以下Java代码
public class GetRenderedStartFormCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected String formEngineName; public GetRenderedStartFormCmd(String processDefinitionId, String formEngineName) { this.processDefinitionId = processDefinitionId; this.formEngineName = formEngineName; } @Override public Object execute(CommandContext commandContext) { ProcessDefinition processDefinition = commandContext .getProcessEngineConfiguration() .getDeploymentManager() .findDeployedProcessDefinitionById(processDefinitionId); if (processDefinition == null) { throw new ActivitiObjectNotFoundException("Process Definition '" + processDefinitionId + "' not found", ProcessDefinition.class); } StartFormHandler startFormHandler = ((ProcessDefinitionEntity) processDefinition).getStartFormHandler(); if (startFormHandler == null) { return null; }
FormEngine formEngine = commandContext .getProcessEngineConfiguration() .getFormEngines() .get(formEngineName); if (formEngine == null) { throw new ActivitiException("No formEngine '" + formEngineName + "' defined process engine configuration"); } StartFormData startForm = startFormHandler.createStartFormData(processDefinition); return formEngine.renderStartForm(startForm); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\GetRenderedStartFormCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class DataStoreConfig { //Configuration for embededded data store through H2 @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .setName("socketDB") .addScript("classpath:schema.sql") .addScript("classpath:data.sql") .setScriptEncoding("UTF-8") .continueOnError(true) .ignoreFailedDrops(true) .build(); } @Bean public JpaVendorAdapter jpaVendorAdapter() { final HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter(); bean.setDatabase(Database.H2); bean.setGenerateDdl(true); return bean; }
@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean(); bean.setDataSource(dataSource); bean.setJpaVendorAdapter(jpaVendorAdapter()); bean.setPackagesToScan("com.baeldung.springsecuredsockets"); //Set properties on Hibernate Properties properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); properties.setProperty("hibernate.hbm2ddl.auto", "update"); bean.setJpaProperties(properties); return bean; } @Bean public JpaTransactionManager transactionManager(EntityManagerFactory emf) { return new JpaTransactionManager(emf); } }
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\config\DataStoreConfig.java
2
请在Spring Boot框架中完成以下Java代码
public void execute(QuartzJob quartzJob) throws Exception { String jobName = quartzJob.getJobClassName().trim(); Date startDate = new Date(); String ymd = DateUtils.date2Str(startDate,DateUtils.yyyymmddhhmmss.get()); String identity = jobName + ymd; //3秒后执行 只执行一次 // 代码逻辑说明: 定时任务立即执行,延迟3秒改成0.1秒------- startDate.setTime(startDate.getTime() + 100L); // 定义一个Trigger SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger() .withIdentity(identity, JOB_TEST_GROUP) .startAt(startDate) .build(); // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(getClass(jobName).getClass()).withIdentity(identity).usingJobData("parameter", quartzJob.getParameter()).build(); // 将trigger和 jobDetail 加入这个调度 scheduler.scheduleJob(jobDetail, trigger); // 启动scheduler scheduler.start(); } @Override @Transactional(rollbackFor = JeecgBootException.class) public void pause(QuartzJob quartzJob){ schedulerDelete(quartzJob.getId()); quartzJob.setStatus(CommonConstant.STATUS_DISABLE); this.updateById(quartzJob); } /** * 添加定时任务 * * @param jobClassName * @param cronExpression * @param parameter */ private void schedulerAdd(String id, String jobClassName, String cronExpression, String parameter) { try { // 启动调度器 scheduler.start(); // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(id).usingJobData("parameter", parameter).build(); // 表达式调度构建器(即任务执行的时间) CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
// 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(id).withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { throw new JeecgBootException("创建定时任务失败", e); } catch (RuntimeException e) { throw new JeecgBootException(e.getMessage(), e); }catch (Exception e) { throw new JeecgBootException("后台找不到该类名:" + jobClassName, e); } } /** * 删除定时任务 * * @param id */ private void schedulerDelete(String id) { try { scheduler.pauseTrigger(TriggerKey.triggerKey(id)); scheduler.unscheduleJob(TriggerKey.triggerKey(id)); scheduler.deleteJob(JobKey.jobKey(id)); } catch (Exception e) { log.error(e.getMessage(), e); throw new JeecgBootException("删除定时任务失败"); } } private static Job getClass(String classname) throws Exception { Class<?> class1 = Class.forName(classname); return (Job) class1.newInstance(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\quartz\service\impl\QuartzJobServiceImpl.java
2
请完成以下Java代码
public OrderLineId getOrderLineId() {return orderLineInfo.getOrderLineId();} public Money getOrderLineNetAmt() {return orderLineInfo.getOrderLineNetAmt();} public Quantity getQtyOrdered() {return orderLineInfo.getQtyOrdered();} public ProductId getProductId() {return orderLineInfo.getProductId();} public CurrencyId getCurrencyId() { return orderLineInfo.getCurrencyId(); } public UomId getUomId() { return orderLineInfo.getUomId(); } public void setOrderLineInfo(@NonNull final OrderCostDetailOrderLinePart orderLineInfo) { this.costAmount.assertCurrencyId(orderLineInfo.getCurrencyId()); Quantity.assertSameUOM(this.inoutQty, orderLineInfo.getQtyOrdered()); this.orderLineInfo = orderLineInfo; } void setCostAmount(@NonNull final Money costAmountNew) { costAmountNew.assertCurrencyId(orderLineInfo.getCurrencyId());
this.costAmount = costAmountNew; } void addInOutCost(@NonNull Money amt, @NonNull Quantity qty) { this.inoutCostAmount = this.inoutCostAmount.add(amt); this.inoutQty = this.inoutQty.add(qty); } public OrderCostDetail copy(@NonNull final OrderCostCloneMapper mapper) { return toBuilder() .id(null) .orderLineInfo(orderLineInfo.withOrderLineId(mapper.getTargetOrderLineId(orderLineInfo.getOrderLineId()))) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostDetail.java
1
请完成以下Java代码
public class C_BPartner { /** * If <code>C_InvoiceSchedule_ID</code> changes, then this MV calls {@link IInvoiceCandDAO#invalidateCandsForBPartnerInvoiceRule(org.compiere.model.I_C_BPartner)} to invalidate those ICs that * might be concerned by the change. */ @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE,// ifColumnsChanged = I_C_BPartner.COLUMNNAME_C_InvoiceSchedule_ID) public void onInvoiceRuleChange(@NonNull final I_C_BPartner bPartnerRecord) throws Exception { try (final MDCCloseable bPartnerRecordMDC = TableRecordMDC.putTableRecordReference(bPartnerRecord)) { final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); final BPartnerId bpartnerid = BPartnerId.ofRepoId(bPartnerRecord.getC_BPartner_ID()); invoiceCandDAO.invalidateCandsForBPartnerInvoiceRule(bpartnerid); } }
/** * Invalidate all invoice candidates of given partner, in case the header/line aggregation definitions were changed. */ @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE,// ifColumnsChanged = { I_C_BPartner.COLUMNNAME_PO_Invoice_Aggregation_ID, I_C_BPartner.COLUMNNAME_PO_InvoiceLine_Aggregation_ID, I_C_BPartner.COLUMNNAME_SO_Invoice_Aggregation_ID, I_C_BPartner.COLUMNNAME_SO_InvoiceLine_Aggregation_ID }) public void onInvoiceAggregationChanged(@NonNull final I_C_BPartner bPartnerRecord) { try (final MDCCloseable bPartnerRecordMDC = TableRecordMDC.putTableRecordReference(bPartnerRecord)) { final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); invoiceCandDAO.invalidateCandsForBPartner(bPartnerRecord); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_BPartner.java
1
请完成以下Java代码
public static List<Integer> findPeaks(int[] arr) { List<Integer> peaks = new ArrayList<>(); if (arr == null || arr.length == 0) { return peaks; } findPeakElements(arr, 0, arr.length - 1, peaks, arr.length); return peaks; } private static void findPeakElements(int[] arr, int low, int high, List<Integer> peaks, int length) { if (low > high) { return; } int mid = low + (high - low) / 2;
boolean isPeak = (mid == 0 || arr[mid] > arr[mid - 1]) && (mid == length - 1 || arr[mid] > arr[mid + 1]); boolean isFirstInSequence = mid > 0 && arr[mid] == arr[mid - 1] && arr[mid] > arr[mid + 1]; if (isPeak || isFirstInSequence) { if (!peaks.contains(arr[mid])) { peaks.add(arr[mid]); } } findPeakElements(arr, low, mid - 1, peaks, length); findPeakElements(arr, mid + 1, high, peaks, length); } }
repos\tutorials-master\core-java-modules\core-java-collections-array-list-2\src\main\java\com\baeldung\peakelements\MultiplePeakFinder.java
1
请完成以下Java代码
public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) { Node parent = childElement.unwrap().getParentNode(); if (parent == null || !parentElement.unwrap().isEqualNode(parent)) { throw LOG.elementIsNotChildOfThisElement(childElement, parentElement); } } /** * Ensures that the expression is not the root expression '/'. * * @param expression the expression to ensure to be not the root expression '/' * @throws SpinXPathException if the expression is the root expression '/' */ public static void ensureNotDocumentRootExpression(String expression) { if (ROOT_EXPRESSION.equals(expression)) { throw LOG.notAllowedXPathExpression(expression); } } /** * Ensure that the node is not null. * * @param node the node to ensure to be not null * @param expression the expression was used to find the node * @throws SpinXPathException if the node is null */ public static void ensureXPathNotNull(Node node, String expression) { if (node == null) { throw LOG.unableToFindXPathExpression(expression);
} } /** * Ensure that the nodeList is either null or empty. * * @param nodeList the nodeList to ensure to be either null or empty * @param expression the expression was used to fine the nodeList * @throws SpinXPathException if the nodeList is either null or empty */ public static void ensureXPathNotEmpty(NodeList nodeList, String expression) { if (nodeList == null || nodeList.getLength() == 0) { throw LOG.unableToFindXPathExpression(expression); } } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\util\DomXmlEnsure.java
1
请在Spring Boot框架中完成以下Java代码
public void addAuthorWithBooks() { Author author = new Author(); author.setId(new AuthorId("Alicia Tom", 38)); author.setGenre("Anthology"); Book book1 = new Book(); book1.setIsbn("001-AT"); book1.setTitle("The book of swords"); Book book2 = new Book(); book2.setIsbn("002-AT"); book2.setTitle("Anthology of a day"); Book book3 = new Book(); book3.setIsbn("003-AT"); book3.setTitle("Anthology today"); author.addBook(book1); // use addBook() helper author.addBook(book2); author.addBook(book3); authorRepository.save(author);
} @Transactional(readOnly = true) public void fetchAuthorByName() { Author author = authorRepository.fetchByName("Alicia Tom"); System.out.println(author); } @Transactional public void removeBookOfAuthor() { Author author = authorRepository.fetchWithBooks(new AuthorId("Alicia Tom", 38)); author.removeBook(author.getBooks().get(0)); } @Transactional public void removeAuthor() { authorRepository.deleteById(new AuthorId("Alicia Tom", 38)); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddable\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
protected final T _this() { return (T) this; } /** * Sets the {@code RelayState} parameter that will accompany this AuthNRequest * @param relayState the relay state value, unencoded. if null or empty, the * parameter will be removed from the map. * @return this object */ public T relayState(String relayState) { this.relayState = relayState; return _this(); } /** * Sets the {@code SAMLRequest} parameter that will accompany this AuthNRequest * @param samlRequest the SAMLRequest parameter. * @return this object */ public T samlRequest(String samlRequest) { this.samlRequest = samlRequest; return _this(); } /** * Sets the {@code authenticationRequestUri}, a URL that will receive the * AuthNRequest message * @param authenticationRequestUri the relay state value, unencoded. * @return this object
*/ public T authenticationRequestUri(String authenticationRequestUri) { this.authenticationRequestUri = authenticationRequestUri; return _this(); } /** * This is the unique id used in the {@link #samlRequest} * @param id the SAML2 request id * @return the {@link AbstractSaml2AuthenticationRequest.Builder} for further * configurations * @since 5.8 */ public T id(String id) { Assert.notNull(id, "id cannot be null"); this.id = id; return _this(); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\AbstractSaml2AuthenticationRequest.java
2
请完成以下Java代码
public Collection<Process> getProcesses() { return processCollection.get(this); } public Collection<Decision> getDecisions() { return decisionCollection.get(this); } public ExtensionElements getExtensionElements() { return extensionElementsChild.getChild(this); } public void setExtensionElements(ExtensionElements extensionElements) { extensionElementsChild.setChild(this, extensionElements); } public Collection<Relationship> getRelationships() { return relationshipCollection.get(this); } public Collection<Artifact> getArtifacts() { return artifactCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, CMMN_ELEMENT_DEFINITIONS) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() { public Definitions newInstance(ModelTypeInstanceContext instanceContext) { return new DefinitionsImpl(instanceContext); } }); idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID) .idAttribute() .build(); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); targetNamespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_NAMESPACE) .required() .build(); expressionLanguageAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPRESSION_LANGUAGE) .defaultValue(XPATH_NS) .build(); exporterAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER) .build(); exporterVersionAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER_VERSION) .build();
authorAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHOR) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); importCollection = sequenceBuilder.elementCollection(Import.class) .build(); caseFileItemDefinitionCollection = sequenceBuilder.elementCollection(CaseFileItemDefinition.class) .build(); caseCollection = sequenceBuilder.elementCollection(Case.class) .build(); processCollection = sequenceBuilder.elementCollection(Process.class) .build(); decisionCollection = sequenceBuilder.elementCollection(Decision.class) .build(); extensionElementsChild = sequenceBuilder.element(ExtensionElements.class) .minOccurs(0) .maxOccurs(1) .build(); relationshipCollection = sequenceBuilder.elementCollection(Relationship.class) .build(); artifactCollection = sequenceBuilder.elementCollection(Artifact.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DefinitionsImpl.java
1
请完成以下Java代码
private static Method getMainMethod(Class<?> application) throws Exception { try { return application.getDeclaredMethod("main", String[].class); } catch (NoSuchMethodException ex) { return application.getDeclaredMethod("main"); } } public static void main(String[] args) throws Exception { int requiredArgs = 6; Assert.state(args.length >= requiredArgs, () -> "Usage: " + SpringApplicationAotProcessor.class.getName() + " <applicationMainClass> <sourceOutput> <resourceOutput> <classOutput> <groupId> <artifactId> <originalArgs...>"); Class<?> application = Class.forName(args[0]); Settings settings = Settings.builder() .sourceOutput(Paths.get(args[1])) .resourceOutput(Paths.get(args[2])) .classOutput(Paths.get(args[3])) .groupId((StringUtils.hasText(args[4])) ? args[4] : "unspecified") .artifactId(args[5]) .build(); String[] applicationArgs = (args.length > requiredArgs) ? Arrays.copyOfRange(args, requiredArgs, args.length) : new String[0]; new SpringApplicationAotProcessor(application, settings, applicationArgs).process(); } /** * {@link SpringApplicationHook} used to capture the {@link ApplicationContext} and * trigger early exit of main method. */ private static final class AotProcessorHook implements SpringApplicationHook { private final Class<?> application; private AotProcessorHook(Class<?> application) { this.application = application; } @Override public SpringApplicationRunListener getRunListener(SpringApplication application) { return new SpringApplicationRunListener() {
@Override public void contextLoaded(ConfigurableApplicationContext context) { throw new AbandonedRunException(context); } }; } private <T> GenericApplicationContext run(ThrowingSupplier<T> action) { try { SpringApplication.withHook(this, action); } catch (AbandonedRunException ex) { ApplicationContext context = ex.getApplicationContext(); Assert.state(context instanceof GenericApplicationContext, () -> "AOT processing requires a GenericApplicationContext but got a " + ((context != null) ? context.getClass().getName() : "null")); return (GenericApplicationContext) context; } throw new IllegalStateException( "No application context available after calling main method of '%s'. Does it run a SpringApplication?" .formatted(this.application.getName())); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationAotProcessor.java
1
请完成以下Java代码
public class HULoadException extends HUException { /** * */ private static final long serialVersionUID = 6554990044648764732L; private final IAllocationRequest request; private final IAllocationResult result; /** * * @param message * @param request initial request * @param result last load result, which failed */ public HULoadException(final String message, final IAllocationRequest request, final IAllocationResult result) { super(message);
Check.assumeNotNull(request, "request not null"); this.request = request; Check.assumeNotNull(result, "result not null"); this.result = result; } public IAllocationRequest getAllocationRequest() { return request; } public IAllocationResult getAllocationResult() { return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\exceptions\HULoadException.java
1
请完成以下Java代码
public void setMSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID (int MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelneAntwort. @return MSV3_VerfuegbarkeitsanfrageEinzelneAntwort */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort_ID); if (ii == null) return 0; return ii.intValue(); } /** * MSV3_VerfuegbarkeitTyp AD_Reference_ID=540817 * Reference name: MSV3_VerfuegbarkeitTyp */
public static final int MSV3_VERFUEGBARKEITTYP_AD_Reference_ID=540817; /** Spezifisch = Spezifisch */ public static final String MSV3_VERFUEGBARKEITTYP_Spezifisch = "Spezifisch"; /** Unspezifisch = Unspezifisch */ public static final String MSV3_VERFUEGBARKEITTYP_Unspezifisch = "Unspezifisch"; /** Set VerfuegbarkeitTyp. @param MSV3_VerfuegbarkeitTyp VerfuegbarkeitTyp */ @Override public void setMSV3_VerfuegbarkeitTyp (java.lang.String MSV3_VerfuegbarkeitTyp) { set_Value (COLUMNNAME_MSV3_VerfuegbarkeitTyp, MSV3_VerfuegbarkeitTyp); } /** Get VerfuegbarkeitTyp. @return VerfuegbarkeitTyp */ @Override public java.lang.String getMSV3_VerfuegbarkeitTyp () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitTyp); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort.java
1
请完成以下Java代码
protected void ensureProcessDefinitionAndTenantIdNotSet() { if (processDefinitionId != null && isTenantIdSet) { throw LOG.exceptionCorrelateMessageWithProcessDefinitionAndTenantId(); } } protected <T> T execute(Command<T> command) { if(commandExecutor != null) { return commandExecutor.execute(command); } else { return command.execute(commandContext); } } // getters ////////////////////////////////// public CommandExecutor getCommandExecutor() { return commandExecutor; } public CommandContext getCommandContext() { return commandContext; } public String getMessageName() { return messageName; } public String getBusinessKey() { return businessKey; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public Map<String, Object> getCorrelationProcessInstanceVariables() { return correlationProcessInstanceVariables;
} public Map<String, Object> getCorrelationLocalVariables() { return correlationLocalVariables; } public Map<String, Object> getPayloadProcessInstanceVariables() { return payloadProcessInstanceVariables; } public VariableMap getPayloadProcessInstanceVariablesLocal() { return payloadProcessInstanceVariablesLocal; } public VariableMap getPayloadProcessInstanceVariablesToTriggeredScope() { return payloadProcessInstanceVariablesToTriggeredScope; } public boolean isExclusiveCorrelation() { return isExclusiveCorrelation; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isExecutionsOnly() { return executionsOnly; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationBuilderImpl.java
1
请完成以下Java代码
public T get() throws InterruptedException, ExecutionException { latch.await(); return get0(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { latch.await(timeout, unit); return get0(); } private T get0() throws ExecutionException { if (!done) { throw new IllegalStateException("Value not available"); } // // We got a cancellation if (canceled)
{ final CancellationException cancelException = new CancellationException(exception.getLocalizedMessage()); cancelException.initCause(exception); throw cancelException; } // // We got an error if (exception != null) { throw new ExecutionException(exception); } return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\FutureValue.java
1
请在Spring Boot框架中完成以下Java代码
public static class RetryConfig { private int retries = 3; private Set<HttpStatus.Series> series = new HashSet<>(List.of(HttpStatus.Series.SERVER_ERROR)); private Set<Class<? extends Throwable>> exceptions = new HashSet<>( List.of(IOException.class, TimeoutException.class, RetryException.class)); private Set<HttpMethod> methods = new HashSet<>(List.of(HttpMethod.GET)); private boolean cacheBody = false; public int getRetries() { return retries; } public RetryConfig setRetries(int retries) { this.retries = retries; return this; } public Set<HttpStatus.Series> getSeries() { return series; } public RetryConfig setSeries(Set<HttpStatus.Series> series) { this.series = series; return this; } public RetryConfig addSeries(HttpStatus.Series... series) { this.series.addAll(Arrays.asList(series)); return this; } public Set<Class<? extends Throwable>> getExceptions() { return exceptions; } public RetryConfig setExceptions(Set<Class<? extends Throwable>> exceptions) { this.exceptions = exceptions; return this; } public RetryConfig addExceptions(Class<? extends Throwable>... exceptions) { this.exceptions.addAll(Arrays.asList(exceptions)); return this; } public Set<HttpMethod> getMethods() { return methods; } public RetryConfig setMethods(Set<HttpMethod> methods) { this.methods = methods; return this; } public RetryConfig addMethods(HttpMethod... methods) { this.methods.addAll(Arrays.asList(methods)); return this; } public boolean isCacheBody() { return cacheBody; }
public RetryConfig setCacheBody(boolean cacheBody) { this.cacheBody = cacheBody; return this; } } public static class RetryException extends NestedRuntimeException { private final ServerRequest request; private final ServerResponse response; RetryException(ServerRequest request, ServerResponse response) { super(null); this.request = request; this.response = response; } public ServerRequest getRequest() { return request; } public ServerResponse getResponse() { return response; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RetryFilterFunctions.java
2
请完成以下Java代码
public static void main(String[] args) { final UserService userService = new UserServiceMapImpl(); post("/users", (request, response) -> { response.type("application/json"); User user = new Gson().fromJson(request.body(), User.class); userService.addUser(user); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS)); }); get("/users", (request, response) -> { response.type("application/json"); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUsers()))); }); get("/users/:id", (request, response) -> { response.type("application/json"); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUser(request.params(":id"))))); }); put("/users/:id", (request, response) -> { response.type("application/json");
User toEdit = new Gson().fromJson(request.body(), User.class); User editedUser = userService.editUser(toEdit); if (editedUser != null) { return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(editedUser))); } else { return new Gson().toJson(new StandardResponse(StatusResponse.ERROR, new Gson().toJson("User not found or error in edit"))); } }); delete("/users/:id", (request, response) -> { response.type("application/json"); userService.deleteUser(request.params(":id")); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, "user deleted")); }); options("/users/:id", (request, response) -> { response.type("application/json"); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, (userService.userExist(request.params(":id"))) ? "User exists" : "User does not exists")); }); } }
repos\tutorials-master\web-modules\spark-java\src\main\java\com\baeldung\sparkjava\SparkRestExample.java
1
请完成以下Java代码
public boolean isCreateAsActive () { Object oo = get_Value(COLUMNNAME_IsCreateAsActive); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Depreciate. @param IsDepreciated The asset will be depreciated */ public void setIsDepreciated (boolean IsDepreciated) { set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated)); } /** Get Depreciate. @return The asset will be depreciated */ public boolean isDepreciated () { Object oo = get_Value(COLUMNNAME_IsDepreciated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set One Asset Per UOM. @param IsOneAssetPerUOM Create one asset per UOM */ public void setIsOneAssetPerUOM (boolean IsOneAssetPerUOM) { set_Value (COLUMNNAME_IsOneAssetPerUOM, Boolean.valueOf(IsOneAssetPerUOM)); } /** Get One Asset Per UOM. @return Create one asset per UOM */ public boolean isOneAssetPerUOM () { Object oo = get_Value(COLUMNNAME_IsOneAssetPerUOM); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Owned. @param IsOwned The asset is owned by the organization */ public void setIsOwned (boolean IsOwned) { set_Value (COLUMNNAME_IsOwned, Boolean.valueOf(IsOwned)); } /** Get Owned.
@return The asset is owned by the organization */ public boolean isOwned () { Object oo = get_Value(COLUMNNAME_IsOwned); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Track Issues. @param IsTrackIssues Enable tracking issues for this asset */ public void setIsTrackIssues (boolean IsTrackIssues) { set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues)); } /** Get Track Issues. @return Enable tracking issues for this asset */ public boolean isTrackIssues () { Object oo = get_Value(COLUMNNAME_IsTrackIssues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group.java
1
请完成以下Java代码
public BigDecimal getValueAsBigDecimal() { return getValue(COL::toBigDecimal); } private static BigDecimal toBigDecimal(final String valueStr) { if (valueStr == null || valueStr.trim().isEmpty()) { return null; } try { return new BigDecimal(valueStr); } catch (final Exception e) { return null; } } public Integer getValueAsInteger() { return getValue(COL::toInteger); } private static Integer toInteger(final String valueStr) {
if (valueStr == null || valueStr.trim().isEmpty()) { return null; } try { return Integer.parseInt(valueStr); } catch (final Exception e) { return null; } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\COL.java
1
请完成以下Java代码
public Set<DocumentId> retrieveRowIdsMatchingFilters( @NonNull final ViewId viewId, @NonNull final DocumentFilterList filters, @NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } final SqlViewRowsWhereClause sqlWhereClause = getSqlWhereClause(viewId, filters, DocumentIdsSelection.of(rowIds), SqlOptions.usingTableName(getTableName())); return retrieveRowIdsByWhereClause(sqlWhereClause); } public Set<DocumentId> retrieveRowIdsMatchingFiltersButNotInView( @NonNull final ViewId viewId, @NonNull final DocumentFilterList filters, @NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } final SqlViewRowsWhereClause sqlWhereClause = getSqlWhereClause(viewId, filters, DocumentIdsSelection.of(rowIds), SqlOptions.usingTableName(getTableName())) .withRowsNotPresentInViewSelection(); return retrieveRowIdsByWhereClause(sqlWhereClause); } private Set<DocumentId> retrieveRowIdsByWhereClause(final SqlViewRowsWhereClause sqlWhereClause) { if (sqlWhereClause.isNoRecords()) { return ImmutableSet.of(); } final SqlViewKeyColumnNamesMap keyColumnNamesMap = sqlViewBinding.getSqlViewKeyColumnNamesMap(); final SqlAndParams sql = SqlAndParams.builder() .append("SELECT ").append(keyColumnNamesMap.getKeyColumnNamesCommaSeparated()) .append("\n FROM " + getTableName()) .append("\n WHERE (\n").append(sqlWhereClause.toSqlAndParams()).append("\n)") .build(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.getSql(), ITrx.TRXNAME_ThreadInherited); DB.setParameters(pstmt, sql.getSqlParams()); rs = pstmt.executeQuery();
final HashSet<DocumentId> rowIds = new HashSet<>(); while (rs.next()) { final DocumentId rowId = keyColumnNamesMap.retrieveRowId(rs); if (rowId != null) { rowIds.add(rowId); } } return rowIds; } catch (final Exception ex) { throw new DBException(ex, sql.getSql(), sql.getSqlParams()); } finally { DB.close(rs, pstmt); } } @Override public List<Object> retrieveFieldValues( @NonNull final ViewEvaluationCtx viewEvalCtx, @NonNull final String selectionId, @NonNull final String fieldName, final int limit) { final SqlViewRowFieldLoader fieldLoader = sqlViewBinding.getFieldLoader(fieldName); final SqlAndParams sql = sqlViewBinding.getSqlViewSelect().selectFieldValues(viewEvalCtx, selectionId, fieldName, limit); final String adLanguage = viewEvalCtx.getAdLanguage(); return DB.retrieveRows( sql.getSql(), sql.getSqlParams(), rs -> fieldLoader.retrieveValue(rs, adLanguage)); } public boolean isQueryIfNoFilters() {return sqlViewBinding.isQueryIfNoFilters();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewDataRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class StockEstimateDeletedHandler implements MaterialEventHandler<AbstractStockEstimateEvent> { private static final transient Logger logger = LogManager.getLogger(StockEstimateDeletedHandler.class); private final StockEstimateEventService stockEstimateEventService; private final CandidateChangeService candidateChangeHandler; private final StockChangeDetailRepo stockChangeDetailRepo; public StockEstimateDeletedHandler( @NonNull final StockEstimateEventService stockEstimateEventService, @NonNull final CandidateChangeService candidateChangeHandler, @NonNull final StockChangeDetailRepo stockChangeDetailRepo) { this.stockEstimateEventService = stockEstimateEventService; this.candidateChangeHandler = candidateChangeHandler; this.stockChangeDetailRepo = stockChangeDetailRepo; } @Override public Collection<Class<? extends AbstractStockEstimateEvent>> getHandledEventType() { return ImmutableList.of(StockEstimateDeletedEvent.class); } @Override public void handleEvent(final AbstractStockEstimateEvent event) { final Candidate candidateToDelete = stockEstimateEventService.retrieveExistingStockEstimateCandidateOrNull(event); if (candidateToDelete == null) { Loggables.withLogger(logger, Level.WARN).addLog("Nothing to do for event, record was already deleted", event); return; } final BusinessCaseDetail businessCaseDetail = candidateToDelete.getBusinessCaseDetail(); if (businessCaseDetail == null) { throw new AdempiereException("No business case detail found for candidate") .appendParametersToMessage() .setParameter("candidateId: ", candidateToDelete.getId());
} final StockChangeDetail existingStockChangeDetail = StockChangeDetail.cast(businessCaseDetail) .toBuilder() .isReverted(true) .build(); final CandidatesQuery query = CandidatesQuery.fromCandidate(candidateToDelete, false); final I_MD_Candidate candidateRecord = RepositoryCommons .mkQueryBuilder(query) .create() .firstOnly(I_MD_Candidate.class); if (candidateRecord == null) { throw new AdempiereException("No MD_Candidate found for candidate") .appendParametersToMessage() .setParameter("candidateId: ", candidateToDelete.getId()); } stockChangeDetailRepo.saveOrUpdate(existingStockChangeDetail, candidateRecord); candidateChangeHandler.onCandidateDelete(candidateToDelete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\stockchange\StockEstimateDeletedHandler.java
2
请完成以下Java代码
public String getAuditmsg() { return auditmsg; } public void setAuditmsg(String auditmsg) { this.auditmsg = auditmsg; } public String getTrialstatus() { return trialstatus; } public void setTrialstatus(String trialstatus) { this.trialstatus = trialstatus; } public String getFirauditer() { return firauditer; } public void setFirauditer(String firauditer) { this.firauditer = firauditer; } public String getFiraudittime() { return firaudittime; } public void setFiraudittime(String firaudittime) { this.firaudittime = firaudittime; } public String getFinauditer() { return finauditer; } public void setFinauditer(String finauditer) { this.finauditer = finauditer; } public String getFinaudittime() { return finaudittime; } public void setFinaudittime(String finaudittime) { this.finaudittime = finaudittime; } public String getEdittime() { return edittime;
} public void setEdittime(String edittime) { this.edittime = edittime; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public String getEnddate() { return enddate; } public void setEnddate(String enddate) { this.enddate = enddate; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtoll.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public boolean hasCorrelationParameterValues() { return correlationParameterValues.size() > 0; } public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } @Override public void migrateToLatestCaseDefinition() { checkValidInformation(); cmmnRuntimeService.migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(this);
} @Override public void migrateToCaseDefinition(String caseDefinitionId) { this.newCaseDefinitionId = caseDefinitionId; checkValidInformation(); cmmnRuntimeService.migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(caseDefinitionId)) { throw new FlowableIllegalArgumentException("The case definition must be provided using the exact id of the version the subscription was registered for."); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionModificationBuilderImpl.java
1
请完成以下Java代码
public class Hash implements java.io.Serializable { /** * */ private static final long serialVersionUID = 7635193444611108511L; private Array keys = new Array(); private Array elements = new Array(); public Hash() { } public void setSize(int newSize) { keys.setSize(newSize); elements.setSize(newSize); } public void setGrow(int growBy) { keys.setGrow(growBy); elements.setGrow(growBy); } public synchronized void put(String key,Object element) { try { if( containsKey(key) ) { elements.add(keys.location(key),element); } else { keys.add( key ); elements.add(element); } } catch(org.apache.ecs.storage.NoSuchObjectException nsoe) { } } public synchronized void remove(String key) { try { if(containsKey(key)) { elements.remove(keys.location(key)); elements.remove(elements.location(key)); } } catch(org.apache.ecs.storage.NoSuchObjectException nsoe) { } } public int size() { return keys.getCurrentSize(); } public boolean contains(Object element)
{ try { elements.location(element); return(true); } catch(org.apache.ecs.storage.NoSuchObjectException noSuchObject) { return false; } } public Enumeration keys() { return keys; } public boolean containsKey(String key) { try { keys.location(key); } catch(org.apache.ecs.storage.NoSuchObjectException noSuchObject) { return false; } return(true); } public Enumeration elements() { return elements; } public Object get(String key) { try { if( containsKey(key) ) return(elements.get(keys.location(key))); } catch(org.apache.ecs.storage.NoSuchObjectException nsoe) { } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Hash.java
1