@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\""));
  }
Exemplo n.º 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();
    }
  }
 private static synchronized void checkClientExceptionMapper() {
   if (ResteasyProviderFactory.getInstance().getClientExceptionMapper(Exception.class) == null) {
     Type exceptionType =
         Types.getActualTypeArgumentsOfAnInterface(
             ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0];
     ResteasyProviderFactory.getInstance()
         .addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);
   }
 }
Exemplo n.º 4
0
 public void cleanup() {
   parentProviderFactory.getContainerRequestFilterRegistry().getListeners().remove(this);
   parentProviderFactory.getContainerResponseFilterRegistry().getListeners().remove(this);
   parentProviderFactory.getServerWriterInterceptorRegistry().getListeners().remove(this);
   for (ValueInjector param : methodInjector.getParams()) {
     if (param instanceof MessageBodyParameterInjector) {
       parentProviderFactory.getServerReaderInterceptorRegistry().getListeners().remove(param);
     }
   }
 }
Exemplo n.º 5
0
 public void registryUpdated(JaxrsInterceptorRegistry registry) {
   if (registry.getIntf().equals(WriterInterceptor.class)) {
     writerInterceptors =
         providerFactory.getServerWriterInterceptorRegistry().postMatch(resourceClass, method);
   } else if (registry.getIntf().equals(ContainerRequestFilter.class)) {
     requestFilters =
         providerFactory.getContainerRequestFilterRegistry().postMatch(resourceClass, method);
   } else if (registry.getIntf().equals(ContainerResponseFilter.class)) {
     responseFilters =
         providerFactory.getContainerResponseFilterRegistry().postMatch(resourceClass, method);
   }
 }
Exemplo n.º 6
0
  private static void startDeployment() throws Exception {
    deployment = new ResteasyDeployment();
    deployment.setSecurityEnabled(true);
    deployment.setApplicationClass(SApp.class.getName());
    ResteasyProviderFactory factory = new ResteasyProviderFactory();
    deployment.setProviderFactory(factory);
    factory.setProperty(SkeletonKeyApplication.SKELETON_KEY_INFINISPAN_CONFIG_FILE, "cache.xml");
    factory.setProperty(SkeletonKeyApplication.SKELETON_KEY_INFINISPAN_CACHE_NAME, "idp-store");

    EmbeddedContainer.start(deployment);
    app = ((SApp) deployment.getApplication()).app;
  }
Exemplo n.º 7
0
  protected static void startRestEasy(Class<?>... classes) throws Exception {
    server = new TJWSEmbeddedJaxrsServer();
    server.setPort(PORT);
    server.start();
    Registry registry = server.getDeployment().getRegistry();
    ResteasyProviderFactory factory = server.getDeployment().getDispatcher().getProviderFactory();

    if (classes != null) for (Class<?> clazz : classes) registry.addPerRequestResource(clazz);

    factory.addExceptionMapper(TMUnavailableMapper.class);
    factory.addExceptionMapper(TransactionStatusMapper.class);
    factory.addExceptionMapper(HttpResponseMapper.class);
    factory.addExceptionMapper(NotFoundMapper.class);
  }
Exemplo n.º 8
0
 /**
  * Path for managing all realm-level or client-level roles defined in this realm by its id.
  *
  * @return
  */
 @Path("roles-by-id")
 public RoleByIdResource rolesById() {
   RoleByIdResource resource = new RoleByIdResource(realm, auth, adminEvent);
   ResteasyProviderFactory.getInstance().injectProperties(resource);
   // resourceContext.initResource(resource);
   return resource;
 }
Exemplo n.º 9
0
 /**
  * Base path for managing users in this realm.
  *
  * @return
  */
 @Path("users")
 public UsersResource users() {
   UsersResource users = new UsersResource(realm, auth, adminEvent);
   ResteasyProviderFactory.getInstance().injectProperties(users);
   // resourceContext.initResource(users);
   return users;
 }
Exemplo n.º 10
0
 /**
  * Base path for managing client initial access tokens
  *
  * @return
  */
 @Path("clients-trusted-hosts")
 public ClientRegistrationTrustedHostResource getClientRegistrationTrustedHost() {
   ClientRegistrationTrustedHostResource resource =
       new ClientRegistrationTrustedHostResource(realm, auth, adminEvent);
   ResteasyProviderFactory.getInstance().injectProperties(resource);
   return resource;
 }
Exemplo n.º 11
0
 @Path("oauth-clients")
 public OAuthClientsResource getOAuthClients() {
   OAuthClientsResource oauth = new OAuthClientsResource(realm, auth, session);
   ResteasyProviderFactory.getInstance().injectProperties(oauth);
   // resourceContext.initResource(oauth);
   return oauth;
 }
Exemplo n.º 12
0
 @Path("applications")
 public ApplicationsResource getApplications() {
   ApplicationsResource applicationsResource = new ApplicationsResource(realm, auth);
   ResteasyProviderFactory.getInstance().injectProperties(applicationsResource);
   // resourceContext.initResource(applicationsResource);
   return applicationsResource;
 }
Exemplo n.º 13
0
 public boolean executeExceptionMapperForClass(
     HttpRequest request, HttpResponse response, Throwable exception, Class clazz) {
   ExceptionMapper mapper = providerFactory.getExceptionMapper(clazz);
   if (mapper == null) return false;
   writeFailure(request, response, mapper.toResponse(exception));
   return true;
 }
  @Override
  public void contextInitialized(ServletContextEvent contextEvent) {
    // Load configuration
    InputStream is =
        contextEvent.getServletContext().getResourceAsStream("/WEB-INF/configuration.properties");

    if (is != null) {
      Configuration.loadProperties(is);
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      throw new Error("Missing configuration file '/WEB-INF/configuration.properties'");
    }

    // Register RESTEasy client provider factory
    RegisterBuiltin.register(ResteasyProviderFactory.getInstance());

    // start polling for MachineStatus changes
    polling = new Timer();
    polling.scheduleAtFixedRate(
        new PollNodeController(),
        0,
        Integer.parseInt(Configuration.getProperty("polling.interval")));
  }
Exemplo n.º 15
0
 @Path("user-storage")
 public UserStorageProviderResource userStorage() {
   UserStorageProviderResource fed = new UserStorageProviderResource(realm, auth, adminEvent);
   ResteasyProviderFactory.getInstance().injectProperties(fed);
   // resourceContext.initResource(fed);
   return fed;
 }
 @Test
 public void testPostProcessWithNullPageRequest() {
   ResteasyProviderFactory.pushContext(Page.class, page);
   when(page.getPageRequest()).thenReturn(null);
   interceptor.postProcess(response);
   verify(page).getPageRequest();
 }
Exemplo n.º 17
0
  public static <T> T getEntity(
      ClientMessage msg, Class<T> type, Type genericType, ResteasyProviderFactory factory) {
    int size = msg.getBodySize();
    if (size <= 0) return null;

    byte[] body = new byte[size];
    msg.getBodyBuffer().readBytes(body);

    String contentType = msg.getStringProperty(HttpHeaderProperty.CONTENT_TYPE);
    if (contentType == null) {
      throw new UnknownMediaType(
          "Message did not have a Content-Type header cannot extract entity");
    }
    MediaType ct = MediaType.valueOf(contentType);
    MessageBodyReader<T> reader = factory.getMessageBodyReader(type, genericType, null, ct);
    if (reader == null) {
      throw new UnmarshalException(
          "Unable to find a JAX-RS reader for type "
              + type.getName()
              + " and media type "
              + contentType);
    }
    try {
      return reader.readFrom(type, genericType, null, ct, null, new ByteArrayInputStream(body));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 18
0
  private int getMaxSize() {
    if (maxSize != -1) {
      return maxSize;
    }

    int size = -1;
    ServletContext context = ResteasyProviderFactory.getContextData(ServletContext.class);
    if (context != null) {
      String s = context.getInitParameter(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT);
      if (s != null) {
        try {
          size = Integer.parseInt(s);
        } catch (NumberFormatException e) {
          LogMessages.LOGGER.invalidFormat(
              ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT,
              Integer.toString(DEFAULT_MAX_SIZE));
        }
      }
    }
    if (size == -1) {
      size = DEFAULT_MAX_SIZE;
    }

    return size;
  }
Exemplo n.º 19
0
 @Path("client-registration-policy")
 public ClientRegistrationPolicyResource getClientRegistrationPolicy() {
   ClientRegistrationPolicyResource resource =
       new ClientRegistrationPolicyResource(realm, auth, adminEvent);
   ResteasyProviderFactory.getInstance().injectProperties(resource);
   return resource;
 }
Exemplo n.º 20
0
  /**
   * Base path for the admin REST API for one particular realm.
   *
   * @param headers
   * @param name realm name (not id!)
   * @return
   */
  @Path("{realm}")
  public RealmAdminResource getRealmAdmin(
      @Context final HttpHeaders headers, @PathParam("realm") final String name) {
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(name);
    if (realm == null) throw new NotFoundException("Realm not found.");

    if (!auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())
        && !auth.getRealm().equals(realm)) {
      throw new ForbiddenException();
    }
    RealmAuth realmAuth;

    if (auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())) {
      realmAuth = new RealmAuth(auth, realm.getMasterAdminClient());
    } else {
      realmAuth =
          new RealmAuth(
              auth, realm.getClientByClientId(realmManager.getRealmAdminClientId(auth.getRealm())));
    }

    AdminEventBuilder adminEvent = new AdminEventBuilder(realm, auth, session, clientConnection);
    session.getContext().setRealm(realm);

    RealmAdminResource adminResource =
        new RealmAdminResource(realmAuth, realm, tokenManager, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(adminResource);
    // resourceContext.initResource(adminResource);
    return adminResource;
  }
  protected void sign(
      KeyRepository repository,
      MultivaluedMap<String, Object> headers,
      byte[] body,
      DKIMSignature dosetaSignature)
      throws NoSuchAlgorithmException, InvalidKeyException, SignatureException,
          UnsupportedEncodingException {
    // if its already signed, don't bother
    if (dosetaSignature.getBased64Signature() != null) return;

    PrivateKey privateKey = dosetaSignature.getPrivateKey();
    if (privateKey == null) {
      if (repository == null)
        repository = ResteasyProviderFactory.getContextData(KeyRepository.class);

      if (repository == null) {
        throw new RuntimeException(
            "Unable to locate a private key to sign message, repository is null.");
      }

      privateKey = repository.findPrivateKey(dosetaSignature);
      if (privateKey == null) {
        throw new RuntimeException(
            "Unable to find key to sign message. Repository returned null. ");
      }
    }
    dosetaSignature.sign(headers, body, privateKey);
  }
 private <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
   CandlepinSingletonScopeData scopeData =
       ResteasyProviderFactory.getContextData(CandlepinSingletonScopeData.class);
   if (scopeData == null) {
     throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
   }
   return scopeData.get();
 }
Exemplo n.º 23
0
 @Path("authentication")
 public AuthenticationManagementResource flows() {
   AuthenticationManagementResource resource =
       new AuthenticationManagementResource(realm, session, auth, adminEvent);
   ResteasyProviderFactory.getInstance().injectProperties(resource);
   // resourceContext.initResource(resource);
   return resource;
 }
Exemplo n.º 24
0
 /**
  * path to realm admin console ui
  *
  * @param name Realm name (not id!)
  * @return
  */
 @Path("{realm}/console")
 public AdminConsole getAdminConsole(final @PathParam("realm") String name) {
   RealmManager realmManager = new RealmManager(session);
   RealmModel realm = locateRealm(name, realmManager);
   AdminConsole service = new AdminConsole(realm);
   ResteasyProviderFactory.getInstance().injectProperties(service);
   return service;
 }
  protected void findRateDataPointsForMetrics(
      AsyncResponse asyncResponse, QueryRequest query, MetricType<? extends Number> type) {
    TimeRange timeRange = new TimeRange(query.getStart(), query.getEnd());
    if (!timeRange.isValid()) {
      asyncResponse.resume(badRequest(new ApiError(timeRange.getProblem())));
      return;
    }

    int limit;
    if (query.getLimit() == null) {
      limit = 0;
    } else {
      limit = query.getLimit();
    }
    Order order;
    if (query.getOrder() == null) {
      order = Order.defaultValue(limit, timeRange.getStart(), timeRange.getEnd());
    } else {
      order = Order.fromText(query.getOrder());
    }

    if (query.getIds().isEmpty()) {
      asyncResponse.resume(badRequest(new ApiError("Metric ids must be specified")));
      return;
    }

    List<MetricId<? extends Number>> metricIds =
        query.getIds().stream().map(id -> new MetricId<>(getTenant(), type, id)).collect(toList());
    Observable<NamedDataPoint<Double>> dataPoints =
        metricsService
            .findRateData(metricIds, timeRange.getStart(), timeRange.getEnd(), limit, order)
            .observeOn(Schedulers.io());

    HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
    HttpServletResponse response =
        ResteasyProviderFactory.getContextData(HttpServletResponse.class);

    if (type == GAUGE) {
      dataPoints.subscribe(new NamedDataPointObserver<>(request, response, mapper, GAUGE));
    } else if (type == COUNTER) {
      dataPoints.subscribe(new NamedDataPointObserver<>(request, response, mapper, COUNTER_RATE));
    } else {
      throw new IllegalArgumentException(
          type + " is not a supported metric type for rate data points");
    }
  }
Exemplo n.º 26
0
  @Test
  public void testCacheControl() {
    MyProviderReader reader = new MyProviderReader();
    ResteasyProviderFactory.getInstance().registerProviderInstance(reader);

    Assert.assertNotNull(reader.headers);
    Assert.assertNotNull(reader.workers);
  }
 @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();
 }
Exemplo n.º 28
0
  @Path("/authz")
  public AuthorizationService authorization() {
    ProfileHelper.requireFeature(Profile.Feature.AUTHORIZATION);

    AuthorizationService resource = new AuthorizationService(this.session, this.client, this.auth);

    ResteasyProviderFactory.getInstance().injectProperties(resource);

    return resource;
  }
    @GET
    @Path("/infinite-forward")
    @Produces("text/plain")
    public int infinitFoward(
        @Context InternalDispatcher dispatcher, @QueryParam("count") @DefaultValue("0") int count) {
      uriStack.push(uriInfo.getAbsolutePath().toString());
      try {
        dispatcher.getEntity("/infinite-forward?count=" + (count + 1));
        // we'll never reach 20, since the max count of times through the
        // system is 20, and first time through is 0
        Assert.assertNotSame(20, count);
      } catch (BadRequestException e) {

      } finally {
        Assert.assertEquals(count, MessageBodyParameterInjector.bodyCount());
        Assert.assertEquals(count + 1, ResteasyProviderFactory.getContextDataLevelCount());
      }
      return ResteasyProviderFactory.getContextDataLevelCount();
    }
Exemplo n.º 30
0
  @POST
  @NoCache
  @Consumes({"application/soap+xml", MediaType.TEXT_XML})
  public Response soapBinding(InputStream inputStream) {
    SamlEcpProfileService bindingService = new SamlEcpProfileService(realm, event);

    ResteasyProviderFactory.getInstance().injectProperties(bindingService);

    return bindingService.authenticate(inputStream);
  }