Exemplo n.º 1
0
  @Test
  public void testGetLegacyPodcasts()
      throws JsonGenerationException, JsonMappingException, IOException {

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonFeature.class);

    Client client = ClientBuilder.newClient(clientConfig);

    WebTarget webTarget =
        client.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");

    Builder request = webTarget.request();
    request.header("Content-type", MediaType.APPLICATION_JSON);

    Response response = request.get();
    Assert.assertTrue(response.getStatus() == 200);

    List<Podcast> podcasts = response.readEntity(new GenericType<List<Podcast>>() {});

    ObjectMapper mapper = new ObjectMapper();
    System.out.print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(podcasts));

    Assert.assertTrue("At least one podcast is present in the LEGACY", podcasts.size() > 0);
  }
Exemplo n.º 2
0
  @Rank(Integer.MAX_VALUE)
  @Singleton
  @Override
  public Client provide() {
    if (!httpServer.isStarted()) {
      throw new TestException("test server not started");
    }

    Object testInstance = testContext.getTestInstance();
    Class<? extends Object> testClass = testInstance.getClass();

    Optional<ClientConfig> optional =
        of(testClass.getDeclaredMethods())
            .filter(p -> p.getDeclaredAnnotation(Config.class) != null)
            .filter(p -> p.getParameterCount() == 0)
            .filter(p -> p.getReturnType().isAssignableFrom(ClientConfig.class))
            .findFirst()
            .map(p -> reflectionUtil.invokeMethod(testInstance, p))
            .map(ClientConfig.class::cast);

    ClientConfig clientConfig = optional.orElseGet(ClientConfig::new);

    JerseyTest jerseyTest =
        testContext.getTestInstance().getClass().getAnnotation(JerseyTest.class);

    if (jerseyTest.logTraffic() && !clientConfig.isRegistered(LoggingFilter.class)) {
      clientConfig.register(new LoggingFilter(log, jerseyTest.dumpEntity()));
    }

    return ClientBuilder.newClient(clientConfig);
  }
Exemplo n.º 3
0
 public static ClientConfig createConfig() {
   ClientConfig clientConfig = new ClientConfig();
   clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 10);
   clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 5000);
   clientConfig.property(ClientProperties.READ_TIMEOUT, 5000);
   return clientConfig;
 }
Exemplo n.º 4
0
  public static Client getClient() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[0];
            }

            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {}

            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {}
          }
        };

    HostnameVerifier hv =
        new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());

    ClientConfig c = new ClientConfig();
    c.register(LoggingFilter.class);

    Client client =
        new JerseyClientBuilder().sslContext(sc).withConfig(c).hostnameVerifier(hv).build();
    return client;
  }
Exemplo n.º 5
0
 protected IceRestClient() {
   ClientConfig clientConfig = new ClientConfig();
   clientConfig.register(IceAuthenticationFilter.class);
   clientConfig.register(PartDataJSONHandler.class);
   clientConfig.register(ArrayDataJSONHandler.class);
   clientConfig.register(MultiPartFeature.class);
   client = ClientBuilder.newClient(clientConfig);
 }
Exemplo n.º 6
0
 private ClientConfig getClientConfig() {
   final ClientConfig cc = new ClientConfig();
   /*2.5-*/
   // cc.register(new HttpDigestAuthFilter("caroline", "zhang"));
   /*2.5+*/
   HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest("caroline", "zhang");
   cc.register(feature);
   return cc;
 }
Exemplo n.º 7
0
 /** Get an existing client or create a new client to handle HTTP request. */
 private Client getClient() {
   if (!hostMap.containsKey(basePath)) {
     ClientConfig config = new ClientConfig();
     config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
     Client client = ClientBuilder.newClient(config);
     client.register(new CsrfProtectionFilter("CSRF"));
     hostMap.put(basePath, client);
   }
   return hostMap.get(basePath);
 }
Exemplo n.º 8
0
  @Test
  public void testCookieResource() {
    ClientConfig cc = new ClientConfig();
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);
    WebTarget r = client.target(getBaseUri());

    assertEquals("NO-COOKIE", r.request().get(String.class));
    assertEquals("value", r.request().get(String.class));
  }
Exemplo n.º 9
0
 /** Initializing jerseyClient. */
 private void initJerseyClient() {
   if (client == null) {
     ClientConfig clientConfig = new ClientConfig();
     clientConfig.register(JacksonJsonProvider.class);
     clientConfig.register(FF4jJacksonMapper.class);
     client = ClientBuilder.newClient(clientConfig);
   }
   if (url == null) {
     throw new IllegalArgumentException(
         "Cannot initialialize Jersey Client : please provide store URL in 'url' attribute");
   }
 }
Exemplo n.º 10
0
 private ClientConfig getClientConfig() {
   final ClientConfig cc = new ClientConfig();
   /*2.5-*/
   // cc.register(new HttpBasicAuthFilter("caroline", "zhang"));
   /*2.5+*/
   HttpAuthenticationFeature feature =
       HttpAuthenticationFeature.basicBuilder()
           .nonPreemptive()
           .credentials("caroline", "zhang")
           .build();
   cc.register(feature);
   return cc;
 }
Exemplo n.º 11
0
  @Test
  public void testCookies() {
    ClientConfig cc = new ClientConfig();
    cc.connectorProvider(new ApacheConnectorProvider());
    JerseyClient client = JerseyClientBuilder.createClient(cc);
    WebTarget r = client.target(getBaseUri());

    assertEquals("NO-COOKIE", r.request().get(String.class));
    assertEquals("value", r.request().get(String.class));

    final ApacheConnector connector = (ApacheConnector) client.getConfiguration().getConnector();
    assertNotNull(connector.getCookieStore().getCookies());
    assertEquals(1, connector.getCookieStore().getCookies().size());
    assertEquals("value", connector.getCookieStore().getCookies().get(0).getValue());
  }
Exemplo n.º 12
0
  @Bean
  public Client webClient() {
    final PoolingHttpClientConnectionManager poolingConnectionManager =
        new PoolingHttpClientConnectionManager();
    poolingConnectionManager.setMaxTotal(webClientConnectionPoolMaxTotal);
    poolingConnectionManager.setDefaultMaxPerRoute(webClientConnectionPoolDefaultMaxPerRoute);

    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(READ_TIMEOUT, 2000);
    clientConfig.property(CONNECT_TIMEOUT, 500);
    clientConfig.property(CONNECTION_MANAGER, poolingConnectionManager);
    clientConfig.connectorProvider(new ApacheConnectorProvider());

    return newClient(clientConfig).register(jacksonJsonProvider());
  }
Exemplo n.º 13
0
  /**
   * Creates an instance of {@link Client}.
   *
   * <p>Checks whether TestContainer provides ClientConfig instance and if not, empty new {@link
   * org.glassfish.jersey.client.ClientConfig} instance will be used to create new client instance.
   *
   * <p>This method is called exactly once when JerseyTest is created.
   *
   * @param tc instance of {@link TestContainer}
   * @param applicationHandler instance of {@link ApplicationHandler}
   * @return A Client instance.
   */
  protected Client getClient(TestContainer tc, ApplicationHandler applicationHandler) {
    ClientConfig cc = tc.getClientConfig();

    if (cc == null) {
      cc = new ClientConfig();
    }

    // check if logging is required
    if (isEnabled(TestProperties.LOG_TRAFFIC)) {
      cc.register(new LoggingFilter(LOGGER, isEnabled(TestProperties.DUMP_ENTITY)));
    }

    configureClient(cc);

    return ClientBuilder.newClient(cc);
  }
Exemplo n.º 14
0
  @Test
  public void testDisabledCookies() {
    ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.DISABLE_COOKIES, true);
    cc.connectorProvider(new ApacheConnectorProvider());
    JerseyClient client = JerseyClientBuilder.createClient(cc);
    WebTarget r = client.target(getBaseUri());

    assertEquals("NO-COOKIE", r.request().get(String.class));
    assertEquals("NO-COOKIE", r.request().get(String.class));

    final ApacheConnector connector = (ApacheConnector) client.getConfiguration().getConnector();
    if (connector.getCookieStore() != null) {
      assertTrue(connector.getCookieStore().getCookies().isEmpty());
    } else {
      assertNull(connector.getCookieStore());
    }
  }
Exemplo n.º 15
0
  @Test
  public void testGetPodcast() throws JsonGenerationException, JsonMappingException, IOException {

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonFeature.class);

    Client client = ClientBuilder.newClient(clientConfig);

    WebTarget webTarget = client.target("http://localhost:8888/demo-rest-jersey-spring/podcasts/2");

    Builder request = webTarget.request(MediaType.APPLICATION_JSON);

    Response response = request.get();
    Assert.assertTrue(response.getStatus() == 200);

    Podcast podcast = response.readEntity(Podcast.class);

    ObjectMapper mapper = new ObjectMapper();
    System.out.print(
        "Received podcast from database *************************** "
            + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(podcast));
  }
Exemplo n.º 16
0
  public EurekaJersey2ClientImpl(
      int connectionTimeout,
      int readTimeout,
      final int connectionIdleTimeout,
      ClientConfig clientConfig) {

    try {
      jerseyClientConfig = clientConfig;
      jerseyClientConfig.register(DiscoveryJerseyProvider.class);
      jerseyClientConfig.connectorProvider(new ApacheConnectorProvider());
      jerseyClientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout);
      jerseyClientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
      apacheHttpClient = ClientBuilder.newClient(jerseyClientConfig);
      connectionCleanerTask = new ConnectionCleanerTask(connectionIdleTimeout);
      eurekaConnCleaner.scheduleWithFixedDelay(
          connectionCleanerTask,
          HTTP_CONNECTION_CLEANER_INTERVAL_MS,
          HTTP_CONNECTION_CLEANER_INTERVAL_MS,
          TimeUnit.MILLISECONDS);
    } catch (Throwable e) {
      throw new RuntimeException("Cannot create Jersey2 client", e);
    }
  }
Exemplo n.º 17
0
  /**
   * Create an instance of test {@link Client} using the client configuration provided by the
   * configured {@link org.glassfish.jersey.test.spi.TestContainer}.
   *
   * <p>If the {@code TestContainer} does not provide any client configuration (passed {@code
   * clientConfig} is {@code null}), the default implementation of this method first creates an
   * empty new {@link org.glassfish.jersey.client.ClientConfig} instance. The client configuration
   * (provided by test container or created) is then passed to {@link
   * #configureClient(org.glassfish.jersey.client.ClientConfig)} which can be overridden in the
   * {@code JerseyTest} subclass to provide custom client configuration. At last, new JAX-RS {@link
   * Client} instance is created based on the resulting client configuration.
   *
   * @param clientConfig test client default configuration. May be {@code null}.
   * @return A Client instance.
   */
  private Client getClient(ClientConfig clientConfig) {
    if (clientConfig == null) {
      clientConfig = new ClientConfig();
    }

    // check if logging is required
    if (isEnabled(TestProperties.LOG_TRAFFIC)) {
      clientConfig.register(new LoggingFilter(LOGGER, isEnabled(TestProperties.DUMP_ENTITY)));
    }

    configureClient(clientConfig);

    return ClientBuilder.newClient(clientConfig);
  }
Exemplo n.º 18
0
  @Override
  protected void configureClient(ClientConfig config) {
    // using AHC as a test client connector to avoid issues with HttpUrlConnection socket
    // management.
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    // adjusting max. connections just to be safe - the testEventSourceReconnect is quite greedy...
    cm.setMaxTotal(MAX_LISTENERS * MAX_ITEMS);
    cm.setDefaultMaxPerRoute(MAX_LISTENERS * MAX_ITEMS);

    config
        .register(SseFeature.class)
        .property(ApacheClientProperties.CONNECTION_MANAGER, cm)
        .property(ClientProperties.READ_TIMEOUT, 2000)
        .connector(new ApacheConnector(config));
  }
Exemplo n.º 19
0
 private static Client makeClient(long requestTimeout, int maxConnections, SSLContext sslContext) {
   ClientConfig clientConfig = new ClientConfig();
   int castRequestTimeout = Ints.checkedCast(requestTimeout);
   clientConfig.register(makeGZipFeature());
   clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, maxConnections);
   clientConfig.property(ClientProperties.CONNECT_TIMEOUT, castRequestTimeout);
   clientConfig.property(ClientProperties.READ_TIMEOUT, castRequestTimeout);
   clientConfig.property(
       ApacheClientProperties.CONNECTION_MANAGER, makeConnectionManager(maxConnections));
   clientConfig.connectorProvider(new ApacheConnectorProvider());
   if (sslContext != null) {
     return ClientBuilder.newBuilder().sslContext(sslContext).withConfig(clientConfig).build();
   } else {
     return ClientBuilder.newClient(clientConfig);
   }
 }
Exemplo n.º 20
0
  private Configuration buildConfig(
      final String name,
      final ExecutorService threadPool,
      final ObjectMapper objectMapper,
      final Validator validator) {
    final ClientConfig config = new ClientConfig();

    for (Object singleton : this.singletons) {
      config.register(singleton);
    }

    for (Class<?> provider : this.providers) {
      config.register(provider);
    }

    config.register(new JacksonMessageBodyProvider(objectMapper));
    config.register(new HibernateValidationFeature(validator));

    for (Map.Entry<String, Object> property : this.properties.entrySet()) {
      config.property(property.getKey(), property.getValue());
    }

    config.register(new DropwizardExecutorProvider(threadPool));
    if (connectorProvider == null) {
      final ConfiguredCloseableHttpClient apacheHttpClient =
          apacheHttpClientBuilder.buildWithDefaultRequestConfiguration(name);
      connectorProvider =
          (client, runtimeConfig) ->
              new DropwizardApacheConnector(
                  apacheHttpClient.getClient(),
                  apacheHttpClient.getDefaultRequestConfig(),
                  configuration.isChunkedEncodingEnabled());
    }
    config.connectorProvider(connectorProvider);

    return config;
  }
Exemplo n.º 21
0
  protected static ClientConfig getClientConfig(
      final Type type,
      final AuthenticationInfo authenticationInfo,
      final boolean includeProxySettings) {
    final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();

    final ClientConfig clientConfig = new ClientConfig().connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);

    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    clientConfig.property(
        ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    // Define fiddler as a local HTTP proxy
    if (includeProxySettings) {
      final String proxyHost;
      if (System.getProperty("proxyHost") != null) {
        proxyHost = System.getProperty("proxyHost");
      } else {
        proxyHost = "127.0.0.1";
      }

      final String proxyPort;
      if (System.getProperty("proxyPort") != null) {
        proxyPort = System.getProperty("proxyPort");
      } else {
        proxyPort = "8888";
      }

      final String proxyUrl = String.format("http://%s:%s", proxyHost, proxyPort);

      clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
      clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }
    return clientConfig;
  }
 protected void configureClient(ClientConfig clientConfig) {
   JacksonJsonProvider json = new JacksonJsonProvider();
   json.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
   clientConfig.register(json);
   clientConfig.connectorProvider(new GrizzlyConnectorProvider());
 }
  /**
   * uploads zip file using the input HTTP URL
   *
   * @param httpURL
   * @param filePath
   * @param filename
   * @return
   * @throws Exception
   */
  public static String testUploadService(String httpURL, File filePath) throws Exception {

    // local variables
    ClientConfig clientConfig = null;
    Client client = null;
    WebTarget webTarget = null;
    Invocation.Builder invocationBuilder = null;
    Response response = null;
    FileDataBodyPart fileDataBodyPart = null;
    FormDataMultiPart formDataMultiPart = null;
    int responseCode;
    String responseMessageFromServer = null;
    String responseString = null;

    try {
      // invoke service after setting necessary parameters
      clientConfig = new ClientConfig();
      clientConfig.register(MultiPartFeature.class);
      client = ClientBuilder.newClient(clientConfig);
      webTarget = client.target(httpURL);

      // set file upload values
      fileDataBodyPart =
          new FileDataBodyPart("uploadFile", filePath, MediaType.APPLICATION_OCTET_STREAM_TYPE);
      formDataMultiPart = new FormDataMultiPart();
      formDataMultiPart.bodyPart(fileDataBodyPart);

      StreamDataBodyPart bodyPart = new StreamDataBodyPart();

      // invoke service
      invocationBuilder = webTarget.request();
      //          invocationBuilder.header("Authorization", "Basic " + authorization);
      response =
          invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

      // get response code
      responseCode = response.getStatus();
      System.out.println("Response code: " + responseCode);

      if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
      }

      // get response message
      responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
      System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

      // get response string
      responseString = response.readEntity(String.class);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      // release resources, if any
      fileDataBodyPart.cleanup();
      formDataMultiPart.cleanup();
      formDataMultiPart.close();
      response.close();
      client.close();
    }
    return responseString;
  }
  @Override
  public void init(DockerClientConfig dockerClientConfig) {
    checkNotNull(dockerClientConfig, "config was not specified");

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.connectorProvider(new ApacheConnectorProvider());
    clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);

    clientConfig.register(ResponseStatusExceptionFilter.class);
    clientConfig.register(JsonClientFilter.class);
    clientConfig.register(JacksonJsonProvider.class);

    // logging may disabled via log level
    clientConfig.register(new SelectiveLoggingFilter(LOGGER, true));

    if (readTimeout != null) {
      clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
    }

    if (connectTimeout != null) {
      clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
    }

    if (clientResponseFilters != null) {
      for (ClientResponseFilter clientResponseFilter : clientResponseFilters) {
        if (clientResponseFilter != null) clientConfig.register(clientResponseFilter);
      }
    }

    if (clientRequestFilters != null) {
      for (ClientRequestFilter clientRequestFilter : clientRequestFilters) {
        if (clientRequestFilter != null) clientConfig.register(clientRequestFilter);
      }
    }

    URI originalUri = dockerClientConfig.getUri();

    SSLContext sslContext = null;

    if (dockerClientConfig.getSslConfig() != null) {
      try {
        sslContext = dockerClientConfig.getSslConfig().getSSLContext();
      } catch (Exception ex) {
        throw new DockerClientException("Error in SSL Configuration", ex);
      }
    }

    PoolingHttpClientConnectionManager connManager =
        new PoolingHttpClientConnectionManager(getSchemeRegistry(originalUri, sslContext));

    if (maxTotalConnections != null) connManager.setMaxTotal(maxTotalConnections);
    if (maxPerRouteConnections != null) connManager.setDefaultMaxPerRoute(maxPerRouteConnections);

    clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager);

    // Configure connection pool timeout
    // clientConfig.property(ApacheClientProperties.REQUEST_CONFIG, RequestConfig.custom()
    // .setConnectionRequestTimeout(1000).build());

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);

    if (sslContext != null) {
      clientBuilder.sslContext(sslContext);
    }

    client = clientBuilder.build();

    if (originalUri.getScheme().equals("unix")) {
      dockerClientConfig.setUri(UnixConnectionSocketFactory.sanitizeUri(originalUri));
    }
    WebTarget webResource = client.target(dockerClientConfig.getUri());

    if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) {
      baseResource = webResource;
    } else {
      baseResource = webResource.path("v" + dockerClientConfig.getVersion());
    }
  }
Exemplo n.º 25
0
 @Override
 protected void configureClient(ClientConfig clientConfig) {
   clientConfig
       .connector(new GrizzlyConnector(clientConfig))
       .property(ClientProperties.READ_TIMEOUT, 1000);
 }
Exemplo n.º 26
0
 @Override
 protected void configureClient(ClientConfig config) {
   config.connectorProvider(new JettyConnectorProvider());
 }
Exemplo n.º 27
0
 /**
  * Register a request customizer for a all requests executed by a client instance configured with
  * this client config.
  *
  * <p>A registered customizer will be used to customize underlying Async HTTP Client request
  * builders for all requests created using the Jersey client instance configured with this client
  * config.
  *
  * <p>Invoking this method on an instance that is not configured to use Grizzly Async HTTP Client
  * connector does not have any effect.
  *
  * @param config Jersey client configuration.
  * @param customizer Async HTTP Client configuration customizer.
  * @return updated JAX-RS client invocation builder with the Grizzly {@link
  *     org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider.RequestCustomizer
  *     RequestCustomizer} attached.
  */
 public static ClientConfig register(ClientConfig config, RequestCustomizer customizer) {
   return config.property(REQUEST_CUSTOMIZER, customizer);
 }
  public void start() {
    String directory = TriplestoreUtil.getTriplestoreLocation();
    Dataset dataset = TDBFactory.createDataset(directory);

    ClientConfig clientConfig = new ClientConfig();
    for (Class providerClass : JenaProvidersRegistry.getProviders()) {
      clientConfig.register(providerClass);
    }
    Client rdfclient = ClientBuilder.newClient(clientConfig);
    System.out.println(
        AMESimAdapterAndTDBSubversionSyncClientWithRevision.oslcServiceProviderCatalogURI);
    Response response =
        rdfclient
            .target(
                AMESimAdapterAndTDBSubversionSyncClientWithRevision.oslcServiceProviderCatalogURI)
            .request("application/rdf+xml")
            .get();
    System.out.println(response.getStatus());
    ServiceProviderCatalog serviceProviderCatalog =
        response.readEntity(ServiceProviderCatalog.class);

    // list to collect all AMESim resources
    ArrayList<AbstractResource> oslcResourcesArrayList = new ArrayList<AbstractResource>();

    for (ServiceProvider serviceProvider : serviceProviderCatalog.getServiceProviders()) {
      System.out.println("serviceProvider " + serviceProvider.getAbout());
      if (serviceProvider.getAbout().toString().endsWith("/serviceProviders/" + fileName)) {

        for (Service service : serviceProvider.getServices()) {
          for (QueryCapability queryCapability : service.getQueryCapabilities()) {
            System.out.println(queryCapability.getQueryBase());
            Response queryCapabilityResponse =
                rdfclient
                    .target(queryCapability.getQueryBase())
                    .request("application/rdf+xml")
                    .get();
            System.out.println(queryCapabilityResponse.getStatus());
            if (queryCapability.getQueryBase().toString().endsWith("components")) {
              AMESimComponent[] oslcResources =
                  queryCapabilityResponse.readEntity(AMESimComponent[].class);
              oslcResourcesArrayList.addAll(
                  Arrays.asList(getResourcesWithVersion(oslcResources, revision)));
            }
            //						else if(queryCapability.getQueryBase().toString().endsWith("lines")){
            //							AMESimLine[] oslcResources =
            // queryCapabilityResponse.readEntity(AMESimLine[].class);
            //
            //	oslcResourcesArrayList.addAll(Arrays.asList(getResourcesWithVersion(oslcResources,
            // revision)));
            //						}
            else if (queryCapability.getQueryBase().toString().endsWith("parameters")) {
              AMESimParameter[] oslcResources =
                  queryCapabilityResponse.readEntity(AMESimParameter[].class);
              oslcResourcesArrayList.addAll(
                  Arrays.asList(getResourcesWithVersion(oslcResources, revision)));
            }
            //						else if(queryCapability.getQueryBase().toString().endsWith("outputports")){
            //							AMESimOutputPort[] oslcResources =
            // queryCapabilityResponse.readEntity(AMESimOutputPort[].class);
            //
            //	oslcResourcesArrayList.addAll(Arrays.asList(getResourcesWithVersion(oslcResources,
            // revision)));
            //						}
            //						else if(queryCapability.getQueryBase().toString().endsWith("inputports")){
            //							AMESimInputPort[] oslcResources =
            // queryCapabilityResponse.readEntity(AMESimInputPort[].class);
            //
            //	oslcResourcesArrayList.addAll(Arrays.asList(getResourcesWithVersion(oslcResources,
            // revision)));
            //						}
            //						else if(queryCapability.getQueryBase().toString().endsWith("model")){
            //							AMESimModel oslcResource =
            // queryCapabilityResponse.readEntity(AMESimModel.class);
            //							oslcResourcesArrayList.add(getResourceWithVersion(oslcResource,revision));
            //						}

          }
        }
      }
    }

    Object[] objects = oslcResourcesArrayList.toArray();

    Model model;
    Model tdbModel = dataset.getDefaultModel();
    try {
      model = JenaModelHelper.createJenaModel(objects);
      tdbModel.add(model);
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (DatatypeConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OslcCoreApplicationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    tdbModel.close();
    dataset.close();
  }
Exemplo n.º 29
0
 @Override
 protected void configureClient(final ClientConfig config) {
   config.register(StringProvider.class);
 }
 @Override
 protected void configureClient(final ClientConfig config) {
   config.register(MoxyJsonFeature.class);
 }