Package org.apache.shindig.protocol

Examples of org.apache.shindig.protocol.ProtocolException


        }
      }
      Collections.sort(result, Collections.reverseOrder());
      return ImmediateFuture.newInstance(new RestfulCollection<ActivityEntry>(result));
    } catch (JSONException je) {
      throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, je.getMessage(), je);
    }
  }
View Full Code Here


              found = true;
              break;
            }
          }
          if (!found) {
            throw new ProtocolException(HttpServletResponse.SC_NOT_FOUND, "Activity not found: " + activityId);
          }
        }
      }
      Collections.sort(result, Collections.reverseOrder());
      return ImmediateFuture.newInstance(new RestfulCollection<ActivityEntry>(result));
    } catch (JSONException je) {
      throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, je.getMessage(), je);
    }
  }
View Full Code Here

    return execute("HEAD", httpReq, request);
  }

  private void assertNoBody(HttpApiRequest httpRequest, String method) {
    if (httpRequest.body != null) {
      throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
         "Request body not supported for " + method);
    }
  }
View Full Code Here

   * @param requestItem TODO
   */
  private HttpApiResponse execute(String method, HttpApiRequest httpApiRequest,
      final BaseRequestItem requestItem) {
    if (httpApiRequest.href == null) {
      throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "href parameter is missing");
    }

    // Canonicalize the path
    Uri href = normalizeUrl(httpApiRequest.href);
    try {
      HttpRequest req = new HttpRequest(href);
      req.setMethod(method);
      if (httpApiRequest.body != null) {
        req.setPostBody(httpApiRequest.body.getBytes());
      }

      // Copy over allowed headers
      for (Map.Entry<String, List<String>> header : httpApiRequest.headers.entrySet()) {
        if (!BAD_HEADERS.contains(header.getKey().trim().toUpperCase())) {
          for (String value : header.getValue()) {
            req.addHeader(header.getKey(), value);
          }
        }
      }

      // Extract the gadget URI from the request or the security token
      final Uri gadgetUri = getGadgetUri(requestItem.getToken(), httpApiRequest);
      if (gadgetUri == null) {
        throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
            "Gadget URI not specified in request");
      }
      req.setGadget(gadgetUri);

      // Detect the authz parsing
      if (httpApiRequest.authz != null) {
        req.setAuthType(AuthType.parse(httpApiRequest.authz));
      }

      final AuthType authType = req.getAuthType();
      if (authType != AuthType.NONE) {
        if (authType == AuthType.OAUTH2) {
          req.setSecurityToken(requestItem.getToken());

          Map<String, String> authSettings = getAuthSettings(requestItem);
          OAuth2Arguments oauth2Args = new OAuth2Arguments(req.getAuthType(), authSettings);

          req.setOAuth2Arguments(oauth2Args);
        } else {
          req.setSecurityToken(requestItem.getToken());

          Map<String, String> authSettings = getAuthSettings(requestItem);
          OAuthArguments oauthArgs = new OAuthArguments(req.getAuthType(), authSettings);
          oauthArgs.setSignOwner(httpApiRequest.signOwner);
          oauthArgs.setSignViewer(httpApiRequest.signViewer);

          req.setOAuthArguments(oauthArgs);
        }
      }

      // TODO: Allow the rewriter to use an externally forced mime type. This is needed
      // allows proper rewriting of <script src="x"/> where x is returned with
      // a content type like text/html which unfortunately happens all too often

      req.setIgnoreCache(httpApiRequest.noCache);
      req.setSanitizationRequested(httpApiRequest.sanitize);

      // If the proxy request specifies a refresh param then we want to force the min TTL for
      // the retrieved entry in the cache regardless of the headers on the content when it
      // is fetched from the original source.
      if (httpApiRequest.refreshInterval != null) {
        req.setCacheTtl(httpApiRequest.refreshInterval);
      }

      final HttpRequest request = req;
      HttpResponse results = requestPipeline.execute(req);
      GadgetContext context = new GadgetContext() {
        @Override
        public Uri getUrl() {
          return gadgetUri;
        }

        @Override
        public String getParameter(String key) {
          return request.getParam(key);
        }

        @Override
        public boolean getIgnoreCache() {
          return request.getIgnoreCache();
        }

        @Override
        public String getContainer() {
          return requestItem.getToken().getContainer();
        }

        @Override
        public boolean getDebug() {
          return "1".equalsIgnoreCase(getParameter(Param.DEBUG.getKey()));
        }
      };
      // TODO: os:HttpRequest and Preload do not use the content rewriter.
      // Should we really do so here?
      try {
        Gadget gadget = processor.process(context);
        results = contentRewriterRegistry.rewriteHttpResponse(req, results, gadget);
      } catch (ProcessingException e) {
        //If there is an error creating the gadget object just rewrite the content without
        //the gadget object.  This will result in any content rewrite params not being
        //honored, but its better than the request failing all together.
        if(LOG.isLoggable(Level.WARNING)) {
          LOG.logp(Level.WARNING, CLASSNAME, "execute", MessageKeys.GADGET_CREATION_ERROR, e);
        }
        results = contentRewriterRegistry.rewriteHttpResponse(req, results, null);
      }

      HttpApiResponse httpApiResponse = new HttpApiResponse(results,
          transformBody(httpApiRequest, results),
          httpApiRequest);

      // Renew the security token if we can
      if (requestItem.getToken() != null) {
        String updatedAuthToken = requestItem.getToken().getUpdatedToken();
        if (updatedAuthToken != null) {
          httpApiResponse.token = updatedAuthToken;
        }
      }
      return httpApiResponse;
    } catch (GadgetException ge) {
      throw new ProtocolException(ge.getHttpStatusCode(), ge.getMessage(), ge);
    } catch (RewritingException re) {
      throw new ProtocolException(re.getHttpStatusCode(),
          re.getMessage(), re);
    }
  }
View Full Code Here

        } else {
          return new JSONObject(body);
        }
      } catch (JSONException e) {
        // TODO: include data block with invalid JSON
        throw new ProtocolException(HttpServletResponse.SC_NOT_ACCEPTABLE, "Response not valid JSON", e);
      }
    }

    return body;
  }
View Full Code Here

  @Operation(httpMethods = {"POST","GET"}, path = "/invalidate")
  public void invalidate(BaseRequestItem request) {
    if (StringUtils.isEmpty(request.getToken().getAppId()) &&
        StringUtils.isEmpty(request.getToken().getAppUrl())) {
      throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
          "Cannot invalidate content without specifying application");
    }

    // Is the invalidation call from the application backend. If not we don't allow
    // invalidation of resources or users other than @viewer
    boolean isBackendInvalidation = AuthenticationMode.OAUTH_CONSUMER_REQUEST.name().equals(
        request.getToken().getAuthenticationMode());

    List<String> keys = request.getListParameter(KEYS_PARAM);
    Set<String> userIds = Sets.newHashSet();
    Set<Uri> resources = Sets.newHashSet();

    // Assume the the viewer content is being invalidated if it is available
    if (!StringUtils.isEmpty(request.getToken().getViewerId())) {
      userIds.add(request.getToken().getViewerId());
    }
    if (keys != null) {
      for (String key : keys) {
        String lowerKey = key.toLowerCase();
        if (lowerKey.startsWith("http")) {
          // Assume key is a gadget spec, message bundle or other resource
          // owned by the gadget
          if (!isBackendInvalidation) {
            throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
                "Cannot flush application resources from a gadget. " +
                    "Must use OAuth consumer request");
          }
          resources.add(Uri.parse(key));
        } else {
          if (key.equals("@viewer")) {
            // Viewer is invalidated by default if available
            continue;
          }
          if (!isBackendInvalidation && !key.equals(request.getToken().getViewerId())) {
            throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
                "Cannot invalidate the content for a user other than the viewer from a gadget.");
          }
          userIds.add(key);
        }
      }
View Full Code Here

    return execute("HEAD", httpReq, request);
  }

  private void assertNoBody(HttpApiRequest httpRequest, String method) {
    if (httpRequest.body != null) {
      throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
         "Request body not supported for " + method);
    }
  }
View Full Code Here

   * @param requestItem TODO
   */
  private HttpApiResponse execute(String method, HttpApiRequest httpApiRequest,
      BaseRequestItem requestItem) {
    if (httpApiRequest.href == null) {
      throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "href parameter is missing");
    }

    // Canonicalize the path
    Uri href = normalizeUrl(httpApiRequest.href);
    try {
      HttpRequest req = new HttpRequest(href);
      req.setMethod(method);
      if (httpApiRequest.body != null) {
        req.setPostBody(httpApiRequest.body.getBytes());
      }

      // Copy over allowed headers
      for (Map.Entry<String, List<String>> header : httpApiRequest.headers.entrySet()) {
        if (!BAD_HEADERS.contains(header.getKey().trim().toUpperCase())) {
          for (String value : header.getValue()) {
            req.addHeader(header.getKey(), value);
          }
        }
      }

      // Extract the gadget URI from the request or the security token
      Uri gadgetUri = getGadgetUri(requestItem.getToken(), httpApiRequest);
      if (gadgetUri == null) {
        throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
            "Gadget URI not specified in request");
      }
      req.setGadget(gadgetUri);

      // Detect the authz parsing
      if (httpApiRequest.authz != null) {
        req.setAuthType(AuthType.parse(httpApiRequest.authz));
      }

      if (req.getAuthType() != AuthType.NONE) {
        req.setSecurityToken(requestItem.getToken());
       
        Map<String, String> authSettings = getAuthSettings(requestItem);
        OAuthArguments oauthArgs = new OAuthArguments(req.getAuthType(), authSettings);
        oauthArgs.setSignOwner(httpApiRequest.signOwner);
        oauthArgs.setSignViewer(httpApiRequest.signViewer);
       
        req.setOAuthArguments(oauthArgs);
      }

      // TODO: Allow the rewriter to use an externally forced mime type. This is needed
      // allows proper rewriting of <script src="x"/> where x is returned with
      // a content type like text/html which unfortunately happens all too often
     
      req.setIgnoreCache(httpApiRequest.noCache);
      req.setSanitizationRequested(httpApiRequest.sanitize);

      // If the proxy request specifies a refresh param then we want to force the min TTL for
      // the retrieved entry in the cache regardless of the headers on the content when it
      // is fetched from the original source.
      if (httpApiRequest.refreshInterval != null) {
        req.setCacheTtl(httpApiRequest.refreshInterval);
      }

      HttpResponse results = requestPipeline.execute(req);
      // TODO: os:HttpRequest and Preload do not use the content rewriter.
      // Should we really do so here?
      results = contentRewriterRegistry.rewriteHttpResponse(req, results);

      HttpApiResponse httpApiResponse = new HttpApiResponse(results,
          transformBody(httpApiRequest, results),
          httpApiRequest);

      // Renew the security token if we can
      if (requestItem.getToken() != null) {
        String updatedAuthToken = requestItem.getToken().getUpdatedToken();
        if (updatedAuthToken != null) {
          httpApiResponse.token = updatedAuthToken;
        }
      }
      return httpApiResponse;
    } catch (GadgetException ge) {
      throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          ge.getMessage(), ge);
    } catch (RewritingException re) {
      throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          re.getMessage(), re);
    }
  }
View Full Code Here

    } else if ("json".equalsIgnoreCase(request.format)) {
      try {
        return new JSONObject(body);
      } catch (JSONException e) {
        // TODO: include data block with invalid JSON
        throw new ProtocolException(HttpServletResponse.SC_NOT_ACCEPTABLE, "Response not valid JSON", e);
      }
    }
   
    return body;
  }
View Full Code Here

    // otherwise find where FROM keyword starts in the query string and set the fromIndex.
    if (!queryInUpperCase.startsWith("FROM ")) {
      fromIndex = queryInUpperCase.indexOf(" FROM ");
      if (fromIndex == -1) {
        // Couldn't find the FROM keyword in the query
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid query [" + query + ']');
      }
    }
    query = "select count(*) " + query.substring(fromIndex, query.length());
    Query q = createQuery(entityManager, query, parametersValues);
    return (Long) q.getSingleResult();
View Full Code Here

TOP

Related Classes of org.apache.shindig.protocol.ProtocolException

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.