@Test
  public void testPostProcessWithPaging() {
    when(page.getPageRequest()).thenReturn(pageRequest);
    when(page.getMaxRecords()).thenReturn(15);
    when(pageRequest.isPaging()).thenReturn(true);
    when(pageRequest.getPage()).thenReturn(2);
    when(pageRequest.getPerPage()).thenReturn(5);

    // We're going to take the quick path through buildBaseUrl.
    when(config.containsKey(eq(ConfigProperties.PREFIX_APIURL))).thenReturn(false);
    when(request.getRequestURL()).thenReturn(new StringBuffer("https://example.com/candlepin"));
    when(request.getQueryString()).thenReturn("order=asc&page=1&per_page=10");

    MultivaluedMap<String, Object> map = new MultivaluedMapImpl<String, Object>();
    when(response.getMetadata()).thenReturn(map);

    ResteasyProviderFactory.pushContext(Page.class, page);
    ResteasyProviderFactory.pushContext(HttpServletRequest.class, request);

    interceptor.postProcess(response);
    String header = (String) map.getFirst(LinkHeaderPostInterceptor.LINK_HEADER);

    // It would be a bit much to parse the entire header, so let's just make
    // sure that we have first, last, next, and prev links.
    assertTrue(header.contains("rel=\"first\""));
    assertTrue(header.contains("rel=\"last\""));
    assertTrue(header.contains("rel=\"next\""));
    assertTrue(header.contains("rel=\"prev\""));
  }
예제 #2
0
  /**
   * These are the expensive operations (initStandardObjects and compileReader/exec). We do them
   * once here, and define this provider as a singleton, so it's only done at provider creation or
   * whenever rules are refreshed.
   *
   * @param rulesCurator
   */
  private void compileRules(RulesCurator rulesCurator) {
    scriptLock.writeLock().lock();
    try {
      // XXX: we need a principal to access the rules,
      // but pushing and popping system principal could be a bad idea
      Principal systemPrincipal = new SystemPrincipal();
      ResteasyProviderFactory.pushContext(Principal.class, systemPrincipal);
      // Check to see if we need to recompile. we do this inside the write lock
      // just to avoid race conditions where we might double compile
      Date newUpdated = rulesCurator.getUpdated();
      if (newUpdated.equals(this.updated)) {
        return;
      }

      log.debug("Recompiling rules with timestamp: " + newUpdated);

      Context context = Context.enter();
      context.setOptimizationLevel(9);
      scope = context.initStandardObjects(null, true);
      try {
        script = context.compileString(rulesCurator.getRules().getRules(), "rules", 1, null);
        script.exec(context, scope);
        ((ScriptableObject) scope).sealObject();
        this.updated = newUpdated;
      } finally {
        Context.exit();
      }
    } finally {
      ResteasyProviderFactory.popContextData(Principal.class);
      scriptLock.writeLock().unlock();
    }
  }
 @Test
 public void testPostProcessWithNullPageRequest() {
   ResteasyProviderFactory.pushContext(Page.class, page);
   when(page.getPageRequest()).thenReturn(null);
   interceptor.postProcess(response);
   verify(page).getPageRequest();
 }
 @Test
 public void testPostProcessWithNonPagingPresentation() {
   when(page.getPageRequest()).thenReturn(pageRequest);
   when(pageRequest.isPaging()).thenReturn(false);
   ResteasyProviderFactory.pushContext(Page.class, page);
   interceptor.postProcess(response);
   verify(page, times(2)).getPageRequest();
   verify(pageRequest).isPaging();
 }
예제 #5
0
  public void service(
      ChannelHandlerContext ctx, HttpRequest request, HttpResponse response, boolean handleNotFound)
      throws IOException {

    try {
      ResteasyProviderFactory defaultInstance = ResteasyProviderFactory.getInstance();
      if (defaultInstance instanceof ThreadLocalResteasyProviderFactory) {
        ThreadLocalResteasyProviderFactory.push(providerFactory);
      }

      SecurityContext securityContext;
      if (domain != null) {
        securityContext = basicAuthentication(request, response);
        if (securityContext == null) // not authenticated
        {
          return;
        }
      } else {
        securityContext = new NettySecurityContext();
      }
      try {

        ResteasyProviderFactory.pushContext(ChannelHandlerContext.class, ctx);
        ResteasyProviderFactory.pushContext(SecurityContext.class, securityContext);
        if (handleNotFound) {
          dispatcher.invoke(request, response);
        } else {
          dispatcher.invokePropagateNotFound(request, response);
        }
      } finally {
        ResteasyProviderFactory.clearContextData();
      }
    } finally {
      ResteasyProviderFactory defaultInstance = ResteasyProviderFactory.getInstance();
      if (defaultInstance instanceof ThreadLocalResteasyProviderFactory) {
        ThreadLocalResteasyProviderFactory.pop();
      }
    }
  }
예제 #6
0
  /**
   * Interrogates the request and sets the principal for the request.
   *
   * @throws WebApplicationException when no auths result in a valid principal
   * @throws Failure when there is an unkown failure in the code
   * @return the Server Response
   */
  public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
      throws Failure, WebApplicationException {

    SecurityHole securityHole = AuthUtil.checkForSecurityHoleAnnotation(method.getMethod());

    Principal principal = null;

    if (log.isDebugEnabled()) {
      log.debug("Authentication check for " + request.getUri().getPath());
    }

    // Check for anonymous calls, and let them through
    if (securityHole != null && securityHole.anon()) {
      log.debug("Request is anonymous, adding NoAuth Principal");
      principal = new NoAuthPrincipal();
    } else {
      // This method is not anonymous, so attempt to
      // establish the identity.
      for (AuthProvider provider : providers) {
        principal = provider.getPrincipal(request);

        if (principal != null) {
          break;
        }
      }
    }

    // At this point, there is no provider that has given a valid principal,
    // so we use the NoAuthPrincipal here if it is set.
    if (principal == null) {
      if (securityHole != null && securityHole.noAuth()) {
        log.debug("No auth allowed for resource; setting NoAuth principal");
        principal = new NoAuthPrincipal();
      } else {
        throw new UnauthorizedException("Invalid credentials.");
      }
    }

    // Expose the principal for Resteasy to inject via @Context
    ResteasyProviderFactory.pushContext(Principal.class, principal);

    if (principal instanceof ConsumerPrincipal) {
      // HACK: We need to do this after the principal has been pushed,
      // lest our security settings start getting upset when we try to
      // update a consumer without any roles:
      ConsumerPrincipal p = (ConsumerPrincipal) principal;
      consumerCurator.updateLastCheckin(p.getConsumer());
    }

    return null;
  }
예제 #7
0
  @Override
  public void onEvent(Event event) {
    // We're outside of a web request here, need to create this event and satisfy the
    // access control interceptor.
    Principal systemPrincipal = new SystemPrincipal();
    ResteasyProviderFactory.pushContext(Principal.class, systemPrincipal);
    if (log.isDebugEnabled()) {
      log.debug("Received event: " + event);
    }

    if (event != null) {
      eventCurator.create(event);
    }
  }
  @Override
  public void doFilter(final ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    ResteasyProviderFactory.pushContext(
        ClientConnection.class,
        new ClientConnection() {
          @Override
          public String getRemoteAddr() {
            return request.getRemoteAddr();
          }

          @Override
          public String getRemoteHost() {
            return request.getRemoteHost();
          }

          @Override
          public int getReportPort() {
            return request.getRemotePort();
          }
        });
    chain.doFilter(request, response);
  }
 public void enter() {
   ResteasyProviderFactory.pushContext(
       CandlepinSingletonScopeData.class, new CandlepinSingletonScopeData());
 }
  protected BuiltResponse invokeOnTarget(
      HttpRequest request, HttpResponse response, Object target) {
    ResteasyProviderFactory.pushContext(
        ResourceInfo.class, resourceInfo); // we don't pop so writer interceptors can get at this

    PostMatchContainerRequestContext requestContext =
        new PostMatchContainerRequestContext(request, this);
    for (ContainerRequestFilter filter : requestFilters) {
      try {
        filter.filter(requestContext);
      } catch (IOException e) {
        throw new ApplicationException(e);
      }
      BuiltResponse serverResponse = (BuiltResponse) requestContext.getResponseAbortedWith();
      if (serverResponse != null) {
        return serverResponse;
      }
    }

    if (validator != null) {
      if (isValidatable) {
        validator.validate(request, target);
      }
      if (methodIsValidatable) {
        request.setAttribute(GeneralValidator.class.getName(), validator);
      } else if (isValidatable) {
        validator.checkViolations(request);
      }
    }

    Object rtn = null;
    try {
      rtn = methodInjector.invoke(request, response, target);
    } catch (RuntimeException ex) {
      if (request.getAsyncContext().isSuspended()) {
        try {
          request.getAsyncContext().getAsyncResponse().resume(ex);
        } catch (Exception e) {
          logger.error("Error resuming failed async operation", e);
        }
        return null;
      } else {
        throw ex;
      }
    }

    if (request.getAsyncContext().isSuspended() || request.wasForwarded()) {
      return null;
    }
    if (rtn == null || method.getReturnType().equals(void.class)) {
      BuiltResponse build = (BuiltResponse) Response.noContent().build();
      build.addMethodAnnotations(method.getAnnotatedMethod());
      return build;
    }
    if (Response.class.isAssignableFrom(method.getReturnType()) || rtn instanceof Response) {
      if (!(rtn instanceof BuiltResponse)) {
        Response r = (Response) rtn;
        Headers<Object> metadata = new Headers<Object>();
        metadata.putAll(r.getMetadata());
        rtn = new BuiltResponse(r.getStatus(), metadata, r.getEntity(), null);
      }
      BuiltResponse rtn1 = (BuiltResponse) rtn;
      rtn1.addMethodAnnotations(method.getAnnotatedMethod());
      if (rtn1.getGenericType() == null) {
        if (getMethod().getReturnType().equals(Response.class)) {
          rtn1.setGenericType(rtn1.getEntityClass());
        } else {
          rtn1.setGenericType(method.getGenericReturnType());
        }
      }
      return rtn1;
    }

    Response.ResponseBuilder builder = Response.ok(rtn);
    BuiltResponse jaxrsResponse = (BuiltResponse) builder.build();
    if (jaxrsResponse.getGenericType() == null) {
      if (getMethod().getReturnType().equals(Response.class)) {
        jaxrsResponse.setGenericType(jaxrsResponse.getEntityClass());
      } else {
        jaxrsResponse.setGenericType(method.getGenericReturnType());
      }
    }
    jaxrsResponse.addMethodAnnotations(method.getAnnotatedMethod());
    return jaxrsResponse;
  }
예제 #11
0
  // this is synchronized in conjunction with finalize to protect against premature finalize called
  // by the GC
  protected synchronized <T2> Object readFrom(
      Class<T2> type, Type genericType, MediaType media, Annotation[] annotations) {
    Type useGeneric = genericType == null ? type : genericType;
    Class<?> useType = type;
    boolean isMarshalledEntity = false;
    if (type.equals(MarshalledEntity.class)) {
      isMarshalledEntity = true;
      ParameterizedType param = (ParameterizedType) useGeneric;
      useGeneric = param.getActualTypeArguments()[0];
      useType = Types.getRawType(useGeneric);
    }

    Providers current = ResteasyProviderFactory.getContextData(Providers.class);
    ResteasyProviderFactory.pushContext(Providers.class, providerFactory);
    Object obj = null;
    try {
      InputStream is = streamFactory.getInputStream();
      if (is == null) {
        throw new ClientResponseFailure(Messages.MESSAGES.inputStreamEmpty(), this);
      }
      if (isMarshalledEntity) {
        is = new InputStreamToByteArray(is);
      }

      final Object finalObj =
          new ClientReaderInterceptorContext(
                  readerInterceptors,
                  providerFactory,
                  useType,
                  useGeneric,
                  annotations,
                  media,
                  getResponseHeaders(),
                  new InputStreamWrapper(is),
                  attributes)
              .proceed();
      obj = finalObj;
      if (isMarshalledEntity) {
        InputStreamToByteArray isba = (InputStreamToByteArray) is;
        final byte[] bytes = isba.toByteArray();
        return new MarshalledEntity() {
          @Override
          public byte[] getMarshalledBytes() {
            return bytes;
          }

          @Override
          public Object getEntity() {
            return finalObj;
          }
        };
      } else {
        return (T2) finalObj;
      }

    } catch (Exception e) {
      if (e instanceof ReaderException) {
        throw (ReaderException) e;
      } else {
        throw new ReaderException(e);
      }
    } finally {
      ResteasyProviderFactory.popContextData(Providers.class);
      if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
      if (obj instanceof ProvidersContextRetainer) {
        ((ProvidersContextRetainer) obj).setProviders(providerFactory);
      }
    }
  }