org.springframework.data.mongodb.core.mapping.Document Java Examples

The following examples show how to use org.springframework.data.mongodb.core.mapping.Document. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JobItem.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Override
public Context convert(org.bson.Document source) {
    Context context = new Context(source);
    context.putIfNotEmpty(Variables.GIT_EVENT);

    // git push / tag
    context.putIfNotEmpty(Variables.GIT_BRANCH);
    context.putIfNotEmpty(Variables.GIT_COMMIT_ID);
    context.putIfNotEmpty(Variables.GIT_COMMIT_URL);
    context.putIfNotEmpty(Variables.GIT_COMMIT_MESSAGE);

    // git pr
    context.putIfNotEmpty(Variables.PR_TITLE);
    context.putIfNotEmpty(Variables.PR_NUMBER);
    context.putIfNotEmpty(Variables.PR_URL);
    context.putIfNotEmpty(Variables.PR_HEAD_REPO_NAME);
    context.putIfNotEmpty(Variables.PR_HEAD_REPO_BRANCH);
    context.putIfNotEmpty(Variables.PR_BASE_REPO_NAME);
    context.putIfNotEmpty(Variables.PR_BASE_REPO_BRANCH);

    return context;
}
 
Example #2
Source File: JobItem.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Override
public Context convert(org.bson.Document source) {
    Context context = new Context(source);
    context.putIfNotEmpty(Variables.GIT_EVENT);

    // git push / tag
    context.putIfNotEmpty(Variables.GIT_BRANCH);
    context.putIfNotEmpty(Variables.GIT_COMMIT_ID);
    context.putIfNotEmpty(Variables.GIT_COMMIT_URL);
    context.putIfNotEmpty(Variables.GIT_COMMIT_MESSAGE);

    // git pr
    context.putIfNotEmpty(Variables.PR_TITLE);
    context.putIfNotEmpty(Variables.PR_NUMBER);
    context.putIfNotEmpty(Variables.PR_URL);
    context.putIfNotEmpty(Variables.PR_HEAD_REPO_NAME);
    context.putIfNotEmpty(Variables.PR_HEAD_REPO_BRANCH);
    context.putIfNotEmpty(Variables.PR_BASE_REPO_NAME);
    context.putIfNotEmpty(Variables.PR_BASE_REPO_BRANCH);

    return context;
}
 
Example #3
Source File: NonReactiveAggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"ConstantConditions", "Duplicates"})
@Override
protected void initializeAnnotation(Method method) throws InvalidAggregationQueryException {
  this.aggregateAnnotation = method.getAnnotation(Aggregate.class);
  Class inputType = aggregateAnnotation.inputType();
  this.collectionName = deriveCollectionName(aggregateAnnotation,
                                             (idx) -> mongoParameterAccessor.getValues()[idx].toString(),
                                             () -> {
                                               Document documentAnnotation = AnnotationUtils.findAnnotation(inputType,
                                                                                                            Document.class);
                                               return documentAnnotation != null ? documentAnnotation.collection() : null;
                                             },
                                             (s) -> {
                                               Expression expression = detectExpression(s);
                                               if (expression != null) {
                                                 return expression.getValue(context, String.class);
                                               }
                                               return s;
                                             });
  this.placeholderRepFn = (q) -> replacePlaceholders((String) q);
  // set queryProcessorFactory here - the base class calls createQuery which needs the factory.
  this.queryProcessorFactory = new DefaultPipelineStageQueryProcessorFactory();
}
 
Example #4
Source File: AggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"Duplicates"})
@Override
protected void initializeAnnotation(Method method) throws InvalidAggregationQueryException {
  this.aggregateAnnotation = method.getAnnotation(Aggregate.class);
  Class inputType = aggregateAnnotation.inputType();
  this.collectionName = deriveCollectionName(aggregateAnnotation,
                                             (idx) -> mongoParameterAccessor.getValues()[idx].toString(),
                                             () -> {
                                               Document documentAnnotation = AnnotationUtils.findAnnotation(inputType,
                                                                                                            Document.class);
                                               return documentAnnotation != null ? documentAnnotation.collection() : null;
                                             },
                                             (s) -> {
                                               Expression expression = detectExpression(s);
                                               if (expression != null) {
                                                 return expression.getValue(context, String.class);
                                               }
                                               return s;
                                             });
  this.placeholderRepFn = (q) -> replacePlaceholders((String) q);
  // set queryProcessorFactory here - the base class calls createQuery which needs the factory.
  this.queryProcessorFactory = new DefaultPipelineStageQueryProcessorFactory();
}
 
Example #5
Source File: MongoConfiguration.java    From POC with Apache License 2.0 6 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void initIndicesAfterStartup() {

	log.info("Mongo InitIndicesAfterStartup init");
	var init = System.currentTimeMillis();

	var mappingContext = this.mongoTemplate.getConverter().getMappingContext();

	if (mappingContext instanceof MongoMappingContext) {
		var resolver = IndexResolver.create(mappingContext);
		mappingContext.getPersistentEntities().stream().filter(clazz -> clazz.isAnnotationPresent(Document.class))
				.forEach(o -> {
					IndexOperations indexOps = this.mongoTemplate.indexOps(o.getType());
					resolver.resolveIndexFor(o.getType()).forEach(indexOps::ensureIndex);
				});
	}

	log.info("Mongo InitIndicesAfterStartup took: {}", (System.currentTimeMillis() - init));
}
 
Example #6
Source File: BeihuMongoDataAutoConfiguration.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions)
		throws ClassNotFoundException {
	MongoMappingContext context = new MongoMappingContext();
	context.setInitialEntitySet(new EntityScanner(this.applicationContext)
			.scan(Document.class, Persistent.class));
	Class<?> strategyClass = this.beihuMongoProperties.getFieldNamingStrategy();
	if (strategyClass != null) {
		context.setFieldNamingStrategy(
				(FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass));
	}
	context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
	return context;
}
 
Example #7
Source File: SecondaryAdaptersComponentsTest.java    From archunit-examples with MIT License 5 votes vote down vote up
@Test
public void documentClassesShouldBeAnnotatedWithDocumentAnnotation() {
  ArchRule rule = ArchRuleDefinition.classes()
    .that().haveSimpleNameEndingWith("Document")
    .should().beAnnotatedWith(Document.class);
  rule.check(classes);
}
 
Example #8
Source File: SecondaryAdaptersComponentsTest.java    From archunit-examples with MIT License 5 votes vote down vote up
@Test
public void noClassesWithDocumentAnnotationShouldResideOutsideOfSecondaryAdaptersPackages() {
  ArchRule rule = ArchRuleDefinition.noClasses()
    .that().areAnnotatedWith(Document.class)
    .should().resideOutsideOfPackage(SECONDARY_ADAPTERS_PACKAGES);
  rule.check(classes);
}
 
Example #9
Source File: MongoMetadata.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 构造方法
 * 
 * @param metadata
 */
MongoMetadata(Class<?> clazz) {
    Document document = clazz.getAnnotation(Document.class);
    if (document == null) {
        throw new IllegalArgumentException();
    }
    ormName = document.collection();
    if (StringUtility.isBlank(ormName)) {
        ormName = clazz.getSimpleName();
        ormName = ormName.substring(0, 1).toLowerCase() + ormName.substring(1, ormName.length());
    }
    ormClass = clazz;
    ReflectionUtility.doWithFields(ormClass, (field) -> {
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            return;
        }
        if (field.isAnnotationPresent(Version.class)) {
            versionName = field.getName();
            return;
        }
        Class<?> type = field.getType();
        fields.put(field.getName(), type);
        if (field.isAnnotationPresent(Id.class)) {
            primaryName = field.getName();
            primaryClass = type;
        }
        if (field.isAnnotationPresent(Indexed.class)) {
            indexNames.add(field.getName());
        }
    });
}
 
Example #10
Source File: MongoXmlParser.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private String[] getResources(String packageName) {
    try {
        // 搜索资源
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)) + "/" + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        // 提取资源
        Set<String> names = new HashSet<String>();
        String document = Document.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (!annotationMetadata.hasAnnotation(document)) {
                continue;
            }
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            names.add(classMetadata.getClassName());
        }
        return names.toArray(new String[0]);
    } catch (IOException exception) {
        String message = "无法获取资源";
        LOGGER.error(message, exception);
        throw new StorageConfigurationException(message, exception);
    }
}
 
Example #11
Source File: MongoDBListener.java    From POC with Apache License 2.0 5 votes vote down vote up
@EventListener(ContextRefreshedEvent.class)
public void initIndicesAfterStartup() {

	MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = this.mongoTemplate
			.getConverter().getMappingContext();

	// consider only entities that are annotated with @Document
	mappingContext.getPersistentEntities().stream().filter(it -> it.isAnnotationPresent(Document.class))
			.forEach(it -> {

				IndexOperations indexOps = this.mongoTemplate.indexOps(it.getType());
				IndexResolver.create(mappingContext).resolveIndexFor(it.getType()).forEach(indexOps::ensureIndex);
			});
}
 
Example #12
Source File: ErrorLogsCounter.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private TailableCursorRequest<Log> getTailableCursorRequest() {
    MessageListener<Document, Log> listener = message -> {
      log.info("ERROR log received: {}", message.getBody());
      counter.incrementAndGet();
    };

    return TailableCursorRequest.builder()
      .collection(collectionName)
      .filter(query(where(LEVEL_FIELD_NAME).is(LogLevel.ERROR)))
      .publishTo(listener)
      .build();
}
 
Example #13
Source File: JobItem.java    From flow-platform-x with Apache License 2.0 4 votes vote down vote up
public Context(org.bson.Document source) {
    this.source = source;
}
 
Example #14
Source File: JobItem.java    From flow-platform-x with Apache License 2.0 4 votes vote down vote up
public Context(org.bson.Document source) {
    this.source = source;
}