private boolean persistNoteImage(String contentType, byte[] bytes, String noteKey) {
    Store.Api api = store.getApi();

    User user = UserServiceFactory.getUserService().getCurrentUser();
    // NoteImage image = new NoteImage(bytes, contentType, user.getEmail(), new Date(), new Date());

    try {
      Author me = api.getOrCreateNewAuthor(user);

      Transaction tx = api.begin();
      Note note = api.getNote(KeyFactory.stringToKey(noteKey));
      if (!note.getAuthorEmail().equalsIgnoreCase(me.getEmail())) {
        return false;
      }

      Transform resize = ImagesServiceFactory.makeResize(400, 400);
      ImagesService imagesService = ImagesServiceFactory.getImagesService();
      Image oldImage = ImagesServiceFactory.makeImage(bytes);
      Image newImage = imagesService.applyTransform(resize, oldImage, OutputEncoding.JPEG);
      note.setImageData(new Blob(newImage.getImageData()));

      note.setContentType(contentType);
      api.saveNote(note);
      tx.commit();

      log.debug("Persisted image with for note: " + note.getKey());

    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      return false;
    } finally {
      api.close();
    }
    return true;
  }
示例#2
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String source = req.getParameter("source");
    ImagesService imagesService = ImagesServiceFactory.getImagesService();

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    List<Filter> filters = new ArrayList<Filter>();
    Query query = new Query(GAEFeedRepository.FEED_ITEM_KIND);
    filters.add(new Query.FilterPredicate("source", FilterOperator.EQUAL, source));
    filters.add(new Query.FilterPredicate("img1A", FilterOperator.EQUAL, 1));
    filters.add(new Query.FilterPredicate("img2A", FilterOperator.EQUAL, 1));

    query.setFilter(CompositeFilterOperator.and(filters));

    query.addSort("publishedDate", SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(query);
    int pageSize = 30;

    resp.setContentType("text/html");
    resp.getWriter().println(" <ul>");

    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
    String startCursor = req.getParameter("cursor");

    // If this servlet is passed a cursor parameter, let's use it
    if (startCursor != null) {
      fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
    }

    QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
    for (Entity entity : results) {
      resp.getWriter()
          .println(
              "<li>"
                  + entity.getProperty("imageLink")
                  + " / "
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + " / <img height=40 width=40 src=\""
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + "\" />");
    }

    resp.getWriter().println("</li>  </entity></ul>  ");

    String cursor = results.getCursor().toWebSafeString();

    // Assuming this servlet lives at '/people'
    resp.getWriter()
        .println(
            "<a href=\"/p8admin/ListFeedItems?cursor="
                + cursor
                + "&source="
                + source
                + "\">Next page</a>");
  }
示例#3
0
 public byte[] process(byte[] data, ImageFormat format, ContentType type, float balance) {
   Image image = ImagesServiceFactory.makeImage(data);
   CompositeTransform tx = ImagesServiceFactory.makeCompositeTransform();
   if (format.isCrop()) {
     float w1 = image.getWidth();
     float h1 = image.getHeight();
     float w2 = format.getWidth();
     float h2 = format.getHeight();
     Crop c = new Crop(w1, h1, w2, h2, balance);
     tx.concatenate(ImagesServiceFactory.makeCrop(c.x, c.y, c.x + c.width, c.y + c.height));
   }
   tx.concatenate(ImagesServiceFactory.makeResize(format.getWidth(), format.getHeight()));
   try {
     ImagesService imagesService = ImagesServiceFactory.getImagesService();
     OutputEncoding outputEncoding = OutputEncoding.valueOf(type.name());
     return imagesService.applyTransform(tx, image, outputEncoding).getImageData();
   } catch (OverQuotaException e) {
     throw new ImageServiceException(e);
   }
 }
 @Test
 public void testResize() throws IOException {
   for (String sfile : FNAMES) {
     for (int[] exptSize : NEW_SIZES) {
       Transform transform = ImagesServiceFactory.makeResize(exptSize[0], exptSize[1]);
       for (OutputEncoding encoding : ENCODES) {
         Image image = imagesService.applyTransform(transform, readImage(sfile), encoding);
         assertTrue((exptSize[0] == image.getWidth()) || (exptSize[1] == image.getHeight()));
       }
     }
   }
 }
 @Test
 public void testFeelLucky() throws IOException {
   // I'm Feeling Lucky is not available in dev_appserver
   if (isRuntimeProduction()) {
     Transform transform = ImagesServiceFactory.makeImFeelingLucky();
     for (String sfile : FNAMES) {
       for (OutputEncoding encoding : ENCODES) {
         applyAndVerify(sfile, transform, ChkType.NORMAL, encoding);
       }
     }
   }
 }
 @Test
 public void testVerticalFlip() throws IOException {
   ChkType chkType = ChkType.NORMAL;
   //        TODO -- fix this for GAE!?
   //        if (isRuntimeProduction()) {
   //            chkType = ChkType.HMINUS;
   //        }
   Transform transform = ImagesServiceFactory.makeVerticalFlip();
   for (String sfile : FNAMES) {
     for (OutputEncoding encoding : ENCODES) {
       applyAndVerify(sfile, transform, chkType, encoding);
     }
   }
 }
 @Test
 public void testChop() throws IOException {
   ChkType chkType = ChkType.CROP;
   String cropLeftX = "0.0";
   String cropTopY = "0.0";
   String cropRightX = "0.5";
   String cropBottomY = "0.5";
   Transform transform =
       ImagesServiceFactory.makeCrop(
           new Float(cropLeftX),
           new Float(cropTopY),
           new Float(cropRightX),
           new Float(cropBottomY));
   for (OutputEncoding encoding : ENCODES) {
     applyAndVerify("pngAttach.png", transform, chkType, encoding);
   }
 }
 @Test
 public void testRotate() throws IOException {
   ChkType chkType;
   for (int dg : DEGREES) {
     Transform transform = ImagesServiceFactory.makeRotate(dg);
     if ((dg == 90) || (dg == 270)) {
       chkType = ChkType.ROTATE;
     } else {
       chkType = ChkType.NORMAL;
     }
     for (String sfile : FNAMES) {
       for (OutputEncoding encoding : ENCODES) {
         applyAndVerify(sfile, transform, chkType, encoding);
       }
     }
   }
 }
示例#9
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (DEBUG) System.out.println("an ajax call was made!");

    boolean namesAdded = false;
    StringBuilder sb = new StringBuilder();
    int maxResults = 10;
    double maxDistance = 0.0; // meters // using 0 will return all distances up to max # of results

    double lat = 0.0;
    double lng = 0.0;

    String callType = req.getParameter("callType");
    String cuisine = req.getParameter("cuisineID");
    String category = req.getParameter("categoryID");
    String price = req.getParameter("priceID");
    String lifestyle = req.getParameter("lifestyleID");
    String distanceS = req.getParameter("distance");
    String pageNumS = req.getParameter("page");

    // lat = Double.parseDouble(req.getParameter("lat"));
    // lng = Double.parseDouble(req.getParameter("lng"));
    String distString = req.getParameter("distance");
    if (null != distString && distString.length() > 0) maxDistance = Integer.parseInt(distString);
    maxResults = Integer.parseInt(req.getParameter("maxResults"));
    Point userLoc = TDUserService.getUserLocation(req);
    // TDPoint tdpoint=TDUserService.getUserLocation(req);
    lat = userLoc.getLat();
    lng = userLoc.getLon();

    long priceID = 0;
    long categoryID = 0;
    long lifestyleID = 0;
    long cuisineID = 0;
    int pageNum = 0;

    try {
      priceID = Long.parseLong(price);

      if (DEBUG) System.out.println("price found: " + priceID);
    } catch (NumberFormatException e) {
      // not a long
      // e.printStackTrace();
    }
    try {
      cuisineID = Long.parseLong(cuisine);

      if (DEBUG) System.out.println("cuisine found: " + cuisineID);
    } catch (NumberFormatException e) {
      // not a long
      // e.printStackTrace();
    }
    try {
      categoryID = Long.parseLong(category);

      if (DEBUG) System.out.println("category found: " + categoryID);
    } catch (NumberFormatException e) {
      // not a long
      // e.printStackTrace();
    }
    try {
      maxDistance = Double.parseDouble(distanceS);

      if (DEBUG) System.out.println("distance found: " + maxDistance);
    } catch (NumberFormatException e) {
      // not a long
      // e.printStackTrace();
    }
    try {
      lifestyleID = Long.parseLong(lifestyle);

      if (DEBUG) System.out.println("lifestyle found: " + lifestyleID);
    } catch (NumberFormatException e) {
      // not a long
      // e.printStackTrace();
    }
    try {
      pageNum = Integer.parseInt(pageNumS);

      if (DEBUG) System.out.println("page number found: " + pageNum);
    } catch (NumberFormatException e) {
      // not a long
      // e.printStackTrace();
    }

    // compute distance from miles to meters
    maxDistance *= 1609.334;

    Tag categoryTag = null;
    Tag priceTag = null;
    Tag lifestyleTag = null;
    Tag cuisineTag = null;
    ArrayList<Key> tagKeysToFilter = new ArrayList<Key>();

    if (category != null && !category.equals("")) {
      categoryTag = (Tag) PMF.get().getPersistenceManager().getObjectById(Tag.class, categoryID);
      tagKeysToFilter.add(categoryTag.getKey());
    }

    if (price != null && !price.equals("")) {
      priceTag = (Tag) PMF.get().getPersistenceManager().getObjectById(Tag.class, priceID);
      tagKeysToFilter.add(priceTag.getKey());
    }

    if (lifestyle != null && !lifestyle.equals("")) {
      lifestyleTag = (Tag) PMF.get().getPersistenceManager().getObjectById(Tag.class, lifestyleID);
      tagKeysToFilter.add(lifestyleTag.getKey());
    }
    if (cuisine != null && !cuisine.equals("")) {
      cuisineTag = (Tag) PMF.get().getPersistenceManager().getObjectById(Tag.class, cuisineID);
      tagKeysToFilter.add(cuisineTag.getKey());
    }

    List<Dish> dishResults = null;

    if (null != callType && callType.equals("search")) {
      String query = req.getParameter("searchWord");
      if (query.isEmpty()) query = " ";

      query = query.toLowerCase();
      String[] qWords = query.split(" ");

      dishResults =
          TDQueryUtils.searchGeoItemsWithFilter(
              qWords,
              userLoc,
              maxResults,
              maxDistance,
              new Dish(),
              pageNum * maxResults,
              tagKeysToFilter,
              new DishPosReviewsComparator());
    } else {
      dishResults =
          AbstractSearch.filterDishes(
              PMF.get().getPersistenceManager(),
              maxResults,
              tagKeysToFilter,
              maxDistance,
              lat,
              lng,
              pageNum * maxResults,
              new DishPosReviewsComparator());
    }

    if (null != dishResults && dishResults.size() > 0) {
      if (DEBUG) System.out.println("result set size: " + dishResults.size());

      sb.append("<DishSearch>");
      sb.append("<count>" + pageNum + "</count>");
      sb.append("<Dishes>");
      namesAdded = true;
      for (Dish dish : dishResults) {
        Restaurant r =
            PMF.get().getPersistenceManager().getObjectById(Restaurant.class, dish.getRestaurant());
        List<Tag> tags = TDQueryUtils.getAll(dish.getTags(), new Tag());
        Photo dishPhoto = null;

        if (dish.getPhotos() != null && dish.getPhotos().size() > 0) {
          dishPhoto =
              PMF.get().getPersistenceManager().getObjectById(Photo.class, dish.getPhotos().get(0));
        }

        int vote = 0;
        try {
          if (TDUserService.getUserLoggedIn())
            vote =
                TDUserService.getUserVote(
                    TDUserService.getUser(PMF.get().getPersistenceManager()).getKey(),
                    dish.getKey());
        } catch (UserNotLoggedInException e) {
          // e.printStackTrace();
        } catch (UserNotFoundException e) {
          // e.printStackTrace();
        }

        BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
        String blobUploadURL = blobstoreService.createUploadUrl("/addReview");

        sb.append("<Dish>");
        sb.append("<blobUploadURL>" + blobUploadURL + "</blobUploadURL>");
        sb.append("<keyId>" + dish.getKey().getId() + "</keyId>");
        sb.append("<name>" + StringEscapeUtils.escapeHtml(dish.getName()) + "</name>");
        sb.append(
            "<description>"
                + StringEscapeUtils.escapeHtml(dish.getDescription())
                + "</description>");
        sb.append(
            "<distance>"
                + TDMathUtils.formattedGeoPtDistanceMiles(userLoc, dish.getLocation())
                + "</distance>");
        boolean isEditable = false;

        if (TDUserService.getUserLoggedIn() && UserServiceFactory.getUserService().isUserAdmin()) {
          isEditable = true;
        } else
          isEditable = TDQueryUtils.isAccessible(Long.valueOf(dish.getKey().getId()), new Dish());
        if (isEditable) sb.append("<allowEdit>T</allowEdit>");
        else sb.append("<allowEdit>F</allowEdit>");
        if (TDUserService.getUserLoggedIn()) {
          sb.append("<userLoggedIn>L</userLoggedIn>");
        } else {
          sb.append("<userLoggedIn>O</userLoggedIn>");
        }
        if (null != dishPhoto) {
          try {
            sb.append(
                "<blobKey>"
                    + ImagesServiceFactory.getImagesService()
                        .getServingUrl(dishPhoto.getBlobKey(), 98, true)
                    + "</blobKey>");
            sb.append("<photoExist>E</photoExist>");
          } catch (Exception e) {
            sb.append("<photoExist>NE</photoExist>");
          }
        } else {
          sb.append("<blobKey></blobKey>");
          sb.append("<photoExist>NE</photoExist>");
        }
        sb.append(
            "<restAddrLine1>"
                + StringEscapeUtils.escapeHtml(r.getAddressLine1())
                + "</restAddrLine1>");
        sb.append("<restCity>" + StringEscapeUtils.escapeHtml(r.getCity()) + "</restCity>");
        sb.append("<restState>" + StringEscapeUtils.escapeHtml(r.getState()) + "</restState>");
        sb.append("<restId>" + r.getKey().getId() + "</restId>");
        sb.append("<restName>" + StringEscapeUtils.escapeHtml(r.getName()) + "</restName>");
        sb.append(
            "<restNeighbourhood>"
                + StringEscapeUtils.escapeHtml(r.getNeighborhood())
                + "</restNeighbourhood>");
        // sb.append("<location>" + dish.getLocation() + "</location>");
        sb.append("<latitude>" + dish.getLocation().getLat() + "</latitude>");
        sb.append("<longitude>" + dish.getLocation().getLon() + "</longitude>");
        sb.append("<posReviews>" + dish.getNumPosReviews() + "</posReviews>");
        sb.append("<negReviews>" + dish.getNumNegReviews() + "</negReviews>");
        String voteString = "LTE0";
        if (vote > 0) voteString = "GT0";
        else if (vote < 0) voteString = "LT0";
        sb.append("<voteString>" + voteString + "</voteString>");
        if (tags != null && !tags.isEmpty()) {
          sb.append("<tagsEmpty>NE</tagsEmpty>");
        } else sb.append("<tagsEmpty>E</tagsEmpty>");
        sb.append("<Tags>");
        for (Tag tag : tags) {
          sb.append(
              "<tag><tagName>" + StringEscapeUtils.escapeHtml(tag.getName()) + "</tagName></tag>");
        }
        sb.append("</Tags>");
        Key lastReviewKey = TDQueryUtils.getLatestReviewByDish(dish.getKey());
        if (null != lastReviewKey) {
          final Review lastReview =
              PMF.get().getPersistenceManager().getObjectById(Review.class, lastReviewKey);
          if (lastReview.getDirection() == Review.POSITIVE_DIRECTION) {
            sb.append("<lastReviewType>P</lastReviewType>");
          } else sb.append("<lastReviewType>N</lastReviewType>");
          sb.append(
              "<lastReview>"
                  + HumanTime.approximately(
                      System.currentTimeMillis() - lastReview.getDateCreated().getTime())
                  + "</lastReview>");
        } else {
          sb.append("<lastReviewType>E</lastReviewType>");
        }
        sb.append("<numReview>" + dish.getNumReviews() + "</numReview>");

        sb.append("</Dish>");
      }
      sb.append("</Dishes>");

      sb.append("</DishSearch>");
    } else {
      namesAdded = true;
      sb.append("<dishMesg>No records found</dishMesg>");
    }

    if (namesAdded) {
      resp.setContentType("text/xml");
      resp.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + sb.toString());
    } else {
      resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
  }
 public static Image getImage(BlobKey blobKey) throws IOException {
   byte[] data = getData(blobKey);
   Image image = ImagesServiceFactory.makeImage(data);
   return image;
 }
 public static String getDownloadUrl(ImageRef ref) {
   ImagesService imagesService = ImagesServiceFactory.getImagesService();
   return imagesService.getServingUrl(
       ServingUrlOptions.Builder.withBlobKey(getBlobkKey(ref))
           .imageSize(ImagesService.SERVING_SIZES_LIMIT));
 }
 private Collection<Future<HTTPResponse>> handleBodyPart(
     HttpServletRequest request, Entity blog, BodyPart bodyPart, final Settings settings)
     throws MessagingException, IOException {
   ImagesService imagesService = ImagesServiceFactory.getImagesService();
   DS ds = DS.get();
   Collection<Future<HTTPResponse>> futures = new ArrayList<>();
   String contentType = bodyPart.getContentType();
   log(contentType);
   Object content = bodyPart.getContent();
   if (content instanceof InputStream) {
     String filename = bodyPart.getFileName();
     byte[] bytes = getBytes(bodyPart);
     String digestString = DS.getDigest(bytes);
     Entity metadata = createMetadata(digestString, filename, contentType, bytes);
     if (contentType.startsWith("image/")) {
       int oWidth;
       int oHeight;
       int wWidth;
       int wHeight;
       Image image = ImagesServiceFactory.makeImage(bytes);
       if (settings.isFixPic()) {
         Transform makeImFeelingLucky = ImagesServiceFactory.makeImFeelingLucky();
         image = imagesService.applyTransform(makeImFeelingLucky, image);
       }
       oWidth = image.getWidth();
       oHeight = image.getHeight();
       if (image.getHeight() > settings.getPicMaxHeight()
           || image.getWidth() > settings.getPicMaxWidth()) {
         log(
             "shrinking ["
                 + image.getHeight()
                 + ", "
                 + image.getWidth()
                 + "] > ["
                 + settings.getPicMaxHeight()
                 + ", "
                 + settings.getPicMaxWidth()
                 + "]");
         Transform makeResize =
             ImagesServiceFactory.makeResize(
                 settings.getPicMaxHeight(), settings.getPicMaxWidth());
         Image shrinken = imagesService.applyTransform(makeResize, image);
         wWidth = shrinken.getWidth();
         wHeight = shrinken.getHeight();
         Future<HTTPResponse> res =
             postBlobs(
                 filename,
                 contentType,
                 digestString,
                 shrinken.getImageData(),
                 WebSizeProperty,
                 request,
                 wWidth,
                 wHeight);
         futures.add(res);
       } else {
         wWidth = image.getWidth();
         wHeight = image.getHeight();
         Future<HTTPResponse> res =
             postBlobs(
                 filename,
                 contentType,
                 digestString,
                 bytes,
                 WebSizeProperty,
                 request,
                 wWidth,
                 wHeight);
         futures.add(res);
       }
       Future<HTTPResponse> res =
           postBlobs(
               filename,
               contentType,
               digestString,
               bytes,
               OriginalSizeProperty,
               request,
               oWidth,
               oHeight);
       futures.add(res);
       String[] cids = bodyPart.getHeader("Content-ID");
       if (cids != null && cids.length > 0) {
         String alt = (String) metadata.getProperty(UserCommentProperty);
         if (alt == null) {
           alt = "";
         }
         replaceBlogRef(blog, cids[0], digestString, wWidth, wHeight, alt);
       }
     }
     if (contentType.startsWith("application/vnd.google-earth.kml+xml")
         || filename.endsWith(".kml")) {
       try {
         InputStream is = (InputStream) content;
         KML kml = new KML(is);
         PlacemarkUpdater pu = new PlacemarkUpdater(ds, kml, LocatorLevel.Field);
         pu.visit(kml, null);
       } catch (JAXBException ex) {
         log("reading kml failed", ex);
       }
     }
     if (contentType.startsWith("application/vnd.google-earth.kmz") || filename.endsWith(".kmz")) {
       try {
         InputStream is = (InputStream) content;
         KMZ kmz = new KMZ(is);
         PlacemarkUpdater pu = new PlacemarkUpdater(ds, kmz, LocatorLevel.Field);
         pu.visit(kmz, null);
       } catch (JAXBException ex) {
         log("reading kmz failed", ex);
       }
     }
     if (filename.endsWith(".gpx")) {
       try {
         InputStream is = (InputStream) content;
         final GPX gpx = new GPX(is);
         final OpenCPNTrackHandler handler = new OpenCPNTrackHandler(ds);
         RunInNamespace rin =
             new RunInNamespace() {
               @Override
               protected Object run() {
                 gpx.browse(
                     settings.getTrackBearingTolerance(),
                     settings.getTrackMinimumDistance(),
                     settings.getTrackMaxSpeed(),
                     handler);
                 return null;
               }
             };
         rin.doIt(null, settings.isCommonPlacemarks());
       } catch (JAXBException ex) {
         log("reading gpx failed", ex);
       }
     }
     if (filename.endsWith(".trc")) {
       InputStream is = (InputStream) content;
       final TrackInput trackInput = new TrackInput(is);
       final CompressedTrackHandler cth = new CompressedTrackHandler(ds);
       RunInNamespace rin =
           new RunInNamespace() {
             @Override
             protected Object run() {
               try {
                 cth.handle(trackInput);
               } catch (IOException ex) {
                 log(ex.getMessage(), ex);
               }
               return null;
             }
           };
       rin.doIt(null, settings.isCommonPlacemarks());
     }
     if (contentType.startsWith("application/X-jsr179-location-nmea")
         || filename.endsWith(".nmea")) {
       log("NMEA not yet supported");
     }
   }
   return futures;
 }