Exemple #1
0
  public String newDocument(InputStream in, Map<String, String> properties)
      throws DocumentException {

    try {
      GridFS gridFS = new GridFS(dataBase);

      GridFSInputFile gridFSInputFile = gridFS.createFile(in);
      ObjectId id = (ObjectId) gridFSInputFile.getId();
      String GUID = id.toStringMongod();

      gridFSInputFile.setFilename(properties.get(DocumentConnector.NAME));
      gridFSInputFile.setContentType(properties.get(DocumentConnector.CONTENT_TYPE));
      gridFSInputFile.put(DocumentConnector.ID, properties.get(DocumentConnector.ID));
      gridFSInputFile.put(
          DocumentConnector.DOCUMENT_TYPE, properties.get(DocumentConnector.DOCUMENT_TYPE));
      gridFSInputFile.save();
      CommandResult result = dataBase.getLastError();
      if (!result.ok()) {
        throw new DocumentException(result.getErrorMessage());
      }

      return GUID;
    } catch (Exception e) {
      log.error("newDocument error:" + e.getMessage());
      e.printStackTrace();
      throw new DocumentException(e.getMessage());
    }
  }
 protected GridFSInputFile create(Type type, boolean createEmptyFile) {
   Assert.notNull(type, "Type must not be null");
   GridFSInputFile file = this.fs.createFile(getFilename(getPath()));
   JailedResourcePath parent = this.path.getParent();
   if (parent != null) {
     file.put(PARENT, parent.getUnjailedPath().toString());
   }
   file.put(RESOURCE_TYPE, type.name());
   if (createEmptyFile) {
     try {
       file.getOutputStream().close();
     } catch (IOException e) {
       throw new ResourceException(e);
     }
   }
   return file;
 }
  /**
   * @param file
   * @param db
   * @param contentType
   * @param filename
   * @param id
   * @return
   */
  private static GridFSInputFile putSongFileInDB(
      File file, DB db, String contentType, String filename, Object id) {
    byte[] songAsBytes = null;
    GridFS myFS = new GridFS(db);
    GridFSInputFile gridFSInputFile = null;
    try {
      songAsBytes = FileUtils.readFileToByteArray(file);
      gridFSInputFile = myFS.createFile(songAsBytes);
      gridFSInputFile.setFilename(filename);
      gridFSInputFile.setContentType(contentType);
      if (id != null) {
        gridFSInputFile.put("_id", id);
      }

      gridFSInputFile.save(); // insert file
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return gridFSInputFile;
  }
 @Override
 public void saveBlob(final MD5 md5, final InputStream data, final boolean sorted)
     throws BlobStoreCommunicationException {
   if (data == null || md5 == null) {
     throw new NullPointerException("Arguments cannot be null");
   }
   if (getFile(md5) != null) {
     return; // already exists
   }
   final GridFSInputFile gif = gfs.createFile(data, true);
   gif.setId(md5.getMD5());
   gif.setFilename(md5.getMD5());
   gif.put(Fields.GFS_SORTED, sorted);
   try {
     gif.save();
   } catch (DuplicateKeyException dk) {
     // already here, done
   } catch (MongoException me) {
     throw new BlobStoreCommunicationException("Could not write to the mongo database", me);
   }
 }
  /*
   * Example for issue #100
   */
  @Test
  public void testImportAttachmentWithCustomMetadata() throws Exception {
    logger.debug("*** testImportAttachmentWithCustomMetadata ***");
    try {
      // createDatabase();
      byte[] content = copyToBytesFromClasspath(TEST_ATTACHMENT_HTML);
      logger.debug("Content in bytes: {}", content.length);
      GridFS gridFS = new GridFS(mongoDB);
      GridFSInputFile in = gridFS.createFile(content);
      in.setFilename("test-attachment.html");
      in.setContentType("text/html");
      BasicDBObject metadata = new BasicDBObject();
      metadata.put("attribut1", "value1");
      metadata.put("attribut2", "value2");
      in.put("metadata", metadata);
      in.save();
      in.validate();

      String id = in.getId().toString();
      logger.debug("GridFS in: {}", in);
      logger.debug("Document created with id: {}", id);

      GridFSDBFile out = gridFS.findOne(in.getFilename());
      logger.debug("GridFS from findOne: {}", out);
      out = gridFS.findOne(new ObjectId(id));
      logger.debug("GridFS from findOne: {}", out);
      Assert.assertEquals(out.getId(), in.getId());

      Thread.sleep(wait);
      refreshIndex();

      CountResponse countResponse = getNode().client().count(countRequest(getIndex())).actionGet();
      logger.debug("Index total count: {}", countResponse.getCount());
      assertThat(countResponse.getCount(), equalTo(1l));

      GetResponse getResponse = getNode().client().get(getRequest(getIndex()).id(id)).get();
      logger.debug("Get request for id {}: {}", id, getResponse.isExists());
      assertThat(getResponse.isExists(), equalTo(true));
      //            countResponse =
      // getNode().client().count(countRequest(getIndex()).query(fieldQuery("_id",
      // id))).actionGet();
      //            logger.debug("Index count for id {}: {}", id, countResponse.getCount());
      //            assertThat(countResponse.getCount(), equalTo(1l));

      SearchResponse response =
          getNode()
              .client()
              .prepareSearch(getIndex())
              .setQuery(QueryBuilders.queryString("metadata.attribut1:value1"))
              .execute()
              .actionGet();
      logger.debug("SearchResponse {}", response.toString());
      long totalHits = response.getHits().getTotalHits();
      logger.debug("TotalHits: {}", totalHits);
      assertThat(totalHits, equalTo(1l));

      gridFS.remove(new ObjectId(id));

      Thread.sleep(wait);
      refreshIndex();

      getResponse = getNode().client().get(getRequest(getIndex()).id(id)).get();
      logger.debug("Get request for id {}: {}", id, getResponse.isExists());
      assertThat(getResponse.isExists(), equalTo(false));
      //            countResponse =
      // getNode().client().count(countRequest(getIndex()).query(fieldQuery("_id",
      // id))).actionGet();
      //            logger.debug("Count after delete request: {}", countResponse.getCount());
      //            assertThat(countResponse.getCount(), equalTo(0L));
    } catch (Throwable t) {
      logger.error("testImportAttachmentWithCustomMetadata failed.", t);
      Assert.fail("testImportAttachmentWithCustomMetadata failed", t);
    } finally {
      // cleanUp();
    }
  }