private boolean _suspend(long time, TimeUnit unit, boolean failOnError)
      throws IllegalStateException {
    boolean suspendSuccessful = false;

    try {
      executionStateMonitor.enter();
      switch (executionState) {
        case RESUMED:
          break;
        case SUSPENDED:
        case CANCELLED:
          if (failOnError) {
            throw new IllegalStateException(
                LocalizationMessages.ILLEGAL_INVOCATION_CONTEXT_STATE(executionState, "suspend"));
          }
          break;
        case RUNNING:
          executionState = State.SUSPENDED;
          suspendSuccessful = true;
      }
    } finally {
      executionStateMonitor.leave();
    }

    // we don't want to invoke the callback or log message
    // as part of the synchronized code
    if (suspendSuccessful) {
      callback.suspended(time, unit, this);
    } else {
      // already resumed - just log fine message & ignore the call
      LOGGER.log(Level.FINE, LocalizationMessages.REQUEST_SUSPEND_FAILED(executionState));
    }

    return suspendSuccessful;
  }
  /**
   * Convert {@code Object} value to a value of the specified class type.
   *
   * @param value {@code Object} value to convert.
   * @param type conversion type.
   * @param <T> converted value type.
   * @return value converted to the specified class type.
   */
  public static <T> T convertValue(Object value, Class<T> type) {
    if (!type.isInstance(value)) {
      // TODO: Move string value readers from server to common and utilize them here
      final Constructor constructor =
          AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
      if (constructor != null) {
        try {
          return type.cast(constructor.newInstance(value));
        } catch (Exception e) {
          // calling the constructor wasn't successful - ignore and try valueOf()
        }
      }

      final Method valueOf =
          AccessController.doPrivileged(ReflectionHelper.getValueOfStringMethodPA(type));
      if (valueOf != null) {
        try {
          return type.cast(valueOf.invoke(null, value));
        } catch (Exception e) {
          // calling valueOf wasn't successful
        }
      }

      // at this point we don't know what to return -> return null
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning(
            LocalizationMessages.PROPERTIES_HELPER_GET_VALUE_NO_TRANSFORM(
                String.valueOf(value), value.getClass().getName(), type.getName()));
      }

      return null;
    }

    return type.cast(value);
  }
  /**
   * Invoke request on the wrapped inflector. The adapter itself serves as a {@link ListenableFuture
   * listenable response future}.
   *
   * @param request request data to be processed.
   */
  public ListenableFuture<RESPONSE> apply(REQUEST request) {
    originatingRequest.set(request);
    final RESPONSE response;

    try {
      response = wrapped.apply(request);

      if (executionStateMonitor.enterIf(runningState)) {
        // The context was not suspended during the call to the wrapped inflector's apply(...)
        // method;
        // mark as resumed & don't invoke callback.resume() since we are resuming synchronously
        try {
          executionState = State.RESUMED;
          set(response);
        } finally {
          executionStateMonitor.leave();
        }
      } else if (response != null) {
        LOGGER.log(Level.FINE, LocalizationMessages.REQUEST_SUSPENDED_RESPONSE_IGNORED(response));
      }
    } catch (Throwable t) {
      resume(t); // resume with throwable (if not resumed by an external event already)
    }
    return this;
  }
 @Override
 public Object convert(String s) {
   if (s.length() != 1) {
     throw new MessageBodyProcessingException(
         LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_CHARACTER_MORECHARS());
   }
   return s.charAt(0);
 }
 /**
  * Extract and return service locator from {@link javax.ws.rs.core.FeatureContext featureContext}.
  * The method can be used to inject custom types into a {@link javax.ws.rs.core.Feature}.
  *
  * <p>Note that features are utilized during initialization phase when not all providers are
  * registered yet. It is undefined which injections are already available in this phase.
  *
  * @param featureContext Feature context.
  * @return Service locator.
  * @throws java.lang.IllegalArgumentException when {@code writerInterceptorContext} is not a
  *     default Jersey instance provided by Jersey in {@link
  *     javax.ws.rs.core.Feature#configure(javax.ws.rs.core.FeatureContext)} method.
  */
 public static ServiceLocator getServiceLocator(FeatureContext featureContext) {
   if (!(featureContext instanceof ServiceLocatorSupplier)) {
     throw new IllegalArgumentException(
         LocalizationMessages.ERROR_SERVICE_LOCATOR_PROVIDER_INSTANCE_FEATURE_CONTEXT(
             featureContext.getClass().getName()));
   }
   return ((ServiceLocatorSupplier) featureContext).getServiceLocator();
 }
 /**
  * Extract and return service locator from {@link javax.ws.rs.ext.ReaderInterceptorContext
  * readerInterceptorContext}. The method can be used to inject custom types into a {@link
  * javax.ws.rs.ext.ReaderInterceptor}.
  *
  * @param readerInterceptorContext Reader interceptor context.
  * @return Service locator.
  * @throws java.lang.IllegalArgumentException when {@code readerInterceptorContext} is not a
  *     default Jersey implementation provided by Jersey as argument in the {@link
  *     javax.ws.rs.ext.ReaderInterceptor#aroundReadFrom(javax.ws.rs.ext.ReaderInterceptorContext)}
  *     method.
  */
 public static ServiceLocator getServiceLocator(
     ReaderInterceptorContext readerInterceptorContext) {
   if (!(readerInterceptorContext instanceof ServiceLocatorSupplier)) {
     throw new IllegalArgumentException(
         LocalizationMessages
             .ERROR_SERVICE_LOCATOR_PROVIDER_INSTANCE_FEATURE_READER_INTERCEPTOR_CONTEXT(
                 readerInterceptorContext.getClass().getName()));
   }
   return ((ServiceLocatorSupplier) readerInterceptorContext).getServiceLocator();
 }
Exemple #7
0
  /**
   * Convert {@link Link} instance to a string version.
   *
   * @param value link instance to be stringified.
   * @return string version of a given link instance.
   */
  static String stringfy(Link value) {
    throwIllegalArgumentExceptionIfNull(value, LocalizationMessages.LINK_IS_NULL());

    Map<String, String> map = value.getParams();
    StringBuilder sb = new StringBuilder();
    sb.append('<').append(value.getUri()).append('>');

    for (Map.Entry<String, String> entry : map.entrySet()) {
      sb.append("; ").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
    }
    return sb.toString();
  }
  @Override
  public Object readFrom(
      Class<Object> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream entityStream)
      throws IOException, WebApplicationException {
    final String entityString = readFromAsString(entityStream, mediaType);
    if (entityString.isEmpty()) {
      throw new NoContentException(LocalizationMessages.ERROR_READING_ENTITY_MISSING());
    }
    final PrimitiveTypes primitiveType = PrimitiveTypes.forType(type);
    if (primitiveType != null) {
      return primitiveType.convert(entityString);
    }

    final Constructor constructor =
        AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
    if (constructor != null) {
      try {
        return type.cast(constructor.newInstance(entityString));
      } catch (Exception e) {
        throw new MessageBodyProcessingException(
            LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_CONSTRUCTOR(type));
      }
    }

    if (AtomicInteger.class.isAssignableFrom(type)) {
      return new AtomicInteger((Integer) PrimitiveTypes.INTEGER.convert(entityString));
    }

    if (AtomicLong.class.isAssignableFrom(type)) {
      return new AtomicLong((Long) PrimitiveTypes.LONG.convert(entityString));
    }

    throw new MessageBodyProcessingException(
        LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_UNKWNOWN(type));
  }
 private static Object getLegacyFallbackValue(
     Map<String, ?> properties, Map<String, String> legacyFallbackMap, String key) {
   if (legacyFallbackMap == null || !legacyFallbackMap.containsKey(key)) {
     return null;
   }
   String fallbackKey = legacyFallbackMap.get(key);
   Object value = properties.get(fallbackKey);
   if (value != null && LOGGER.isLoggable(Level.CONFIG)) {
     LOGGER.config(
         LocalizationMessages.PROPERTIES_HELPER_DEPRECATED_PROPERTY_NAME(fallbackKey, key));
   }
   return value;
 }
 @Override
 public void cancel() {
   if (executionStateMonitor.enterIf(cancellableState)) {
     try {
       executionState = State.CANCELLED;
     } finally {
       executionStateMonitor.leave();
     }
     super.cancel(true);
   } else {
     // just log fine message & ignore the call
     LOGGER.log(Level.FINE, LocalizationMessages.REQUEST_CANCEL_FAILED(executionState));
   }
 }
 private void resume(final Runnable resumeHandler) {
   if (executionStateMonitor.enterIf(resumableState)) {
     final boolean invokeCallback;
     try {
       invokeCallback = executionState == State.SUSPENDED;
       executionState = State.RESUMED;
     } finally {
       executionStateMonitor.leave();
     }
     try {
       resumeHandler.run();
     } finally {
       if (invokeCallback) {
         callback.resumed();
       }
     }
   } else {
     throw new IllegalStateException(
         LocalizationMessages.ILLEGAL_INVOCATION_CONTEXT_STATE(executionState, "resume"));
   }
 }
Exemple #12
0
 /**
  * Initialize an existing Jersey link builder with the link data provided in a form of a string.
  *
  * @param lb link builder to be initialized.
  * @param value link data as a string.
  * @return initialized link builder.
  */
 static JerseyLink.Builder initBuilder(JerseyLink.Builder lb, String value) {
   throwIllegalArgumentExceptionIfNull(value, LocalizationMessages.LINK_IS_NULL());
   try {
     value = value.trim();
     String params;
     if (value.startsWith("<")) {
       int gtIndex = value.indexOf('>');
       if (gtIndex != -1) {
         lb.uri(value.substring(1, gtIndex).trim());
         params = value.substring(gtIndex + 1).trim();
       } else {
         throw new IllegalArgumentException("Missing token > in " + value);
       }
     } else {
       throw new IllegalArgumentException("Missing starting token < in " + value);
     }
     if (params != null) {
       StringTokenizer st = new StringTokenizer(params, ";=\"", true);
       while (st.hasMoreTokens()) {
         checkToken(st, ";");
         String n = st.nextToken().trim();
         checkToken(st, "=");
         checkToken(st, "\"");
         String v = st.nextToken();
         checkToken(st, "\"");
         lb.param(n, v);
       }
     }
   } catch (Throwable e) {
     if (LOGGER.isLoggable(Level.FINER)) {
       LOGGER.log(Level.FINER, "Error parsing link value '" + value + "'", e);
     }
     lb = null;
   }
   if (lb == null) {
     throw new IllegalArgumentException("Unable to parse link " + value);
   }
   return lb;
 }
  @Override
  public final Object readFrom(
      Class<Object> type,
      Type genericType,
      Annotation annotations[],
      MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream inputStream)
      throws IOException {

    try {
      final EntityInputStream entityStream = EntityInputStream.create(inputStream);
      if (entityStream.isEmpty()) {
        throw new NoContentException(LocalizationMessages.ERROR_READING_ENTITY_MISSING());
      }
      return readFrom(type, mediaType, getUnmarshaller(type, mediaType), entityStream);
    } catch (UnmarshalException ex) {
      throw new BadRequestException(ex);
    } catch (JAXBException ex) {
      throw new InternalServerErrorException(ex);
    }
  }
  /**
   * Create new SSL context instance using the current SSL context configuration.
   *
   * @return newly configured SSL context instance.
   */
  public SSLContext createSSLContext() {
    TrustManagerFactory trustManagerFactory = null;
    KeyManagerFactory keyManagerFactory = null;

    KeyStore _keyStore = keyStore;
    if (_keyStore == null && (keyStoreBytes != null || keyStoreFile != null)) {
      try {
        if (keyStoreProvider != null) {
          _keyStore =
              KeyStore.getInstance(
                  keyStoreType != null ? keyStoreType : KeyStore.getDefaultType(),
                  keyStoreProvider);
        } else {
          _keyStore =
              KeyStore.getInstance(keyStoreType != null ? keyStoreType : KeyStore.getDefaultType());
        }
        InputStream keyStoreInputStream = null;
        try {
          if (keyStoreBytes != null) {
            keyStoreInputStream = new ByteArrayInputStream(keyStoreBytes);
          } else if (!keyStoreFile.equals("NONE")) {
            keyStoreInputStream = new FileInputStream(keyStoreFile);
          }
          _keyStore.load(keyStoreInputStream, keyStorePass);
        } finally {
          try {
            if (keyStoreInputStream != null) {
              keyStoreInputStream.close();
            }
          } catch (IOException ignored) {
          }
        }
      } catch (KeyStoreException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KS_IMPL_NOT_FOUND(), e);
      } catch (CertificateException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KS_CERT_LOAD_ERROR(), e);
      } catch (FileNotFoundException e) {
        throw new IllegalStateException(
            LocalizationMessages.SSL_KS_FILE_NOT_FOUND(keyStoreFile), e);
      } catch (IOException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KS_LOAD_ERROR(keyStoreFile), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KS_PROVIDERS_NOT_REGISTERED(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(
            LocalizationMessages.SSL_KS_INTEGRITY_ALGORITHM_NOT_FOUND(), e);
      }
    }
    if (_keyStore != null) {
      String kmfAlgorithm = keyManagerFactoryAlgorithm;
      if (kmfAlgorithm == null) {
        kmfAlgorithm =
            AccessController.doPrivileged(
                PropertiesHelper.getSystemProperty(
                    KEY_MANAGER_FACTORY_ALGORITHM, KeyManagerFactory.getDefaultAlgorithm()));
      }
      try {
        if (keyManagerFactoryProvider != null) {
          keyManagerFactory =
              KeyManagerFactory.getInstance(kmfAlgorithm, keyManagerFactoryProvider);
        } else {
          keyManagerFactory = KeyManagerFactory.getInstance(kmfAlgorithm);
        }
        final char[] password = keyPass != null ? keyPass : keyStorePass;
        if (password != null) {
          keyManagerFactory.init(_keyStore, password);
        } else {
          String ksName =
              keyStoreProvider != null
                  ? LocalizationMessages.SSL_KMF_NO_PASSWORD_FOR_PROVIDER_BASED_KS()
                  : keyStoreBytes != null
                      ? LocalizationMessages.SSL_KMF_NO_PASSWORD_FOR_BYTE_BASED_KS()
                      : keyStoreFile;

          LOGGER.config(LocalizationMessages.SSL_KMF_NO_PASSWORD_SET(ksName));
          keyManagerFactory = null;
        }
      } catch (KeyStoreException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KMF_INIT_FAILED(), e);
      } catch (UnrecoverableKeyException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KMF_UNRECOVERABLE_KEY(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KMF_ALGORITHM_NOT_SUPPORTED(), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_KMF_PROVIDER_NOT_REGISTERED(), e);
      }
    }

    KeyStore _trustStore = trustStore;
    if (_trustStore == null && (trustStoreBytes != null || trustStoreFile != null)) {
      try {
        if (trustStoreProvider != null) {
          _trustStore =
              KeyStore.getInstance(
                  trustStoreType != null ? trustStoreType : KeyStore.getDefaultType(),
                  trustStoreProvider);
        } else {
          _trustStore =
              KeyStore.getInstance(
                  trustStoreType != null ? trustStoreType : KeyStore.getDefaultType());
        }
        InputStream trustStoreInputStream = null;
        try {
          if (trustStoreBytes != null) {
            trustStoreInputStream = new ByteArrayInputStream(trustStoreBytes);
          } else if (!trustStoreFile.equals("NONE")) {
            trustStoreInputStream = new FileInputStream(trustStoreFile);
          }
          _trustStore.load(trustStoreInputStream, trustStorePass);
        } finally {
          try {
            if (trustStoreInputStream != null) {
              trustStoreInputStream.close();
            }
          } catch (IOException ignored) {
          }
        }
      } catch (KeyStoreException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TS_IMPL_NOT_FOUND(), e);
      } catch (CertificateException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TS_CERT_LOAD_ERROR(), e);
      } catch (FileNotFoundException e) {
        throw new IllegalStateException(
            LocalizationMessages.SSL_TS_FILE_NOT_FOUND(trustStoreFile), e);
      } catch (IOException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TS_LOAD_ERROR(trustStoreFile), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TS_PROVIDERS_NOT_REGISTERED(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(
            LocalizationMessages.SSL_TS_INTEGRITY_ALGORITHM_NOT_FOUND(), e);
      }
    }
    if (_trustStore != null) {
      String tmfAlgorithm = trustManagerFactoryAlgorithm;
      if (tmfAlgorithm == null) {
        tmfAlgorithm =
            AccessController.doPrivileged(
                PropertiesHelper.getSystemProperty(
                    TRUST_MANAGER_FACTORY_ALGORITHM, TrustManagerFactory.getDefaultAlgorithm()));
      }

      try {
        if (trustManagerFactoryProvider != null) {
          trustManagerFactory =
              TrustManagerFactory.getInstance(tmfAlgorithm, trustManagerFactoryProvider);
        } else {
          trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
        }
        trustManagerFactory.init(_trustStore);
      } catch (KeyStoreException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TMF_INIT_FAILED(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TMF_ALGORITHM_NOT_SUPPORTED(), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalStateException(LocalizationMessages.SSL_TMF_PROVIDER_NOT_REGISTERED(), e);
      }
    }

    try {
      String secProtocol = "TLS";
      if (securityProtocol != null) {
        secProtocol = securityProtocol;
      }
      final SSLContext sslContext = SSLContext.getInstance(secProtocol);
      sslContext.init(
          keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null,
          trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null,
          null);
      return sslContext;
    } catch (KeyManagementException e) {
      throw new IllegalStateException(LocalizationMessages.SSL_CTX_INIT_FAILED(), e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(LocalizationMessages.SSL_CTX_ALGORITHM_NOT_SUPPORTED(), e);
    }
  }