Package ch.entwine.weblounge.common.content.image

Examples of ch.entwine.weblounge.common.content.image.ImageResource


      logger.warn("Error searching for image with given subjects.");
      return SKIP_BODY;
    }

    ResourceURI uri = null;
    ImageResource image = null;
    ImageContent imageContent = null;
    String linkToImage = null;
    PrintWriter writer = null;

    try {
      writer = response.getWriter();

      for (int i = 0; i < result.getItems().length; i++) {
        uri = new ImageResourceURIImpl(site, null, result.getItems()[i].getId());
        if (repository.exists(uri)) {
          image = (ImageResource) repository.get(uri);
          language = LanguageUtils.getPreferredLanguage(image, request, site);
          image.switchTo(language);
          imageContent = image.getContent(language);

          linkToImage = UrlUtils.concat("/weblounge-images", image.getIdentifier(), imageContent.getFilename());

          // Find the image style

          writer.write("<a href=\"");
          writer.write(linkToImage + "?style=" + this.styleNormal); // normal
View Full Code Here


    // Check if the request uri matches the special uri for images. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI imageURI = null;
    ImageResource imageResource = null;
    try {
      String id = null;
      String imagePath = null;

      if (path.startsWith(URI_PREFIX)) {
        String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
        uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

        // Check whether we are looking at a uuid or a url path
        if (uriSuffix.length() == UUID_LENGTH) {
          id = uriSuffix;
        } else if (uriSuffix.length() >= UUID_LENGTH) {
          int lastSeparator = uriSuffix.indexOf('/');
          if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
            id = uriSuffix.substring(0, lastSeparator);
            fileName = uriSuffix.substring(lastSeparator + 1);
          } else {
            imagePath = uriSuffix;
            fileName = FilenameUtils.getName(imagePath);
          }
        } else {
          imagePath = "/" + uriSuffix;
          fileName = FilenameUtils.getName(imagePath);
        }
      } else {
        imagePath = path;
        fileName = FilenameUtils.getName(imagePath);
      }

      // Try to load the resource
      imageURI = new ImageResourceURIImpl(site, imagePath, id);
      imageResource = contentRepository.get(imageURI);
      if (imageResource == null) {
        logger.debug("No image found at {}", imageURI);
        return false;
      }
    } catch (ContentRepositoryException e) {
      logger.error("Error loading image from {}: {}", contentRepository, e.getMessage());
      DispatchUtils.sendInternalError(request, response);
      return true;
    } catch (UnsupportedEncodingException e) {
      logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage());
      DispatchUtils.sendInternalError(request, response);
      return true;
    }

    // Agree to serve the image
    logger.debug("Image handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
      String verbs = "OPTIONS,GET";
      logger.trace("Answering options request to {} with {}", url, verbs);
      response.setHeader("Allow", verbs);
      response.setContentLength(0);
      return true;
    } else if (!"GET".equals(requestMethod)) {
      logger.debug("Image request handler does not support {} requests", requestMethod);
      DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
      return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the image be accessed by the current user?
    User user = request.getUser();
    try {
      // TODO: Check permission
      // PagePermission p = new PagePermission(page, user);
      // AccessController.checkPermission(p);
    } catch (SecurityException e) {
      logger.warn("Access to image {} denied for user {}", imageURI, user);
      DispatchUtils.sendAccessDenied(request, response);
      return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
      for (ImageContent c : imageResource.contents()) {
        if (c.getFilename().equalsIgnoreCase(fileName)) {
          if (language != null) {
            logger.debug("Unable to determine language from ambiguous filename");
            language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
            break;
          }
          language = c.getLanguage();
        }
      }
      if (language == null)
        language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    } else {
      language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
      logger.warn("Image {} does not exist in any supported language", imageURI);
      DispatchUtils.sendNotFound(request, response);
      return true;
    }

    // Extract the image style and scale the image
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
      try {
        StringBuffer redirect = new StringBuffer(PathUtils.concat(PreviewRequestHandlerImpl.URI_PREFIX, imageResource.getURI().getIdentifier()));
        redirect.append("?style=").append(styleId);
        response.sendRedirect(redirect.toString());
      } catch (Throwable t) {
        logger.debug("Error sending redirect to the client: {}", t.getMessage());
      }
      return true;
    }

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, imageResource, language)) {
      logger.debug("Image {} was not modified", imageURI);
      response.setDateHeader("Expires", expirationDate);
      DispatchUtils.sendNotModified(request, response);
      return true;
    }

    // Load the image contents from the repository
    ImageContent imageContents = imageResource.getContent(language);

    // Add mime type header
    String contentType = imageContents.getMimetype();
    if (contentType == null)
      contentType = MediaType.APPLICATION_OCTET_STREAM;
View Full Code Here

    } catch (ContentRepositoryException e) {
      logger.error("Error trying to look up image {} from {}", imageId, repository);
      return SKIP_BODY;
    }

    ImageResource image = null;
    ImageContent imageContent = null;
    ImageStyle style = null;
    String linkToImage = null;
    int imageWidth = 0;
    int imageHeight = 0;

    // Try to determine the language
    Language language = request.getLanguage();

    // Load the content
    try {
      image = (ImageResource) repository.get(uri);
      if (image == null) {
        logger.warn("Non existing image {} requested on {}", uri, request.getUrl());
        return SKIP_BODY;
      }
      image.switchTo(language);

      Language contentLanguage = null;
      contentLanguage = LanguageUtils.getPreferredContentLanguage(image, request, site);
      if (contentLanguage == null) {
        logger.warn("Image {} does not have suitable content", image);
        return SKIP_BODY;
      }

      imageContent = image.getContent(contentLanguage);
      if (imageContent == null)
        imageContent = image.getOriginalContent();
      imageWidth = imageContent.getWidth();
      imageHeight = imageContent.getHeight();
      // TODO: Make this a reference rather than a hard coded string
      linkToImage = UrlUtils.concat("/weblounge-images", image.getIdentifier(), language.getIdentifier());
    } catch (ContentRepositoryException e) {
      logger.warn("Error trying to load image " + uri + " on " + request.getUrl() + ": " + e.getMessage(), e);
      return SKIP_BODY;
    }

    // Find the image style
    if (StringUtils.isNotBlank(imageStyle)) {
      style = ImageStyleUtils.findStyle(imageStyle, site);
      if (style != null) {
        linkToImage += "?style=" + style.getIdentifier();
        imageWidth = ImageStyleUtils.getStyledWidth(imageContent, style);
        imageHeight = ImageStyleUtils.getStyledHeight(imageContent, style);
        stashAndSetAttribute(ImageResourceTagExtraInfo.STYLE, style);
      } else {
        logger.warn("Image style '{}' not found to render on {}", imageStyle, request.getUrl());
      }
    }

    // TODO: Check the permissions

    // Store the image and the image content in the request
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE, image);
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE_CONTENT, imageContent);
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE_WIDTH, imageWidth);
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE_HEIGHT, imageHeight);
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE_SRC, linkToImage);
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE_TITLE, image.getTitle(language));
    stashAndSetAttribute(ImageResourceTagExtraInfo.IMAGE_DESC, image.getDescription(language));

    // Add the cache tags to the response
    response.addTag(CacheTag.Resource, image.getURI().getIdentifier());
    response.addTag(CacheTag.Url, image.getURI().getPath());

    return EVAL_BODY_INCLUDE;
  }
View Full Code Here

   *      ch.entwine.weblounge.common.language.Language)
   */
  public Resource<ImageContent> newResource(Site site, InputStream is,
      User user, Language language) {
    ImageMetadata imageMetadata = ImageMetadataUtils.extractMetadata(new BufferedInputStream(is));
    ImageResource imageResource = new ImageResourceImpl(new ImageResourceURIImpl(site));
    imageResource.setCreated(user, new Date());

    if (imageMetadata == null)
      return imageResource;

    if (!StringUtils.isBlank(imageMetadata.getCaption())) {
      imageResource.setTitle(imageMetadata.getCaption(), language);
    }
    if (!StringUtils.isBlank(imageMetadata.getLegend())) {
      imageResource.setDescription(imageMetadata.getLegend(), language);
    }
    for (String keyword : imageMetadata.getKeywords()) {
      imageResource.addSubject(keyword);
    }
    if (!StringUtils.isBlank(imageMetadata.getCopyright())) {
      imageResource.setRights(imageMetadata.getCopyright(), language);
    }
    return imageResource;
  }
View Full Code Here

    for (ResourceMetadata<?> metadataItem : metadata) {
      if (XML.equals(metadataItem.getName())) {
        String resourceXml = (String) metadataItem.getValues().get(0);
        try {
          ResourceReader<ImageContent, ImageResource> reader = getReader();
          ImageResource image = reader.read(IOUtils.toInputStream(resourceXml, "UTF-8"), site);
          return image;
        } catch (SAXException e) {
          logger.warn("Error parsing image resource from metadata", e);
          return null;
        } catch (IOException e) {
View Full Code Here

TOP

Related Classes of ch.entwine.weblounge.common.content.image.ImageResource

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.