Exemplo n.º 1
0
  @Override
  public List<T> asList(final FindOptions options) {
    final List<T> results = new ArrayList<T>();
    final MorphiaIterator<T, T> iter = fetch(options);
    try {
      for (final T ent : iter) {
        results.add(ent);
      }
    } finally {
      iter.close();
    }

    if (LOG.isTraceEnabled()) {
      LOG.trace(
          format(
              "asList: %s \t %d entities, iterator time: driver %d ms, mapper %d ms %n\t cache: %s %n\t for %s",
              dbColl.getName(),
              results.size(),
              iter.getDriverTime(),
              iter.getMapperTime(),
              cache.stats(),
              getQueryObject()));
    }

    return results;
  }
Exemplo n.º 2
0
  @Override
  public MorphiaIterator<T, T> fetch(final FindOptions options) {
    final DBCursor cursor = prepareCursor(options);
    if (LOG.isTraceEnabled()) {
      LOG.trace("Getting cursor(" + dbColl.getName() + ")  for query:" + cursor.getQuery());
    }

    return new MorphiaIterator<T, T>(ds, cursor, ds.getMapper(), clazz, dbColl.getName(), cache);
  }
Exemplo n.º 3
0
 @Override
 @Deprecated
 public long countAll() {
   final DBObject query = getQueryObject();
   if (LOG.isTraceEnabled()) {
     LOG.trace("Executing count(" + dbColl.getName() + ") for query: " + query);
   }
   return dbColl.getCount(query);
 }
Exemplo n.º 4
0
  @SuppressWarnings("deprecation")
  com.mongodb.client.model.IndexOptions convert(
      final IndexOptions options, final boolean background) {
    if (options.dropDups()) {
      LOG.warning(
          "dropDups value is no longer supported by the server.  Please set this value to false and "
              + "validate your system behaves as expected.");
    }
    com.mongodb.client.model.IndexOptions indexOptions =
        new com.mongodb.client.model.IndexOptions()
            .background(options.background() || background)
            .sparse(options.sparse())
            .unique(options.unique());

    if (!options.language().equals("")) {
      indexOptions.defaultLanguage(options.language());
    }
    if (!options.languageOverride().equals("")) {
      indexOptions.languageOverride(options.languageOverride());
    }
    if (!options.name().equals("")) {
      indexOptions.name(options.name());
    }
    if (options.expireAfterSeconds() != -1) {
      indexOptions.expireAfter((long) options.expireAfterSeconds(), TimeUnit.SECONDS);
    }
    if (!options.partialFilter().equals("")) {
      indexOptions.partialFilterExpression(Document.parse(options.partialFilter()));
    }
    if (!options.collation().locale().equals("")) {
      indexOptions.collation(convert(options.collation()));
    }

    return indexOptions;
  }
Exemplo n.º 5
0
  private List<Index> collectTopLevelIndexes(final MappedClass mc) {
    List<Index> list = new ArrayList<Index>();
    final List<Indexes> annotations = mc.getAnnotations(Indexes.class);
    if (annotations != null) {
      for (final Indexes indexes : annotations) {
        for (final Index index : indexes.value()) {
          Index updated = index;
          if (index.fields().length == 0) {
            LOG.warning(
                format(
                    "This index on '%s' is using deprecated configuration options.  Please update to use the "
                        + "fields value on @Index: %s",
                    mc.getClazz().getName(), index.toString()));
            updated = new IndexBuilder().migrate(index);
          }
          List<Field> fields = new ArrayList<Field>();
          for (Field field : updated.fields()) {
            fields.add(
                new FieldBuilder()
                    .value(findField(mc, index.options(), asList(field.value().split("\\."))))
                    .type(field.type())
                    .weight(field.weight()));
          }

          list.add(replaceFields(updated, fields));
        }
      }
    }
    return list;
  }
Exemplo n.º 6
0
  @Override
  public MorphiaIterator<U, U> aggregate(
      final String collectionName,
      final Class<U> target,
      final AggregationOptions options,
      final ReadPreference readPreference) {
    LOG.debug("stages = " + stages);

    Cursor cursor = collection.aggregate(stages, options, readPreference);
    return new MorphiaIterator<U, U>(
        cursor, mapper, target, collection.getName(), mapper.createEntityCache());
  }
Exemplo n.º 7
0
  private DBCursor prepareCursor(final FindOptions findOptions) {
    final DBObject query = getQueryObject();

    if (LOG.isTraceEnabled()) {
      LOG.trace(
          String.format(
              "Running query(%s) : %s, options: %s,", dbColl.getName(), query, findOptions));
    }

    if (findOptions.isSnapshot()
        && (findOptions.getSortDBObject() != null || findOptions.hasHint())) {
      LOG.warning("Snapshotted query should not have hint/sort.");
    }

    if (findOptions.getCursorType() != NonTailable && (findOptions.getSortDBObject() != null)) {
      LOG.warning("Sorting on tail is not allowed.");
    }

    return dbColl
        .find(
            query,
            findOptions.getOptions().copy().sort(getSortObject()).projection(getFieldsObject()))
        .setDecoderFactory(ds.getDecoderFact());
  }
Exemplo n.º 8
0
  @SuppressWarnings("deprecation")
  Index convert(final Indexed indexed, final String nameToStore) {
    if (indexed.dropDups() || indexed.options().dropDups()) {
      LOG.warning(
          "dropDups value is no longer supported by the server.  Please set this value to false and "
              + "validate your system behaves as expected.");
    }
    final Map<String, Object> newOptions = extractOptions(indexed.options());
    if (!extractOptions(indexed).isEmpty() && !newOptions.isEmpty()) {
      throw new MappingException(
          "Mixed usage of deprecated @Indexed values with the new @IndexOption values is not "
              + "allowed.  Please migrate all settings to @IndexOptions");
    }

    List<Field> fields =
        Collections.<Field>singletonList(
            new FieldBuilder().value(nameToStore).type(fromValue(indexed.value().toIndexValue())));
    return newOptions.isEmpty()
        ? new IndexBuilder().options(new IndexOptionsBuilder().migrate(indexed)).fields(fields)
        : new IndexBuilder().options(indexed.options()).fields(fields);
  }
Exemplo n.º 9
0
 BsonDocument calculateKeys(final MappedClass mc, final Index index) {
   BsonDocument keys = new BsonDocument();
   for (Field field : index.fields()) {
     String path;
     try {
       path =
           findField(
               mc, index.options(), new ArrayList<String>(asList(field.value().split("\\."))));
     } catch (Exception e) {
       path = field.value();
       String message =
           format(
               "The path '%s' can not be validated against '%s' and may represent an invalid index",
               path, mc.getClazz().getName());
       if (!index.options().disableValidation()) {
         throw new MappingException(message);
       }
       LOG.warning(message);
     }
     keys.putAll(toBsonDocument(path, field.type().toIndexValue()));
   }
   return keys;
 }
Exemplo n.º 10
0
  /** Validate the path, and value type, returning the mapped field for the field at the path */
  static MappedField validateQuery(
      final Class clazz,
      final Mapper mapper,
      final StringBuilder origProp,
      final FilterOperator op,
      final Object val,
      final boolean validateNames,
      final boolean validateTypes) {
    // TODO: cache validations (in static?).

    MappedField mf = null;
    final String prop = origProp.toString();
    boolean hasTranslations = false;

    if (validateNames) {
      final String[] parts = prop.split("\\.");
      if (clazz == null) {
        return null;
      }

      MappedClass mc = mapper.getMappedClass(clazz);
      // CHECKSTYLE:OFF
      for (int i = 0; ; ) {
        // CHECKSTYLE:ON
        final String part = parts[i];
        boolean fieldIsArrayOperator = part.equals("$");

        mf = mc.getMappedField(part);

        // translate from java field name to stored field name
        if (mf == null && !fieldIsArrayOperator) {
          mf = mc.getMappedFieldByJavaField(part);
          if (mf == null) {
            throw new ValidationException(
                format(
                    "The field '%s' could not be found in '%s' while validating - %s; if "
                        + "you wish to continue please disable validation.",
                    part, clazz.getName(), prop));
          }
          hasTranslations = true;
          parts[i] = mf.getNameToStore();
        }

        i++;
        if (mf != null && mf.isMap()) {
          // skip the map key validation, and move to the next part
          i++;
        }

        if (i >= parts.length) {
          break;
        }

        if (!fieldIsArrayOperator) {
          // catch people trying to search/update into @Reference/@Serialized fields
          if (!canQueryPast(mf)) {
            throw new ValidationException(
                format(
                    "Can not use dot-notation past '%s' could not be found in '%s' while"
                        + " validating - %s",
                    part, clazz.getName(), prop));
          }

          // get the next MappedClass for the next field validation
          mc = mapper.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubClass());
        }
      }

      // record new property string if there has been a translation to any part
      if (hasTranslations) {
        origProp.setLength(0); // clear existing content
        origProp.append(parts[0]);
        for (int i = 1; i < parts.length; i++) {
          origProp.append('.');
          origProp.append(parts[i]);
        }
      }

      if (validateTypes && mf != null) {
        List<ValidationFailure> typeValidationFailures = new ArrayList<ValidationFailure>();
        boolean compatibleForType =
            isCompatibleForOperator(mc, mf, mf.getType(), op, val, typeValidationFailures);
        List<ValidationFailure> subclassValidationFailures = new ArrayList<ValidationFailure>();
        boolean compatibleForSubclass =
            isCompatibleForOperator(mc, mf, mf.getSubClass(), op, val, subclassValidationFailures);

        if ((mf.isSingleValue() && !compatibleForType)
            || mf.isMultipleValues() && !(compatibleForSubclass || compatibleForType)) {

          if (LOG.isWarningEnabled()) {
            LOG.warning(
                format(
                    "The type(s) for the query/update may be inconsistent; using an instance of type '%s' "
                        + "for the field '%s.%s' which is declared as '%s'",
                    val.getClass().getName(),
                    mf.getDeclaringClass().getName(),
                    mf.getJavaFieldName(),
                    mf.getType().getName()));
            typeValidationFailures.addAll(subclassValidationFailures);
            LOG.warning("Validation warnings: \n" + typeValidationFailures);
          }
        }
      }
    }
    return mf;
  }