Example #1
0
  public String newDocument(InputStream in, String json) throws DocumentException {

    try {
      GridFS gridFS = new GridFS(dataBase);

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

      DBObject dbObject = (DBObject) JSON.parse(json);

      gridFSInputFile.setFilename((String) dbObject.get(NAME));
      gridFSInputFile.setContentType((String) dbObject.get(CONTENT_TYPE));
      gridFSInputFile.setMetaData(dbObject);
      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());
    }
  }
Example #2
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());
    }
  }
Example #3
0
  public Photo saveImg(FileItem item) throws Exception {
    Photo photo = new Photo();
    String filename = item.getName();
    if (filename == null || filename.length() == 0) {
      log.error("img name illegal");
      return null;
    }
    int index = filename.lastIndexOf(".");
    String type = filename.substring(index + 1);
    if (!ImgTools.checkImgFormatValidata(type)) {
      log.error("img type illegal");
      return null;
    }
    ObjectId id = ObjectIdGenerator.generate();
    // filename = new ObjectId() + filename.substring(index);
    photo.setId(id.toString());
    photo.setType(type);

    GridFS mphoto = new GridFS(MongoDBPool.getInstance().getDB(), collection);
    GridFSInputFile in = null;
    in = mphoto.createFile(item.getInputStream());
    in.setId(id);
    in.setFilename(id.toString());
    in.setContentType(type);
    in.save();
    item.getInputStream().close();
    return photo;
  }
  @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));
  }
  /**
   * @param args
   * @throws UnknownHostException
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("test");
    String newFileName = "mkyong-java-image5";
    File imageFile = new File("c:\\mongodb.jpg");
    GridFS gfsPhoto = new GridFS(db);
    GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
    gfsFile.setFilename(newFileName);
    gfsFile.setContentType("image/jpeg");
    gfsFile.save();
    /// System.out.println(gfsFile.getId());

    gfsFile = gfsPhoto.createFile(imageFile);
    gfsFile.setFilename(newFileName);
    gfsFile.setContentType("image/jpeg");
    gfsFile.save();
    System.out.println(gfsFile.getId());

    /*  RegistryKey rg = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(suffix);
    object obj=rg.GetValue("Content Type");
    result =obj!=null?obj.ToString():string.Empty;
    rg.Close(); */
  }
  /**
   * @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;
  }
  public FileEntity saveFile(
      String filePath,
      String fileName,
      String contentType,
      InputStream inputStream,
      String objectId) {

    if (filePath == null) filePath = "fs";
    GridFS gridFS = new GridFS(db, filePath);
    GridFSInputFile gfsFile = gridFS.createFile(inputStream);
    gfsFile.setFilename(fileName);
    gfsFile.setContentType(contentType);
    if (objectId != null) gfsFile.setId(new ObjectId(objectId));
    // String objectId = gfsFile.getId().toString();
    gfsFile.save();

    GridFSDBFile dbFile = gridFS.findOne(new ObjectId(gfsFile.getId().toString()));

    FileEntity entity = new FileEntity(dbFile);

    return entity;
  }
 public void setContentType(String contentType) {
   input.setContentType(contentType);
 }
  @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();
    }
  }