Exemplo n.º 1
0
  /* (non-Javadoc)
   * @see org.springframework.extensions.surf.mvc.AbstractWebFrameworkView#validateRequestContext(org.springframework.extensions.surf.RequestContext, javax.servlet.http.HttpServletRequest)
   */
  @Override
  protected void validateRequestContext(RequestContext rc, HttpServletRequest req)
      throws Exception {
    super.validateRequestContext(rc, req);

    String themeId = null;

    // test to see if this is a site page
    String siteId = rc.getUriTokens().get("site");
    if (siteId != null) {
      // find the site dashboard page - and look for a theme override
      Page dashboard = getObjectService().getPage("site/" + siteId + "/dashboard");
      if (dashboard != null) {
        themeId = dashboard.getProperty("theme");
      }
    } else {
      // examine current page directly for custom properties with a theme override
      // this allows a different theme per page
      themeId = rc.getPage().getProperty("theme");
    }

    // if themeId different to current theme then look it up
    if (themeId != null && themeId.length() != 0 && !rc.getThemeId().equals(themeId)) {
      Theme theme = getObjectService().getTheme(themeId);
      if (theme != null) {
        // found a valid theme - set it current ready for page rendering
        rc.setTheme(theme);
      }
    }
  }
Exemplo n.º 2
0
  @Override
  public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    Writer writer = null;
    try {
      writer = res.getWriter();

      // Get the section placed in the request context by ApplicationDataInterceptor
      RequestContext requestContext = ThreadLocalRequestContext.getRequestContext();
      Section section = (Section) requestContext.getValue("section");
      WebSite webSite = (WebSite) requestContext.getValue("webSite");

      // Get the collection property from the page definition
      String collectionName = requestContext.getPage().getProperty("collection");
      if (collectionName == null)
        throw new WebScriptException("collectionName property must be supplied");

      // Fetch the named collection
      AssetCollection collection =
          (AssetCollection) collectionFactory.getCollection(section.getId(), collectionName);

      // Use ROME library to output the colleciton as a syndication feed
      SyndFeed feed = new SyndFeedImpl();
      feed.setFeedType(FEED_TYPE);

      feed.setTitle(section.getTitle());
      feed.setLink(urlUtils.getWebsiteDomain(webSite) + urlUtils.getUrl(section));
      feed.setDescription(section.getDescription());

      List<SyndEntry> entries = new ArrayList<SyndEntry>();
      for (Asset asset : collection.getAssets()) {
        SyndEntry entry = new SyndEntryImpl();
        entry.setTitle(asset.getTitle());
        entry.setLink(urlUtils.getWebsiteDomain(webSite) + urlUtils.getUrl(asset));
        entry.setUri(urlUtils.getWebsiteDomain(webSite) + urlUtils.getShortUrl(asset));
        entry.setPublishedDate((Date) asset.getProperties().get(Asset.PROPERTY_PUBLISHED_TIME));
        SyndContent description = new SyndContentImpl();
        description.setType("text/html");
        description.setValue(asset.getDescription());
        entry.setDescription(description);
        entries.add(entry);
      }
      feed.setEntries(entries);

      SyndFeedOutput output = new SyndFeedOutput();
      output.output(feed, writer);
      writer.flush();
    } catch (IOException e) {
      log.error("Unable to output rss", e);
    } catch (FeedException e) {
      log.error("Unable to output rss", e);
    }
  }
Exemplo n.º 3
0
 @Override
 public String toString() {
   try {
     String out = "";
     final RequestContext rc = ThreadLocalRequestContext.getRequestContext();
     final String userId = rc.getUserId();
     if (userId != null && !AuthenticationUtil.isGuest(userId)) {
       int idx = userId.indexOf('@');
       if (idx != -1) {
         out = "Mimetypes for user domain: " + userId.substring(idx) + "\r\n";
       }
     }
     return out + getMimetypes().toString();
   } catch (Throwable e) {
     return super.toString();
   }
 }
Exemplo n.º 4
0
  @Override
  protected Map<String, Mimetype> retrieveValue(final String userId, final String storeId)
      throws ConnectorServiceException {
    Map<String, Mimetype> mimetypes;

    // initiate a call to retrieve the dictionary from the repository
    final RequestContext rc = ThreadLocalRequestContext.getRequestContext();
    final Connector conn =
        rc.getServiceRegistry()
            .getConnectorService()
            .getConnector("alfresco", userId, ServletUtil.getSession());
    final Response response = conn.call("/api/mimetypes/descriptions");
    if (response.getStatus().getCode() == Status.STATUS_OK) {
      logger.info("Successfully retrieved mimetypes information from Alfresco.");

      mimetypes = new HashMap<String, Mimetype>(128);

      try {
        // Extract mimetype information
        final JSONObject json = new JSONObject(response.getResponse());
        final JSONObject data = json.getJSONObject("data");

        Iterator<String> types = data.keys();
        while (types.hasNext()) {
          // The type is the key
          String mimetype = types.next();

          // The details come from the value
          Mimetype details = new Mimetype(mimetype, data.getJSONObject(mimetype));

          mimetypes.put(mimetype, details);
        }
      } catch (JSONException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      }
    } else {
      throw new AlfrescoRuntimeException(
          "Unable to retrieve mimetypes information from Alfresco: "
              + response.getStatus().getCode());
    }

    return mimetypes;
  }
Exemplo n.º 5
0
  /**
   * Gets the remote config.
   *
   * @return the remote config
   */
  private RemoteConfigElement getRemoteConfig(RequestContext context) {
    if (this.config == null) {
      // retrieve the remote configuration
      this.config =
          (RemoteConfigElement)
              context
                  .getServiceRegistry()
                  .getConfigService()
                  .getConfig("Remote")
                  .getConfigElement("remote");
    }

    return this.config;
  }
Exemplo n.º 6
0
  /* (non-Javadoc)
   * @see org.springframework.extensions.surf.mvc.AbstractWebFrameworkView#renderView(org.springframework.extensions.surf.render.RequestContext)
   */
  protected void renderView(RequestContext context) throws Exception {
    // this method assumes that the uri tokens have already been processed through the
    // uri template mappings.
    //
    // the tokens are represented by:
    //
    //    <mode>/<focus>/<scopeId>/<regionId>/<sourceId>

    // tokens
    Map<String, String> uriTokens = getUriTokens();
    String mode = uriTokens.get(MODE);
    String focus = uriTokens.get(FOCUS);
    String scopeId = uriTokens.get(SCOPE_ID);
    String regionId = uriTokens.get(REGION_ID);
    String sourceId = uriTokens.get(SOURCE_ID);

    // defaults
    if (scopeId == null) {
      scopeId = REGION_SCOPE_GLOBAL;
    }
    if (sourceId == null) {
      sourceId = REGION_SCOPE_GLOBAL;
    }

    // the region id always has to be provided
    if (regionId == null) {
      throw new RequestDispatchException("Region ID is missing");
    }

    // determine the render attributes
    RenderMode renderMode = RenderMode.VIEW;
    if (mode != null) {
      renderMode = RenderMode.valueOf(mode.toUpperCase());
    }

    RenderFocus renderFocus = RenderFocus.BODY;
    if (focus != null) {
      renderFocus = RenderFocus.valueOf(focus.toUpperCase());
    }

    // create the component id
    String componentId = RenderUtil.generateComponentId(scopeId, regionId, sourceId);

    // determine the valid component id
    Component component = getObjectService().getComponent(componentId);
    if (component == null) {
      if (componentId.startsWith("/")) {
        // try taking the "/" off the front
        component = getObjectService().getComponent(componentId.substring(1));
      } else {
        // try adding a "/" to the front
        component = getObjectService().getComponent("/" + componentId);
      }
    }

    // set the render mode
    context.setRenderMode(renderMode);

    // do the render of the component
    getRenderService().renderComponent(context, renderFocus, component, null, false);
  }
Exemplo n.º 7
0
  @Override
  protected boolean loginRequiredForPage(
      RequestContext context, HttpServletRequest request, Page page) {
    boolean externalAuth = false;
    EndpointDescriptor descriptor =
        getRemoteConfig(context).getEndpointDescriptor(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
    if (descriptor != null) {
      externalAuth = descriptor.getExternalAuth();
    }

    boolean login = false;
    User user = context.getUser();
    switch (page.getAuthentication()) {
      case guest:
        {
          login = (user == null);
          break;
        }

        // Enhanced test over the super class implementation - to check that the user has
        // credentials to
        // use the default "alfresco" endpoint - ensures that say a user ID is in the session from
        // access to an RSS feed endpoint, they are not given permission to proceed until after a
        // full login
      case user:
        {
          try {
            login =
                (user == null || AuthenticationUtil.isGuest(user.getId()))
                    || (!context
                            .getServiceRegistry()
                            .getConnectorService()
                            .getCredentialVault(request.getSession(), user.getId())
                            .hasCredentials(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID)
                        && externalAuth == false);
          } catch (CredentialVaultProviderException err) {
            throw new PlatformRuntimeException(
                "Unable to retrieve credentials for current user.", err);
          }
          break;
        }

      case admin:
        {
          try {
            login =
                (user == null || !user.isAdmin())
                    || (!context
                            .getServiceRegistry()
                            .getConnectorService()
                            .getCredentialVault(request.getSession(), user.getId())
                            .hasCredentials(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID)
                        && externalAuth == false);
          } catch (CredentialVaultProviderException err) {
            throw new PlatformRuntimeException(
                "Unable to retrieve credentials for current user.", err);
          }
          if (login) {
            // special case for admin - need to clear user context before
            // we can login again to "upgrade" our user authentication level
            AuthenticationUtil.clearUserContext(request);
          }
          break;
        }
    }
    return login;
  }
  /**
   * Checks for the existence of a resource on a remote store
   *
   * @param context the request context
   * @param request http servlet request
   * @param response http servlet response
   * @param path the path to the asset
   * @param endpointId the endpoint where the resource lives
   * @param storeId the store within which the resource lives
   * @param webappId the web application that the resource lives in
   * @return boolean
   * @throws ServletException
   * @throws IOException
   */
  public boolean checkRemoteResourceExists(
      RequestContext context,
      HttpServletRequest request,
      HttpServletResponse response,
      String path,
      String endpointId,
      String storeId,
      String webappId)
      throws ServletException, IOException {
    boolean exists = false;

    // default treatment of these fellows
    if (endpointId == null) {
      endpointId = this.remoteConfig.getDefaultEndpointId();
    }
    if (storeId != null) {
      // use the currently bound request context store id
      storeId =
          context
              .getServiceRegistry()
              .getObjectPersistenceService()
              .getPersistenceContext()
              .getStoreId();
    }
    if (webappId == null) {
      // use the currently bound request context web app id
      webappId =
          context
              .getServiceRegistry()
              .getObjectPersistenceService()
              .getPersistenceContext()
              .getWebappId();
    }

    // build a URL to the endpoint proxy servlet
    StringBuilder fb = new StringBuilder(128);
    fb.append(request.getServletPath());
    fb.append("/endpoint/");
    fb.append(endpointId);
    fb.append("/avmstore/has/s/");
    fb.append(storeId);
    fb.append("/w/");
    fb.append(webappId);

    if (!path.startsWith("/")) {
      fb.append("/");
    }
    fb.append(path);

    String newUri = fb.toString();

    if (logger.isDebugEnabled()) logger.debug("Formed virtual retrieval path: " + newUri);

    // build some wrapper objects so that we can dispatch to endpoint proxy servlet
    // this means that we can avoid building connectors by hand
    WrappedHttpServletRequest wrappedRequest = new WrappedHttpServletRequest(request);
    WrappedHttpServletResponse wrappedResponse = new WrappedHttpServletResponse(response);

    // dispatch to the endpoint proxy servlet
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(newUri);
    dispatcher.include(wrappedRequest, wrappedResponse);

    // check whether the resource exists
    String result = wrappedResponse.getOutput();
    if ("true".equalsIgnoreCase(result)) {
      exists = true;
    }

    return exists;
  }
  /**
   * Retrieves content from the given remote store and streams back to the response
   *
   * @param request http servlet request
   * @param response http servlet response
   * @param path the path to be included
   * @param endpointId the endpoint to utilize (optional)
   * @param storeId the store to utilize (optional)
   * @param webappId the webapp to utilize (optional)
   * @return whether the resource was served back successfully
   */
  public boolean retrieveRemoteResource(
      HttpServletRequest request,
      HttpServletResponse response,
      String path,
      String endpointId,
      String storeId,
      String webappId)
      throws ServletException, IOException {
    boolean resolved = false;

    // get the request context
    RequestContext context = ThreadLocalRequestContext.getRequestContext();

    // default treatment of these fellows
    if (endpointId == null) {
      endpointId = this.remoteConfig.getDefaultEndpointId();
    }
    if (storeId != null) {
      // use the currently bound request context store id
      storeId =
          context
              .getServiceRegistry()
              .getObjectPersistenceService()
              .getPersistenceContext()
              .getStoreId();
    }
    if (webappId == null) {
      // use the currently bound request context web app id
      webappId =
          context
              .getServiceRegistry()
              .getObjectPersistenceService()
              .getPersistenceContext()
              .getWebappId();
    }

    // check whether the resource exists on the remote store
    // TODO: this is expensive... is this the cost of preview-able virtualized remote retrieval?
    // TODO: ideally, we could hold a cache and have the authoring server notify test servers of
    // changes, but that will require more investigation
    boolean exists =
        checkRemoteResourceExists(context, request, response, path, endpointId, storeId, webappId);
    if (exists) {
      // build a URL to the endpoint proxy servlet
      StringBuilder fb = new StringBuilder(128);
      fb.append(request.getServletPath());
      fb.append("/endpoint/");
      fb.append(endpointId);
      fb.append("/avmstore/get/s/");
      fb.append(storeId);
      fb.append("/w/");
      fb.append(webappId);

      if (!path.startsWith("/")) {
        fb.append("/");
      }
      fb.append(path);

      String newUri = fb.toString();

      if (logger.isDebugEnabled()) logger.debug("Formed virtual retrieval path: " + newUri);

      // make sure the request uri is properly established so that we can
      // flow through the proxy servlet
      if (request instanceof WrappedHttpServletRequest) {
        ((WrappedHttpServletRequest) request).setRequestURI(request.getContextPath() + newUri);
      }

      // dispatch to the endpoint proxy servlet
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(newUri);
      dispatcher.include(request, response);

      resolved = true;
    }

    return resolved;
  }