Package ch.entwine.weblounge.common.repository

Examples of ch.entwine.weblounge.common.repository.ContentRepository


   *          the pareURI
   * @return the page
   */
  private Page getPage(Site site, ResourceURI pageURI) {
    // Get hold of the site's content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
      logger.warn("No content repository found for site '{}'", site);
      throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }

    // Load the page
    Page page = null;
    try {
      page = (Page) contentRepository.get(pageURI);
    } catch (ContentRepositoryException e) {
      logger.error("Error trying to access content repository {}: {}", contentRepository, e);
      throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
    return page;
View Full Code Here


  ContentRepositoryException, ContentRepositoryUnavailableException {

    try {
      WebUrl url = getRequest().getUrl();
      Site site = request.getSite();
      ContentRepository contentRepository = site.getContentRepository();
      if (contentRepository == null) {
        logger.debug("Content repository unavailable for site '{}'", site.getIdentifier());
        throw new ContentRepositoryUnavailableException("Repository is offline");
      }

      targetPage = (Page) getRequest().getAttribute(WebloungeRequest.PAGE);

      // If no page was specified, take homepage instead.
      if (targetPage == null) {
        ResourceURI homeURI = new PageURIImpl(site, "/");
        try {
          targetPage = (Page) contentRepository.get(homeURI);
          if (targetPage == null) {
            logger.warn("No page was found while processing composer on " + url);
            return;
          }
        } catch (SecurityException e) {
          logger.warn("Composer '" + id + "' was unable to choose homepage as fallback: " + e.getMessage());
          return;
        } catch (ContentRepositoryException e) {
          logger.warn("Composer '" + id + "' was unable to choose homepage as fallback: " + e.getMessage());
          return;
        }
      }

      if (contentProvider == null)
        contentProvider = targetPage;

      Pagelet[] content = contentProvider.getPagelets(id);
      Pagelet[] ghostContent = new Pagelet[0];

      // If composer is empty and ghost content is enabled, go up the page
      // hierarchy and try to find content for this composer
      Page contentPage = contentProvider;
      if (content.length == 0 && inheritFromParent) {
        String pageUrl = contentPage.getURI().getPath();
        while (ghostContent.length == 0 && pageUrl.length() > 1) {
          if (pageUrl.endsWith("/") && !"/".equals(pageUrl))
            pageUrl = pageUrl.substring(0, pageUrl.length() - 1);
          int urlSeparator = pageUrl.lastIndexOf("/");
          if (urlSeparator < 0) {
            contentPage = null;
            break;
          } else {
            pageUrl = pageUrl.substring(0, urlSeparator);
            if ("".equals(pageUrl))
              pageUrl = "/";
            ResourceURI pageURI = new PageURIImpl(site, pageUrl);
            try {
              contentPage = (Page) contentRepository.get(pageURI);
            } catch (SecurityException e) {
              logger.debug("Prevented loading of protected content from inherited page {} for composer {}", pageURI, id);
            }

            // Did we find anything? If not, keep looking...
View Full Code Here

  ContentRepositoryUnavailableException {
    Site site = request.getSite();

    // Check if headers have already been loaded
    if (pages == null) {
      ContentRepository repository = site.getContentRepository();
      if (repository == null) {
        logger.debug("Unable to load content repository for site '{}'", site);
        throw new ContentRepositoryUnavailableException();
      }

      // Specify which pages to load
      SearchQuery query = new SearchQueryImpl(site);
      query.withVersion(Resource.LIVE);

      // Add the keywords (or)
      for (String subject : subjects) {
        query.withSubject(subject);
      }

      // Add the pagelets required on stage (and)
      if (requiredPagelets.size() > 0) {
        List<Pagelet> pagelets = new ArrayList<Pagelet>();
        for (String headline : requiredPagelets) {
          String[] parts = headline.split("/");
          if (parts.length > 1) {
            Pagelet pagelet = new PageletImpl(parts[0], parts[1]);
            pagelets.add(pagelet);
          }
        }
        query.withPagelets(All, pagelets.toArray(new Pagelet[pagelets.size()])).inStage();
      }

      // Order by date and limit the result set
      query.sortByPublishingDate(SearchQuery.Order.Descending);
      query.withLimit(count);

      // Finally Load the pages
      pages = repository.find(query);
    }

    boolean found = false;
    PageSearchResultItem item = null;
    Page page = null;
View Full Code Here

   */
  public int doStartTag() throws JspException {
    Site site = request.getSite();
    Language language = request.getLanguage();

    ContentRepository repository = site.getContentRepository();
    if (repository == null) {
      logger.debug("Unable to load content repository for site '{}'", site);
      response.invalidate();
      return SKIP_BODY;
    }

    // Create the page uri, either from the id or the path. If none is
    // specified, and we are not in jsp compilation mode, issue a warning
    ResourceURI uri = null;
    if (StringUtils.isNotBlank(pageId)) {
      uri = new PageURIImpl(site, null, pageId);
    } else if (StringUtils.isNotBlank(pagePath)) {
      uri = new PageURIImpl(site, pagePath, null);
    } else if (!request.getRequestURI().endsWith(".jsp")) {
      logger.warn("Neither uuid nor path were specified for image");
      return SKIP_BODY;
    } else {
      return SKIP_BODY;
    }

    // Try to load the page from the content repository
    try {
      if (!repository.exists(uri)) {
        logger.warn("Non existing page {} requested on {}", uri, request.getUrl());
        return SKIP_BODY;
      }
    } catch (ContentRepositoryException e) {
      logger.error("Error trying to look up page {} from {}", pageId, repository);
      return SKIP_BODY;
    }

    Page page = null;

    // Store the result in the jsp page context
    try {
      page = (Page) repository.get(uri);
      language = LanguageUtils.getPreferredLanguage(page, request, site);
      if (language != null)
        page.switchTo(language);
    } catch (ContentRepositoryException e) {
      logger.warn("Error trying to load page " + uri + ": " + e.getMessage(), e);
View Full Code Here

    if (RequestUtils.isPrecompileRequest(request))
      return SKIP_BODY;

    Site site = request.getSite();

    ContentRepository repository = site.getContentRepository();
    if (repository == null) {
      logger.debug("Unable to load content repository for site '{}'", site);
      response.invalidate();
      throw new JspException();
    }

    // Create the resource uri, either from the id or the path. If none is
    // specified, and we are not in jsp compilation mode, issue a warning
    ResourceURI uri = null;
    if (StringUtils.isNotBlank(resourceId)) {
      uri = new GeneralResourceURIImpl(site, null, resourceId);
    } else if (StringUtils.isNotBlank(resourcePath)) {
      uri = new GeneralResourceURIImpl(site, resourcePath);
    } else {
      logger.warn("Neither uuid nor path were specified for resource on {}", request.getUrl());
      return SKIP_BODY;
    }

    // Try to load the resource from the content repository
    try {
      if (!repository.exists(uri)) {
        logger.warn("Non existing resource {} requested on {}", uri, request.getUrl());
        return SKIP_BODY;
      }
    } catch (ContentRepositoryException e) {
      logger.error("Error trying to look up resource {} from {}", resourceId, repository);
      return SKIP_BODY;
    }

    Resource<?> resource = null;
    ResourceContent resourceContent = null;

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

    // Store the result in the jsp page context
    try {
      resource = repository.get(uri);
      resource.switchTo(language);

      Language contentLanguage = null;
      contentLanguage = LanguageUtils.getPreferredContentLanguage(resource, request, site);
      if (contentLanguage == null) {
View Full Code Here

        return SKIP_BODY;
      } else {
        throw new JspException("Page preview tag on " + request.getUrl() + " requires either a page id or embedding inside a PageListTag");
      }
    } else {
      ContentRepository contentRepository = null;
      contentRepository = site.getContentRepository();
      if (contentRepository == null) {
        logger.debug("Content repository is offline");
        response.invalidate();
        return SKIP_BODY;
      }

      ResourceURI pageURI = new PageURIImpl(site, null, pageId);

      try {
        page = (Page) contentRepository.get(pageURI);
        if (page == null) {
          logger.error("No data available for page {}", pageURI);
          return EVAL_PAGE;
        }
      } catch (SecurityException e) {
View Full Code Here

        limit = DEFAULT_LIMIT;
      }
    }

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
      logger.warn("No content repository found for site '{}'", site);
      return null;
    } else if (contentRepository.isIndexing()) {
      logger.debug("Content repository of site '{}' is currently being indexed", site);
      DispatchUtils.sendServiceUnavailable(request, response);
      return null;
    }

    // User and language
    Language language = request.getLanguage();
    // User user = request.getUser();

    // Determine the feed type
    feedType = feedType.toLowerCase() + "_" + feedVersion;
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType(feedType);
    feed.setLink(request.getRequestURL().toString());
    feed.setTitle(site.getName());
    feed.setDescription(site.getName());
    feed.setLanguage(language.getIdentifier());
    feed.setPublishedDate(new Date());

    // TODO: Add more feed metadata, ask site

    SearchQuery query = new SearchQueryImpl(site);
    query.withVersion(Resource.LIVE);
    query.withTypes(Page.TYPE);
    query.withLimit(limit);
    query.sortByPublishingDate(Order.Descending);
    for (String subject : subjects) {
      query.withSubject(subject);
    }

    // Load the result and add feed entries
    SearchResult result = contentRepository.find(query);
    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    limit = result.getItems().length;

    while (limit > 0) {
      SearchResultItem item = result.getItems()[limit - 1];
View Full Code Here

        pageURI = page.getURI();
      }

      // Load the page from the content repository
      else {
        ContentRepository contentRepository = site.getContentRepository();
        if (contentRepository == null) {
          logger.debug("No content repository found for site '{}'", site);
          return false;
        } else if (contentRepository.isIndexing()) {
          logger.debug("Content repository of site '{}' is currently being indexed", site);
          DispatchUtils.sendServiceUnavailable(request, response);
          return true;
        }

        ResourceURI requestURI = null;
        ResourceURI requestedURI = null;

        // Load the page. Note that we are taking care of the special case where
        // a user may have created a page with a url that matches a valid
        // language identifier, in which case it would have been stripped from
        // request.getUrl().
        try {
          if (action != null) {
            pageURI = getPageURIForAction(action, request);
            requestURI = pageURI;
          } else if (path.startsWith(URI_PREFIX)) {
            String uriSuffix = StringUtils.substringBefore(path.substring(URI_PREFIX.length()), "/");
            uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");
            ResourceURI uri = new PageURIImpl(site, null, uriSuffix, request.getVersion());
            requestURI = uri;
            WebUrl requestedUrl = request.getRequestedUrl();
            if (requestedUrl.hasLanguagePathSegment()) {
              String requestedPath = UrlUtils.concat(path, request.getLanguage().getIdentifier());
              String requestedUriSuffix = StringUtils.substringBefore(requestedPath.substring(URI_PREFIX.length()), "/");
              requestedUriSuffix = URLDecoder.decode(requestedUriSuffix, "utf-8");
              requestedURI = new PageURIImpl(site, requestedUriSuffix, null, request.getVersion());
            }
          } else {
            long version = isEditing ? Resource.WORK : Resource.LIVE;
            ResourceURI uri = new PageURIImpl(request);
            uri.setVersion(version);
            requestURI = uri;
            WebUrl requestedUrl = request.getRequestedUrl();
            if (requestedUrl.hasLanguagePathSegment()) {
              String requestedPath = UrlUtils.concat(path, request.getLanguage().getIdentifier());
              requestedPath = URLDecoder.decode(requestedPath, "utf-8");
              requestedURI = new PageURIImpl(site, requestedPath, null, version);
            }
          }

          // Is this a request with potential path clashes?
          if (requestedURI != null) {
            long version = requestedURI.getVersion();
            if (contentRepository.existsInAnyVersion(requestedURI)) {
              if (!isEditing && version == Resource.LIVE && contentRepository.exists(requestedURI)) {
                pageURI = requestedURI;
                ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage());
              } else if (isEditing && version == Resource.WORK && !contentRepository.exists(requestedURI)) {
                requestedURI.setVersion(Resource.LIVE);
                pageURI = requestedURI;
                ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage());
              } else if (isEditing && version == Resource.WORK && !contentRepository.exists(requestedURI)) {
                pageURI = requestedURI;
                ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage());
              }
            }
          }

          // Does the page exist?
          if (pageURI == null && contentRepository.existsInAnyVersion(requestURI)) {
            long version = requestURI.getVersion();

            // If the work version is requested, we need to make sure
            // a) it exists and b) the user is in editing mode
            if (version == Resource.WORK && isEditing) {
              if (contentRepository.exists(requestURI)) {
                pageURI = requestURI;
              } else {
                requestURI.setVersion(Resource.LIVE);
                if (contentRepository.exists(requestURI))
                  pageURI = requestURI;
              }
            } else if (contentRepository.exists(requestURI)) {
              pageURI = requestURI;
            }
          }

          // Did we find a matching uri?
          if (pageURI == null) {
            DispatchUtils.sendNotFound(request, response);
            return true;
          }

          page = (Page) contentRepository.get(pageURI);
          if (page == null) {
            DispatchUtils.sendNotFound(request, response);
            return true;
          }
        } catch (ContentRepositoryException e) {
View Full Code Here

    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
      logger.warn("No content repository found for site '{}'", site);
      return false;
    } else if (contentRepository.isIndexing()) {
      logger.debug("Content repository of site '{}' is currently being indexed", site);
      DispatchUtils.sendServiceUnavailable(request, response);
      return true;
    }

    // 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;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
      response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
      response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Determine the resource's modification date
    long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime();

    // Add last modified header
    response.setDateHeader("Last-Modified", resourceLastModified);

    // Add ETag header
    response.setHeader("ETag", ResourceUtils.getETagValue(imageResource));

    // Load the input stream from the repository
    InputStream imageInputStream = null;
    try {
      imageInputStream = contentRepository.getContent(imageURI, language);
    } catch (Throwable t) {
      logger.error("Error loading {} image '{}' from {}: {}", new Object[] {
          language,
          imageResource,
          contentRepository,
View Full Code Here

    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
      logger.warn("No content repository found for site '{}'", site);
      return false;
    } else if (contentRepository.isIndexing()) {
      logger.debug("Content repository of site '{}' is currently being indexed", site);
      DispatchUtils.sendServiceUnavailable(request, response);
      return true;
    }

    // Check if the request uri matches the special uri for files. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is a file with the current path.
    ResourceURI fileURI = null;
    Resource<? extends FileContent> fileResource = null;
    try {
      String id = null;
      String filePath = 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 {
            filePath = uriSuffix;
            fileName = FilenameUtils.getName(filePath);
          }
        } else {
          filePath = "/" + uriSuffix;
          fileName = FilenameUtils.getName(filePath);
        }
        fileURI = new GeneralResourceURIImpl(site, filePath, id);
      } else {
        filePath = path;
        fileName = FilenameUtils.getName(filePath);
        fileURI = new FileResourceURIImpl(site, filePath, null);
      }

      // Try to load the resource
      try {
        fileResource = (Resource<? extends FileContent>) contentRepository.get(fileURI);
        if (fileResource == null) {
          logger.debug("No file found at {}", fileURI);
          return false;
        }
      } catch (ClassCastException e) {
        logger.debug("Resource {} does not extend file resource {}", fileURI);
        return false;
      }
    } catch (ContentRepositoryException e) {
      logger.error("Error loading file from {}: {}", contentRepository, e);
      DispatchUtils.sendInternalError(request, response);
      return true;
    } catch (UnsupportedEncodingException e) {
      logger.error("Error decoding file url {} using utf-8: {}", path, e.getMessage());
      DispatchUtils.sendInternalError(request, response);
      return true;
    }

    // Try to serve the file
    logger.debug("File 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("File request handler does not support {} requests", requestMethod);
      DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
      return true;
    }

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

    // Can the page 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 file {} denied for user {}", fileURI, user);
      DispatchUtils.sendAccessDenied(request, response);
      return true;
    }

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

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

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

    // Add mime type header
    FileContent content = fileResource.getContent(language);

    // If the content is hosted externally, send a redirect and be done with it
    if (content.getExternalLocation() != null) {
      try {
        response.sendRedirect(content.getExternalLocation().toExternalForm());
      } catch (IOException e) {
        logger.debug("Client ignore redirect to {}", content.getExternalLocation());
      }
      return true;
    }

    String contentType = content.getMimetype();
    if (contentType == null)
      contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
      response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
      response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Add last modified header
    response.setDateHeader("Last-Modified", ResourceUtils.getModificationDate(fileResource, language).getTime());

    // Add ETag header
    String eTag = ResourceUtils.getETagValue(fileResource);
    response.setHeader("ETag", eTag);

    // Set the Expires header
    response.setDateHeader("Expires", expirationDate);

    // Add content disposition header
    response.setHeader("Content-Disposition", "inline; filename=" + content.getFilename());

    // Add content size
    response.setHeader("Content-Length", Long.toString(content.getSize()));

    // Write the file back to the response
    InputStream fileContents = null;
    try {
      fileContents = contentRepository.getContent(fileURI, language);
      IOUtils.copy(fileContents, response.getOutputStream());
      response.getOutputStream().flush();
      return true;
    } catch (ContentRepositoryException e) {
      logger.error("Unable to load file {}: {}", new Object[] {
View Full Code Here

TOP

Related Classes of ch.entwine.weblounge.common.repository.ContentRepository

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.