Example #1
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>");
  }
  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;
  }
 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);
   }
 }
 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;
 }