예제 #1
0
  private SSLContext getSslContext(final Client client, final Configuration config) {
    final SslConfigurator sslConfigurator =
        PropertiesHelper.getValue(
            config.getProperties(), JettyClientProperties.SSL_CONFIG, SslConfigurator.class, null);

    return sslConfigurator != null ? sslConfigurator.createSSLContext() : client.getSslContext();
  }
  @Override
  public boolean configure(FeatureContext context) {
    if (oAuth1Provider != null) {
      context.register(oAuth1Provider);
    }

    context.register(OAuth1ServerFilter.class);

    if (!context.getConfiguration().isRegistered(OAuth1SignatureFeature.class)) {
      context.register(OAuth1SignatureFeature.class);
    }

    final Map<String, Object> properties = context.getConfiguration().getProperties();
    final Boolean propertyResourceEnabled =
        PropertiesHelper.getValue(
            properties, OAuth1ServerProperties.ENABLE_TOKEN_RESOURCES, null, Boolean.class);

    boolean registerResources =
        propertyResourceEnabled != null
            ? propertyResourceEnabled
            : requestTokenUri != null & accessTokenUri != null;

    if (registerResources) {
      String requestUri =
          PropertiesHelper.getValue(
              properties, OAuth1ServerProperties.REQUEST_TOKEN_URI, null, String.class);
      if (requestUri == null) {
        requestUri = requestTokenUri == null ? "requestToken" : requestTokenUri;
      }

      String accessUri =
          PropertiesHelper.getValue(
              properties, OAuth1ServerProperties.ACCESS_TOKEN_URI, null, String.class);
      if (accessUri == null) {
        accessUri = accessTokenUri == null ? "accessToken" : accessTokenUri;
      }

      final Resource requestResource =
          Resource.builder(RequestTokenResource.class).path(requestUri).build();
      final Resource accessResource =
          Resource.builder(AccessTokenResource.class).path(accessUri).build();

      context.register(new OAuthModelProcessor(requestResource, accessResource));
    }
    return true;
  }
예제 #3
0
 /**
  * Get the value of the specified property.
  *
  * <p>If the property is not set or the real value type is not compatible with the specified value
  * type, returns {@code defaultValue}.
  *
  * @param properties Map of properties to get the property value from.
  * @param runtime Runtime type which is used to check whether there is a property with the same
  *     {@code key} but post-fixed by runtime type (<tt>.server</tt> or {@code .client}) which
  *     would override the {@code key} property.
  * @param propertyName Name of the property.
  * @param defaultValue Default value if property is not registered
  * @param type Type to retrieve the value as.
  * @param <T> Type of the property value.
  * @return Value of the property or {@code null}.
  * @since 2.8
  */
 public static <T> T getValue(
     Map<String, ?> properties,
     RuntimeType runtime,
     String propertyName,
     T defaultValue,
     Class<T> type) {
   return PropertiesHelper.getValue(
       properties,
       runtime,
       propertyName,
       defaultValue,
       type,
       CommonProperties.LEGACY_FALLBACK_MAP);
 }
예제 #4
0
 private static int getProperty(final String varName, int defaultValue) {
   if (null == varName) {
     return defaultValue;
   }
   String varValue = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(varName));
   if (null != varValue) {
     try {
       return Integer.parseInt(varValue);
     } catch (NumberFormatException e) {
       // will return default value bellow
     }
   }
   return defaultValue;
 }
예제 #5
0
  private String getProperty(final String propertyName) {
    if (forcedPropertyMap.containsKey(propertyName)) {
      return forcedPropertyMap.get(propertyName);
    }

    final Properties systemProperties =
        AccessController.doPrivileged(PropertiesHelper.getSystemProperties());
    if (systemProperties.containsKey(propertyName)) {
      return systemProperties.getProperty(propertyName);
    }

    if (propertyMap.containsKey(propertyName)) {
      return propertyMap.get(propertyName);
    }

    return null;
  }
예제 #6
0
  /**
   * 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);
    }
  }
예제 #7
0
 private SslConfigurator(boolean readSystemProperties) {
   if (readSystemProperties) {
     retrieve(AccessController.doPrivileged(PropertiesHelper.getSystemProperties()));
   }
 }
예제 #8
0
 /**
  * Get the value of the specified property.
  *
  * <p>If the property is not set or the real value type is not compatible with the specified value
  * type, returns {@code defaultValue}.
  *
  * @param properties Map of properties to get the property value from.
  * @param key Name of the property.
  * @param defaultValue Default value if property is not registered
  * @param type Type to retrieve the value as.
  * @param <T> Type of the property value.
  * @return Value of the property or {@code null}.
  * @since 2.8
  */
 public static <T> T getValue(
     Map<String, ?> properties, String key, T defaultValue, Class<T> type) {
   return PropertiesHelper.getValue(properties, key, defaultValue, type, null);
 }
예제 #9
0
 private static String getSystemProperty(final String propertyName) {
   final Properties systemProperties =
       AccessController.doPrivileged(PropertiesHelper.getSystemProperties());
   return systemProperties.getProperty(propertyName);
 }
예제 #10
0
 /**
  * Get the value of the specified property.
  *
  * <p>If the property is not set or the real value type is not compatible with {@code
  * defaultValue} type, the specified {@code defaultValue} is returned. Calling this method is
  * equivalent to calling {@code CommonProperties.getValue(properties, key, defaultValue,
  * (Class<T>) defaultValue.getClass())}
  *
  * @param properties Map of properties to get the property value from.
  * @param propertyName Name of the property.
  * @param defaultValue Default value if property is not registered
  * @param <T> Type of the property value.
  * @return Value of the property or {@code null}.
  * @since 2.8
  */
 public static <T> T getValue(Map<String, ?> properties, String propertyName, T defaultValue) {
   return PropertiesHelper.getValue(
       properties, propertyName, defaultValue, CommonProperties.LEGACY_FALLBACK_MAP);
 }
예제 #11
0
 public static Object getValue(Map<String, ?> properties, String propertyName, Class<?> type) {
   return PropertiesHelper.getValue(
       properties, propertyName, type, CommonProperties.LEGACY_FALLBACK_MAP);
 }
예제 #12
0
  /**
   * The test method itself - installs the war-bundle and sends two testing requests
   *
   * @throws Exception
   */
  public void defaultWebAppTestMethod() throws Exception {
    // Start the war-bundle
    final Bundle warBundle =
        bundleContext.installBundle(
            AccessController.doPrivileged(
                PropertiesHelper.getSystemProperty(BundleLocationProperty)));
    warBundle.start();

    StringBuilder sb = new StringBuilder();
    sb.append("-- Bundle list -- \n");
    for (Bundle b : bundleContext.getBundles()) {
      sb.append(String.format("%1$5s", "[" + b.getBundleId() + "]"))
          .append(" ")
          .append(String.format("%1$-70s", b.getSymbolicName()))
          .append(" | ")
          .append(String.format("%1$-20s", b.getVersion()))
          .append(" |");
      try {
        b.start();
        sb.append(" STARTED  | ");
      } catch (BundleException e) {
        sb.append(" *FAILED* | ").append(e.getMessage());
      }
      sb.append(b.getLocation()).append("\n");
    }
    sb.append("-- \n\n");
    LOGGER.info(sb.toString());

    // and wait until it's ready
    LOGGER.fine(
        "Waiting for jersey/test/DEPLOYED event with timeout "
            + MAX_WAITING_SECONDS
            + " seconds...");
    LOGGER.fine(
        "Waiting for jersey/test/DEPLOYED event with timeout "
            + MAX_WAITING_SECONDS
            + " seconds...");
    if (!countDownLatch.await(MAX_WAITING_SECONDS, TimeUnit.SECONDS)) {
      throw new TimeoutException(
          "The event jersey/test/DEPLOYED did not arrive in "
              + MAX_WAITING_SECONDS
              + " seconds. Waiting timed out.");
    }

    // server should be listening now and everything should be initialized
    final Client c = ClientBuilder.newClient();
    final WebTarget target = c.target(baseUri);

    // send request and check response - helloworld resource
    final String helloResult =
        target
            .path("/webresources/helloworld")
            .request()
            .build("GET")
            .invoke()
            .readEntity(String.class);
    LOGGER.info("HELLO RESULT = " + helloResult);
    assertEquals("Hello World", helloResult);

    // send request and check response - another resource
    final String anotherResult =
        target
            .path("/webresources/another")
            .request()
            .build("GET")
            .invoke()
            .readEntity(String.class);
    LOGGER.info("ANOTHER RESULT = " + anotherResult);
    assertEquals("Another", anotherResult);

    // send request and check response for the additional bundle - should fail now
    final String additionalResult =
        target
            .path("/webresources/additional")
            .request()
            .build("GET")
            .invoke()
            .readEntity(String.class);

    LOGGER.info("ADDITIONAL RESULT = " + additionalResult);
    assertEquals("Additional Bundle!", additionalResult);
  }
예제 #13
0
  /**
   * Generic OSGi options - defines which dependencies (bundles) should be loaded into runtime
   *
   * @return
   */
  public List<Option> genericOsgiOptions() {
    @SuppressWarnings("RedundantStringToString")
    final String bundleLocation =
        mavenBundle()
            .groupId("org.glassfish.jersey.examples.osgi-helloworld-webapp")
            .artifactId("war-bundle")
            .type("war")
            .versionAsInProject()
            .getURL()
            .toString();

    List<Option> options =
        Arrays.asList(
            options(
                // vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"),

                systemProperty("org.osgi.service.http.port").value(String.valueOf(port)),
                systemProperty("org.osgi.framework.system.packages.extra")
                    .value("javax.annotation"),
                systemProperty("jersey.config.test.container.port").value(String.valueOf(port)),
                systemProperty(BundleLocationProperty).value(bundleLocation),

                // do not remove the following line
                // systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("FINEST"),

                // uncomment for logging (do not remove the following two lines)
                // mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.4"),
                // mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.4"),

                // javax.annotation must go first!
                mavenBundle()
                    .groupId("javax.annotation")
                    .artifactId("javax.annotation-api")
                    .versionAsInProject(),

                // pax exam dependencies
                mavenBundle("org.ops4j.pax.url", "pax-url-mvn"),
                junitBundles(), // adds junit classes to the OSGi context

                // HK2
                mavenBundle()
                    .groupId("org.glassfish.hk2")
                    .artifactId("hk2-api")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.hk2")
                    .artifactId("osgi-resource-locator")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.hk2")
                    .artifactId("hk2-locator")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.hk2")
                    .artifactId("hk2-utils")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.hk2.external")
                    .artifactId("javax.inject")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.hk2.external")
                    .artifactId("asm-all-repackaged")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.hk2.external")
                    .artifactId("aopalliance-repackaged")
                    .versionAsInProject(),
                mavenBundle().groupId("org.javassist").artifactId("javassist").versionAsInProject(),

                // Google Guava
                mavenBundle().groupId("com.google.guava").artifactId("guava").versionAsInProject(),

                // JAX-RS API
                mavenBundle()
                    .groupId("javax.ws.rs")
                    .artifactId("javax.ws.rs-api")
                    .versionAsInProject(),

                // validation - required by jersey-container-servlet-core
                mavenBundle()
                    .groupId("javax.validation")
                    .artifactId("validation-api")
                    .versionAsInProject(),

                // Jersey bundles
                mavenBundle()
                    .groupId("org.glassfish.jersey.core")
                    .artifactId("jersey-common")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.jersey.core")
                    .artifactId("jersey-server")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.jersey.core")
                    .artifactId("jersey-client")
                    .versionAsInProject(),
                mavenBundle()
                    .groupId("org.glassfish.jersey.containers")
                    .artifactId("jersey-container-servlet-core")
                    .versionAsInProject(),

                // Those two bundles have different (unique) maven coordinates, but represent the
                // same OSGi bundle in two
                // different versions.
                // (see the maven bundle plugin configuration in each of the two pom.xml files
                // Both bundles are explicitly loaded here to ensure, that both co-exist within the
                // OSGi runtime;
                mavenBundle()
                    .groupId("org.glassfish.jersey.examples.osgi-helloworld-webapp")
                    .artifactId("additional-bundle")
                    .versionAsInProject(),

                // The alternate-version-bundle contains the same resource in the same package
                // (org.glassfish.jersey.examples.osgi.helloworld.additional.resource.AdditionalResource),
                // mapped to the same URI (/additional), but returning a different string as a
                // response.
                // ---> if the test passes, it ensures, that Jersey sees/uses the correct version of
                // the bundle
                mavenBundle()
                    .groupId("org.glassfish.jersey.examples.osgi-helloworld-webapp")
                    .artifactId("alternate-version-bundle")
                    .versionAsInProject()

                // Debug
                // vmOption( "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005" )
                ));

    final String localRepository =
        AccessController.doPrivileged(PropertiesHelper.getSystemProperty("localRepository"));
    if (localRepository != null) {
      options = new ArrayList<Option>(options);
      options.add(systemProperty("org.ops4j.pax.url.mvn.localRepository").value(localRepository));
    }

    return options;
  }