org.glassfish.jersey.logging.LoggingFeature Java Examples

The following examples show how to use org.glassfish.jersey.logging.LoggingFeature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 8 votes vote down vote up
/**
 * Build the Client used to make HTTP requests.
 * @param debugging Debug setting
 * @return Client
 */
protected Client buildHttpClient(boolean debugging) {
  final ClientConfig clientConfig = new ClientConfig();
  clientConfig.register(MultiPartFeature.class);
  clientConfig.register(json);
  clientConfig.register(JacksonFeature.class);
  clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
  // turn off compliance validation to be able to send payloads with DELETE calls
  clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
  if (debugging) {
    clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
    clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
    // Set logger to ALL
    java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL);
  } else {
    // suppress warnings for payloads with DELETE calls:
    java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE);
  }
  performAdditionalClientConfiguration(clientConfig);
  ClientBuilder clientBuilder = ClientBuilder.newBuilder();
  customizeClientBuilder(clientBuilder);
  clientBuilder = clientBuilder.withConfig(clientConfig);
  return clientBuilder.build();
}
 
Example #2
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 6 votes vote down vote up
protected Client buildClient(Consumer<ClientBuilder> httpClientConfig) {
  ClientBuilder builder = ClientBuilder.newBuilder()
      .register(new MattermostModelMapperProvider(ignoreUnknownProperties))
      .register(JacksonFeature.class).register(MultiPartFeature.class)
      // needs for PUT request with null entity
      // (/commands/{command_id}/regen_token)
      .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
  if (clientLogLevel != null) {
    builder.register(new LoggingFeature(Logger.getLogger(getClass().getName()), clientLogLevel,
        Verbosity.PAYLOAD_ANY, 100000));
  }

  httpClientConfig.accept(builder);

  return builder.build();
}
 
Example #3
Source File: JerseyConfig.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
public JerseyConfig() {
    scan("com.devicehive.resource.converters",
            "com.devicehive.resource.exceptions",
            "com.devicehive.resource.filter");

    registerClasses(AuthApiInfoResourceImpl.class,
            JwtTokenResourceImpl.class);

    property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

    register(RequestContextFilter.class);
    register(LoggingFeature.class);
    register(ContentTypeFilter.class);

    register(io.swagger.jaxrs.listing.ApiListingResource.class);
    register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
}
 
Example #4
Source File: ApiClient.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Build the Client used to make HTTP requests.
 * @param debugging Debug setting
 * @return Client
 */
protected Client buildHttpClient(boolean debugging) {
  final ClientConfig clientConfig = new ClientConfig();
  clientConfig.register(MultiPartFeature.class);
  clientConfig.register(json);
  clientConfig.register(JacksonFeature.class);
    clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    if(debugging) {
        clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024 * 50 /* Log payloads up to 50K */));
        clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
        // Set logger to ALL
        java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL);
    }
    performAdditionalClientConfiguration(clientConfig);
  return ClientBuilder.newClient(clientConfig);
}
 
Example #5
Source File: ApiClient.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Build the Client used to make HTTP requests.
 * @param debugging Debug setting
 * @return Client
 */
protected Client buildHttpClient(boolean debugging) {
  final ClientConfig clientConfig = new ClientConfig();
  clientConfig.register(MultiPartFeature.class);
  clientConfig.register(json);
  clientConfig.register(JacksonFeature.class);
  clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
  if (debugging) {
    clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
    clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
    // Set logger to ALL
    java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL);
  }
  performAdditionalClientConfiguration(clientConfig);
  return ClientBuilder.newClient(clientConfig);
}
 
Example #6
Source File: JerseyConfig.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
public JerseyConfig() {
    scan("com.devicehive.resource.converters",
            "com.devicehive.resource.exceptions",
            "com.devicehive.resource.filter");

    registerClasses(ApiInfoResourceImpl.class,
            ConfigurationResourceImpl.class,
            DeviceCommandResourceImpl.class,
            DeviceNotificationResourceImpl.class,
            DeviceResourceImpl.class,
            NetworkResourceImpl.class,
            DeviceTypeResourceImpl.class,
            WelcomeResourceImpl.class,
            UserResourceImpl.class);

    property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

    register(RequestContextFilter.class);
    register(LoggingFeature.class);
    register(ContentTypeFilter.class);

    register(io.swagger.jaxrs.listing.ApiListingResource.class);
    register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
}
 
Example #7
Source File: JerseyConfig.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
public JerseyConfig() {
    scan("com.devicehive.resource.converters",
            "com.devicehive.resource.exceptions",
            "com.devicehive.resource.filter");

    registerClasses(PluginApiInfoResourceImpl.class,
            PluginResourceImpl.class);

    property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

    register(RequestContextFilter.class);
    register(LoggingFeature.class);
    register(ContentTypeFilter.class);

    register(io.swagger.jaxrs.listing.ApiListingResource.class);
    register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
}
 
Example #8
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Build the Client used to make HTTP requests.
 * @param debugging Debug setting
 * @return Client
 */
protected Client buildHttpClient(boolean debugging) {
  final ClientConfig clientConfig = new ClientConfig();
  clientConfig.register(MultiPartFeature.class);
  clientConfig.register(json);
  clientConfig.register(JacksonFeature.class);
  clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
  // turn off compliance validation to be able to send payloads with DELETE calls
  clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
  if (debugging) {
    clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
    clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
    // Set logger to ALL
    java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL);
  } else {
    // suppress warnings for payloads with DELETE calls:
    java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE);
  }
  performAdditionalClientConfiguration(clientConfig);
  ClientBuilder clientBuilder = ClientBuilder.newBuilder();
  customizeClientBuilder(clientBuilder);
  clientBuilder = clientBuilder.withConfig(clientConfig);
  return clientBuilder.build();
}
 
Example #9
Source File: ResolverClient.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private WebTarget resource() {
    // https://resolver.nkp.cz/api/v3
    WebTarget target = getHttpClient().target(serviceUrl);
    if (LOG.isLoggable(Level.FINEST)) {
        target.register(new LoggingFeature(LOG));
    }
    return target;
}
 
Example #10
Source File: ResourcesClient.java    From event-sourcing-cqrs-examples with MIT License 5 votes vote down vote up
public ResourcesClient(Environment environment, int port) {
  this.client = new JerseyClientBuilder(checkNotNull(environment))
      .build(ResourcesClient.class.getName())
      .property(CONNECT_TIMEOUT, 2000)
      .property(READ_TIMEOUT, 3000)
      .register(new LoggingFeature(getLogger(DEFAULT_LOGGER_NAME), INFO, PAYLOAD_ANY, 1024));
  this.resourcesUrls = new ResourcesUrls(port);
}
 
Example #11
Source File: OaiCatalog.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private Client createClient() {
    ClientBuilder builder = ClientBuilder.newBuilder();
    if (user != null) {
        builder.register(HttpAuthenticationFeature.basic(user, password));
    }
    if (LOG.isLoggable(Level.FINEST)) {
        builder.register(new LoggingFeature(LOG));
    }
    Client client = builder
            .property(ClientProperties.FOLLOW_REDIRECTS, true)
            .property(ClientProperties.CONNECT_TIMEOUT, 2 * 60 * 1000) // 2 min
            .property(ClientProperties.READ_TIMEOUT, 1 * 60 * 1000) // 1 min
            .build();
    return client;
}
 
Example #12
Source File: ServerApplication.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static void enableRequestResponseLogging(final Environment environment) {
  environment
      .jersey()
      .register(
          new LoggingFeature(
              Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
              Level.INFO,
              LoggingFeature.Verbosity.PAYLOAD_ANY,
              LoggingFeature.DEFAULT_MAX_ENTITY_SIZE));
}
 
Example #13
Source File: UnauthedAdminProxyHandlerTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testVipStatus() throws Exception {
    Client client = ClientBuilder.newClient(new ClientConfig().register(LoggingFeature.class));
    WebTarget webTarget = client.target("http://127.0.0.1:" + webServer.getListenPortHTTP().get())
            .path("/status.html");
    String response = webTarget.request().get(String.class);
    Assert.assertEquals(response, "OK");
    client.close();
}
 
Example #14
Source File: ProxyStatsTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Change proxy log level dynamically
 * 
 * @throws Exception
 */
@Test
public void testChangeLogLevel() throws Exception {
    Assert.assertEquals(proxyService.getProxyLogLevel(), 2);
    int newLogLevel = 1;
    Client httpClient = ClientBuilder.newClient(new ClientConfig().register(LoggingFeature.class));
    Response r = httpClient.target(proxyWebServer.getServiceUri()).path("/proxy-stats/logging/" + newLogLevel)
            .request().post(Entity.entity("", MediaType.APPLICATION_JSON));
    Assert.assertEquals(r.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
    Assert.assertEquals(proxyService.getProxyLogLevel(), newLogLevel);
}
 
Example #15
Source File: ProxyStatsTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Validates proxy connection stats api.
 * 
 * @throws Exception
 */
@Test
public void testConnectionsStats() throws Exception {
    final String topicName1 = "persistent://sample/test/local/connections-stats";
    PulsarClient client = PulsarClient.builder().serviceUrl(proxyService.getServiceUrl()).build();
    Producer<byte[]> producer = client.newProducer(Schema.BYTES).topic(topicName1).enableBatching(false)
            .messageRoutingMode(MessageRoutingMode.SinglePartition).create();

    // Create a consumer directly attached to broker
    Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName1).subscriptionName("my-sub").subscribe();

    int totalMessages = 10;
    for (int i = 0; i < totalMessages; i++) {
        producer.send("test".getBytes());
    }

    for (int i = 0; i < totalMessages; i++) {
        Message<byte[]> msg = consumer.receive(1, TimeUnit.SECONDS);
        checkNotNull(msg);
        consumer.acknowledge(msg);
    }

    Client httpClient = ClientBuilder.newClient(new ClientConfig().register(LoggingFeature.class));
    Response r = httpClient.target(proxyWebServer.getServiceUri()).path("/proxy-stats/connections").request()
            .get();
    Assert.assertEquals(r.getStatus(), Response.Status.OK.getStatusCode());
    String response = r.readEntity(String.class).trim();
    List<ConnectionStats> connectionStats = new Gson().fromJson(response, new TypeToken<List<ConnectionStats>>() {
    }.getType());

    assertNotNull(connectionStats);

    consumer.close();
    client.close();
}
 
Example #16
Source File: ResourcesClient.java    From microservices-testing-examples with MIT License 5 votes vote down vote up
public ResourcesClient(Environment environment, int port) {
  this.client = new JerseyClientBuilder(checkNotNull(environment))
      .build(ResourcesClient.class.getName())
      .property(CONNECT_TIMEOUT, 2000)
      .property(READ_TIMEOUT, 10000)
      .register(new LoggingFeature(getLogger(DEFAULT_LOGGER_NAME), INFO, PAYLOAD_ANY, 1024));
  this.resourcesUrls = new ResourcesUrls(port);
}
 
Example #17
Source File: ResourcesClient.java    From microservices-testing-examples with MIT License 5 votes vote down vote up
public ResourcesClient(Environment environment, int port) {
  this.client = new JerseyClientBuilder(checkNotNull(environment))
      .build(ResourcesClient.class.getName())
      .property(CONNECT_TIMEOUT, 2000)
      .property(READ_TIMEOUT, 10000)
      .register(new LoggingFeature(getLogger(DEFAULT_LOGGER_NAME), INFO, PAYLOAD_ANY, 1024));
  this.resourcesUrls = new ResourcesUrls(port);
}
 
Example #18
Source File: WebServicesConfiguration.java    From microservices-transactions-tcc with Apache License 2.0 5 votes vote down vote up
public WebServicesConfiguration() {
	// Register endpoints, providers, ...
	this.register(ContentController.class);
	this.register(new LoggingFeature(
			Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), 
			Level.SEVERE, 
			LoggingFeature.Verbosity.PAYLOAD_ANY, 
			maxlog));
}
 
Example #19
Source File: WebServicesConfiguration.java    From microservices-transactions-tcc with Apache License 2.0 5 votes vote down vote up
public WebServicesConfiguration() {
	register(ForumController.class);
	register(new LoggingFeature(
			Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), 
			Level.SEVERE, 
			LoggingFeature.Verbosity.PAYLOAD_ANY, 
			maxlog));
}
 
Example #20
Source File: MattermostClientTest.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
default MattermostClient createClient() {
  return MattermostClient.builder() //
      .url(getApplicationUrl()) //
      .httpConfig(b -> b.register(new LoggingFeature(Logger.getLogger(MattermostClient.class.getName()), Level.INFO,
          Verbosity.PAYLOAD_ANY, 100000))) //
      .build();
}
 
Example #21
Source File: IncomingWebhookClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
protected Client createClient(Level clientLogLevel) {
  ClientBuilder builder = ClientBuilder.newBuilder().register(MattermostModelMapperProvider.class)
      .register(JacksonFeature.class);
  if (clientLogLevel != null) {
    builder.register(new LoggingFeature(Logger.getLogger(getClass().getName()), clientLogLevel,
        Verbosity.PAYLOAD_ANY, 1000));
  }
  return builder.build();
}
 
Example #22
Source File: Player.java    From acs-demos with MIT License 5 votes vote down vote up
/**
 * Attempts to connect to an Engine API. Returns null if no response or the
 * response object containing the response to a GET of the current status.
 * 
 * @param statusPath
 * @param url
 * @return
 */
protected static Response checkEngineStatus(String url) {
	String statusPath = "api/v0.1/tournament/status";
	Client client = ClientBuilder.newClient(new ClientConfig().register(LoggingFeature.class));
	WebTarget webTarget = client.target(url).path(statusPath);
	Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
	try {
		Response response = invocationBuilder.get();
		logger.debug("Engine response recieved from " + url + statusPath + " : " + response.readEntity(String.class));
		return response;
	} catch (Exception e) {
		logger.debug("Unable to get engine status from " + url + statusPath + " - " + e.getMessage());
		return null;
	}
}
 
Example #23
Source File: Player.java    From acs-demos with MIT License 5 votes vote down vote up
/**
 * Request to join a game.
 * 
 * This sends a request to the game engine (via REST API at
 * `engineEndpoint`) to join a game. When a game is ready the engine will
 * call back to the player via the player API and the game can start.
 * 
 */
public void joinTournament(String engineEndpoint, int numOfPlayers) {
	this.getStatus().setState(PlayerStatus.State.Requesting);
	Client client = ClientBuilder.newClient(new ClientConfig().register( LoggingFeature.class ));
	WebTarget webTarget = client.target(engineEndpoint).path("api/v0.1/tournament/join");

	Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
	GameTicket ticket = new GameTicket(this, numOfPlayers);
	Response response = invocationBuilder.put(Entity.entity(ticket, MediaType.APPLICATION_JSON));
	
	GameStatusResponse status = response.readEntity(GameStatusResponse.class);
	/*
	 * FIXME: Saw this intermittent error circa 1/1/2017
	 * 1705 [main] DEBUG org.gardler.biglittlechallenge.trials.ai.AiPlayerApp  - Waiting for 0ms before requesting to join a new game.
        * 1948 [main] INFO  org.gardler.biglittlechallenge.trials.ai.DumbAIUI  - Created Dumb AI Player UI
        * Exception in thread "main" java.lang.NullPointerException
        *      at org.gardler.biglittlechallenge.core.model.Player.joinTournament(Player.java:146)
        *	    at org.gardler.biglittlechallenge.trials.ai.AiPlayerApp.main(AiPlayerApp.java:64)
	 * 
	 */
	if (status.getState() == GameStatus.State.WaitingForPlayers
			|| status.getState() == GameStatus.State.Starting) {
		this.getStatus().setState(PlayerStatus.State.Waiting);
	}
	
	logger.debug("Request to join tournament - response (status " + response.getStatus() + "): " + status);
}
 
Example #24
Source File: Tournament.java    From acs-demos with MIT License 5 votes vote down vote up
@Override
protected RoundResult playRound(Round round) {
	logger.info("Playing round: " + round.getName());
	
	Iterator<GameTicket> itr = getStatus().getTickets().iterator();
	while (itr.hasNext()) {
		GameTicket player = itr.next();
		logger.debug("Requesting cards from " + player.getPlayerName());
		
		// Ask player for cards
		Client client = ClientBuilder.newClient(new ClientConfig().register( LoggingFeature.class ));
		WebTarget webTarget = client.target(player.getPlayerEndpoint()).path("player/round");
		Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
		Response response = invocationBuilder.put(Entity.entity(round, MediaType.APPLICATION_JSON));
		if (response.getStatus() != 200) {
			logger.warn("Response from " + player.getPlayerName() + " indicates a lack of success.");
			String msg = response.readEntity(String.class);
			logger.warn(response.getStatus() + " - " + msg);
		}
		
		PlayedCards cards = response.readEntity(PlayedCards.class);
		round.addCards(player, cards);
	}
	
	RoundResult results = round.getResults();
	logger.info("Round is complete. Results:\n" + results.toString());
	return results;
}
 
Example #25
Source File: MetricsHttpServer.java    From metrics with Apache License 2.0 5 votes vote down vote up
public void start() {
        URI baseUri = UriBuilder.fromUri("http://localhost/").port(getPort()).build();

        Logger jerseyLogger = Logger.getLogger("org.glassfish.jersey");
        jerseyLogger.setLevel(Level.WARNING);

        resourceConfig.register(MetricsResource.class)
                .register(MetricsController.class)
                .property(ServerProperties.TRACING, TracingConfig.ON_DEMAND.name())
//                .register(new LoggingFilter(jerseyLogger, false))
                .register(new LoggingFeature(jerseyLogger))
                .register(JerseyEventListener.class)
                .register(FastJsonFeature.class);


        String bindingHost = System.getProperty(ALI_METRICS_BINDING_HOST, DEFAULT_BINDING_HOST);

        // set up map request response time for http server
        // http server will run a dedicated thread to check if the connection are expired and close them
        if (System.getProperty("sun.net.httpserver.maxReqTime") == null) {
            // set max time in seconds to wait for a request to finished
            System.setProperty("sun.net.httpserver.maxReqTime", "30");
        }
        if (System.getProperty("sun.net.httpserver.maxRspTime") == null) {
            // set max time in seconds to wait for a response to finished
            System.setProperty("sun.net.httpserver.maxRspTime", "30");
        }

        try {
            Class fastJsonAutoDiscoverClass = MetricsHttpServer.class.getClassLoader()
                    .loadClass("com.alibaba.fastjson.support.jaxrs.FastJsonAutoDiscoverable");
            Field autoDscoverField = fastJsonAutoDiscoverClass.getField("autoDiscover");
            autoDscoverField.set(null, false);
        } catch (Exception e) {
            // ignore
        }

        httpServer = HttpServerFactory.createHttpServer(baseUri, bindingHost, corePoolSize, maxPoolSize,
                keepAliveTimeout, maxQueueSize, resourceConfig);
    }
 
Example #26
Source File: ExampleSecretInjectionApplication.java    From fernet-java8 with Apache License 2.0 5 votes vote down vote up
public ExampleSecretInjectionApplication() {
    register(new LoggingFeature(Logger.getLogger("SecretInjectionApplication"), Verbosity.PAYLOAD_ANY));
    register(FernetSecretFeature.class);
    register(fernetParameterBinder);
    register(AuthenticationResource.class);
    register(ProtectedResource.class);
}
 
Example #27
Source File: RestClientUtil.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private static ClientBuilder enableRestDebug(ClientBuilder builder) {
    return builder.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, Verbosity.PAYLOAD_ANY)
            .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, "INFO");
}
 
Example #28
Source File: HttpClientCommon.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public List<Stage.ConfigIssue> init(List<Stage.ConfigIssue> issues, Stage.Context context) {
  this.context = context;
  if (jerseyClientConfig.tlsConfig.isEnabled()) {
    jerseyClientConfig.tlsConfig.init(
        context,
        Groups.TLS.name(),
        SSL_CONFIG_PREFIX,
        issues
    );
  }

  resourceVars = context.createELVars();
  resourceEval = context.createELEval(RESOURCE_CONFIG_NAME);

  methodVars = context.createELVars();
  methodEval = context.createELEval(HTTP_METHOD_CONFIG_NAME);

  headerVars = context.createELVars();
  headerEval = context.createELEval(HEADER_CONFIG_NAME);

  String proxyUsername = null;
  String proxyPassword = null;
  if(jerseyClientConfig.useProxy) {
    proxyUsername = jerseyClientConfig.proxy.resolveUsername(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
    proxyPassword = jerseyClientConfig.proxy.resolvePassword(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
  }

  jerseyClientConfig.init(context, Groups.PROXY.name(), "conf.client.", issues);
  // Validation succeeded so configure the client.
  if (issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.CONNECT_TIMEOUT, jerseyClientConfig.connectTimeoutMillis)
        .property(ClientProperties.READ_TIMEOUT, jerseyClientConfig.readTimeoutMillis)
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, jerseyClientConfig.numThreads)
        .property(ClientProperties.REQUEST_ENTITY_PROCESSING, jerseyClientConfig.transferEncoding)
        .property(ClientProperties.USE_ENCODING, jerseyClientConfig.httpCompression.getValue());

    if(jerseyClientConfig.useProxy) {
        clientConfig = clientConfig.connectorProvider(new GrizzlyConnectorProvider(new GrizzlyClientCustomizer(
          jerseyClientConfig.useProxy,
          proxyUsername,
          proxyPassword
        )));
    }

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

    if (jerseyClientConfig.requestLoggingConfig.enableRequestLogging) {
      Feature feature = new LoggingFeature(
          REQUEST_LOGGER,
          Level.parse(jerseyClientConfig.requestLoggingConfig.logLevel),
          jerseyClientConfig.requestLoggingConfig.verbosity, jerseyClientConfig.requestLoggingConfig.maxEntitySize
      );
      clientBuilder = clientBuilder.register(feature);
    }

    configureCompression(clientBuilder);

    if (jerseyClientConfig.useProxy) {
      JerseyClientUtil.configureProxy(
        jerseyClientConfig.proxy.uri,
        proxyUsername,
        proxyPassword, clientBuilder
      );
    }

    JerseyClientUtil.configureSslContext(jerseyClientConfig.tlsConfig, clientBuilder);

    configureAuthAndBuildClient(clientBuilder, issues);


    if(jerseyClientConfig.authType.equals(AuthenticationType.KERBEROS_SPNEGO)) {

      String principal = jerseyClientConfig.spnegoPrincipal;
      String keytab = jerseyClientConfig.spnegoKeytabFile;
      CredentialValue princPass = jerseyClientConfig.spnegoPrincipalPassword;
      String pathnameSpnegoConf = context.getResourcesDirectory() + "/spnego.conf";
      File f = new File(pathnameSpnegoConf);
      try {
        PrintWriter pw = new PrintWriter(f);
        pw.println(String.format(SPNEGO_CLIENT_LOGIN, principal, keytab));
        pw.close();
      } catch (IOException e) {
        throw new StageException(HTTP_36,e);
      }

      System.setProperty(JAVAX_SECURITY_AUTH_USE_SUBJECT_CREDS_ONLY, "false");
      System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, pathnameSpnegoConf);

      Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          String kuser = principal;
          String kpass = princPass.get();
          return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
      });
    }
  }
  return issues;
}
 
Example #29
Source File: App.java    From jersey-streaming with Apache License 2.0 4 votes vote down vote up
protected static Server startServer() throws IOException {
    System.out.println("Starting jetty...");
    ResourceConfig config = new ResourceConfig(MediaResource.class);
    config.register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.INFO, LoggingFeature.Verbosity.PAYLOAD_TEXT, Integer.MAX_VALUE));
    return JettyHttpContainerFactory.createServer(BASE_URI, config);
}
 
Example #30
Source File: VerbosityChooserValues.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public VerbosityChooserValues() {
  super(LoggingFeature.Verbosity.class);
}