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 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;
  }
 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();
 }
  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");
    }
  }
 public CollectionProvider() {
   ResteasyConfiguration context =
       ResteasyProviderFactory.getContextData(ResteasyConfiguration.class);
   if (context != null) {
     String s = context.getParameter("resteasy.document.expand.entity.references");
     if (s != null) {
       setExpandEntityReferences(Boolean.parseBoolean(s));
     }
   }
 }
  protected <T> void findRawDataPointsForMetrics(
      AsyncResponse asyncResponse, QueryRequest query, MetricType<T> 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<T>> metricIds =
        query.getIds().stream().map(id -> new MetricId<>(getTenant(), type, id)).collect(toList());
    Observable<NamedDataPoint<T>> dataPoints =
        metricsService
            .findDataPoints(metricIds, timeRange.getStart(), timeRange.getEnd(), limit, order)
            .observeOn(Schedulers.io());

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

    dataPoints.subscribe(new NamedDataPointObserver<>(request, response, mapper, type));
  }
  // 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);
      }
    }
  }
Example #8
0
 public void writeTo(
     File uploadFile,
     Class<?> type,
     Type genericType,
     Annotation[] annotations,
     MediaType mediaType,
     MultivaluedMap<String, Object> httpHeaders,
     OutputStream entityStream)
     throws IOException {
   HttpHeaders headers = ResteasyProviderFactory.getContextData(HttpHeaders.class);
   if (headers == null) {
     writeIt(uploadFile, entityStream);
     return;
   }
   String range = headers.getRequestHeaders().getFirst("Range");
   if (range == null) {
     writeIt(uploadFile, entityStream);
     return;
   }
   range = range.trim();
   if (range.indexOf(',') > -1) {
     // we don't support this
     writeIt(uploadFile, entityStream);
     return;
   }
   int separator = range.indexOf('-');
   if (separator < 0) {
     writeIt(uploadFile, entityStream);
     return;
   } else if (separator == 0) {
     long fileSize = uploadFile.length();
     long begin = Long.parseLong(range);
     if (fileSize + begin < 1) {
       writeIt(uploadFile, entityStream);
       return;
     }
     throw new FileRangeException(mediaType, uploadFile, fileSize + begin, fileSize - 1);
   } else {
     try {
       long fileSize = uploadFile.length();
       long begin = Long.parseLong(range.substring(0, separator));
       if (begin >= fileSize) {
         throw new WebApplicationException(416);
       }
       long end;
       if (range.endsWith("-")) {
         end = fileSize - 1;
       } else {
         String substring = range.substring(separator + 1);
         end = Long.parseLong(substring);
       }
       if (begin == 0 && end + 1 >= fileSize) {
         writeIt(uploadFile, entityStream);
         return;
       }
       throw new FileRangeException(mediaType, uploadFile, begin, end);
     } catch (NumberFormatException e) {
       writeIt(uploadFile, entityStream);
       return;
     }
   }
 }