instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Collection<InputsCaseParameter> getInputs() { return inputsCollection.get(this); } public Collection<OutputsCaseParameter> getOutputs() { return outputsCollection.get(this); } public Collection<InputCaseParameter> getInputParameters() { return inputParameterCollection.get(this); } public Collection<OutputCaseParameter> getOutputParameters() { return outputParameterCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Task.class, CMMN_ELEMENT_TASK) .namespaceUri(CMMN11_NS) .extendsType(PlanItemDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<Task>() { public Task newInstance(ModelTypeInstanceContext instanceContext) { return new TaskImpl(instanceContext); }
}); isBlockingAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_IS_BLOCKING) .defaultValue(true) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputsCollection = sequenceBuilder.elementCollection(InputsCaseParameter.class) .build(); outputsCollection = sequenceBuilder.elementCollection(OutputsCaseParameter.class) .build(); inputParameterCollection = sequenceBuilder.elementCollection(InputCaseParameter.class) .build(); outputParameterCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PersonServiceImpl implements PersonService { private static final Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class); @Autowired PersonRepository personRepository; @Override @CachePut(value = "people", key = "#person.id") public Person save(Person person) { Person p = personRepository.save(person); logger.info("为id、key为:" + p.getId() + "数据做了缓存"); return p; } @Override @CacheEvict(value = "people")//2 public void remove(Long id) { logger.info("删除了id、key为" + id + "的数据缓存"); //这里不做实际删除操作 } /** * Cacheable * value:缓存key的前缀。 * key:缓存key的后缀。 * sync:设置如果缓存过期是不是只放一个请求去请求数据库,其他请求阻塞,默认是false。 */ @Override @Cacheable(value = "people", key = "#person.id", sync = true) public Person findOne(Person person, String a, String[] b, List<Long> c) { Person p = personRepository.findOne(person.getId()); logger.info("为id、key为:" + p.getId() + "数据做了缓存"); return p; }
@Override @Cacheable(value = "people1")//3 public Person findOne1() { Person p = personRepository.findOne(2L); logger.info("为id、key为:" + p.getId() + "数据做了缓存"); return p; } @Override @Cacheable(value = "people2")//3 public Person findOne2(Person person) { Person p = personRepository.findOne(person.getId()); logger.info("为id、key为:" + p.getId() + "数据做了缓存"); return p; } }
repos\spring-boot-student-master\spring-boot-student-cache-caffeine\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java
2
请完成以下Java代码
public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { Assert.notNull(objectIdentityRetrievalStrategy, "ObjectIdentityRetrievalStrategy required"); this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy; } protected void setProcessConfigAttribute(String processConfigAttribute) { Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory"); this.processConfigAttribute = processConfigAttribute; } public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) { Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null"); this.processDomainObjectClass = processDomainObjectClass; } public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required"); this.sidRetrievalStrategy = sidRetrievalStrategy; } @Override public boolean supports(ConfigAttribute attribute) {
return this.processConfigAttribute.equals(attribute.getAttribute()); } /** * This implementation supports any type of class, because it does not query the * presented secure object. * @param clazz the secure object * @return always <code>true</code> */ @Override public boolean supports(Class<?> clazz) { return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\afterinvocation\AbstractAclProvider.java
1
请完成以下Java代码
public I_PA_Measure getPA_Measure() throws RuntimeException { return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name) .getPO(getPA_Measure_ID(), get_TrxName()); } /** Set Measure. @param PA_Measure_ID Concrete Performance Measurement */ public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first
*/ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java
1
请完成以下Java代码
public class EventListenerActivityBehavior extends EventListenerOrMilestoneActivityBehavior { protected static final CmmnBehaviorLogger LOG = ProcessEngineLogger.CMNN_BEHAVIOR_LOGGER; public void created(CmmnActivityExecution execution) { // TODO: implement this: // (1) in case of a UserEventListener there is nothing to do! // (2) in case of TimerEventListener we have to check // whether the timer must be triggered, when a transition // on another plan item or case file item happens! } protected String getTypeName() { return "event listener"; } protected boolean isAtLeastOneEntryCriterionSatisfied(CmmnActivityExecution execution) {
return false; } public void fireEntryCriteria(CmmnActivityExecution execution) { throw LOG.criteriaNotAllowedForEventListenerException("entry", execution.getId()); } public void repeat(CmmnActivityExecution execution) { // It is not possible to repeat a event listener } protected boolean evaluateRepetitionRule(CmmnActivityExecution execution) { // It is not possible to define a repetition rule on an event listener return false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public class MyMessagingProperties { private List<String> addresses = new ArrayList<>(Arrays.asList("a", "b")); private ContainerType containerType = ContainerType.SIMPLE; // @fold:on // getters/setters ... public List<String> getAddresses() { return this.addresses; } public void setAddresses(List<String> addresses) { this.addresses = addresses; }
public ContainerType getContainerType() { return this.containerType; } public void setContainerType(ContainerType containerType) { this.containerType = containerType; } // @fold:off public enum ContainerType { SIMPLE, DIRECT } }
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\appendix\configurationmetadata\annotationprocessor\automaticmetadatageneration\MyMessagingProperties.java
2
请完成以下Java代码
static boolean checkUsingIsDigitMethod(String input) { if (input == null || input.isEmpty()) { return false; } for (char c : input.toCharArray()) { if (Character.isDigit(c)) { return true; } } return false; } static boolean checkUsingStreamApi(String input) { if (input == null || input.isEmpty()) { return false; } return input.chars() .anyMatch(Character::isDigit);
} static boolean checkUsingApacheCommonsLang(String input) { String result = StringUtils.getDigits(input); return result != null && !result.isEmpty(); } static boolean checkUsingGuava(String input) { if (input == null || input.isEmpty()) { return false; } String result = CharMatcher.forPredicate(Character::isDigit) .retainFrom(input); return !result.isEmpty(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\strcontainsnumber\StrContainsNumberUtils.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setMobileUI_UserProfile_Picking_BPartner_ID (final int MobileUI_UserProfile_Picking_BPartner_ID) { if (MobileUI_UserProfile_Picking_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_Picking_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_Picking_BPartner_ID, MobileUI_UserProfile_Picking_BPartner_ID); } @Override public int getMobileUI_UserProfile_Picking_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_BPartner_ID); } @Override public org.compiere.model.I_MobileUI_UserProfile_Picking getMobileUI_UserProfile_Picking() { return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class); } @Override public void setMobileUI_UserProfile_Picking(final org.compiere.model.I_MobileUI_UserProfile_Picking MobileUI_UserProfile_Picking) { set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class, MobileUI_UserProfile_Picking); } @Override public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID) { if (MobileUI_UserProfile_Picking_ID < 1) set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null); else
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID); } @Override public int getMobileUI_UserProfile_Picking_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID); } @Override public org.compiere.model.I_MobileUI_UserProfile_Picking_Job getMobileUI_UserProfile_Picking_Job() { return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, org.compiere.model.I_MobileUI_UserProfile_Picking_Job.class); } @Override public void setMobileUI_UserProfile_Picking_Job(final org.compiere.model.I_MobileUI_UserProfile_Picking_Job MobileUI_UserProfile_Picking_Job) { set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, org.compiere.model.I_MobileUI_UserProfile_Picking_Job.class, MobileUI_UserProfile_Picking_Job); } @Override public void setMobileUI_UserProfile_Picking_Job_ID (final int MobileUI_UserProfile_Picking_Job_ID) { if (MobileUI_UserProfile_Picking_Job_ID < 1) set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, null); else set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, MobileUI_UserProfile_Picking_Job_ID); } @Override public int getMobileUI_UserProfile_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking_BPartner.java
1
请完成以下Java代码
public static PickingSlotQRCode getPickingSlotQRCode(final DocumentFilterList filters) { final String barcodeString = StringUtils.trimBlankToNull(filters.getParamValueAsString(PickingSlotBarcodeFilter_FilterId, PARAM_Barcode)); if (barcodeString == null) { return null; } // // Try parsing the Global QR Code, if possible final GlobalQRCode globalQRCode = GlobalQRCode.parse(barcodeString).orNullIfError(); // // Case: valid Global QR Code if (globalQRCode != null)
{ return PickingSlotQRCode.ofGlobalQRCode(globalQRCode); } // // Case: Legacy barcode support else { final IPickingSlotDAO pickingSlotDAO = Services.get(IPickingSlotDAO.class); return pickingSlotDAO.getPickingSlotIdAndCaptionByCode(barcodeString) .map(PickingSlotQRCode::ofPickingSlotIdAndCaption) .orElseThrow(() -> new AdempiereException("Invalid barcode: " + barcodeString)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewFilters.java
1
请完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public Set<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitions() { return activatePlanItemDefinitions; } public Set<MoveToAvailablePlanItemDefinitionMapping> getChangeToAvailableStatePlanItemDefinitions() { return changeToAvailableStatePlanItemDefinitions; } public Set<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitions() { return terminatePlanItemDefinitions; } public Set<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitions() { return waitingForRepetitionPlanItemDefinitions; } public Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitions() { return removeWaitingForRepetitionPlanItemDefinitions; } public Set<ChangePlanItemIdMapping> getChangePlanItemIds() { return changePlanItemIds;
} public Set<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdsWithDefinitionId() { return changePlanItemIdsWithDefinitionId; } public Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIds() { return changePlanItemDefinitionWithNewTargetIds; } public Map<String, Object> getCaseVariables() { return caseVariables; } public Map<String, Map<String, Object>> getChildInstanceTaskVariables() { return childInstanceTaskVariables; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\ChangePlanItemStateBuilderImpl.java
1
请完成以下Java代码
public Iterator<AssignableInvoiceCandidate> getAllAssigned( @NonNull final RefundInvoiceCandidate refundInvoiceCandidate) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Candidate_Assignment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Term_ID, refundInvoiceCandidate.getId().getRepoId()) .andCollect( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Assigned_ID, I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(assignableInvoiceCandidateFactory::ofRecord) .iterator(); } /**
* In production, assignable invoice candidates are created elsewhere and are only loaded if they are relevant for refund contracts. * That's why this method is intended only for (unit-)testing. */ @VisibleForTesting public AssignableInvoiceCandidate saveNew(@NonNull final AssignableInvoiceCandidate assignableCandidate) { final I_C_Invoice_Candidate assignableCandidateRecord = newInstance(I_C_Invoice_Candidate.class); saveRecord(assignableCandidateRecord); return assignableCandidate .toBuilder() .id(InvoiceCandidateId.ofRepoId(assignableCandidateRecord.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidateRepository.java
1
请完成以下Java代码
public IQuery<I_C_Queue_WorkPackage> createQuery(final Properties ctx, final IWorkPackageQuery packageQuery) { return new POJOQuery<>(ctx, I_C_Queue_WorkPackage.class, null, // tableName=null => get it from the given model class ITrx.TRXNAME_None) .addFilter(new QueueFilter(packageQuery)) .setLimit(QueryLimit.getQueryLimitOrNoLimit(packageQuery.getLimit())) .setOrderBy(queueOrderByComparator); } private static class QueueFilter implements IQueryFilter<I_C_Queue_WorkPackage> { private final IWorkPackageQuery packageQuery; public QueueFilter(final IWorkPackageQuery packageQuery) { this.packageQuery = packageQuery; } @Override public boolean accept(final I_C_Queue_WorkPackage workpackage) { if (packageQuery.getProcessed() != null && packageQuery.getProcessed() != workpackage.isProcessed()) { return false; } if (packageQuery.getReadyForProcessing() != null && packageQuery.getReadyForProcessing() != workpackage.isReadyForProcessing()) { return false; } if (packageQuery.getError() != null && packageQuery.getError() != workpackage.isError()) { return false; } if (!workpackage.isActive()) { return false; } // Only packages that have not been skipped, // or where 'retryTimeoutMillis' has already passed since they were skipped. final Timestamp nowMinusTimeOut = new Timestamp(SystemTime.millis() - packageQuery.getSkippedTimeoutMillis()); final Timestamp skippedAt = workpackage.getSkippedAt(); if (skippedAt != null && skippedAt.compareTo(nowMinusTimeOut) > 0) {
return false; } // Only work packages for given process final Set<QueuePackageProcessorId> packageProcessorIds = packageQuery.getPackageProcessorIds(); if (packageProcessorIds != null) { if (packageProcessorIds.isEmpty()) { slogger.warn("There were no package processor Ids set in the package query. This could be a posible development error" +"\n Package query: "+packageQuery); } final QueuePackageProcessorId packageProcessorId = QueuePackageProcessorId.ofRepoId(workpackage.getC_Queue_PackageProcessor_ID()); if (!packageProcessorIds.contains(packageProcessorId)) { return false; } } final String priorityFrom = packageQuery.getPriorityFrom(); if (priorityFrom != null && priorityFrom.compareTo(workpackage.getPriority()) > 0) { return false; } return true; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\PlainQueueDAO.java
1
请在Spring Boot框架中完成以下Java代码
public CreateArticleResult handle(CreateArticle command) { var currentUserId = authenticationService.getRequiredCurrentUserId(); var existsByTitle = articleRepository.existsByTitle(command.getTitle()); if (existsByTitle) { throw badRequest("article [title=%s] already exists", command.getTitle()); } var tags = handleTags(command); var article = Article.builder() .slug(slugService.makeSlug(command.getTitle())) .title(command.getTitle()) .description(command.getDescription()) .body(command.getBody()) .authorId(currentUserId) .tags(tags) .build(); var savedArticle = articleRepository.save(article); var articleAssembly = articleRepository.findAssemblyById(currentUserId, savedArticle.id()).orElseThrow(); var data = conversionService.convert(articleAssembly, ArticleDto.class); return new CreateArticleResult(data); } private List<Tag> handleTags(CreateArticle command) { List<Tag> tags = new ArrayList<>(); var tagList = command.getTagList(); if (tagList != null && !tagList.isEmpty()) { var existingTags = tagRepository.findAllByNameIn(tagList); var existingTagNames = existingTags.stream() .map(Tag::name) .collect(Collectors.toSet());
var newTags = tagList.stream() .filter(name -> !existingTagNames.contains(name)) .map(Tag::new) .toList(); for (var newTag : newTags) { Tag tag; try { tag = tagRepository.save(newTag); } catch (DbActionExecutionException ex) { if (ex.getCause() instanceof DuplicateKeyException) { tag = tagRepository.findByName(newTag.name()).orElseThrow(); } throw ex; } tags.add(tag); } tags.addAll(existingTags); Collections.sort(tags); } return tags; } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\application\command\CreateArticleHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class DynamicPropertySource extends MapPropertySource { public DynamicPropertySource(String name, Map<String, Object> source) { super(name, source); } public static Builder builder(){ return new Builder(); } public static class Builder{ private String sourceName; private Map<String, Object> sourceMap = new HashMap<>(); public Builder setSourceName(String sourceName) { this.sourceName = sourceName; return this; }
public Builder setProperty(String key, String value) { this.sourceMap.put(key, value); return this; } public Builder setProperty(Map<String, Object> sourceMap) { this.sourceMap.putAll(sourceMap); return this; } public DynamicPropertySource build() { return new DynamicPropertySource(this.sourceName,this.sourceMap); } } }
repos\spring-boot-quick-master\quick-activemq2\src\main\java\com\active2\config\DynamicPropertySource.java
2
请完成以下Java代码
public class PostInvocationAdviceProvider implements AfterInvocationProvider { protected final Log logger = LogFactory.getLog(getClass()); private final PostInvocationAuthorizationAdvice postAdvice; public PostInvocationAdviceProvider(PostInvocationAuthorizationAdvice postAdvice) { this.postAdvice = postAdvice; } @Override public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { PostInvocationAttribute postInvocationAttribute = findPostInvocationAttribute(config); if (postInvocationAttribute == null) { return returnedObject; } return this.postAdvice.after(authentication, (MethodInvocation) object, postInvocationAttribute, returnedObject); } private @Nullable PostInvocationAttribute findPostInvocationAttribute(Collection<ConfigAttribute> config) { for (ConfigAttribute attribute : config) {
if (attribute instanceof PostInvocationAttribute) { return (PostInvocationAttribute) attribute; } } return null; } @Override public boolean supports(ConfigAttribute attribute) { return attribute instanceof PostInvocationAttribute; } @Override public boolean supports(Class<?> clazz) { return MethodInvocation.class.isAssignableFrom(clazz); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\prepost\PostInvocationAdviceProvider.java
1
请完成以下Java代码
protected String getClassBeanName(ListableBeanFactory listableBeanFactory) { String[] beanNames = listableBeanFactory.getBeanNamesForAnnotation(EnableExternalTaskClient.class); List<String> classBeanNames = Arrays.stream(beanNames) .filter(isClassAnnotation(listableBeanFactory)) .collect(Collectors.toList()); int classBeanNameCount = classBeanNames.size(); if (classBeanNameCount > 1) { throw LOG.noUniqueAnnotation(); } else if (classBeanNameCount == 1) { return classBeanNames.get(0); } else { // no client annotation in spring boot return null; } } Predicate<String> isClassAnnotation(ListableBeanFactory listableBeanFactory) { return beanName -> ((BeanDefinitionRegistry) listableBeanFactory) .getBeanDefinition(beanName).getSource() == null; } protected EnableExternalTaskClient getAnnotation(BeanDefinitionRegistry registry, String classBeanName) { BeanDefinition beanDefinitionConfig = registry.getBeanDefinition(classBeanName); AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinitionConfig; AnnotationMetadata metadata = annotatedBeanDefinition.getMetadata(); return AnnotationUtil.get(EnableExternalTaskClient.class, metadata); }
protected String getClientBeanName(ListableBeanFactory listableBeanFactory) { String[] beanNamesForType = listableBeanFactory.getBeanNamesForType(ExternalTaskClient.class); if (beanNamesForType.length > 1) { throw LOG.noUniqueClientException(); } else if (beanNamesForType.length == 1) { return beanNamesForType[0]; } else { return null; } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientPostProcessor.java
1
请完成以下Java代码
public void setRfQ_Win_MailText_ID (int RfQ_Win_MailText_ID) { if (RfQ_Win_MailText_ID < 1) set_Value (COLUMNNAME_RfQ_Win_MailText_ID, null); else set_Value (COLUMNNAME_RfQ_Win_MailText_ID, Integer.valueOf(RfQ_Win_MailText_ID)); } /** Get RfQ win mail text. @return RfQ win mail text */ @Override public int getRfQ_Win_MailText_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_MailText_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_PrintFormat getRfQ_Win_PrintFormat() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class); } @Override public void setRfQ_Win_PrintFormat(org.compiere.model.I_AD_PrintFormat RfQ_Win_PrintFormat) { set_ValueFromPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, RfQ_Win_PrintFormat); } /** Set RfQ Won Druck - Format. @param RfQ_Win_PrintFormat_ID RfQ Won Druck - Format */ @Override public void setRfQ_Win_PrintFormat_ID (int RfQ_Win_PrintFormat_ID) { if (RfQ_Win_PrintFormat_ID < 1) set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, null); else set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, Integer.valueOf(RfQ_Win_PrintFormat_ID)); } /** Get RfQ Won Druck - Format. @return RfQ Won Druck - Format */ @Override public int getRfQ_Win_PrintFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_PrintFormat_ID);
if (ii == null) return 0; return ii.intValue(); } /** * RfQType AD_Reference_ID=540661 * Reference name: RfQType */ public static final int RFQTYPE_AD_Reference_ID=540661; /** Default = D */ public static final String RFQTYPE_Default = "D"; /** Procurement = P */ public static final String RFQTYPE_Procurement = "P"; /** Set Ausschreibung Art. @param RfQType Ausschreibung Art */ @Override public void setRfQType (java.lang.String RfQType) { set_Value (COLUMNNAME_RfQType, RfQType); } /** Get Ausschreibung Art. @return Ausschreibung Art */ @Override public java.lang.String getRfQType () { return (java.lang.String)get_Value(COLUMNNAME_RfQType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_Topic.java
1
请完成以下Java代码
public Class< ? > getType(ELContext context, Object base, Object property) { return getWrappedResolver().getType(wrapContext(context), base, property); } @Override public Object getValue(ELContext context, Object base, Object property) { //we need to resolve a bean only for the first "member" of expression, e.g. bean.property1.property2 if (base == null) { Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager()); if (result != null) { context.setPropertyResolved(true); } return result; } else { return null; } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return getWrappedResolver().isReadOnly(wrapContext(context), base, property);
} @Override public void setValue(ELContext context, Object base, Object property, Object value) { getWrappedResolver().setValue(wrapContext(context), base, property, value); } @Override public Object invoke(ELContext context, Object base, Object method, java.lang.Class< ? >[] paramTypes, Object[] params) { return getWrappedResolver().invoke(wrapContext(context), base, method, paramTypes, params); } protected javax.el.ELContext wrapContext(ELContext context) { return new ElContextDelegate(context, getWrappedResolver()); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\el\CdiResolver.java
1
请完成以下Java代码
public void setIsRequiredMailAddres (boolean IsRequiredMailAddres) { set_Value (COLUMNNAME_IsRequiredMailAddres, Boolean.valueOf(IsRequiredMailAddres)); } /** Get Requires Mail Address. @return Requires Mail Address */ @Override public boolean isRequiredMailAddres () { Object oo = get_Value(COLUMNNAME_IsRequiredMailAddres); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** * MarketingPlatformGatewayId AD_Reference_ID=540858 * Reference name: MarketingPlatformGatewayId */ public static final int MARKETINGPLATFORMGATEWAYID_AD_Reference_ID=540858; /** CleverReach = CleverReach */ public static final String MARKETINGPLATFORMGATEWAYID_CleverReach = "CleverReach"; /** Set Marketing Platform GatewayId. @param MarketingPlatformGatewayId Marketing Platform GatewayId */ @Override public void setMarketingPlatformGatewayId (java.lang.String MarketingPlatformGatewayId) { set_Value (COLUMNNAME_MarketingPlatformGatewayId, MarketingPlatformGatewayId); } /** Get Marketing Platform GatewayId. @return Marketing Platform GatewayId */ @Override public java.lang.String getMarketingPlatformGatewayId () { return (java.lang.String)get_Value(COLUMNNAME_MarketingPlatformGatewayId); } /** Set MKTG_Platform. @param MKTG_Platform_ID MKTG_Platform */ @Override public void setMKTG_Platform_ID (int MKTG_Platform_ID) { if (MKTG_Platform_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID)); } /** Get MKTG_Platform. @return MKTG_Platform */ @Override public int getMKTG_Platform_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Platform.java
1
请在Spring Boot框架中完成以下Java代码
public String getMessage() { return MESSAGE; } /** * @return the title of the process */ @Override public String getSubject() { return subject; } /**
* @return the title of the process */ @Override public String getTitle() { return title; } @Override public String getTo() { return to; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\BPartnerEmailParams.java
2
请完成以下Java代码
class JarEntriesStream implements Closeable { private static final int BUFFER_SIZE = 4 * 1024; private final JarInputStream in; private final byte[] inBuffer = new byte[BUFFER_SIZE]; private final byte[] compareBuffer = new byte[BUFFER_SIZE]; private final Inflater inflater = new Inflater(true); private JarEntry entry; JarEntriesStream(InputStream in) throws IOException { this.in = new JarInputStream(in); } JarEntry getNextEntry() throws IOException { this.entry = this.in.getNextJarEntry(); this.inflater.reset(); return this.entry; } boolean matches(boolean directory, int size, int compressionMethod, InputStreamSupplier streamSupplier) throws IOException { if (this.entry.isDirectory() != directory) { fail("directory"); } if (this.entry.getMethod() != compressionMethod) { fail("compression method"); } if (this.entry.isDirectory()) { this.in.closeEntry(); return true; } try (DataInputStream expected = new DataInputStream(getInputStream(size, streamSupplier))) { assertSameContent(expected); } return true; } private InputStream getInputStream(int size, InputStreamSupplier streamSupplier) throws IOException { InputStream inputStream = streamSupplier.get(); return (this.entry.getMethod() != ZipEntry.DEFLATED) ? inputStream : new ZipInflaterInputStream(inputStream, this.inflater, size); } private void assertSameContent(DataInputStream expected) throws IOException { int len; while ((len = this.in.read(this.inBuffer)) > 0) { try { expected.readFully(this.compareBuffer, 0, len); if (Arrays.equals(this.inBuffer, 0, len, this.compareBuffer, 0, len)) { continue; }
} catch (EOFException ex) { // Continue and throw exception due to mismatched content length. } fail("content"); } if (expected.read() != -1) { fail("content"); } } private void fail(String check) { throw new IllegalStateException("Content mismatch when reading security info for entry '%s' (%s check)" .formatted(this.entry.getName(), check)); } @Override public void close() throws IOException { this.inflater.end(); this.in.close(); } @FunctionalInterface interface InputStreamSupplier { InputStream get() throws IOException; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\JarEntriesStream.java
1
请在Spring Boot框架中完成以下Java代码
public final class AuthorizedUrlVariable { private final String variable; private AuthorizedUrlVariable(String variable) { this.variable = variable; } /** * Compares the value of a path variable in the URI with an `Authentication` * attribute * <p> * For example, <pre> * requestMatchers("/user/{username}").hasVariable("username").equalTo(Authentication::getName)); * </pre>
* @param function a function to get value from {@link Authentication}. * @return the {@link AuthorizationManagerRequestMatcherRegistry} for further * customization. */ public AuthorizationManagerRequestMatcherRegistry equalTo(Function<Authentication, String> function) { return access((auth, requestContext) -> { String value = requestContext.getVariables().get(this.variable); return new AuthorizationDecision(function.apply(auth.get()).equals(value)); }); } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AuthorizeHttpRequestsConfigurer.java
2
请完成以下Java代码
public @Nullable Function<Long, Long> getOffsetComputeFunction() { return this.offsetComputeFunction; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TopicPartitionOffset that = (TopicPartitionOffset) o; return Objects.equals(this.topicPartition, that.topicPartition) && Objects.equals(this.position, that.position); }
@Override public int hashCode() { return Objects.hash(this.topicPartition, this.position); } @Override public String toString() { return "TopicPartitionOffset{" + "topicPartition=" + this.topicPartition + ", offset=" + this.offset + ", relativeToCurrent=" + this.relativeToCurrent + (this.position == null ? "" : (", position=" + this.position.name())) + '}'; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\TopicPartitionOffset.java
1
请完成以下Java代码
final class SystemEnvironmentPropertyMapper implements PropertyMapper { public static final PropertyMapper INSTANCE = new SystemEnvironmentPropertyMapper(); private final Map<String, ConfigurationPropertyName> propertySourceNameCache = new ConcurrentReferenceHashMap<>(); @Override public List<String> map(ConfigurationPropertyName configurationPropertyName) { List<String> mapped = new ArrayList<>(4); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.SYSTEM_ENVIRONMENT, true)); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.LEGACY_SYSTEM_ENVIRONMENT, true)); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.SYSTEM_ENVIRONMENT, false)); addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.LEGACY_SYSTEM_ENVIRONMENT, false)); return mapped; } private void addIfMissing(List<String> list, String value) { if (!list.contains(value)) { list.add(value); } } @Override public ConfigurationPropertyName map(String propertySourceName) { ConfigurationPropertyName configurationPropertyName = this.propertySourceNameCache.get(propertySourceName); if (configurationPropertyName == null) { configurationPropertyName = convertName(propertySourceName); this.propertySourceNameCache.put(propertySourceName, configurationPropertyName); } return configurationPropertyName; } private ConfigurationPropertyName convertName(String propertySourceName) { try {
return ConfigurationPropertyName.adapt(propertySourceName, '_', this::processElementValue); } catch (Exception ex) { return ConfigurationPropertyName.EMPTY; } } private CharSequence processElementValue(CharSequence value) { String result = value.toString().toLowerCase(Locale.ENGLISH); return isNumber(result) ? "[" + result + "]" : result; } private static boolean isNumber(String string) { return string.chars().allMatch(Character::isDigit); } @Override public BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> getAncestorOfCheck() { return this::isAncestorOf; } private boolean isAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { return name.isAncestorOf(candidate) || isLegacyAncestorOf(name, candidate); } private boolean isLegacyAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { if (!name.hasDashedElement()) { return false; } ConfigurationPropertyName legacyCompatibleName = name.asSystemEnvironmentLegacyName(); return legacyCompatibleName != null && legacyCompatibleName.isAncestorOf(candidate); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\SystemEnvironmentPropertyMapper.java
1
请完成以下Java代码
protected void writePlanItemDefinitionSpecificAttributes(T planItemDefinition, XMLStreamWriter xtw) throws Exception { } /** * Writes common elements like planItem documentation. * Subclasses should call super.writePlanItemDefinitionCommonElements(), it is recommended to override * writePlanItemDefinitionBody instead * * @param planItemDefinition the plan item definition to write * @param xtw the XML to write the definition to * @throws Exception in case of write exception */ protected boolean writePlanItemDefinitionCommonElements(CmmnModel model, T planItemDefinition, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception { if (StringUtils.isNotEmpty(planItemDefinition.getDocumentation())) { xtw.writeStartElement(ELEMENT_DOCUMENTATION); xtw.writeCharacters(planItemDefinition.getDocumentation()); xtw.writeEndElement(); } boolean didWriteExtensionStartElement = false; if (options.isSaveElementNameWithNewLineInExtensionElement()) { didWriteExtensionStartElement = CmmnXmlUtil.writeElementNameExtensionElement(planItemDefinition, didWriteExtensionStartElement, xtw); } return CmmnXmlUtil.writeExtensionElements(planItemDefinition, didWriteExtensionStartElement, model.getNamespaces(), xtw); } protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, T planItemDefinition, boolean didWriteExtensionElement, XMLStreamWriter xtw) throws Exception { return FlowableListenerExport.writeFlowableListeners(xtw, CmmnXmlConstants.ELEMENT_PLAN_ITEM_LIFECYCLE_LISTENER, planItemDefinition.getLifecycleListeners(), didWriteExtensionElement); }
protected void writePlanItemDefinitionDefaultItemControl(CmmnModel model, T planItemDefinition, XMLStreamWriter xtw) throws Exception { if (planItemDefinition.getDefaultControl() != null) { PlanItemControlExport.writeDefaultControl(model, planItemDefinition.getDefaultControl(), xtw); } } /** * Subclasses can override this method to write the content body xml content of the plainItemDefinition * * @param planItemDefinition the plan item definition to write * @param xtw the XML to write the definition to * @throws Exception in case of write exception */ protected void writePlanItemDefinitionBody(CmmnModel model, T planItemDefinition, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception { } protected void writePlanItemDefinitionEndElement(XMLStreamWriter xtw) throws Exception { xtw.writeEndElement(); } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\AbstractPlanItemDefinitionExport.java
1
请完成以下Java代码
public String getMilestoneInstanceId() { return milestoneInstanceId; } @Override public String getId() { return milestoneInstanceId; } public String getName() { return name; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseDefinitionId() { return caseDefinitionId; } public Date getReachedBefore() { return reachedBefore;
} public Date getReachedAfter() { return reachedAfter; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MilestoneInstanceQueryImpl.java
1
请完成以下Java代码
public void close() { } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream(message.getBytes()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } public HttpStatus getStatus() {
return status; } public void setStatus(HttpStatus status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul-fallback\spring-cloud-zuul-fallback-api-gateway\src\main\java\com\baeldung\spring\cloud\apigateway\fallback\GatewayClientResponse.java
1
请完成以下Java代码
String getName() { return this.name; } DataLoaderOptions getOptions() { return this.optionsSupplier.get(); } @Override public CompletionStage<List<V>> load(List<K> keys, BatchLoaderEnvironment environment) { GraphQLContext graphQLContext = environment.getContext(); Assert.state(graphQLContext != null, "No GraphQLContext available"); ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(graphQLContext); try { return snapshot.wrap(() -> this.loader.apply(keys, environment) .collectList() .contextWrite(snapshot::updateContext) .toFuture()) .call(); } catch (Exception ex) { return CompletableFuture.failedFuture(ex); } } } /** * {@link MappedBatchLoaderWithContext} that delegates to a {@link Mono} * batch loading function and exposes Reactor context to it. */ private static final class ReactorMappedBatchLoader<K, V> implements MappedBatchLoaderWithContext<K, V> { private final String name; private final BiFunction<Set<K>, BatchLoaderEnvironment, Mono<Map<K, V>>> loader; private final Supplier<DataLoaderOptions> optionsSupplier; private ReactorMappedBatchLoader(String name, BiFunction<Set<K>, BatchLoaderEnvironment, Mono<Map<K, V>>> loader, Supplier<DataLoaderOptions> optionsSupplier) { this.name = name;
this.loader = loader; this.optionsSupplier = optionsSupplier; } String getName() { return this.name; } DataLoaderOptions getOptions() { return this.optionsSupplier.get(); } @Override public CompletionStage<Map<K, V>> load(Set<K> keys, BatchLoaderEnvironment environment) { GraphQLContext graphQLContext = environment.getContext(); Assert.state(graphQLContext != null, "No GraphQLContext available"); ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(graphQLContext); try { return snapshot.wrap(() -> this.loader.apply(keys, environment) .contextWrite(snapshot::updateContext) .toFuture()) .call(); } catch (Exception ex) { return CompletableFuture.failedFuture(ex); } } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\DefaultBatchLoaderRegistry.java
1
请完成以下Java代码
public class JMSConsumerThread { private static final String USERNAME= ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名 private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码 private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址 ConnectionFactory connectionFactory=null; // 连接工厂 private Connection connection = null; private Session session = null; private Destination destination=null; // 消息的目的地 public void init(){ // 实例化连接工厂 connectionFactory=new ActiveMQConnectionFactory(JMSConsumerThread.USERNAME, JMSConsumerThread.PASSWORD, JMSConsumerThread.BROKEURL); try { connection=connectionFactory.createConnection(); // 通过连接工厂获取连接 connection.start(); } catch (JMSException e) { e.printStackTrace(); } }
public void consumer(){ MessageConsumer messageConsumer; // 消息的消费者 try { session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); // 创建Session destination=session.createQueue("queue1"); messageConsumer=session.createConsumer(destination); // 创建消息消费者 messageConsumer.setMessageListener(new Listener3()); // 注册消息监听 } catch (JMSException e) { e.printStackTrace(); } } }
repos\spring-boot-quick-master\quick-activemq\src\main\java\com\mq\client\JMSConsumerThread.java
1
请完成以下Java代码
public R apply(final T input) { final K key = keyFunction.apply(input); lock.readLock().lock(); boolean readLockAcquired = true; boolean writeLockAcquired = false; try { if (Objects.equals(lastKey, key)) { return lastValue; } // Upgrade to write lock lock.readLock().unlock(); // must release read lock before acquiring write lock readLockAcquired = false; lock.writeLock().lock(); writeLockAcquired = true; try { lastValue = delegate.apply(input); lastKey = key; return lastValue; } finally { // Downgrade to read lock lock.readLock().lock(); // acquire read lock before releasing write lock readLockAcquired = true; lock.writeLock().unlock(); // unlock write, still hold read writeLockAcquired = false; } } finally { if (writeLockAcquired) { lock.writeLock().unlock(); } if (readLockAcquired) { lock.readLock().unlock(); } } } @Override public R peek(final T input) { final ReadLock readLock = lock.readLock(); readLock.lock(); try { return lastValue; } finally { readLock.unlock();
} } @Override public void forget() { final WriteLock writeLock = lock.writeLock(); writeLock.lock(); try { lastKey = null; lastValue = null; } finally { writeLock.unlock(); } } } private static final class SimpleMemoizingFunction<T, R> extends MemoizingFunctionWithKeyExtractor<T, R, T> { private SimpleMemoizingFunction(final Function<T, R> delegate) { super(delegate, input -> input); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Functions.java
1
请在Spring Boot框架中完成以下Java代码
public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @ApiModelProperty(example = "null") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "5") public String getCaseInstanceId() {
return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/5") public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricIdentityLinkResponse.java
2
请完成以下Java代码
protected void checkAccess(CommandContext commandContext, BatchEntity batch) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checkAccess(checker, batch); } } protected abstract void checkAccess(CommandChecker checker, BatchEntity batch); protected void setJobDefinitionState(CommandContext commandContext, String jobDefinitionId) { createSetJobDefinitionStateCommand(jobDefinitionId).execute(commandContext); } protected AbstractSetJobDefinitionStateCmd createSetJobDefinitionStateCommand(String jobDefinitionId) { AbstractSetJobDefinitionStateCmd suspendJobDefinitionCmd = createSetJobDefinitionStateCommand(new UpdateJobDefinitionSuspensionStateBuilderImpl() .byJobDefinitionId(jobDefinitionId)
.includeJobs(true) ); suspendJobDefinitionCmd.disableLogUserOperation(); return suspendJobDefinitionCmd; } protected abstract AbstractSetJobDefinitionStateCmd createSetJobDefinitionStateCommand(UpdateJobDefinitionSuspensionStateBuilderImpl builder); protected void logUserOperation(CommandContext commandContext, String tenantId) { PropertyChange propertyChange = new PropertyChange(SUSPENSION_STATE_PROPERTY, null, getNewSuspensionState().getName()); commandContext.getOperationLogManager() .logBatchOperation(getUserOperationType(), batchId, tenantId, propertyChange); } protected abstract String getUserOperationType(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetBatchStateCmd.java
1
请完成以下Java代码
protected String doIt() throws Exception { final ShipperTransportationId shipperTransportationId = ShipperTransportationId.ofRepoId(getRecord_ID()); final I_M_ShipperTransportation shipperTransportation = shipperTransportationDAO.getById(shipperTransportationId); Check.assumeNotNull(shipperTransportation, "shipperTransportation not null"); // // If the document is processed, we not allowed to run this process (06058) if (shipperTransportation.isProcessed()) { throw new AdempiereException("@" + CreateFromPickingSlots_MSG_DOC_PROCESSED + "@"); } final I_M_Tour tour = Services.get(ITourDAO.class).getById(p_M_Tour_ID); Check.assumeNotNull(tour, "tour not null"); // // Fetch delivery days final Timestamp deliveryDate = shipperTransportation.getDateDoc(); final List<I_M_DeliveryDay> deliveryDays = deliveryDayDAO.retrieveDeliveryDays(tour, deliveryDate); if (deliveryDays.isEmpty()) { // No delivery days for tour; return "OK"; } // used to make sure no order is added more than once final Map<Integer, I_C_Order> orderId2order = new LinkedHashMap<>(); // we shall allow only those partner which are set in delivery days and that are vendors and have purchase orders for (final I_M_DeliveryDay dd : deliveryDays) { if (!dd.isToBeFetched()) { continue; // nothing to do }
// skip generic delivery days final I_C_BPartner_Location bpLocation = dd.getC_BPartner_Location(); if (bpLocation == null) { continue; } final List<I_C_Order> purchaseOrders = orderDAO.retrievePurchaseOrdersForPickup(bpLocation, dd.getDeliveryDate(), dd.getDeliveryDateTimeMax()); if (purchaseOrders.isEmpty()) { continue; // nothing to do } for (final I_C_Order purchaseOrder : purchaseOrders) { orderId2order.put(purchaseOrder.getC_Order_ID(), purchaseOrder); } } // // Iterate collected orders and create shipment packages for them for (final I_C_Order order : orderId2order.values()) { orderToShipperTransportationService.addPurchaseOrderToShipperTransportation( OrderId.ofRepoId(order.getC_Order_ID()), ShipperTransportationId.ofRepoId(shipperTransportation.getM_ShipperTransportation_ID())); } return "OK"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\M_ShippingPackage_CreateFromTourplanning.java
1
请完成以下Java代码
public abstract class AbstractSideAction implements ISideAction { private static final transient String GENERATED_ID_Prefix = "ID_" + UUID.randomUUID() + "_"; private static final transient AtomicLong GENERATED_ID_Next = new AtomicLong(0); private final String id; public AbstractSideAction() { this((String)null); // id=null => generate } public AbstractSideAction(final String id) { super(); // // Set provided ID or generate a new one if (id == null)
{ this.id = GENERATED_ID_Prefix + GENERATED_ID_Next.incrementAndGet(); } else { this.id = id; } } @Override public final String getId() { return id; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\AbstractSideAction.java
1
请完成以下Java代码
public JSONDocumentChangedWebSocketEvent copy() { return new JSONDocumentChangedWebSocketEvent(this); } JSONDocumentChangedWebSocketEvent markRootDocumentAsStaled() { stale = Boolean.TRUE; return this; } JSONDocumentChangedWebSocketEvent markActiveTabStaled() { activeTabStaled = Boolean.TRUE; return this; } private HashMap<String, JSONIncludedTabInfo> getIncludedTabsInfo() { if (includedTabsInfoByTabId == null) { includedTabsInfoByTabId = new HashMap<>(); } return includedTabsInfoByTabId; } private JSONIncludedTabInfo getIncludedTabInfo(final DetailId tabId) { return getIncludedTabsInfo().computeIfAbsent(tabId.toJson(), k -> JSONIncludedTabInfo.newInstance(tabId)); } void addIncludedTabInfo(@NonNull final JSONIncludedTabInfo tabInfo) { getIncludedTabsInfo().compute(tabInfo.getTabId().toJson(), (tabId, existingTabInfo) -> { if (existingTabInfo == null) { return tabInfo.copy(); } else { existingTabInfo.mergeFrom(tabInfo); return existingTabInfo; } }); }
@Override @JsonIgnore public WebsocketTopicName getWebsocketEndpoint() { return WebsocketTopicNames.buildDocumentTopicName(windowId, id); } public void staleTabs(@NonNull final Collection<DetailId> tabIds) { tabIds.stream().map(this::getIncludedTabInfo).forEach(JSONIncludedTabInfo::markAllRowsStaled); } public void staleIncludedRows(@NonNull final DetailId tabId, @NonNull final DocumentIdsSelection rowIds) { getIncludedTabInfo(tabId).staleRows(rowIds); } void mergeFrom(@NonNull final JSONDocumentChangedWebSocketEvent from) { if (!Objects.equals(windowId, from.windowId) || !Objects.equals(id, from.id)) { throw new AdempiereException("Cannot merge events because they are not matching") .setParameter("from", from) .setParameter("to", this) .appendParametersToMessage(); } if (from.stale != null && from.stale) { stale = from.stale; } from.getIncludedTabsInfo().values().forEach(this::addIncludedTabInfo); if (from.activeTabStaled != null && from.activeTabStaled) { activeTabStaled = from.activeTabStaled; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEvent.java
1
请完成以下Java代码
public void setM_Product_AlbertaBillableTherapy_ID (final int M_Product_AlbertaBillableTherapy_ID) { if (M_Product_AlbertaBillableTherapy_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaBillableTherapy_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaBillableTherapy_ID, M_Product_AlbertaBillableTherapy_ID); } @Override public int getM_Product_AlbertaBillableTherapy_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaBillableTherapy_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } /** * Therapy AD_Reference_ID=541282 * Reference name: Therapy */ public static final int THERAPY_AD_Reference_ID=541282; /** Unknown = 0 */ public static final String THERAPY_Unknown = "0"; /** ParenteralNutrition = 1 */ public static final String THERAPY_ParenteralNutrition = "1"; /** EnteralNutrition = 2 */ public static final String THERAPY_EnteralNutrition = "2"; /** Stoma = 3 */ public static final String THERAPY_Stoma = "3"; /** Tracheostoma = 4 */ public static final String THERAPY_Tracheostoma = "4"; /** Inkontinenz ableitend = 5 */ public static final String THERAPY_InkontinenzAbleitend = "5"; /** Wundversorgung = 6 */ public static final String THERAPY_Wundversorgung = "6"; /** IV-Therapien = 7 */ public static final String THERAPY_IV_Therapien = "7"; /** Beatmung = 8 */ public static final String THERAPY_Beatmung = "8"; /** Sonstiges = 9 */ public static final String THERAPY_Sonstiges = "9"; /** OSA = 10 */ public static final String THERAPY_OSA = "10"; /** Hustenhilfen = 11 */ public static final String THERAPY_Hustenhilfen = "11";
/** Absaugung = 12 */ public static final String THERAPY_Absaugung = "12"; /** Patientenüberwachung = 13 */ public static final String THERAPY_Patientenueberwachung = "13"; /** Sauerstoff = 14 */ public static final String THERAPY_Sauerstoff = "14"; /** Inhalations- und Atemtherapie = 15 */ public static final String THERAPY_Inhalations_UndAtemtherapie = "15"; /** Lagerungshilfsmittel = 16 */ public static final String THERAPY_Lagerungshilfsmittel = "16"; /** Schmerztherapie = 17 */ public static final String THERAPY_Schmerztherapie = "17"; @Override public void setTherapy (final String Therapy) { set_Value (COLUMNNAME_Therapy, Therapy); } @Override public String getTherapy() { return get_ValueAsString(COLUMNNAME_Therapy); } @Override public void setValue (final @Nullable String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaBillableTherapy.java
1
请完成以下Java代码
private void removeCredential(HttpServletRequest request, HttpServletResponse response, @Nullable String id) throws IOException { this.userCredentials.delete(Bytes.fromBase64(id)); response.setStatus(HttpStatus.NO_CONTENT.value()); } static class WebAuthnRegistrationRequest { private @Nullable RelyingPartyPublicKey publicKey; @Nullable RelyingPartyPublicKey getPublicKey() { return this.publicKey; } void setPublicKey(RelyingPartyPublicKey publicKey) { this.publicKey = publicKey; } }
public static class SuccessfulUserRegistrationResponse { private final CredentialRecord credentialRecord; SuccessfulUserRegistrationResponse(CredentialRecord credentialRecord) { this.credentialRecord = credentialRecord; } public boolean isSuccess() { return true; } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\registration\WebAuthnRegistrationFilter.java
1
请完成以下Java代码
public class JwtRequest implements Serializable { private static final long serialVersionUID = 5926468583005150707L; private String username; private String password; //need default constructor for JSON Parsing public JwtRequest() { } public JwtRequest(String username, String password) { this.setUsername(username); this.setPassword(password); }
public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-boot-jwt-without-JPA\spring-boot-jwt\src\main\java\com\javainuse\model\JwtRequest.java
1
请完成以下Java代码
public void performOperationAsync(AtomicOperation executionOperation, ExecutionEntity execution) { performOperation(executionOperation, execution, true); } public void performOperation(final AtomicOperation executionOperation, final ExecutionEntity execution, final boolean performAsync) { AtomicOperationInvocation invocation = new AtomicOperationInvocation(executionOperation, execution, performAsync); queuedInvocations.add(0, invocation); performNext(); } protected void performNext() { AtomicOperationInvocation nextInvocation = queuedInvocations.get(0); if(nextInvocation.operation.isAsyncCapable() && isExecuting) { // will be picked up by while loop below return; } ProcessApplicationReference targetProcessApplication = getTargetProcessApplication(nextInvocation.execution); if(requiresContextSwitch(targetProcessApplication)) { Context.executeWithinProcessApplication(new Callable<Void>() { public Void call() throws Exception { performNext(); return null; } }, targetProcessApplication, new InvocationContext(nextInvocation.execution)); } else { if(!nextInvocation.operation.isAsyncCapable()) { // if operation is not async capable, perform right away. invokeNext(); } else { try { isExecuting = true; while (! queuedInvocations.isEmpty()) { // assumption: all operations are executed within the same process application... invokeNext(); } } finally { isExecuting = false; } } } } protected void invokeNext() { AtomicOperationInvocation invocation = queuedInvocations.remove(0);
try { invocation.execute(bpmnStackTrace, processDataContext); } catch(RuntimeException e) { // log bpmn stacktrace bpmnStackTrace.printStackTrace(Context.getProcessEngineConfiguration().isBpmnStacktraceVerbose()); // rethrow throw e; } } protected boolean requiresContextSwitch(ProcessApplicationReference processApplicationReference) { return ProcessApplicationContextUtil.requiresContextSwitch(processApplicationReference); } protected ProcessApplicationReference getTargetProcessApplication(ExecutionEntity execution) { return ProcessApplicationContextUtil.getTargetProcessApplication(execution); } public void rethrow() { if (throwable != null) { if (throwable instanceof Error) { throw (Error) throwable; } else if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else { throw new ProcessEngineException("exception while executing command " + command, throwable); } } } public ProcessDataContext getProcessDataContext() { return processDataContext; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandInvocationContext.java
1
请完成以下Java代码
boolean isBooked() { return status == Status.BOOKED; } boolean isCancelled() { return status == Status.BOOKING_CANCELLED; } BookedTicket(Long movieId, String seatNumber) { this.movieId = movieId; this.seatNumber = seatNumber; } Long id() { return id; } Long movieId() {
return movieId; } String seatNumber() { return seatNumber; } Instant createdAt() { return createdAt; } Status status() { return status; } protected BookedTicket() { // Default constructor for JPA } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\java\com\baeldung\spring\modulith\cqrs\ticket\BookedTicket.java
1
请完成以下Java代码
public static OptionalBoolean ofNullableBoolean(@Nullable final Boolean value) { return value != null ? ofBoolean(value) : UNKNOWN; } public static OptionalBoolean ofNullableString(@Nullable final String value) { return ofNullableBoolean(StringUtils.toBooleanOrNull(value)); } public boolean isTrue() { return this == TRUE; } public boolean isFalse() { return this == FALSE; } public boolean isPresent() { return this == TRUE || this == FALSE; } public boolean isUnknown() { return this == UNKNOWN; } public boolean orElseTrue() {return orElse(true);} public boolean orElseFalse() {return orElse(false);} public boolean orElse(final boolean other) { if (this == TRUE) { return true; } else if (this == FALSE) { return false; } else { return other; } } @NonNull public OptionalBoolean ifUnknown(@NonNull final OptionalBoolean other) { return isPresent() ? this : other; } @NonNull public OptionalBoolean ifUnknown(@NonNull final Supplier<OptionalBoolean> otherSupplier) { return isPresent() ? this : otherSupplier.get();
} @JsonValue @Nullable public Boolean toBooleanOrNull() { switch (this) { case TRUE: return Boolean.TRUE; case FALSE: return Boolean.FALSE; case UNKNOWN: return null; default: throw new IllegalStateException("Type not handled: " + this); } } @Nullable public String toBooleanString() { return StringUtils.ofBoolean(toBooleanOrNull()); } public void ifPresent(@NonNull final BooleanConsumer action) { if (this == TRUE) { action.accept(true); } else if (this == FALSE) { action.accept(false); } } public void ifTrue(@NonNull final Runnable action) { if (this == TRUE) { action.run(); } } public <U> Optional<U> map(@NonNull final BooleanFunction<? extends U> mapper) { return isPresent() ? Optional.ofNullable(mapper.apply(isTrue())) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalBoolean.java
1
请完成以下Java代码
public void setMD_Candidate_RebookedFrom(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate_RebookedFrom) { set_ValueFromPO(COLUMNNAME_MD_Candidate_RebookedFrom_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate_RebookedFrom); } @Override public void setMD_Candidate_RebookedFrom_ID (final int MD_Candidate_RebookedFrom_ID) { if (MD_Candidate_RebookedFrom_ID < 1) set_Value (COLUMNNAME_MD_Candidate_RebookedFrom_ID, null); else set_Value (COLUMNNAME_MD_Candidate_RebookedFrom_ID, MD_Candidate_RebookedFrom_ID); } @Override public int getMD_Candidate_RebookedFrom_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_RebookedFrom_ID); } @Override public void setMD_Candidate_Transaction_Detail_ID (final int MD_Candidate_Transaction_Detail_ID) { if (MD_Candidate_Transaction_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_Transaction_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_Transaction_Detail_ID, MD_Candidate_Transaction_Detail_ID); } @Override public int getMD_Candidate_Transaction_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_Transaction_Detail_ID); } @Override public void setMD_Stock_ID (final int MD_Stock_ID) { if (MD_Stock_ID < 1) set_Value (COLUMNNAME_MD_Stock_ID, null); else set_Value (COLUMNNAME_MD_Stock_ID, MD_Stock_ID); }
@Override public int getMD_Stock_ID() { return get_ValueAsInt(COLUMNNAME_MD_Stock_ID); } @Override public void setMovementQty (final BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } @Override public BigDecimal getMovementQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTransactionDate (final @Nullable java.sql.Timestamp TransactionDate) { set_Value (COLUMNNAME_TransactionDate, TransactionDate); } @Override public java.sql.Timestamp getTransactionDate() { return get_ValueAsTimestamp(COLUMNNAME_TransactionDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Transaction_Detail.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((color == null) ? 0 : color.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof Square)) { return false; } Square other = (Square) obj; if (color == null) {
if (other.color != null) { return false; } } else if (!color.equals(other.color)) { return false; } return true; } protected Color getColor() { return color; } protected void setColor(Color color) { this.color = color; } }
repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\equalshashcode\entities\Square.java
1
请完成以下Java代码
public GridController getCurrentGridController() { return this.m_curGC; } public final AppsAction getIgnoreAction() { return aIgnore; } public final boolean isAlignVerticalTabsWithHorizontalTabs() { return alignVerticalTabsWithHorizontalTabs; } /** * For a given component, it removes component's key bindings (defined in ancestor's map) that this panel also have defined. * * The main purpose of doing this is to make sure menu/toolbar key bindings will not be intercepted by given component, so panel's key bindings will work when given component is embedded in our * panel. * * @param comp component or <code>null</code> */ public final void removeAncestorKeyBindingsOf(final JComponent comp, final Predicate<KeyStroke> isRemoveKeyStrokePredicate) { // Skip null components (but tolerate that) if (comp == null) { return; } // Get component's ancestors input map (the map which defines which key bindings will work when pressed in a component which is included inside this component). final InputMap compInputMap = comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); // NOTE: don't check and exit if "compInputMap.size() <= 0" because it might be that this map is empty but the key bindings are defined in it's parent map. // Iterate all key bindings for our panel and remove those which are also present in component's ancestor map. final InputMap thisInputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); for (final KeyStroke key : thisInputMap.allKeys()) { // Check if the component has a key binding defined for our panel key binding. final Object compAction = compInputMap.get(key);
if (compAction == null) { continue; } if (isRemoveKeyStrokePredicate != null && !isRemoveKeyStrokePredicate.apply(key)) { continue; } // NOTE: Instead of removing it, it is much more safe to bind it to "none", // to explicitly say to not consume that key event even if is defined in some parent map of this input map. compInputMap.put(key, "none"); if (log.isDebugEnabled()) { log.debug("Removed " + key + "->" + compAction + " which in this component is binded to " + thisInputMap.get(key) + "\n\tThis panel: " + this + "\n\tComponent: " + comp); } } } } // APanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\APanel.java
1
请完成以下Spring Boot application配置
# # Configurações de acesso ao Minio # aws: s3: region: sa-east-1 # When using AWS, the library will use one of the available # credential sources described in the documentation.
# accessKeyId: **** # secretAccessKey: **** bucket: dev1.token.com.br
repos\tutorials-master\aws-modules\aws-reactive\src\main\resources\application.yml
2
请完成以下Java代码
public class HomepageForwardingMatcher<T> implements Predicate<T> { private final List<Pattern> includeRoutes; private final List<Pattern> excludeRoutes; private final Function<T, String> methodAccessor; private final Function<T, String> pathAccessor; private final Function<T, List<MediaType>> acceptsAccessor; public HomepageForwardingMatcher(List<String> includeRoutes, List<String> excludeRoutes, Function<T, String> methodAccessor, Function<T, String> pathAccessor, Function<T, List<MediaType>> acceptsAccessor) { this.includeRoutes = toPatterns(includeRoutes); this.excludeRoutes = toPatterns(excludeRoutes); this.methodAccessor = methodAccessor; this.pathAccessor = pathAccessor; this.acceptsAccessor = acceptsAccessor; } public boolean test(T request) { if (!HttpMethod.GET.matches(this.methodAccessor.apply(request))) { return false; }
String path = this.pathAccessor.apply(request); boolean isExcludedRoute = this.excludeRoutes.stream().anyMatch((p) -> p.matcher(path).matches()); boolean isIncludedRoute = this.includeRoutes.stream().anyMatch((p) -> p.matcher(path).matches()); if (isExcludedRoute || !isIncludedRoute) { return false; } return this.acceptsAccessor.apply(request).stream().anyMatch((t) -> t.includes(MediaType.TEXT_HTML)); } private List<Pattern> toPatterns(List<String> routes) { return routes.stream() .map((r) -> "^" + r.replaceAll("/[*][*]", "(/.*)?").replaceAll("/[*]/", "/[^/]+/") + "$") .map(Pattern::compile) .toList(); } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\HomepageForwardingMatcher.java
1
请在Spring Boot框架中完成以下Java代码
public static JsonWFProcess of( @NonNull final WFProcess wfProcess, @NonNull final WFProcessHeaderProperties headerProperties, @NonNull final ImmutableMap<WFActivityId, UIComponent> uiComponents, @NonNull final JsonOpts jsonOpts) { return builder() .id(wfProcess.getId().getAsString()) .headerProperties(JsonWFProcessHeaderProperties.of(headerProperties, jsonOpts)) .activities(wfProcess.getActivities() .stream() .map(activity -> JsonWFActivity.of( activity, uiComponents.get(activity.getId()), jsonOpts)) .collect(ImmutableList.toImmutableList()))
.isAllowAbort(wfProcess.isAllowAbort()) .build(); } @JsonIgnore public JsonWFActivity getActivityById(@NonNull final String activityId) { return activities.stream().filter(activity -> activity.getActivityId().equals(activityId)) .findFirst() .orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG) .appendParametersToMessage() .setParameter("ID", activityId) .setParameter("WFProcess", this)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\json\JsonWFProcess.java
2
请在Spring Boot框架中完成以下Java代码
public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 //rcm.setDefaultExpiration(60);//秒
return rcm; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\config\RedisConfig.java
2
请完成以下Java代码
public NativeHistoricVariableInstanceQuery disableCustomObjectDeserialization() { this.isCustomObjectDeserializationEnabled = false; return this; } public List<HistoricVariableInstance> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults) { List<HistoricVariableInstance> historicVariableInstances = commandContext .getHistoricVariableInstanceManager() .findHistoricVariableInstancesByNativeQuery(parameterMap, firstResult, maxResults); if (historicVariableInstances!=null) { for (HistoricVariableInstance historicVariableInstance: historicVariableInstances) { HistoricVariableInstanceEntity variableInstanceEntity = (HistoricVariableInstanceEntity) historicVariableInstance; try { variableInstanceEntity.getTypedValue(isCustomObjectDeserializationEnabled); } catch(Exception t) {
// do not fail if one of the variables fails to load LOG.exceptionWhileGettingValueForVariable(t); } } } return historicVariableInstances; } public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) { return commandContext .getHistoricVariableInstanceManager() .findHistoricVariableInstanceCountByNativeQuery(parameterMap); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\NativeHistoricVariableInstanceQueryImpl.java
1
请完成以下Java代码
public Builder setParentDocument(final Document parentDocument) { this.parentDocument = parentDocument; return this; } public Builder noSorting() { _noSorting = true; _orderBys = null; return this; } public boolean isNoSorting() { return _noSorting; } public Builder addOrderBy(@NonNull final DocumentQueryOrderBy orderBy) { Check.assume(!_noSorting, "sorting not disabled for {}", this); if (_orderBys == null) { _orderBys = new ArrayList<>(); } _orderBys.add(orderBy); return this; } public Builder setOrderBys(final DocumentQueryOrderByList orderBys) { if (orderBys == null || orderBys.isEmpty()) { _orderBys = null; } else
{ _orderBys = new ArrayList<>(orderBys.toList()); } return this; } private DocumentQueryOrderByList getOrderBysEffective() { return _noSorting ? DocumentQueryOrderByList.EMPTY : DocumentQueryOrderByList.ofList(_orderBys); } public Builder setFirstRow(final int firstRow) { this.firstRow = firstRow; return this; } public Builder setPageLength(final int pageLength) { this.pageLength = pageLength; return this; } public Builder setExistingDocumentsSupplier(final Function<DocumentId, Document> existingDocumentsSupplier) { this.existingDocumentsSupplier = existingDocumentsSupplier; return this; } public Builder setChangesCollector(IDocumentChangesCollector changesCollector) { this.changesCollector = changesCollector; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQuery.java
1
请在Spring Boot框架中完成以下Java代码
public Result<JwSysUserDepartVo> getThirdUserByWechat(HttpServletRequest request){ //获取企业微信配置 Integer tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request),0); SysThirdAppConfig config = appConfigService.getThirdConfigByThirdType(tenantId, MessageTypeEnum.QYWX.getType()); if (null != config) { JwSysUserDepartVo list = wechatEnterpriseService.getThirdUserByWechat(tenantId); return Result.ok(list); } return Result.error("企业微信尚未配置,请配置企业微信"); } /** * 同步企业微信部门和用户到本地 * @param jwUserDepartJson * @param request * @return */ @GetMapping("/sync/wechatEnterprise/departAndUser/toLocal")
public Result<SyncInfoVo> syncWechatEnterpriseDepartAndUserToLocal(@RequestParam(name = "jwUserDepartJson") String jwUserDepartJson,HttpServletRequest request){ int tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request), 0); SyncInfoVo syncInfoVo = wechatEnterpriseService.syncWechatEnterpriseDepartAndUserToLocal(jwUserDepartJson,tenantId); return Result.ok(syncInfoVo); } /** * 查询被绑定的企业微信用户 * @param request * @return */ @GetMapping("/getThirdUserBindByWechat") public Result<List<JwUserDepartVo>> getThirdUserBindByWechat(HttpServletRequest request){ int tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request), 0); List<JwUserDepartVo> jwSysUserDepartVos = wechatEnterpriseService.getThirdUserBindByWechat(tenantId); return Result.ok(jwSysUserDepartVos); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\ThirdAppController.java
2
请完成以下Java代码
public style setMedia(String media) { addAttribute("media",media); return this; } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public style addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public style addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public style addElement(Element element) {
addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public style addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public style removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\style.java
1
请完成以下Java代码
public WebGraphQlHandler.Builder interceptor(WebGraphQlInterceptor... interceptors) { return interceptors(Arrays.asList(interceptors)); } @Override public WebGraphQlHandler.Builder interceptors(List<WebGraphQlInterceptor> interceptors) { this.interceptors.addAll(interceptors); interceptors.forEach((interceptor) -> { if (interceptor instanceof WebSocketGraphQlInterceptor) { Assert.isNull(this.webSocketInterceptor, "There can be at most 1 WebSocketInterceptor"); this.webSocketInterceptor = (WebSocketGraphQlInterceptor) interceptor; } }); return this; } @Override public WebGraphQlHandler.Builder contextSnapshotFactory(ContextSnapshotFactory snapshotFactory) { this.snapshotFactory = snapshotFactory; return this; } @Override public WebGraphQlHandler build() { ContextSnapshotFactory snapshotFactory = ContextPropagationHelper.selectInstance(this.snapshotFactory); Chain endOfChain = (request) -> this.service.execute(request).map(WebGraphQlResponse::new); Chain executionChain = this.interceptors.stream() .reduce(WebGraphQlInterceptor::andThen) .map((interceptor) -> interceptor.apply(endOfChain)) .orElse(endOfChain); return new WebGraphQlHandler() { @Override public WebSocketGraphQlInterceptor getWebSocketInterceptor() { return (DefaultWebGraphQlHandlerBuilder.this.webSocketInterceptor != null) ? DefaultWebGraphQlHandlerBuilder.this.webSocketInterceptor : new WebSocketGraphQlInterceptor() { }; }
@Override public ContextSnapshotFactory contextSnapshotFactory() { return snapshotFactory; } @Override public Mono<WebGraphQlResponse> handleRequest(WebGraphQlRequest request) { ContextSnapshot snapshot = snapshotFactory.captureAll(); return executionChain.next(request).contextWrite((context) -> { context = ContextPropagationHelper.saveInstance(snapshotFactory, context); return snapshot.updateContext(context); }); } }; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\DefaultWebGraphQlHandlerBuilder.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-admin-server # Spring 应用名 cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 service: ${spring.application.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.nam
e}。 metadata: user.name: user # Spring Security 安全认证的账号 user.password: user # Spring Security 安全认证的密码
repos\SpringBoot-Labs-master\labx-15\labx-15-admin-03-adminserver\src\main\resources\application.yaml
2
请完成以下Java代码
public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) { this.decisionDefinitionIdIn = decisionDefinitionIdIn; } @CamundaQueryParam(value = "decisionDefinitionKeyIn", converter = StringArrayConverter.class) public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; } @CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class) public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value = "compact", converter = BooleanConverter.class) public void setCompact(Boolean compact) { this.compact = compact; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected CleanableHistoricDecisionInstanceReport createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricDecisionInstanceReport(); } @Override protected void applyFilters(CleanableHistoricDecisionInstanceReport query) { if (decisionDefinitionIdIn != null && decisionDefinitionIdIn.length > 0) { query.decisionDefinitionIdIn(decisionDefinitionIdIn); } if (decisionDefinitionKeyIn != null && decisionDefinitionKeyIn.length > 0) { query.decisionDefinitionKeyIn(decisionDefinitionKeyIn); }
if (Boolean.TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIdIn != null && tenantIdIn.length > 0) { query.tenantIdIn(tenantIdIn); } if (Boolean.TRUE.equals(compact)) { query.compact(); } } @Override protected void applySortBy(CleanableHistoricDecisionInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { query.orderByFinished(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportDto.java
1
请在Spring Boot框架中完成以下Java代码
public final class RSocketMessagingAutoConfiguration { @Bean @ConditionalOnMissingBean RSocketMessageHandler messageHandler(RSocketStrategies rSocketStrategies, ObjectProvider<RSocketMessageHandlerCustomizer> customizers, ApplicationContext context) { RSocketMessageHandler messageHandler = new RSocketMessageHandler(); messageHandler.setRSocketStrategies(rSocketStrategies); customizers.orderedStream().forEach((customizer) -> customizer.customize(messageHandler)); return messageHandler; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ControllerAdviceBean.class) static class MessagingAdviceConfiguration { @Bean MessagingAdviceRSocketMessageHandlerCustomizer messagingAdviceRSocketMessageHandlerCustomizer( ApplicationContext applicationContext) { return new MessagingAdviceRSocketMessageHandlerCustomizer(applicationContext); } } static final class MessagingAdviceRSocketMessageHandlerCustomizer implements RSocketMessageHandlerCustomizer { private final ApplicationContext applicationContext; MessagingAdviceRSocketMessageHandlerCustomizer(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void customize(RSocketMessageHandler messageHandler) { ControllerAdviceBean.findAnnotatedBeans(this.applicationContext) .forEach((controllerAdviceBean) -> messageHandler .registerMessagingAdvice(new ControllerAdviceBeanWrapper(controllerAdviceBean))); }
} private static final class ControllerAdviceBeanWrapper implements MessagingAdviceBean { private final ControllerAdviceBean adviceBean; private ControllerAdviceBeanWrapper(ControllerAdviceBean adviceBean) { this.adviceBean = adviceBean; } @Override public @Nullable Class<?> getBeanType() { return this.adviceBean.getBeanType(); } @Override public Object resolveBean() { return this.adviceBean.resolveBean(); } @Override public boolean isApplicableToBeanType(Class<?> beanType) { return this.adviceBean.isApplicableToBeanType(beanType); } @Override public int getOrder() { return this.adviceBean.getOrder(); } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketMessagingAutoConfiguration.java
2
请完成以下Java代码
private StagingData retrieveStagingData(@NonNull final String transactionId) { return cache.getOrLoad(transactionId, this::retrieveStagingData0); } @NonNull private StagingData retrieveStagingData0(@NonNull final String transactionId) { final ImmutableList<I_M_ReceiptSchedule_ExportAudit> exportAuditRecord = queryBL.createQueryBuilder(I_M_ReceiptSchedule_ExportAudit.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ReceiptSchedule_ExportAudit.COLUMN_TransactionIdAPI, transactionId) .create() .listImmutable(I_M_ReceiptSchedule_ExportAudit.class); return new StagingData(
Maps.uniqueIndex(exportAuditRecord, I_M_ReceiptSchedule_ExportAudit::getM_ReceiptSchedule_ID), exportAuditRecord); } @Value private static class StagingData { @NonNull ImmutableMap<Integer, I_M_ReceiptSchedule_ExportAudit> schedIdToRecords; @NonNull ImmutableList<I_M_ReceiptSchedule_ExportAudit> records; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\exportaudit\ReceiptScheduleAuditRepository.java
1
请完成以下Java代码
final class OAuth2AuthorizationRequestDeserializer extends ValueDeserializer<OAuth2AuthorizationRequest> { @Override public OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context) { JsonNode root = context.readTree(parser); return deserialize(parser, context, root); } private OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context, JsonNode root) { AuthorizationGrantType authorizationGrantType = convertAuthorizationGrantType( JsonNodeUtils.findObjectNode(root, "authorizationGrantType")); Builder builder = getBuilder(parser, authorizationGrantType); builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri")); builder.clientId(JsonNodeUtils.findStringValue(root, "clientId")); builder.redirectUri(JsonNodeUtils.findStringValue(root, "redirectUri")); builder.scopes(JsonNodeUtils.findValue(root, "scopes", JsonNodeUtils.STRING_SET, context)); builder.state(JsonNodeUtils.findStringValue(root, "state")); builder.additionalParameters( JsonNodeUtils.findValue(root, "additionalParameters", JsonNodeUtils.STRING_OBJECT_MAP, context)); builder.authorizationRequestUri(JsonNodeUtils.findStringValue(root, "authorizationRequestUri")); builder.attributes(JsonNodeUtils.findValue(root, "attributes", JsonNodeUtils.STRING_OBJECT_MAP, context)); return builder.build(); }
private Builder getBuilder(JsonParser parser, AuthorizationGrantType authorizationGrantType) { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) { return OAuth2AuthorizationRequest.authorizationCode(); } throw new InvalidFormatException(parser, "Invalid authorizationGrantType", authorizationGrantType, AuthorizationGrantType.class); } private static AuthorizationGrantType convertAuthorizationGrantType(JsonNode jsonNode) { String value = JsonNodeUtils.findStringValue(jsonNode, "value"); if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) { return AuthorizationGrantType.AUTHORIZATION_CODE; } return null; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\jackson\OAuth2AuthorizationRequestDeserializer.java
1
请完成以下Spring Boot application配置
spring: datasource: url: jdbc:h2:mem:mydb;MODE=Oracle username: sa password: password driverClassName: org.h2.Driver jpa: database-platform: org.hibernate.dialect.OracleDialect defer-datasource-initialization: true sho
w-sql: true properties: hibernate: format_sql: true sql: init: data-locations:
repos\tutorials-master\persistence-modules\hibernate6\src\main\resources\application-oracle.yaml
2
请完成以下Java代码
public int breakCipher(String message) { return probableOffset(chiSquares(message)); } private double[] chiSquares(String message) { double[] expectedLettersFrequencies = expectedLettersFrequencies(message.length()); double[] chiSquares = new double[ALPHABET_SIZE]; for (int offset = 0; offset < chiSquares.length; offset++) { String decipheredMessage = decipher(message, offset); long[] lettersFrequencies = observedLettersFrequencies(decipheredMessage); double chiSquare = new ChiSquareTest().chiSquare(expectedLettersFrequencies, lettersFrequencies); chiSquares[offset] = chiSquare; } return chiSquares; } private long[] observedLettersFrequencies(String message) { return IntStream.rangeClosed(LETTER_A, LETTER_Z) .mapToLong(letter -> countLetter((char) letter, message)) .toArray(); } private long countLetter(char letter, String message) { return message.chars() .filter(character -> character == letter) .count(); } private double[] expectedLettersFrequencies(int messageLength) { return Arrays.stream(ENGLISH_LETTERS_PROBABILITIES)
.map(probability -> probability * messageLength) .toArray(); } private int probableOffset(double[] chiSquares) { int probableOffset = 0; for (int offset = 0; offset < chiSquares.length; offset++) { log.debug(String.format("Chi-Square for offset %d: %.2f", offset, chiSquares[offset])); if (chiSquares[offset] < chiSquares[probableOffset]) { probableOffset = offset; } } return probableOffset; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\caesarcipher\CaesarCipher.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Duration getInitialDelay() { return this.initialDelay; } public void setInitialDelay(@Nullable Duration initialDelay) { this.initialDelay = initialDelay; } public @Nullable String getCron() { return this.cron; } public void setCron(@Nullable String cron) { this.cron = cron; } } public static class Management { /** * Whether Spring Integration components should perform logging in the main * message flow. When disabled, such logging will be skipped without checking the * logging level. When enabled, such logging is controlled as normal by the * logging system's log level configuration. */ private boolean defaultLoggingEnabled = true; /** * List of simple patterns to match against the names of Spring Integration * components. When matched, observation instrumentation will be performed for the * component. Please refer to the javadoc of the smartMatch method of Spring * Integration's PatternMatchUtils for details of the pattern syntax. */ private List<String> observationPatterns = new ArrayList<>();
public boolean isDefaultLoggingEnabled() { return this.defaultLoggingEnabled; } public void setDefaultLoggingEnabled(boolean defaultLoggingEnabled) { this.defaultLoggingEnabled = defaultLoggingEnabled; } public List<String> getObservationPatterns() { return this.observationPatterns; } public void setObservationPatterns(List<String> observationPatterns) { this.observationPatterns = observationPatterns; } } }
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationProperties.java
2
请完成以下Java代码
public static FileValueBuilder fileValue(String filename, boolean isTransient) { return new FileValueBuilderImpl(filename).setTransient(isTransient); } /** * Shortcut for calling {@code Variables.fileValue(name).file(file).mimeType(type).create()}. * The name is set to the file name and the mime type is detected via {@link MimetypesFileTypeMap}. */ public static FileValue fileValue(File file){ String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file); return new FileValueBuilderImpl(file.getName()).file(file).mimeType(contentType).create(); } /** * Shortcut for calling {@code Variables.fileValue(name).file(file).mimeType(type).setTransient(isTransient).create()}.
* The name is set to the file name and the mime type is detected via {@link MimetypesFileTypeMap}. */ public static FileValue fileValue(File file, boolean isTransient){ String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file); return new FileValueBuilderImpl(file.getName()).file(file).mimeType(contentType).setTransient(isTransient).create(); } /** * @return an empty {@link VariableContext} (from which no variables can be resolved). */ public static VariableContext emptyVariableContext() { return EmptyVariableContext.INSTANCE; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\Variables.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductId implements RepoIdAware { int repoId; @JsonCreator public static ProductId ofRepoId(final int repoId) { return new ProductId(repoId); } @Nullable public static ProductId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new ProductId(repoId) : null; } @Nullable public static ProductId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ProductId(repoId) : null; } public static Optional<ProductId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static Set<ProductId> ofRepoIds(final Collection<Integer> repoIds) { return repoIds.stream() .filter(repoId -> repoId != null && repoId > 0) .map(ProductId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } public static int toRepoId(@Nullable final ProductId productId) { return productId != null ? productId.getRepoId() : -1; } public static Set<Integer> toRepoIds(final Collection<ProductId> productIds)
{ return productIds.stream() .filter(Objects::nonNull) .map(ProductId::toRepoId) .collect(ImmutableSet.toImmutableSet()); } public static boolean equals(@Nullable final ProductId o1, @Nullable final ProductId o2) { return Objects.equals(o1, o2); } private ProductId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "productId"); } @Override @JsonValue public int getRepoId() { return repoId; } public String getAsString() {return String.valueOf(getRepoId());} public TableRecordReference toTableRecordReference() { return TableRecordReference.of(I_M_Product.Table_Name, getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\product\ProductId.java
2
请完成以下Java代码
protected boolean shouldInclude(Term term) { // 除掉停用词 return CoreStopWordDictionary.shouldInclude(term); } /** * 设置关键词提取器使用的分词器 * * @param segment 任何开启了词性标注的分词器 * @return 自己 */ public KeywordExtractor setSegment(Segment segment) { defaultSegment = segment; return this; } public Segment getSegment() { return defaultSegment; } /** * 提取关键词 * * @param document 关键词 * @param size 需要几个关键词 * @return */ public List<String> getKeywords(String document, int size) { return getKeywords(defaultSegment.seg(document), size);
} /** * 提取关键词(top 10) * * @param document 文章 * @return */ public List<String> getKeywords(String document) { return getKeywords(defaultSegment.seg(document), 10); } protected void filter(List<Term> termList) { ListIterator<Term> listIterator = termList.listIterator(); while (listIterator.hasNext()) { if (!shouldInclude(listIterator.next())) listIterator.remove(); } } abstract public List<String> getKeywords(List<Term> termList, int size); }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\summary\KeywordExtractor.java
1
请完成以下Spring Boot application配置
spring.application.name=mcp-server-oauth2 server.port=8090 spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:9000 spring.ai.mcp.server.enabled=true spring.ai.mcp.server.name=mcp-calculator-server spring.ai.mcp.server.version=1.0.0 spring.ai.mcp.server.stdio=fal
se logging.level.org.springframework.security=DEBUG logging.level.org.springframework.ai.mcp=INFO logging.level.root=INFO
repos\tutorials-master\spring-ai-modules\spring-ai-mcp-oauth\mcp-server-oauth2\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public <I extends EntityId> I getExternalIdByInternal(I internalId) { ExportableEntityDao<I, ?> dao = getExportableEntityDao(internalId.getEntityType()); if (dao == null) { return null; } return dao.getExternalIdByInternal(internalId); } private boolean belongsToTenant(HasId<? extends EntityId> entity, TenantId tenantId) { return tenantId.equals(((HasTenantId) entity).getTenantId()); } @Override public <I extends EntityId> void removeById(TenantId tenantId, I id) { EntityType entityType = id.getEntityType(); EntityDaoService entityService = entityServiceRegistry.getServiceByEntityType(entityType); entityService.deleteEntity(tenantId, id, false); } private <I extends EntityId, E extends ExportableEntity<I>> ExportableEntityDao<I, E> getExportableEntityDao(EntityType entityType) { Dao<E> dao = getDao(entityType); if (dao instanceof ExportableEntityDao) { return (ExportableEntityDao<I, E>) dao; } else { return null; } }
@SuppressWarnings("unchecked") private <E> Dao<E> getDao(EntityType entityType) { return (Dao<E>) daos.get(entityType); } @Autowired private void setDaos(Collection<Dao<?>> daos) { daos.forEach(dao -> { if (dao.getEntityType() != null) { this.daos.put(dao.getEntityType(), dao); } }); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\exporting\DefaultExportableEntitiesService.java
2
请完成以下Java代码
public void setIsMultiLine (final boolean IsMultiLine) { set_Value (COLUMNNAME_IsMultiLine, IsMultiLine); } @Override public boolean isMultiLine() { return get_ValueAsBoolean(COLUMNNAME_IsMultiLine); } @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 setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing()
{ return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSkipFirstNRows (final int SkipFirstNRows) { set_Value (COLUMNNAME_SkipFirstNRows, SkipFirstNRows); } @Override public int getSkipFirstNRows() { return get_ValueAsInt(COLUMNNAME_SkipFirstNRows); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat.java
1
请完成以下Java代码
public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", subjectId=").append(subjectId); sb.append(", memberNickName=").append(memberNickName); sb.append(", memberIcon=").append(memberIcon); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubjectComment.java
1
请完成以下Java代码
default <T> void accumulateAndProcessBeforeCommit( @NonNull final String propertyName, @NonNull final Collection<T> itemsToAccumulate, @NonNull final Consumer<ImmutableList<T>> beforeCommitListProcessor) { final ITrx trx = getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (isActive(trx) && canRegisterOnTiming(ITrxListenerManager.TrxEventTiming.BEFORE_COMMIT)) { trx.accumulateAndProcessBeforeCommit(propertyName, itemsToAccumulate, beforeCommitListProcessor); } else { beforeCommitListProcessor.accept(ImmutableList.copyOf(itemsToAccumulate)); } } default <T> void accumulateAndProcessAfterCommit( @NonNull final String propertyName, @NonNull final Collection<T> itemsToAccumulate, @NonNull final Consumer<ImmutableList<T>> afterCommitListProcessor) { final ITrx trx = getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (isActive(trx) && canRegisterOnTiming(ITrxListenerManager.TrxEventTiming.AFTER_COMMIT)) { trx.accumulateAndProcessAfterCommit(propertyName, itemsToAccumulate, afterCommitListProcessor);
} else { afterCommitListProcessor.accept(ImmutableList.copyOf(itemsToAccumulate)); } } default <T> void accumulateAndProcessAfterRollback( @NonNull final String propertyName, @NonNull final Collection<T> itemsToAccumulate, @NonNull final Consumer<ImmutableList<T>> processor) { final ITrx trx = getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (isActive(trx)) { trx.accumulateAndProcessAfterRollback(propertyName, itemsToAccumulate, processor); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\ITrxManager.java
1
请完成以下Java代码
public class C_DocType_Clone_Selection extends JavaProcess implements IProcessPrecondition { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); private static final String PARAM_AD_ORG_ID = I_AD_Org.COLUMNNAME_AD_Org_ID; @Param(parameterName = PARAM_AD_ORG_ID, mandatory = true) private int toOrgId; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final OrgId orgId = OrgId.ofRepoId(toOrgId); final PInstanceId pinstanceId = getPinstanceId(); final ImmutableList<I_C_DocType> docTypes = docTypeBL.retrieveForSelection(pinstanceId); for (final I_C_DocType docType : docTypes) { docTypeBL.cloneToOrg(docType, orgId); } return "@Copied@=" + docTypes.size(); } @Override @RunOutOfTrx protected void prepare() {
if (createSelection() <= 0) { throw new AdempiereException("@NoSelection@"); } } private int createSelection() { final IQueryBuilder<I_C_DocType> queryBuilder = createDocTypesQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); return queryBuilder .create() .createSelection(adPInstanceId); } @NonNull private IQueryBuilder<I_C_DocType> createDocTypesQueryBuilder() { final IQueryFilter<I_C_DocType> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_C_DocType.class, getCtx(), ITrx.TRXNAME_None) .filter(userSelectionFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\process\C_DocType_Clone_Selection.java
1
请完成以下Java代码
public class ChatGPTEventListener extends EventSourceListener { private SseEmitter sseEmitter; private String traceId; private List<String> answer = new ArrayList<>(); public ChatGPTEventListener(SseEmitter sseEmitter, String traceId) { this.sseEmitter = sseEmitter; this.traceId = traceId; } public ChatGPTEventListener() { } @Override public void onOpen(EventSource eventSource, Response response) { log.info("OpenAI服务器连接成功!,traceId[{}]", traceId); } @SneakyThrows @Override public void onEvent(EventSource eventSource, String id, String type, String data) { log.info("on event data: {}", data); if (data.equals("[DONE]")) { log.info("OpenAI服务器发送结束标志!,traceId[{}]", traceId); /** * 1、完成token计算 * 2、完成数据存储 * 3、返回json格式,用于页面渲染 */ sseEmitter.send(SseEmitter.event() .id("[DONE]") .data("[DONE]") .reconnectTime(3000)); return; } JSONObject jsonObject = JSONUtil.parseObj(data); JSONArray choicesJsonArray = jsonObject.getJSONArray("choices"); String content = null; if (choicesJsonArray.isEmpty()) { content = ""; } else {
JSONObject choiceJson = choicesJsonArray.getJSONObject(0); JSONObject deltaJson = choiceJson.getJSONObject("delta"); String text = deltaJson.getStr("content"); if (text != null) { content = text; answer.add(content); sseEmitter.send(SseEmitter.event() .data(content) .reconnectTime(2000)); } } } @Override public void onClosed(EventSource eventSource) { log.info("OpenAI服务器关闭连接!,traceId[{}]", traceId); log.info("complete answer: {}", StrUtil.join("", answer)); sseEmitter.complete(); } @SneakyThrows @Override public void onFailure(EventSource eventSource, Throwable t, Response response) { // TODO 处理前端中断 log.error("OpenAI服务器连接异常!response:[{}],traceId[{}] 当前内容:{}", response, traceId, StrUtil.join("", answer), t); eventSource.cancel(); sseEmitter.completeWithError(t); } }
repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\event\ChatGPTEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public int updateStatus(Long id, Integer status) { SmsHomeAdvertise record = new SmsHomeAdvertise(); record.setId(id); record.setStatus(status); return advertiseMapper.updateByPrimaryKeySelective(record); } @Override public SmsHomeAdvertise getItem(Long id) { return advertiseMapper.selectByPrimaryKey(id); } @Override public int update(Long id, SmsHomeAdvertise advertise) { advertise.setId(id); return advertiseMapper.updateByPrimaryKeySelective(advertise); } @Override public List<SmsHomeAdvertise> list(String name, Integer type, String endTime, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample(); SmsHomeAdvertiseExample.Criteria criteria = example.createCriteria(); if (!StrUtil.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (type != null) { criteria.andTypeEqualTo(type); } if (!StrUtil.isEmpty(endTime)) { String startStr = endTime + " 00:00:00"; String endStr = endTime + " 23:59:59";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start = null; try { start = sdf.parse(startStr); } catch (ParseException e) { e.printStackTrace(); } Date end = null; try { end = sdf.parse(endStr); } catch (ParseException e) { e.printStackTrace(); } if (start != null && end != null) { criteria.andEndTimeBetween(start, end); } } example.setOrderByClause("sort desc"); return advertiseMapper.selectByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeAdvertiseServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String toString() { return "Cluster{" + "ip='" + ip + '\'' + ", path='" + path + '\'' + '}'; } } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public List<Cluster> getCluster() { return cluster; } public void setCluster(List<Cluster> cluster) { this.cluster = cluster; } @Override public String toString() { return "ServerProperties{" + "email='" + email + '\'' + ", cluster=" + cluster + '}'; } }
repos\spring-boot-master\profile-properties\src\main\java\com\mkyong\config\ServerProperties.java
2
请完成以下Java代码
public de.metas.dimension.model.I_DIM_Dimension_Spec getDIM_Dimension_Spec() { return get_ValueAsPO(COLUMNNAME_DIM_Dimension_Spec_ID, de.metas.dimension.model.I_DIM_Dimension_Spec.class); } @Override public void setDIM_Dimension_Spec(de.metas.dimension.model.I_DIM_Dimension_Spec DIM_Dimension_Spec) { set_ValueFromPO(COLUMNNAME_DIM_Dimension_Spec_ID, de.metas.dimension.model.I_DIM_Dimension_Spec.class, DIM_Dimension_Spec); } /** Set Dimensionsspezifikation. @param DIM_Dimension_Spec_ID Dimensionsspezifikation */ @Override public void setDIM_Dimension_Spec_ID (int DIM_Dimension_Spec_ID) { if (DIM_Dimension_Spec_ID < 1) set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_ID, null);
else set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_ID, Integer.valueOf(DIM_Dimension_Spec_ID)); } /** Get Dimensionsspezifikation. @return Dimensionsspezifikation */ @Override public int getDIM_Dimension_Spec_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_Assignment.java
1
请完成以下Java代码
public void setType(String type) { this.type = type; } public void setRequired(boolean required) { this.required = required; } public void setDisplay(Boolean display) { this.display = display; } public void setDisplayName(String displayName) { this.displayName = displayName; } public boolean isAnalytics() {
return analytics; } public void setAnalytics(boolean analytics) { this.analytics = analytics; } public void setEphemeral(boolean ephemeral) { this.ephemeral = ephemeral; } public boolean isEphemeral() { return ephemeral; } }
repos\Activiti-develop\activiti-core-common\activiti-connector-model\src\main\java\org\activiti\core\common\model\connector\VariableDefinition.java
1
请完成以下Java代码
public List<HistoricProcessInstance> getRunningHistoricProcessInstances(Date startedAfter, Date startedAt, int maxResults) { return commandExecutor.execute( new OptimizeRunningHistoricProcessInstanceQueryCmd(startedAfter, startedAt, maxResults) ); } public List<HistoricVariableUpdate> getHistoricVariableUpdates(Date occurredAfter, Date occurredAt, boolean excludeObjectValues, int maxResults) { return commandExecutor.execute( new OptimizeHistoricVariableUpdateQueryCmd(occurredAfter, occurredAt, excludeObjectValues, maxResults) ); } public List<HistoricIncidentEntity> getCompletedHistoricIncidents(Date finishedAfter, Date finishedAt, int maxResults) { return commandExecutor.execute( new OptimizeCompletedHistoricIncidentsQueryCmd(finishedAfter, finishedAt, maxResults) );
} public List<HistoricIncidentEntity> getOpenHistoricIncidents(Date createdAfter, Date createdAt, int maxResults) { return commandExecutor.execute( new OptimizeOpenHistoricIncidentsQueryCmd(createdAfter, createdAt, maxResults) ); } public List<HistoricDecisionInstance> getHistoricDecisionInstances(Date evaluatedAfter, Date evaluatedAt, int maxResults) { return commandExecutor.execute( new OptimizeHistoricDecisionInstanceQueryCmd(evaluatedAfter, evaluatedAt, maxResults) ); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\OptimizeService.java
1
请完成以下Java代码
public void run() { // Skip if the find panel is not expanded if (!findPanel.isExpanded()) { return; } // NOTE: because when the change event is triggered only the collapsed state is changed, and the actual component layout is happening later, // we are enqueuing an event to be processed in next EDT round. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { detail.scrollToVisible(); } }); } }); } }
public VEditor getEditor(final String columnName) { return columnName2editor.get(columnName); } public final List<String> getEditorColumnNames() { return new ArrayList<>(columnName2editor.keySet()); } public final CLabel getEditorLabel(final String columnName) { return columnName2label.get(columnName); } public final void updateVisibleFieldGroups() { for (final VPanelFieldGroup panel : fieldGroupPanels) { panel.updateVisible(); } } } // VPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanel.java
1
请完成以下Java代码
class AliasedConfigurationPropertySource implements ConfigurationPropertySource { private final ConfigurationPropertySource source; private final ConfigurationPropertyNameAliases aliases; AliasedConfigurationPropertySource(ConfigurationPropertySource source, ConfigurationPropertyNameAliases aliases) { Assert.notNull(source, "'source' must not be null"); Assert.notNull(aliases, "'aliases' must not be null"); this.source = source; this.aliases = aliases; } @Override public @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { Assert.notNull(name, "'name' must not be null"); ConfigurationProperty result = getSource().getConfigurationProperty(name); if (result == null) { ConfigurationPropertyName aliasedName = getAliases().getNameForAlias(name); result = (aliasedName != null) ? getSource().getConfigurationProperty(aliasedName) : null; } return result; } @Override public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { Assert.notNull(name, "'name' must not be null"); ConfigurationPropertyState result = this.source.containsDescendantOf(name); if (result != ConfigurationPropertyState.ABSENT) { return result; } for (ConfigurationPropertyName alias : getAliases().getAliases(name)) { ConfigurationPropertyState aliasResult = this.source.containsDescendantOf(alias); if (aliasResult != ConfigurationPropertyState.ABSENT) { return aliasResult; } } for (ConfigurationPropertyName from : getAliases()) { for (ConfigurationPropertyName alias : getAliases().getAliases(from)) { if (name.isAncestorOf(alias)) { if (this.source.getConfigurationProperty(from) != null) { return ConfigurationPropertyState.PRESENT; }
} } } return ConfigurationPropertyState.ABSENT; } @Override public @Nullable Object getUnderlyingSource() { return this.source.getUnderlyingSource(); } protected ConfigurationPropertySource getSource() { return this.source; } protected ConfigurationPropertyNameAliases getAliases() { return this.aliases; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\AliasedConfigurationPropertySource.java
1
请完成以下Java代码
public class Application { public static Twitter getTwitterinstance() { /** * if not using properties file, we can set access token by following way */ // ConfigurationBuilder cb = new ConfigurationBuilder(); // cb.setDebugEnabled(true) // .setOAuthConsumerKey("//TODO") // .setOAuthConsumerSecret("//TODO") // .setOAuthAccessToken("//TODO") // .setOAuthAccessTokenSecret("//TODO"); // TwitterFactory tf = new TwitterFactory(cb.build()); // Twitter twitter = tf.getSingleton(); Twitter twitter = TwitterFactory.getSingleton(); return twitter; } public static String createTweet(String tweet) throws TwitterException { Twitter twitter = getTwitterinstance(); Status status = twitter.updateStatus("creating baeldung API"); return status.getText(); } public static List<String> getTimeLine() throws TwitterException { Twitter twitter = getTwitterinstance(); List<Status> statuses = twitter.getHomeTimeline(); return statuses.stream().map( item -> item.getText()).collect( Collectors.toList()); } public static String sendDirectMessage(String recipientName, String msg) throws TwitterException { Twitter twitter = getTwitterinstance(); DirectMessage message = twitter.sendDirectMessage(recipientName, msg); return message.getText(); } public static List<String> searchtweets() throws TwitterException { Twitter twitter = getTwitterinstance(); Query query = new Query("source:twitter4j baeldung"); QueryResult result = twitter.search(query); List<Status> statuses = result.getTweets(); return statuses.stream().map( item -> item.getText()).collect( Collectors.toList()); } public static void streamFeed() { StatusListener listener = new StatusListener(){ @Override public void onException(Exception e) { e.printStackTrace(); } @Override public void onDeletionNotice(StatusDeletionNotice arg) {
System.out.println("Got a status deletion notice id:" + arg.getStatusId()); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); } @Override public void onStatus(Status status) { System.out.println(status.getUser().getName() + " : " + status.getText()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); } }
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
1
请完成以下Java代码
public void setUserAgent (final @Nullable java.lang.String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } @Override public java.lang.String getUserAgent() { return get_ValueAsString(COLUMNNAME_UserAgent); } @Override public void setUserName (final java.lang.String UserName) { set_ValueNoCheck (COLUMNNAME_UserName, UserName); } @Override
public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } @Override public void setVersion (final java.lang.String Version) { set_ValueNoCheck (COLUMNNAME_Version, Version); } @Override public java.lang.String getVersion() { return get_ValueAsString(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Issue.java
1
请完成以下Java代码
public String getDocumentInfo() { final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); final DocTypeId docTypeId = DocTypeId.ofRepoId(getC_DocType_ID()); final ITranslatableString docTypeName = docTypeBL.getNameById(docTypeId); return docTypeName.translate(Env.getADLanguageOrBaseLanguage()) + " " + getDocumentNo(); } private PPOrderRouting getOrderRouting() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return Services.get(IPPOrderRoutingRepository.class).getByOrderId(orderId); } @Override public String toString() { return "MPPOrder[ID=" + get_ID() + "-DocumentNo=" + getDocumentNo() + ",IsSOTrx=" + isSOTrx() + ",C_DocType_ID=" + getC_DocType_ID() + "]"; } /** * Auto report the first Activity and Sub contracting if are Milestone Activity */ private void autoReportActivities() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { if (activity.isMilestone() && (activity.isSubcontracting() || orderRouting.isFirstActivity(activity))) { ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder() .order(this) .orderActivity(activity)
.qtyMoved(activity.getQtyToDeliver()) .durationSetup(Duration.ZERO) .duration(Duration.ZERO) .build()); } } } private void createVariances() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); // for (final I_PP_Order_BOMLine bomLine : getLines()) { ppCostCollectorBL.createMaterialUsageVariance(this, bomLine); } // final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { ppCostCollectorBL.createResourceUsageVariance(this, activity); } } } // MPPOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java
1
请在Spring Boot框架中完成以下Java代码
public class JobsConfig { private static final Logger log = LoggerFactory.getLogger(SequentialJobsConfig.class); @Bean public Job jobOne(JobRepository jobRepository, Step stepOne) { return new JobBuilder("jobOne", jobRepository).start(stepOne) .build(); } @Bean public Step stepOne(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("stepOne", jobRepository).tasklet((contribution, chunkContext) -> { log.info("Hello"); return RepeatStatus.FINISHED; }, transactionManager) .build(); }
@Bean public Job jobTwo(JobRepository jobRepository, Step stepTwo) { return new JobBuilder("jobTwo", jobRepository).start(stepTwo) .build(); } @Bean public Step stepTwo(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("stepTwo", jobRepository).tasklet((contribution, chunkContext) -> { log.info("World"); return RepeatStatus.FINISHED; }, transactionManager) .build(); } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\springbatch\jobs\JobsConfig.java
2
请完成以下Java代码
public static void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { DEFAULT.parseText(text, processor); } /** * 解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构) * * @param text 文本 * @param processor 处理器 */ public static void parseText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { DEFAULT.parseText(text, processor); } /** * 最长匹配 * * @param text 文本 * @param processor 处理器 */ public static void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor)
{ DEFAULT.parseLongestText(text, processor); } /** * 热更新(重新加载)<br> * 集群环境(或其他IOAdapter)需要自行删除缓存文件(路径 = HanLP.Config.CustomDictionaryPath[0] + Predefine.BIN_EXT) * * @return 是否加载成功 */ public static boolean reload() { return DEFAULT.reload(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CustomDictionary.java
1
请完成以下Java代码
public void setMessageID (java.lang.String MessageID) { set_Value (COLUMNNAME_MessageID, MessageID); } /** Get Message-ID. @return EMail Message-ID */ @Override public java.lang.String getMessageID () { return (java.lang.String)get_Value(COLUMNNAME_MessageID); } @Override public org.compiere.model.I_R_Request getR_Request() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class); } @Override public void setR_Request(org.compiere.model.I_R_Request R_Request) { set_ValueFromPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class, R_Request); } /** Set Aufgabe. @param R_Request_ID Request from a Business Partner or Prospect */ @Override public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Aufgabe. @return Request from a Business Partner or Prospect */ @Override public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Betreff. @param Subject Mail Betreff
*/ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } @Override public org.compiere.model.I_AD_User getTo_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setTo_User(org.compiere.model.I_AD_User To_User) { set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User); } /** Set To User. @param To_User_ID To User */ @Override public void setTo_User_ID (int To_User_ID) { if (To_User_ID < 1) set_Value (COLUMNNAME_To_User_ID, null); else set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID)); } /** Get To User. @return To User */ @Override public int getTo_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_To_User_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_C_Mail.java
1
请完成以下Java代码
public class X_Data_Export_Audit extends org.compiere.model.PO implements I_Data_Export_Audit, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1753567361L; /** Standard Constructor */ public X_Data_Export_Audit (final Properties ctx, final int Data_Export_Audit_ID, @Nullable final String trxName) { super (ctx, Data_Export_Audit_ID, trxName); } /** Load Constructor */ public X_Data_Export_Audit (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setData_Export_Audit_ID (final int Data_Export_Audit_ID) { if (Data_Export_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID); }
@Override public int getData_Export_Audit_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID); } @Override public org.compiere.model.I_Data_Export_Audit getData_Export_Audit_Parent() { return get_ValueAsPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class); } @Override public void setData_Export_Audit_Parent(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit_Parent) { set_ValueFromPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit_Parent); } @Override public void setData_Export_Audit_Parent_ID (final int Data_Export_Audit_Parent_ID) { if (Data_Export_Audit_Parent_ID < 1) set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, null); else set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, Data_Export_Audit_Parent_ID); } @Override public int getData_Export_Audit_Parent_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Parent_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit.java
1
请完成以下Java代码
public class SysDictVo { /** * 字典id */ @TableId(type = IdType.ASSIGN_ID) private String id; /** * 字典名称 */ private String dictName; /** * 字典编码 */ private String dictCode;
/** * 应用id */ private String lowAppId; /** * 租户ID */ private Integer tenantId; /** * 字典子项 */ private List<SysDictItem> dictItemsList; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\lowapp\SysDictVo.java
1
请完成以下Java代码
public void setIsApplyToTUs (final boolean IsApplyToTUs) { set_Value (COLUMNNAME_IsApplyToTUs, IsApplyToTUs); } @Override public boolean isApplyToTUs() { return get_ValueAsBoolean(COLUMNNAME_IsApplyToTUs); } @Override public void setIsAutoPrint (final boolean IsAutoPrint) { set_Value (COLUMNNAME_IsAutoPrint, IsAutoPrint); } @Override public boolean isAutoPrint() { return get_ValueAsBoolean(COLUMNNAME_IsAutoPrint); } @Override public void setLabelReport_Process_ID (final int LabelReport_Process_ID) { if (LabelReport_Process_ID < 1) set_Value (COLUMNNAME_LabelReport_Process_ID, null); else set_Value (COLUMNNAME_LabelReport_Process_ID, LabelReport_Process_ID); }
@Override public int getLabelReport_Process_ID() { return get_ValueAsInt(COLUMNNAME_LabelReport_Process_ID); } @Override public void setM_HU_Label_Config_ID (final int M_HU_Label_Config_ID) { if (M_HU_Label_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, M_HU_Label_Config_ID); } @Override public int getM_HU_Label_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Label_Config_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Label_Config.java
1
请完成以下Java代码
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Other_ConfigParameter_ID (final int ExternalSystem_Other_ConfigParameter_ID) { if (ExternalSystem_Other_ConfigParameter_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID, ExternalSystem_Other_ConfigParameter_ID); } @Override public int getExternalSystem_Other_ConfigParameter_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID); } @Override public void setName (final String Name) {
set_Value (COLUMNNAME_Name, Name); } @Override public String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final @Nullable String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Other_ConfigParameter.java
1
请完成以下Java代码
public Account getAccount( @NonNull final ProductAcctType acctType, @NonNull final AcctSchema as) { final ProductId productId = getProductId(); if (productId == null) { return super.getAccount(acctType, as); } else { final String acctColumnName = acctType.getColumnName(); final String sql = " SELECT " + " COALESCE(pa." + acctColumnName + ",pca." + acctColumnName + ",asd." + acctColumnName + ")" + " FROM M_Product p" + " INNER JOIN M_Product_Acct pa ON (pa.M_Product_ID=p.M_Product_ID)" + " INNER JOIN M_Product_Category_Acct pca ON (pca.M_Product_Category_ID=p.M_Product_Category_ID AND pca.C_AcctSchema_ID=pa.C_AcctSchema_ID)" + " INNER JOIN C_AcctSchema_Default asd ON (asd.C_AcctSchema_ID=pa.C_AcctSchema_ID)" + " WHERE pa.M_Product_ID=? AND pa.C_AcctSchema_ID=?"; final AccountId accountId = AccountId.ofRepoIdOrNull(DB.getSQLValueEx(ITrx.TRXNAME_None, sql, productId, as.getId())); if (accountId == null) { throw newPostingException().setAcctSchema(as).setDetailMessage("No Product Account for account type " + acctType + ", product " + productId + " and " + as); } return Account.of(accountId, acctType); } } public ExplainedOptional<AggregatedCostAmount> getCreateCosts(final AcctSchema as) { final AcctSchemaId acctSchemaId = as.getId(); if (isReversalLine()) { return services.createReversalCostDetailsOrEmpty( CostDetailReverseRequest.builder() .acctSchemaId(acctSchemaId) .reversalDocumentRef(CostingDocumentRef.ofCostCollectorId(get_ID())) .initialDocumentRef(CostingDocumentRef.ofCostCollectorId(getReversalLine_ID())) .date(getDateAcctAsInstant()) .build()) .map(CostDetailCreateResultsList::toAggregatedCostAmount);
} else { return services.createCostDetailOrEmpty( CostDetailCreateRequest.builder() .acctSchemaId(acctSchemaId) .clientId(getClientId()) .orgId(getOrgId()) .productId(getProductId()) .attributeSetInstanceId(getAttributeSetInstanceId()) .documentRef(CostingDocumentRef.ofCostCollectorId(get_ID())) .qty(getQty()) .amt(CostAmount.zero(as.getCurrencyId())) // N/A .date(getDateAcctAsInstant()) .build()) .map(CostDetailCreateResultsList::toAggregatedCostAmount); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\acct\DocLine_CostCollector.java
1
请完成以下Java代码
private static Optional<InvalidEmail> createInvalidEmailInfo(final Pattern regExpInvalidAddress, final String reponseString) { final Matcher invalidAddressMatcher = regExpInvalidAddress.matcher(reponseString); if (invalidAddressMatcher.matches()) { final String errorMsg = invalidAddressMatcher.group(); final String invalidAddress = invalidAddressMatcher.group(1); return Optional.of(new InvalidEmail(invalidAddress, errorMsg)); } return Optional.empty(); } @Value private static class InvalidEmail { String email; String errorMessage; } private LocalToRemoteSyncResult createOrUpdateGroup(@NonNull final Campaign campaign) { if (Check.isEmpty(campaign.getRemoteId())) { final Group createdGroup = createGroup(campaign); final Campaign campaignWithRemoteId = campaign .toBuilder() .remoteId(Integer.toString(createdGroup.getId())) .build(); return LocalToRemoteSyncResult.inserted(campaignWithRemoteId); }
updateGroup(campaign); return LocalToRemoteSyncResult.updated(campaign); } @Override public void sendEmailActivationForm( @NonNull final String formId, @NonNull final String email) { final String url = "/forms/" + formId + "/send/activate"; final SendEmailActivationFormRequest body = SendEmailActivationFormRequest.builder() .email(email) .doidata(SendEmailActivationFormRequest.DoubleOptInData.builder() .user_ip("1.2.3.4") .referer("metasfresh") .user_agent("metasfresh") .build()) .build(); getLowLevelClient().post(body, SINGLE_HETEROGENOUS_TYPE, url); // returns the email as string in case of success } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\CleverReachClient.java
1
请在Spring Boot框架中完成以下Java代码
public void run(String... args) { var authors = insertAuthors(); listAllAuthors(); findById(authors); findByPartialName(); queryFindByName(); deleteAll(); } private void deleteAll() { this.authorRepository.deleteAll(); long count = this.authorRepository.count(); System.out.printf("deleteAll(): count = %d%n", count); } private void queryFindByName() { Author author1 = this.authorRepository.queryFindByName("Josh Long").orElse(null); Author author2 = this.authorRepository.queryFindByName("Martin Kleppmann").orElse(null); System.out.printf("queryFindByName(): author1 = %s%n", author1); System.out.printf("queryFindByName(): author2 = %s%n", author2); } private void findByPartialName() { Author author1 = this.authorRepository.findByNameContainingIgnoreCase("sh lo").orElse(null); Author author2 = this.authorRepository.findByNameContainingIgnoreCase("in kl").orElse(null); System.out.printf("findByPartialName(): author1 = %s%n", author1); System.out.printf("findByPartialName(): author2 = %s%n", author2); } private void findById(List<Author> authors) { Author author1 = this.authorRepository.findById(authors.get(0).getId()).orElse(null); Author author2 = this.authorRepository.findById(authors.get(1).getId()).orElse(null);
System.out.printf("findById(): author1 = %s%n", author1); System.out.printf("findById(): author2 = %s%n", author2); } private void listAllAuthors() { List<Author> authors = this.authorRepository.findAll(); for (Author author : authors) { System.out.printf("listAllAuthors(): author = %s%n", author); for (Book book : author.getBooks()) { System.out.printf("\t%s%n", book); } } } private List<Author> insertAuthors() { Author author1 = this.authorRepository.save(new Author(null, "Josh Long", Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java")))); Author author2 = this.authorRepository.save( new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications")))); System.out.printf("insertAuthors(): author1 = %s%n", author1); System.out.printf("insertAuthors(): author2 = %s%n", author2); return Arrays.asList(author1, author2); } }
repos\spring-data-examples-main\jpa\graalvm-native\src\main\java\com\example\data\jpa\CLR.java
2
请完成以下Java代码
public ProductPrice convertProductPriceToUom( @NonNull final ProductPrice price, @NonNull final UomId toUomId, @NonNull final CurrencyPrecision pricePrecision) { if (price.getUomId().equals(toUomId)) { return price; } final UOMConversionRate rate = getRate(price.getProductId(), toUomId, price.getUomId()); final BigDecimal priceConv = pricePrecision.round(rate.convert(price.toBigDecimal(), UOMPrecision.TWELVE)); return price.withValueAndUomId(priceConv, toUomId); }
@Override public void createUOMConversion(@NonNull final CreateUOMConversionRequest request) { uomConversionsDAO.createUOMConversion(request); } @Override public @NonNull Quantity convertToKilogram(@NonNull final Quantity qty, @NonNull final ProductId productId) { final UomId kilogramUomId = uomDAO.getUomIdByX12DE355(X12DE355.KILOGRAM); return convertQuantityTo(qty, UOMConversionContext.of(productId), kilogramUomId) .roundToUOMPrecision(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMConversionBL.java
1
请在Spring Boot框架中完成以下Java代码
public class XmlXtraStationary { XMLGregorianCalendar hospitalizationDate; Duration treatmentDays; String hospitalizationType; String hospitalizationMode; String clazz; String sectionMajor; Boolean hasExpenseLoading; Boolean doCostAssessment; @NonNull XmlGrouperData admissionType; @NonNull XmlGrouperData dischargeType; @NonNull XmlGrouperData providerType;
@NonNull XmlBfsData bfsResidenceBeforeAdmission; @NonNull XmlBfsData bfsAdmissionType; @NonNull XmlBfsData bfsDecisionForDischarge; @NonNull XmlBfsData bfsResidenceAfterDischarge; @Singular List<XmlCaseDetail> caseDetails; }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\treatment\XmlXtraStationary.java
2
请完成以下Java代码
public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", commentId=").append(commentId); sb.append(", newsId=").append(newsId); sb.append(", commentator=").append(commentator); sb.append(", commentBody=").append(commentBody); sb.append(", commentStatus=").append(commentStatus); sb.append(", isDeleted=").append(isDeleted); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsComment.java
1
请完成以下Java代码
protected boolean checkActivityOutputParameterSupported(Element activityElement, ActivityImpl activity) { String tagName = activityElement.getTagName(); if (tagName.equals("endEvent")) { addError("camunda:outputParameter not allowed for element type '" + tagName + "'.", activityElement); return true; } else if (getMultiInstanceScope(activity) != null) { addError("camunda:outputParameter not allowed for multi-instance constructs", activityElement); return false; } else { return true; } } protected void ensureNoIoMappingDefined(Element element) { Element inputOutput = findCamundaExtensionElement(element, "inputOutput"); if (inputOutput != null) { addError("camunda:inputOutput mapping unsupported for element type '" + element.getTagName() + "'.", element); } } protected ParameterValueProvider createParameterValueProvider(Object value, ExpressionManager expressionManager) { if (value == null) { return new NullValueProvider(); } else if (value instanceof String) { Expression expression = expressionManager.createExpression((String) value); return new ElValueProvider(expression); } else { return new ConstantValueProvider(value); }
} protected void addTimeCycleWarning(Element timeCycleElement, String type, String timerElementId) { String warning = "It is not recommended to use a " + type + " timer event with a time cycle."; addWarning(warning, timeCycleElement, timerElementId); } protected void ensureNoExpressionInMessageStartEvent(Element element, EventSubscriptionDeclaration messageStartEventSubscriptionDeclaration, String parentElementId) { boolean eventNameContainsExpression = false; if(messageStartEventSubscriptionDeclaration.hasEventName()) { eventNameContainsExpression = !messageStartEventSubscriptionDeclaration.isEventNameLiteralText(); } if (eventNameContainsExpression) { String messageStartName = messageStartEventSubscriptionDeclaration.getUnresolvedEventName(); addError("Invalid message name '" + messageStartName + "' for element '" + element.getTagName() + "': expressions in the message start event name are not allowed!", element, parentElementId); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\BpmnParse.java
1
请完成以下Java代码
public class ContactDetails { private String mobile; private String landline; @XStreamAsAttribute private String contactType; public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getLandline() { return landline;
} public void setLandline(String landline) { this.landline = landline; } public String getContactType() { return contactType; } public void setContactType(String contactType) { this.contactType = contactType; } @Override public String toString() { return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]"; } }
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\implicit\collection\pojo\ContactDetails.java
1
请完成以下Java代码
public void removeTreeCheckingListener(TreeCheckingListener tsl) { this.checkingModel.removeTreeCheckingListener(tsl); } /** * Expand completely a tree */ public void expandAll() { expandSubTree(getPathForRow(0)); } private void expandSubTree(TreePath path) { expandPath(path); Object node = path.getLastPathComponent(); int childrenNumber = getModel().getChildCount(node); TreePath[] childrenPath = new TreePath[childrenNumber]; for (int childIndex = 0; childIndex < childrenNumber; childIndex++) { childrenPath[childIndex] = path.pathByAddingChild(getModel().getChild(node, childIndex)); expandSubTree(childrenPath[childIndex]); } }
/** * @return a string representation of the tree, including the checking, * enabling and greying sets. */ @Override public String toString() { String retVal = super.toString(); TreeCheckingModel tcm = getCheckingModel(); if (tcm != null) { return retVal + "\n" + tcm.toString(); } return retVal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\CheckboxTree.java
1
请完成以下Java代码
public OrderItemBuilder purchasedQty(@NonNull final Quantity purchasedQty) { innerBuilder.purchasedQty(purchasedQty); return this; } public OrderItemBuilder remotePurchaseOrderId(final String remotePurchaseOrderId) { innerBuilder.remotePurchaseOrderId(remotePurchaseOrderId); return this; } public OrderItemBuilder transactionReference(final ITableRecordReference transactionReference) { innerBuilder.transactionReference(transactionReference); return this; } public OrderItemBuilder dimension(final Dimension dimension) { innerBuilder.dimension(dimension); return this; } public PurchaseOrderItem buildAndAddToParent() { final PurchaseOrderItem newItem = innerBuilder.build(); parent.purchaseOrderItems.add(newItem); return newItem; } } public OrderItemBuilder createOrderItem() { return new OrderItemBuilder(this); } /** * Intended to be used by the persistence layer */ public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem) { final PurchaseCandidateId id = getId(); Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this); Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(), "The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}", purchaseOrderItem, this);
purchaseOrderItems.add(purchaseOrderItem); } public Quantity getPurchasedQty() { return purchaseOrderItems.stream() .map(PurchaseOrderItem::getPurchasedQty) .reduce(Quantity::add) .orElseGet(() -> getQtyToPurchase().toZero()); } public List<PurchaseOrderItem> getPurchaseOrderItems() { return ImmutableList.copyOf(purchaseOrderItems); } public List<PurchaseErrorItem> getPurchaseErrorItems() { return ImmutableList.copyOf(purchaseErrorItems); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java
1
请完成以下Java代码
public ManufacturingOrderExportAudit getByTransactionId(@NonNull final APITransactionId transactionId) { final StagingData stagingData = retrieveStagingData(transactionId); return toExportAudit(stagingData); } private static ManufacturingOrderExportAudit toExportAudit(@NonNull final StagingData stagingData) { return ManufacturingOrderExportAudit.builder() .transactionId(stagingData.getTransactionId()) .items(stagingData.getRecords() .stream() .map(record -> toExportAuditItem(record)) .collect(ImmutableList.toImmutableList())) .build(); } private static ManufacturingOrderExportAuditItem toExportAuditItem(final I_PP_Order_ExportAudit record) { return ManufacturingOrderExportAuditItem.builder() .orderId(extactPPOrderId(record)) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .exportStatus(APIExportStatus.ofCode(record.getExportStatus())) .issueId(AdIssueId.ofRepoIdOrNull(record.getAD_Issue_ID())) .jsonRequest(record.getJsonRequest()) .build(); } @NonNull private StagingData retrieveStagingData(@NonNull final APITransactionId transactionId) { final ImmutableList<I_PP_Order_ExportAudit> records = queryBL.createQueryBuilder(I_PP_Order_ExportAudit.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Order_ExportAudit.COLUMNNAME_TransactionIdAPI, transactionId.toJson()) .create() .listImmutable(I_PP_Order_ExportAudit.class); return StagingData.builder() .transactionId(transactionId) .records(records) .build(); } private static PPOrderId extactPPOrderId(@NonNull final I_PP_Order_ExportAudit record) { return PPOrderId.ofRepoId(record.getPP_Order_ID());
} @Value private static class StagingData { private final APITransactionId transactionId; private final ImmutableList<I_PP_Order_ExportAudit> records; @Getter(AccessLevel.NONE) ImmutableMap<PPOrderId, I_PP_Order_ExportAudit> recordsByOrderId; @Builder private StagingData( @NonNull final APITransactionId transactionId, @NonNull final List<I_PP_Order_ExportAudit> records) { this.transactionId = transactionId; this.recordsByOrderId = Maps.uniqueIndex(records, record -> extactPPOrderId(record)); this.records = ImmutableList.copyOf(records); } @Nullable public I_PP_Order_ExportAudit getByOrderIdOrNull(@NonNull final PPOrderId orderId) { return recordsByOrderId.get(orderId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\ManufacturingOrderExportAuditRepository.java
1
请完成以下Java代码
public ASILayout getLayout() { return descriptor.getLayout(); } public DocumentId getDocumentId() { return data.getDocumentId(); } AttributeSetId getAttributeSetId() { return descriptor.getAttributeSetId(); } void processValueChanges(final List<JSONDocumentChangedEvent> events, final ReasonSupplier reason) { assertNotCompleted(); data.processValueChanges(events, reason); } public Collection<IDocumentFieldView> getFieldViews() { return data.getFieldViews(); } public JSONASIDocument toJSONASIDocument( final JSONDocumentOptions docOpts, final JSONDocumentLayoutOptions layoutOpts) { return JSONASIDocument.builder() .id(data.getDocumentId()) .layout(JSONASILayout.of(getLayout(), layoutOpts)) .fieldsByName(JSONDocument.ofDocument(data, docOpts).getFieldsByName()) .build(); } public LookupValuesPage getFieldLookupValuesForQuery(final String attributeName, final String query) { return data.getFieldLookupValuesForQuery(attributeName, query); } public LookupValuesList getFieldLookupValues(final String attributeName) { return data.getFieldLookupValues(attributeName); } public boolean isCompleted() { return completed; } IntegerLookupValue complete()
{ assertNotCompleted(); final I_M_AttributeSetInstance asiRecord = createM_AttributeSetInstance(this); final IntegerLookupValue lookupValue = IntegerLookupValue.of(asiRecord.getM_AttributeSetInstance_ID(), asiRecord.getDescription()); completed = true; return lookupValue; } private static I_M_AttributeSetInstance createM_AttributeSetInstance(final ASIDocument asiDoc) { // // Create M_AttributeSetInstance final AttributeSetId attributeSetId = asiDoc.getAttributeSetId(); final I_M_AttributeSetInstance asiRecord = InterfaceWrapperHelper.newInstance(I_M_AttributeSetInstance.class); asiRecord.setM_AttributeSet_ID(attributeSetId.getRepoId()); InterfaceWrapperHelper.save(asiRecord); // // Create M_AttributeInstances asiDoc.getFieldViews() .forEach(asiField -> asiField .getDescriptor() .getDataBindingNotNull(ASIAttributeFieldBinding.class) .createAndSaveM_AttributeInstance(asiRecord, asiField)); // // Update the ASI description Services.get(IAttributeSetInstanceBL.class).setDescription(asiRecord); InterfaceWrapperHelper.save(asiRecord); return asiRecord; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIDocument.java
1