Example #1
0
  @Override
  public void reset() {
    super.reset();
    try {
      String ritePropertiesFilename = Rite.getInstance().getProperty(Rite.PropertyKeys.HOST);
      Properties hostProps = new Properties();
      hostProps.load(new FileInputStream(ritePropertiesFilename));
      String hostname = hostProps.getProperty("hostname");
      int port = Integer.parseInt(hostProps.getProperty("port"));
      String dbname = hostProps.getProperty("dbname");
      boolean auth = Boolean.parseBoolean(hostProps.getProperty("auth"));
      Mongo mongo = new Mongo(hostname, port);
      DB db = mongo.getDB(dbname);
      if (auth) {
        String user = hostProps.getProperty("user");
        String pass = hostProps.getProperty("pass");
        db.authenticate(user, pass.toCharArray());
      }

      GridFS gfs = new GridFS(db);
      String filename = getFileName();
      File f = new File(filename);
      f.delete();
      gfs.remove(filename);
      mongo.close();
    } catch (Exception e) {
      this.fail();
      this.complete();
    }
  }
 @Override
 public void saveAvatar(String userName, InputStream originalIs) throws AvatarUploadException {
   ByteArrayOutputStream os = null;
   InputStream is = null;
   try {
     BufferedImage originalImage = ImageIO.read(originalIs);
     BufferedImage thumbnail =
         Thumbnails.of(originalImage).crop(Positions.CENTER).size(128, 128).asBufferedImage();
     os = new ByteArrayOutputStream();
     ImageIO.write(thumbnail, "png", os);
     is = new ByteArrayInputStream(os.toByteArray());
     String fileName = String.format(AVATAR_NAME, userName);
     GridFS avatarFS = new GridFS(m_template.getDb());
     avatarFS.remove(fileName);
     GridFSInputFile gfsFile = avatarFS.createFile(is);
     gfsFile.setFilename(fileName);
     gfsFile.save();
   } catch (Exception ex) {
     throw new AvatarUploadException(ex);
   } finally {
     IOUtils.closeQuietly(originalIs);
     IOUtils.closeQuietly(is);
     IOUtils.closeQuietly(os);
   }
 }
  @Test
  public void testImportAttachment() throws Exception {
    logger.debug("*** testImportAttachment ***");
    byte[] content =
        copyToBytesFromClasspath(
            "/test/elasticsearch/plugin/river/mongodb/gridfs/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");
    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));

    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("Aliquam"))
            .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();

    countResponse =
        getNode().client().count(countRequest(getIndex()).query(fieldQuery("_id", id))).actionGet();
    logger.debug("Count after delete request: {}", countResponse.getCount());
    assertThat(countResponse.getCount(), equalTo(0L));
  }
  /**
   * Update the GridFSDBFile in the associated DB with the key/values in updateKeys
   *
   * @param updateKeys Map of new tag data
   * @param file GridFSDBFile to update with tag data
   * @param db
   * @param songId ID of Song to update with tag data
   * @return
   */
  public static boolean updateFile(
      Map<String, String> updateKeys,
      GridFSDBFile file,
      DB db,
      ObjectId songId) { // TODO updateKeys?
    File audioFile = null;
    try {
      audioFile = File.createTempFile("tmp", ".mp3");
    } catch (IOException e) {
      log.error("tmp file not created", e);
    }

    audioFile.deleteOnExit();
    AudioFile f = null;
    ObjectId id = (ObjectId) file.getId();
    ObjectId oid = null;
    try {
      file.writeTo(audioFile);
      f = AudioFileIO.read(audioFile);
      Tag tag = f.getTagOrCreateAndSetDefault();
      DBObject q = new BasicDBObject("_id", songId);
      DBObject o = new BasicDBObject("$set", new BasicDBObject(updateKeys));

      if (updateKeys.get("artist") != null) {
        tag.setField(FieldKey.ARTIST, updateKeys.get("artist"));
      }
      if (updateKeys.get("album") != null) {
        tag.setField(FieldKey.ALBUM, updateKeys.get("album"));
      }
      if (updateKeys.get("title") != null) {
        tag.setField(FieldKey.TITLE, updateKeys.get("title"));
      }
      if (updateKeys.get("track") != null) {
        tag.setField(FieldKey.TRACK, updateKeys.get("track"));
      }
      if (updateKeys.get("year") != null) {
        tag.setField(FieldKey.YEAR, updateKeys.get("year"));
      }
      AudioFileIO.write(f);
      GridFS myFS = new GridFS(db);
      myFS.remove(id);
      GridFSInputFile inputFile =
          putSongFileInDB(f.getFile(), db, file.getContentType(), file.getFilename(), id);
      oid = (ObjectId) inputFile.getId();
      if (oid.equals(id)) {
        db.getCollection("songs").update(q, o);
      }
    } catch (KeyNotFoundException knfe) {
      log.error("key not found", knfe);
    } catch (FieldDataInvalidException fdie) {
      log.error("tried to set field with invalid value", fdie);
    } catch (Exception e) {
      log.error("error reading/writing file", e);
    }
    return (oid.equals(id));
  }
 @Override
 public void removeBlob(MD5 md5) throws BlobStoreCommunicationException {
   final DBObject query = new BasicDBObject();
   query.put(Fields.MONGO_ID, md5.getMD5());
   try {
     gfs.remove(query);
   } catch (MongoException me) {
     throw new BlobStoreCommunicationException("Could not write to the mongo database", me);
   }
 }
Example #6
0
  public void deleteDocument(String GUID) throws DocumentException {

    try {
      GridFS gridFS = new GridFS(dataBase);

      ObjectId key = new ObjectId(GUID);
      gridFS.remove(key);
      CommandResult result = dataBase.getLastError();
      if (!result.ok()) {
        throw new DocumentException(result.getErrorMessage());
      }
    } catch (Exception e) {
      log.error("deleteDocument error:" + e.getMessage());
      e.printStackTrace();
      throw new DocumentException(e.getMessage());
    }
  }
 @Override
 public void deleteFileByFileName(String filePath, String fileName) {
   GridFS gridFS = new GridFS(db, filePath);
   gridFS.remove(fileName);
 }
 @Override
 public void deleteFileByObjectId(String filePath, String objectId) {
   GridFS gridFS = new GridFS(db, filePath);
   gridFS.remove(new ObjectId(objectId));
 }
  @Test
  public void testImportAttachment() throws Exception {
    logger.debug("*** testImportAttachment ***");
    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");
      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("Aliquam"))
              .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("testImportAttachment failed.", t);
      Assert.fail("testImportAttachment failed", t);
    } finally {
      // cleanUp();
    }
  }
Example #10
0
 /**
  * removes all files matching the given filename
  *
  * @param filename
  * @throws MongoException
  */
 public void remove(String filename) {
   if (filename == null) {
     throw new IllegalArgumentException("filename can not be null");
   }
   remove(new BasicDBObject("filename", filename));
 }
 @Override
 public void deleteAvatar(String userName) {
   GridFS avatarFS = new GridFS(m_template.getDb());
   avatarFS.remove(String.format(AVATAR_NAME, userName));
 }