Package ch.entwine.weblounge.common.content.page

Examples of ch.entwine.weblounge.common.content.page.Page


   */
  protected Page getTargetPage(Action action, WebloungeRequest request)
      throws ContentRepositoryException {

    ResourceURI target = null;
    Page page = null;
    Site site = request.getSite();
    boolean targetForced = false;

    // Check if a target-page parameter was passed
    String targetPage = request.getParameter(HTMLAction.TARGET_PAGE);
View Full Code Here


    // Get the renderer id that has been registered with the url. For this,
    // we first have to load the page data, then get the associated renderer
    // bundle.
    try {
      Page page = null;
      ResourceURI pageURI = null;
      Site site = request.getSite();

      // Check if a page was passed as an attribute
      if (request.getAttribute(WebloungeRequest.PAGE) != null) {
        page = (Page) request.getAttribute(WebloungeRequest.PAGE);
        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) {
          logger.error("Unable to load page {} from {}: {}", new Object[] {
              pageURI,
              contentRepository,
              e.getMessage(),
              e });
          DispatchUtils.sendInternalError(request, response);
          return true;
        }
      }

      // Check the request method. This handler only supports GET, POST and
      // OPTIONS
      String requestMethod = request.getMethod().toUpperCase();
      if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS, GET, POST";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
      } else if (!"GET".equals(requestMethod) && !"POST".equals(requestMethod) && !RequestUtils.containsAction(request)) {
        logger.debug("Url {} does not handle {} requests", url, requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
      }

      // Is it published?
      if (!page.isPublished() && !(page.getVersion() == Resource.WORK)) {
        logger.debug("Access to unpublished page {}", pageURI);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        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("Accessed to page {} denied for user {}", pageURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
      }

      // Check for explicit no cache instructions
      boolean ignoreCache = request.getParameter(ResponseCache.NOCACHE_PARAM) != null;

      // Check if the page is already part of the cache. If so, our task is
      // already done!
      if (!ignoreCache && request.getVersion() == Resource.LIVE && !isEditing) {

        // Create the set of tags that identify the page
        CacheTagSet cacheTags = createPrimaryCacheTags(request);

        if (action == null) {
          long expirationTime = Renderer.DEFAULT_VALID_TIME;
          long revalidationTime = Renderer.DEFAULT_RECHECK_TIME;

          // Check if the page is already part of the cache
          if (response.startResponse(cacheTags.getTags(), expirationTime, revalidationTime)) {
            logger.debug("Page handler answered request for {} from cache", request.getUrl());
            return true;
          }
        }

        processingMode = Mode.Cached;
        cacheTags.add(CacheTag.Resource, page.getURI().getIdentifier());
        response.addTags(cacheTags);

      } else if (Http11Constants.METHOD_HEAD.equals(requestMethod)) {
        // handle HEAD requests
        Http11Utils.startHeadResponse(response);
        processingMode = Mode.Head;
      } else if (request.getVersion() == Resource.WORK) {
        response.setCacheExpirationTime(0);
      }

      // Set the default maximum render and valid times for pages
      response.setClientRevalidationTime(Renderer.DEFAULT_RECHECK_TIME);
      response.setCacheExpirationTime(Renderer.DEFAULT_VALID_TIME);

      // Store the page in the request
      request.setAttribute(WebloungeRequest.PAGE, page);

      // Get hold of the page template
      PageTemplate template = null;
      try {
        template = getPageTemplate(page, request);
        template.setEnvironment(request.getEnvironment());
      } catch (IllegalStateException e) {
        logger.debug(e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
      }

      // Does the template support the requested flavor?
      if (!template.supportsFlavor(contentFlavor)) {
        logger.warn("Template '{}' does not support requested flavor {}", template, contentFlavor);
        DispatchUtils.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, request, response);
        return true;
      }

      // Suggest a last modified data. Note that this may not be the final date
      // as the page may contain content embedded from other pages that feature
      // more recent modification dates
      response.setModificationDate(page.getLastModified());

      // Set the content type
      String characterEncoding = response.getCharacterEncoding();
      if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType("text/html; charset=" + characterEncoding.toLowerCase());
View Full Code Here

      logger.error("Error trying to access the content repository", e);
      throw new WebApplicationException(e);
    }

    // Load the target page used to render the search result
    Page page = null;
    try {
      page = getTargetPage(request);
      request.setAttribute(WebloungeRequest.PAGE, page);
    } catch (ContentRepositoryException e) {
      logger.error("Error loading target page at {}", url);
      DispatchUtils.sendInternalError(request, response);
      return true;
    }

    // Get hold of the page template
    PageTemplate template = null;
    try {
      template = getTargetTemplate(page, request);
      if (template == null)
        template = site.getDefaultTemplate();
    } catch (IllegalStateException e) {
      logger.warn(e.getMessage());
      DispatchUtils.sendInternalError(request, response);
      return true;
    }

    // Identify the stage composer and remove any existing content
    String stage = template.getStage();
    logger.trace("Removing existing pagelets from composer '{}'", stage);
    while (page.getComposer(stage) != null && page.getComposer(stage).size() > 0) {
      page.removePagelet(stage, 0);
    }

    // Add the search result to the main composer
    logger.trace("Adding search result to composer '{}'", stage);
    for (SearchResultItem item : result.getItems()) {

      Renderer renderer = item.getPreviewRenderer();

      // Is this search result coming from the search index or from a module?
      if (!(item instanceof ResourceSearchResultItem)) {
        renderer = item.getPreviewRenderer();
        if (!(renderer instanceof PageletRenderer)) {
          logger.warn("Skipping search result '{}' since it's preview renderer is not a pagelet", item);
          continue;
        }
        PageletImpl pagelet = new PageletImpl((PageletRenderer) renderer);
        pagelet.setContent(item.getContent());
        page.addPagelet(pagelet, stage);
        continue;
      }

      // The search result item seems to be coming from the search index

      // Convert the search result item into a resource search result item
      ResourceSearchResultItem resourceItem = (ResourceSearchResultItem) item;
      ResourceURI uri = resourceItem.getResourceURI();

      ResourceSerializer<?, ?> serializer = serializerService.getSerializerByType(uri.getType());
      if (serializer == null) {
        logger.debug("Skipping search result since it's type ({}) is unknown", uri.getType());
        continue;
      }

      // Load the resource
      Resource<?> resource = serializer.toResource(site, resourceItem.getMetadata());

      // Get the renderer and make sure it's a pagelet renderer. First check
      // the item itself, there may already be a renderer attached. If not,
      // use the serializer to get the appropriate renderer
      renderer = item.getPreviewRenderer();
      if (renderer == null) {
        renderer = serializer.getSearchResultRenderer(resource);
        if (renderer == null) {
          logger.warn("Skipping search result since a renderer can't be determined");
          continue;
        }
      }

      // Create the pagelet
      PageletRenderer pageletRenderer = (PageletRenderer) renderer;
      PageletImpl pagelet = new PageletImpl(pageletRenderer);
      pagelet.setContent(resource);

      // Add the pagelet's data
      for (ResourceMetadata<?> metadata : resourceItem.getMetadata()) {
        String key = metadata.getName();
        if (metadata.isLocalized()) {
          for (Entry<Language, ?> localizedMetadata : metadata.getLocalizedValues().entrySet()) {
            Language language = localizedMetadata.getKey();
            List<Object> values = (List<Object>) localizedMetadata.getValue();
            for (Object value : values) {
              pagelet.setContent(key, value.toString(), language);
            }
          }
        } else {
          for (Object value : metadata.getValues()) {
            pagelet.addProperty(key, value.toString());
          }
        }
      }

      // TODO: Set modified etc.

      // Store the pagelet in the page
      page.addPagelet(pagelet, stage);
    }

    // Search results are not being cached
    // TODO: Implement caching strategy
    response.setCacheExpirationTime(0);
View Full Code Here

   */
  protected Page getTargetPage(WebloungeRequest request)
      throws ContentRepositoryException {

    ResourceURI target = null;
    Page page = null;
    Site site = request.getSite();
    boolean targetForced = false;

    // Check if a target-page parameter was passed
    String targetPage = request.getParameter(HTMLAction.TARGET_PAGE);
View Full Code Here

    ResourceURI liveOnlyURI = new PageURIImpl(site, "/liveonly", LIVE);
    ResourceURI liveAndWorkLiveURI = new PageURIImpl(site, "/liveandwork", LIVE);
    ResourceURI liveAndWorkWorkURI = new PageURIImpl(site, "/liveandwork", WORK);
    ResourceURI workOnlyURI = new PageURIImpl(site, "/workonly", WORK);

    Page liveOnly = new PageImpl(liveOnlyURI);
    liveOnly.setTemplate(template.getIdentifier());
    Page liveAndWorkLive = new PageImpl(liveAndWorkLiveURI);
    liveAndWorkLive.setTemplate(template.getIdentifier());
    Page liveAndWorkWork = new PageImpl(liveAndWorkWorkURI);
    liveAndWorkWork.setTemplate(template.getIdentifier());
    Page workOnly = new PageImpl(workOnlyURI);
    workOnly.setTemplate(template.getIdentifier());

    // Add the live only live page
    repository.put(liveOnly);
    assertEquals(0, repository.find(workOnlyQuery).getDocumentCount());
    assertEquals(1, repository.find(liveOnlyQuery).getDocumentCount());
View Full Code Here

      SearchResultItem item = result.getItems()[limit - 1];
      limit--;

      // Get the page
      PageSearchResultItem pageItem = (PageSearchResultItem) item;
      Page page = pageItem.getPage();

      // TODO: Can the page be accessed?

      // Set the page's language to the feed language
      page.switchTo(language);

      // Tag the cache entry
      response.addTag(CacheTag.Resource, page.getIdentifier());

      // If this is to become the most recent entry, let's set the feed's
      // modification date to be that of this entry
      if (entries.size() == 0) {
        feed.setPublishedDate(page.getPublishFrom());
      }

      // Create the entry
      SyndEntry entry = new SyndEntryImpl();
      entry.setPublishedDate(page.getPublishFrom());
      entry.setLink(site.getHostname(request.getEnvironment()).toExternalForm() + item.getUrl().getLink());
      entry.setAuthor(page.getCreator().getName());
      entry.setTitle(page.getTitle());

      // Categories
      if (page.getSubjects().length > 0) {
        List<SyndCategory> categories = new ArrayList<SyndCategory>();
        for (String subject : page.getSubjects()) {
          SyndCategory category = new SyndCategoryImpl();
          category.setName(subject);
          categories.add(category);
        }
        entry.setCategories(categories);
      }

      // TODO: Can the page be accessed?

      // Try to render the preview pagelets and write them to the feed
      List<SyndContent> entryContent = new ArrayList<SyndContent>();
      Composer composer = new ComposerImpl("preview", page.getPreview());

      for (Pagelet pagelet : composer.getPagelets()) {
        Module module = site.getModule(pagelet.getModule());
        PageletRenderer renderer = null;
        if (module == null) {
View Full Code Here

        response.invalidate();
        return SKIP_BODY;
      }
     
      ResourceURI pageURI = new PageURIImpl(request.getSite(), null, resourceid);
      Page page = (Page) repository.get(pageURI);
      if (page == null) {
        logger.warn("Unable to link to non-existing page {}", pageURI);
        return SKIP_BODY;
      }

      // Add cache tag
      response.addTag(CacheTag.Resource, page.getURI().getIdentifier());
      response.addTag(CacheTag.Url, page.getURI().getPath());
     
      // Adjust modification date
      response.setModificationDate(page.getLastModified());

      String link = page.getURI().getPath();

      // anchor
      if (anchor != null && anchor.length() > 0)
        link += "#" + anchor;
View Full Code Here

      return;
    }

    // What are we looking at?
    ContentRepository repository = site.getContentRepository();
    Page page = null;

    // Is it a page?
    try {
      String objectId = args[0];
      // TODO: What if we hit a file or an image?
      if (objectId.startsWith("/"))
        page = (Page) repository.get(new PageURIImpl(site, args[0]));
      else
        page = (Page) repository.get(new PageURIImpl(site, null, args[0]));
      if (page != null) {
        title("page");
        pad("id", page.getURI().getIdentifier().toString());
        pad("path", page.getURI().getPath());

        section("lifecycle");

        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG);

        // Created
        if (page.getCreationDate() != null) {
          StringBuffer buf = new StringBuffer();
          buf.append(df.format(page.getCreationDate()));
          if (page.getCreator() != null) {
            buf.append(" by ").append(page.getCreator().toString());
          }
          pad("created", buf.toString());
        }

        // Modified
        if (page.getModificationDate() != null) {
          StringBuffer buf = new StringBuffer();
          buf.append(df.format(page.getModificationDate()));
          if (page.getModifier() != null) {
            buf.append(" by ").append(page.getModifier().toString());
          }
          pad("modified", buf.toString());
        }

        // Published
        if (page.getPublishFrom() != null) {
          StringBuffer buf = new StringBuffer();
          buf.append(df.format(page.getPublishFrom()));
          if (page.getPublisher() != null) {
            buf.append(" by ").append(page.getPublisher().toString());
          }
          pad("published", buf.toString());
          if (page.getPublishTo() != null)
            pad("published until", df.format(page.getPublishTo()));
        }

        section("header");

        if (page.getTitle() != null)
          pad("title", page.getTitle());

        // subjects
        StringBuffer subjectList = new StringBuffer();
        for (String c : page.getSubjects()) {
          if (subjectList.length() > 0)
            subjectList.append(", ");
          subjectList.append(c);
        }
        pad("subjects", subjectList.toString());

        section("content");

        // composers
        StringBuffer composerList = new StringBuffer();
        for (Composer c : page.getComposers()) {
          if (composerList.length() > 0)
            composerList.append(", ");
          composerList.append(c.getIdentifier());
          composerList.append(" (").append(c.getPagelets().length).append(")");
        }
View Full Code Here

        break;
      default:
        environment = STEAL_PRODUCTION;
    }

    Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);

    // Add the current path to header for the editor
    response.addHeader("path", page.getPath());

    try {
      pageContext.getOut().write("<script> window.currentLanguage = '" + request.getLanguage().getIdentifier() + "';");
      pageContext.getOut().write("window.currentPagePath = '" + page.getPath() + "';</script>");
      pageContext.getOut().write(String.format(WORKBENCH_SCRIPT, workbenchPath, environment));
    } catch (IOException e) {
      throw new JspException(e);
    }
  }
View Full Code Here

      request.setMethod(site.getHostname(environment).getURL().getProtocol());
      request.setServletPath("");

      // Prepare a fake page in order to prevent erratic behavior during
      // precompilation
      Page page = new MockPageImpl(site);
      Pagelet pagelet = null;
      for (Module m : site.getModules()) {
        if (m.getRenderers().length > 0) {
          PageletRenderer r = m.getRenderers()[0];
          PageletURI pageletURI = new PageletURIImpl(page.getURI(), PageTemplate.DEFAULT_STAGE, 0);
          pagelet = new PageletImpl(pageletURI, m.getIdentifier(), r.getIdentifier());
        }
      }

      // Collect all renderers from modules and ask for precompilation
      List<URL> rendererUrls = new ArrayList<URL>();
      for (Module m : site.getModules()) {
        if (!m.isEnabled())
          break;
        for (PageletRenderer p : m.getRenderers()) {
          if (p.getRenderer() != null)
            rendererUrls.add(p.getRenderer());
          if (p.getRenderer(RendererType.Feed.name()) != null)
            rendererUrls.add(p.getRenderer(RendererType.Feed.name()));
          if (p.getRenderer(RendererType.Search.name()) != null)
            rendererUrls.add(p.getRenderer(RendererType.Search.name()));
          if (p.getEditor() != null)
            rendererUrls.add(p.getEditor());
        }
      }

      // Collect all site templates and ask for precompilation
      for (PageTemplate t : site.getTemplates()) {
        if (t.getRenderer() != null)
          rendererUrls.add(t.getRenderer());
      }

      if (rendererUrls.size() < 1) {
        logger.debug("No java server pages found to precompile for {}", site);
        return;
      }

      // Make sure there is a user
      security.setUser(new Guest(site.getIdentifier()));
      security.setSite(site);

      logger.info("Precompiling java server pages for '{}'", site);
      int errorCount = 0;
      Iterator<URL> rendererIterator = rendererUrls.iterator();
      while (keepGoing && rendererIterator.hasNext()) {
        MockHttpServletResponse response = new MockHttpServletResponse();
        URL entry = rendererIterator.next();
        String path = entry.getPath();
        String pathInfo = path.substring(path.indexOf(site.getIdentifier()) + site.getIdentifier().length());
        request.setPathInfo(pathInfo);
        request.setRequestURI(pathInfo);
        request.setAttribute(WebloungeRequest.PAGE, page);
        request.setAttribute(WebloungeRequest.COMPOSER, page.getComposer(PageTemplate.DEFAULT_STAGE));
        if (pagelet != null)
          request.setAttribute(WebloungeRequest.PAGELET, pagelet);

        try {
          logger.debug("Precompiling {}:/{}", site, pathInfo);
View Full Code Here

TOP

Related Classes of ch.entwine.weblounge.common.content.page.Page

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.