@InSequence(10)
  @Test
  @OperateOnDeployment("dep1")
  public void insertIntoBlobstoreOnDep1() throws Exception {
    BlobstoreService service = BlobstoreServiceFactory.getBlobstoreService();

    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile("text/plain", "uploadedText.txt");
    FileWriteChannel channel = fileService.openWriteChannel(file, true);
    try {
      channel.write(ByteBuffer.wrap(TEXT.getBytes()));
    } finally {
      channel.closeFinally();
    }

    waitForSync();
    BlobKey blobKey = fileService.getBlobKey(file);
    System.out.println("Blob key: " + blobKey);
    byte[] bytes = service.fetchData(blobKey, 0, Long.MAX_VALUE);

    Assert.assertEquals(TEXT, new String(bytes));

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Entity dsBK = new Entity("blobTestId", 1);
    dsBK.setProperty("blogId", blobKey.getKeyString());
    ds.put(dsBK);
    waitForSync();
  }
 protected Key getMetadataKeyForBlobKey(BlobKey blobKey) {
   String origNamespace = NamespaceManager.get();
   NamespaceManager.set("");
   try {
     return KeyFactory.createKey(null, BlobInfoFactory.KIND, blobKey.getKeyString());
   } finally {
     NamespaceManager.set(origNamespace);
   }
 }
 public AppEngineFile getBlobFile(BlobKey blobKey) throws FileNotFoundException {
   if (blobKey == null) {
     throw new NullPointerException("blobKey is null");
   }
   Entity entity = getEntity(blobKey);
   String creationHandle = (String) entity.getProperty(BLOB_INFO_CREATION_HANDLE_PROPERTY);
   String namePart = (creationHandle == null ? blobKey.getKeyString() : creationHandle);
   AppEngineFile file = new AppEngineFile(AppEngineFile.FileSystem.BLOBSTORE, namePart);
   setCachedBlobKey(file, blobKey);
   return file;
 }
  /**
   * Exposed as `POST /api/photos`.
   *
   * <p>Takes the following payload in the request body. Payload represents a Photo that should be
   * created. { "id":0, "ownerUserId":0, "ownerDisplayName":"", "ownerProfileUrl":"",
   * "ownerProfilePhoto":"", "themeId":0, "themeDisplayName":"", "numVotes":0, "voted":false, //
   * Whether or not the current user has voted on this. "created":0, "fullsizeUrl":"",
   * "thumbnailUrl":"", "voteCtaUrl":"", // URL for Vote interactive post button.
   * "photoContentUrl":"" // URL for Google crawler to hit to get info. }
   *
   * <p>Returns the following JSON response representing the created Photo. { "id":0,
   * "ownerUserId":0, "ownerDisplayName":"", "ownerProfileUrl":"", "ownerProfilePhoto":"",
   * "themeId":0, "themeDisplayName":"", "numVotes":0, "voted":false, // Whether or not the current
   * user has voted on this. "created":0, "fullsizeUrl":"", "thumbnailUrl":"", "voteCtaUrl":"", //
   * URL for Vote interactive post button. "photoContentUrl":"" // URL for Google crawler to hit to
   * get info. }
   *
   * <p>Issues the following errors along with corresponding HTTP response codes: 400: "Bad Request"
   * if the request is missing image data. 401: "Unauthorized request" (if certain parameters are
   * present in the request) 401: "Access token expired" (there is a logged in user, but he doesn't
   * have a refresh token and his access token is expiring in less than 100 seconds, get a new token
   * and retry) 500: "Error while writing app activity: " + error from client library.
   *
   * @see javax.servlet.http.HttpServlet#doPost( javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    try {
      checkAuthorization(req);
      List<BlobKey> blobKeys = blobstoreService.getUploads(req).get("image");
      BlobKey imageKey = null;

      if (blobKeys != null) {
        imageKey = blobKeys.iterator().next();
      }

      if (imageKey == null) {
        sendError(resp, 400, "Missing image data.");
      }

      Long currentUserId = (Long) req.getSession().getAttribute(CURRENT_USER_SESSION_KEY);
      User author = ofy().load().type(User.class).id(currentUserId).get();
      GoogleCredential credential = this.getCredentialFromLoggedInUser(req);
      Photo photo = new Photo();
      photo.setOwnerUserId(author.getId());
      photo.setOwnerDisplayName(author.getGoogleDisplayName());
      photo.setOwnerProfilePhoto(author.getGooglePublicProfilePhotoUrl());
      photo.setOwnerProfileUrl(author.getGooglePublicProfileUrl());
      photo.setThemeId(Theme.getCurrentTheme().getId());
      photo.setThemeDisplayName(Theme.getCurrentTheme().getDisplayName());
      photo.setCreated(Calendar.getInstance().getTime());
      photo.setNumVotes(0);
      photo.setImageBlobKey(imageKey.getKeyString());
      ofy().save().entity(photo).now();
      ofy().clear();
      photo = ofy().load().type(Photo.class).id(photo.getId()).get();
      addPhotoToGooglePlusHistory(author, photo, credential);
      sendResponse(req, resp, photo);
    } catch (UserNotAuthorizedException e) {
      sendError(resp, 401, "Unauthorized request");
    } catch (MomentWritingException e) {
      sendError(resp, 500, "Error while writing app activity: " + e.getMessage());
    } catch (GoogleTokenExpirationException e) {
      sendError(resp, 401, "Access token expired");
    }
  }
示例#5
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
    Map<String, List<BlobKey>> blobs = bs.getUploads(req);
    List<BlobKey> imageBlobs = blobs.get("source");

    JsonObject retObj = new JsonObject();

    if (imageBlobs.size() > 0) {
      BlobKey image = imageBlobs.get(0);
      retObj.addProperty("result", "success");
      retObj.addProperty("blobKey", image.getKeyString());
    }

    if (retObj.get("result") == null) {
      retObj.addProperty("result", "fail");
    }

    resp.getWriter().write(retObj.toString());
  }
  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
      return false;
    }
    BlobstoreRecordKey that = (BlobstoreRecordKey) obj;

    return offset == that.offset && blobKey.equals(that.blobKey);
  }
  private void updateImage(StoredImage image, String imageCsObjectName, BlobKey blobKey) {
    String oldObjectName = image.getCloudStorageObjectName();

    boolean deleted = deleteImage(oldObjectName);
    if (!deleted) {
      log.warning("Failed to delete: " + oldObjectName);
    }

    image.setCloudStorageObjectName(imageCsObjectName);
    image.setBlobKey(blobKey.getKeyString());
    backend().save().entity(image).now();
  }
  private void addImage(ImageRef ref, String imageCsObjectName, BlobKey blobKey) {
    Optional<StoredReport> report = reportStore.tryLoadReport(ref.getOwnerId(), ref.getReportId());
    Preconditions.checkArgument(report.isPresent(), "Report not found: " + ref.toString());

    StoredImage image =
        StoredImage.builder()
            .setKey(StoredImage.toKey(ref))
            .setReport(Ref.create(report.get()))
            .setImageFileName(ref.getImageName())
            .setCloudStorageObjectName(imageCsObjectName)
            .setBlobKey(blobKey.getKeyString())
            .build();
    backend().save().entity(image).now();
  }
 public InputStream getStream(BlobKey blobKey) throws FileNotFoundException {
   GridFilesystem gfs = getGridFilesystem();
   return gfs.getInput(blobKey.getKeyString());
 }
示例#10
0
 public void delete(BlobKey... blobKeys) {
   GridFilesystem gfs = getGridFilesystem();
   for (BlobKey key : blobKeys) gfs.remove(key.getKeyString(), true);
 }