/**
   * Keep track of invalid cache paths to later inform cluster to invalidate the given paths from
   * caches.
   *
   * @param path ModelObject storage path
   */
  private void addInvalidCachePath(final String path) {
    if (logger.isDebugEnabled()) logger.debug("Adding invalid cache path: " + path);

    RequestContext rc = ThreadLocalRequestContext.getRequestContext();
    if (!(rc instanceof ClusterAwareRequestContext)) {
      throw new IllegalStateException(
          "Incorrect Share cluster configuration detected - ClusterAwareRequestContextFactory is required.");
    }
    ((ClusterAwareRequestContext) rc).addInvalidCachePath(path);
  }
Exemplo n.º 2
0
  /**
   * Constructs a new <code>PageView</code> object using and sets it's URL to the current view name
   * providing that a <code>Page</code> object is stored on the current <code>RequestContext</code>
   * object.
   *
   * @param viewName The name of the view to build.
   */
  @Override
  protected AbstractUrlBasedView buildView(String viewName) {
    PageView view = null;
    Page page = ThreadLocalRequestContext.getRequestContext().getPage();
    if (page != null) {
      view =
          new AikauPageView(
              getWebframeworkConfigElement(),
              getModelObjectService(),
              getWebFrameworkResourceService(),
              getWebFrameworkRenderService(),
              getTemplatesContainer());
      view.setUrl(viewName);
      view.setPage(page);
      view.setUriTokens(ThreadLocalRequestContext.getRequestContext().getUriTokens());
      view.setUrlHelperFactory(getUrlHelperFactory());
    }

    return view;
  }
Exemplo n.º 3
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.º 4
0
 @Override
 protected Page lookupPage(String pageId) {
   if (ThreadLocalRequestContext.getRequestContext().getUser() == null) {
     HttpServletRequest req = AikauAuthenticationFilter.getCurrentServletRequest();
     if (req != null) {
       try {
         // init the request user context if the thread local is found containing the
         // servlet request information - this ensures an authenticated Connector is
         // used when makes a remote call to resolve the Page from the view name
         RequestContextUtil.initRequestContext(getApplicationContext(), req);
       } catch (RequestContextException e) {
         throw new PlatformRuntimeException(
             "Failed to init Request Context: " + e.getMessage(), e);
       }
     }
   }
   // see if a page has been set-up already - @see UserDashboardInterceptor
   Page page = ThreadLocalRequestContext.getRequestContext().getPage();
   if (page != null) {
     return page;
   }
   return super.lookupPage(pageId);
 }
  /**
   * Thread-safe get of the singleton value. Can be optionally stored per tenant based on user Id.
   *
   * @param tenant True to get/store per tenant, false for a single value for all repo instances.
   * @return singleton value, optionally per tenant.
   */
  protected final T getSingletonValue(final boolean tenant) {
    T result;

    final String userId = ThreadLocalRequestContext.getRequestContext().getUserId();
    final String storeId = tenant ? getTenantUserStore(userId) : "";

    // NOTE: currently there is a single RRW lock for all values -
    // in a heavily multi-tenant scenario (especially ones with new tenants
    // being created often) the first access of a new tenant dictionary would
    // potentially slow other tenant users access to their dictionary.
    // In this situation a lock per tenant would be preferable.
    this.lock.readLock().lock();
    try {
      result = storeValues.get(storeId);
      if (result == null) {
        this.lock.readLock().unlock();
        this.lock.writeLock().lock();
        try {
          // check again, as more than one thread could have been waiting on the Write lock
          result = storeValues.get(storeId);
          if (result == null) {
            // call the retrieve implementation - probably going to do a remote call or similar
            result = retrieveValue(userId, storeId);

            // store result against the current store i.e. tenant
            storeValues.put(storeId, result);
          }
        } catch (ConnectorServiceException cerr) {
          throw new AlfrescoRuntimeException(
              "Unable to retrieve "
                  + getValueName()
                  + " configuration from Alfresco: "
                  + cerr.getMessage());
        } catch (Exception err) {
          throw new AlfrescoRuntimeException(
              "Failed during processing of "
                  + getValueName()
                  + " configuration from Alfresco: "
                  + err.getMessage());
        } finally {
          this.lock.readLock().lock();
          this.lock.writeLock().unlock();
        }
      }
    } finally {
      this.lock.readLock().unlock();
    }

    return result;
  }
Exemplo n.º 6
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.º 7
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;
  }
  /**
   * 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;
  }