org.glassfish.jersey.jackson.JacksonFeature Java Examples

The following examples show how to use org.glassfish.jersey.jackson.JacksonFeature. 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: JettyServerProvider.java    From browserup-proxy with Apache License 2.0 8 votes vote down vote up
@Inject
public JettyServerProvider(@Named("port") int port, @Named("address") String address, MitmProxyManager proxyManager) throws UnknownHostException {
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.setConfigLocation(SWAGGER_CONFIG_NAME);

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(SWAGGER_PACKAGE);
    resourceConfig.register(openApiResource);
    resourceConfig.register(proxyManagerToHkBinder(proxyManager));
    resourceConfig.register(JacksonFeature.class);
    resourceConfig.register(ConstraintViolationExceptionMapper.class);
    resourceConfig.registerClasses(LoggingFilter.class);

    resourceConfig.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    resourceConfig.property(ServerProperties.WADL_FEATURE_DISABLE, true);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    context.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));;
    context.addServlet(DefaultServlet.class, "/");
    context.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    server = new Server(new InetSocketAddress(InetAddress.getByName(address), port));
    server.setHandler(context);
}
 
Example #2
Source File: Main.java    From batfish with Apache License 2.0 6 votes vote down vote up
private static void initWorkManager(BindPortFutures bindPortFutures) {
  FileBasedStorage fbs = new FileBasedStorage(_settings.getContainersLocation(), _logger);
  _workManager = new WorkMgr(_settings, _logger, new StorageBasedIdManager(fbs), fbs);
  _workManager.startWorkManager();
  // Initialize and start the work manager service using the legacy API and Jettison.
  startWorkManagerService(
      WorkMgrService.class,
      Lists.newArrayList(JettisonFeature.class, MultiPartFeature.class),
      _settings.getServiceWorkPort(),
      bindPortFutures.getWorkPort());
  // Initialize and start the work manager service using the v2 RESTful API and Jackson.

  startWorkManagerService(
      WorkMgrServiceV2.class,
      Lists.newArrayList(
          ServiceObjectMapper.class,
          JacksonFeature.class,
          ApiKeyAuthenticationFilter.class,
          VersionCompatibilityFilter.class),
      _settings.getServiceWorkV2Port(),
      bindPortFutures.getWorkV2Port());
}
 
Example #3
Source File: JerseyApplication.java    From onedev with MIT License 6 votes vote down vote up
@Inject
public JerseyApplication(ServiceLocator serviceLocator) {
	GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
	GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(AppLoader.injector);
    
    String disableMoxy = PropertiesHelper.getPropertyNameForRuntime(
    		CommonProperties.MOXY_JSON_FEATURE_DISABLE,
               getConfiguration().getRuntimeType());
       property(disableMoxy, true);
       property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

       // add the default Jackson exception mappers
       register(JacksonFeature.class);
       
       packages(JerseyApplication.class.getPackage().getName());
       
    for (JerseyConfigurator configurator: AppLoader.getExtensions(JerseyConfigurator.class)) {
    	configurator.configure(this);
    }
}
 
Example #4
Source File: DefaultWebhook.java    From TelegramBots with MIT License 6 votes vote down vote up
public void startServer() throws TelegramApiRequestException {
    ResourceConfig rc = new ResourceConfig();
    rc.register(restApi);
    rc.register(JacksonFeature.class);

    final HttpServer grizzlyServer;
    if (keystoreServerFile != null && keystoreServerPwd != null) {
        SSLContextConfigurator sslContext = new SSLContextConfigurator();

        // set up security context
        sslContext.setKeyStoreFile(keystoreServerFile); // contains server keypair
        sslContext.setKeyStorePass(keystoreServerPwd);

        grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc, true,
                new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false));
    } else {
        grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
    }

    try {
        grizzlyServer.start();
    } catch (IOException e) {
        throw new TelegramApiRequestException("Error starting webhook server", e);
    }
}
 
Example #5
Source File: BitmexRestClient.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public BitmexRestClient(boolean useProduction) {
    if (useProduction) {
        apiURL = productionApiUrl;
    } else {
        apiURL = testnetApiUrl;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(mapper, new Annotations[0]);
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);   
    config.register(provider);
    config.register(JacksonFeature.class);
            
    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example #6
Source File: BitmexRestClient.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public BitmexRestClient(boolean useProduction) {
    if (useProduction) {
        apiURL = productionApiUrl;
    } else {
        apiURL = testnetApiUrl;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(mapper, new Annotations[0]);
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);   
    config.register(provider);
    config.register(JacksonFeature.class);
            
    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example #7
Source File: SFAPIEntryPoint.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public SFAPIEntryPoint() {
    register(MultiPartFeature.class);
    register(ServiceResource.class);
    register(MatrixResource.class);
    register(DictionaryResource.class);
    register(SFRestApiListener.class);
    register(ResponseResolver.class);
    register(TestscriptRunResource.class);
    register(EnvironmentResource.class);
    register(ActionsResource.class);
    register(StatisticsResource.class);
    register(MachineLearningResource.class);
    register(MachineLearningResourceV2.class);
    register(BigButtonResource.class);
    register(TestLibraryResource.class);
    register(SailfishInfoResource.class);
    register(JacksonFeature.class);
    register(StorageResource.class);
    register(InternalResources.class);
    register(VariableSetsResource.class);
    register(ConfigurationResource.class);

    register(CommonExceptionMapper.class);
    register(WebApplicationExceptionMapper.class);
}
 
Example #8
Source File: AdminApiKeyStoreTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient() throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
            KEYSTORE_TYPE,
            CLIENT_KEYSTORE_FILE_PATH,
            CLIENT_KEYSTORE_PW,
            KEYSTORE_TYPE,
            BROKER_TRUSTSTORE_FILE_PATH,
            BROKER_TRUSTSTORE_PW);

    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #9
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 #10
Source File: RestDemoServiceIT.java    From demo-restWS-spring-jersey-tomcat-mybatis with MIT License 6 votes vote down vote up
@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-spring-jersey-tomcat-mybatis-0.0.1-SNAPSHOT/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));

}
 
Example #11
Source File: RestDemoServiceIT.java    From demo-restWS-spring-jersey-jpa2-hibernate with MIT License 6 votes vote down vote up
@Test
public void testGetLegacyPodcast() 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-spring-jersey-jpa2-hibernate-0.0.1-SNAPSHOT/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));

}
 
Example #12
Source File: OpenTsdb.java    From metrics with Apache License 2.0 6 votes vote down vote up
private OpenTsdb(String baseURL, Integer connectionTimeout, Integer readTimeout) {
    final Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
    client.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout);
    client.property(ClientProperties.READ_TIMEOUT, readTimeout);

    this.apiResource = client.target(baseURL);
}
 
Example #13
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient(String user) throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    X509Certificate trustCertificates[] = SecurityUtility.loadCertificatesFromPemFile(
            getTLSFile("ca.cert"));
    SSLContext sslCtx = SecurityUtility.createSslContext(
            false, trustCertificates,
            SecurityUtility.loadCertificatesFromPemFile(getTLSFile(user + ".cert")),
            SecurityUtility.loadPrivateKeyFromPemFile(getTLSFile(user + ".key-pk8")));
    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #14
Source File: AbstractClientTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
public TestApplication(boolean querySpec, boolean jsonApiFilter) {
	property(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, "io.katharsis.client.mock");

	if (!querySpec) {
		feature = new KatharsisTestFeature(new ObjectMapper(), new QueryParamsBuilder(new DefaultQueryParamsParser()), new SampleJsonServiceLocator());
	} else {
		feature = new KatharsisTestFeature(new ObjectMapper(), new DefaultQuerySpecDeserializer(), new SampleJsonServiceLocator());
	}

	feature.addModule(new TestModule());

	if (jsonApiFilter) {
		register(new JsonApiResponseFilter(feature));
		register(new JsonapiExceptionMapperBridge(feature));
		register(new JacksonFeature());
	}

	setupFeature(feature);

	register(feature);
}
 
Example #15
Source File: BaseApplicaionConfig.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public BaseApplicaionConfig() {
	//设置默认时区
	System.setProperty("user.timezone","Asia/Shanghai");
	
	register(ValidationContextResolver.class);
	property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true);
			
	this.packages(packages());
	
	register(ObjectMapperResolver.class);
	register(JacksonFeature.class);
	register(JacksonJsonProvider.class);
	register(new BaseExceptionMapper(createExcetionWrapper()));
	register(RequestContextFilter.class);
	
	register(DefaultWebFilter.class);
	//
	if(FilterConfig.apiDocEnabled()){
		register(SwaggerSerializers.class);
	}
}
 
Example #16
Source File: RestDemoServiceIT.java    From demo-rest-jersey-spring with MIT License 6 votes vote down vote up
@Test
public void testGetLegacyPodcast() 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/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 LEGACY database *************************** "
					+ mapper.writerWithDefaultPrettyPrinter()
							.writeValueAsString(podcast));

}
 
Example #17
Source File: Server.java    From Stargraph with MIT License 6 votes vote down vote up
void start() {
    try {
        Config config = stargraph.getMainConfig();
        String urlStr = config.getString("networking.rest-url");
        ResourceConfig rc = new ResourceConfig();
        rc.register(LoggingFilter.class);
        rc.register(JacksonFeature.class);
        rc.register(MultiPartFeature.class);
        rc.register(CatchAllExceptionMapper.class);
        rc.register(SerializationExceptionMapper.class);
        rc.register(AdminResourceImpl.class);
        rc.register(new KBResourceImpl(stargraph));
        rc.register(new QueryResourceImpl(stargraph));
        httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(urlStr), rc, true);
        logger.info(marker, "Stargraph listening on {}", urlStr);
    } catch (Exception e) {
        throw new StarGraphException(e);
    }
}
 
Example #18
Source File: RestDemoServiceIT.java    From demo-rest-jersey-spring with MIT License 6 votes vote down vote up
@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));

}
 
Example #19
Source File: RxJerseyTest.java    From rx-jersey with MIT License 6 votes vote down vote up
@Override
protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig()
            .register(InjectTestFeature.class)
            .register(JacksonFeature.class)
            .register(RxJerseyClientFeature.class)
            .register(ServerResource.class)
            .register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(RxJerseyTest.this).to(JerseyTest.class);
                }
            });

    configure(resourceConfig);

    return resourceConfig;
}
 
Example #20
Source File: RestResourceConfig.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Autowired
public RestResourceConfig(final ApplicationContext applicationContext) {
    property("contextConfig", applicationContext);
    scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.resetFilters(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Path.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
    register(RequestContextFilter.class);
    register(MultiPartFeature.class);
    register(ObjectMapperProvider.class);
    register(JacksonFeature.class);
    registerResources("com.clicktravel.cheddar.rest.exception.mapper", "com.clicktravel.cheddar.server.http.filter",
            "com.clicktravel.cheddar.server.rest.resource.status", "com.clicktravel.services",
            "com.clicktravel.cheddar.rest.body.writer");
    property(ServerProperties.LOCATION_HEADER_RELATIVE_URI_RESOLUTION_DISABLED, true);
    property(ServerProperties.WADL_FEATURE_DISABLE, true);
}
 
Example #21
Source File: AbstractClientTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public TestApplication(boolean jsonApiFilter, boolean serializeLinksAsObjects) {
	property(CrnkProperties.SERIALIZE_LINKS_AS_OBJECTS, Boolean.toString(serializeLinksAsObjects));

	feature = new CrnkTestFeature();
	feature.getObjectMapper().findAndRegisterModules();

	feature.addModule(new io.crnk.test.mock.TestModule());
	feature.addModule(new ClientTestModule());

	if (jsonApiFilter) {
		register(new JsonApiResponseFilter(feature));
		register(new JsonapiExceptionMapperBridge(feature));
		register(new JacksonFeature());
	}

	setupFeature(feature);

	register(feature);
}
 
Example #22
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 #23
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 #24
Source File: HttpClient.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
/**
 * Private constructor to initiate a HttpClient with a base URL.
 *
 * @param baseUri The base URL to which all HTTP requests are to be made
 * @param ignoreSslErrors Flag can be set to true when any SSL-related errors should be ignored.
 * @param accept The media type which is acceptable for all request by this given HTTP client
 */
private HttpClient(final String baseUri, final boolean ignoreSslErrors, final MediaType accept,
        final MultivaluedMap<String, String> headers) {
    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    this.ignoreSslErrors = ignoreSslErrors;
    if (this.ignoreSslErrors) {
        buildIgnoreSslErrorClient(clientBuilder);
    }
    final Client client = clientBuilder.withConfig(clientConfig()).build();
    client.register(MultiPartFeature.class);
    client.register(ObjectMapperProvider.class);
    client.register(JacksonFeature.class);
    target = client.target(baseUri);
    clientHeaders = mapHeadersToClientHeaders(headers);
    this.headers = headers;
    this.accept = accept;
}
 
Example #25
Source File: RestManager.java    From cep with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Starts the HTTP server exposing the resources defined in the RestRules class.
 * It takes a reference to an object that implements the RestListener interface,
 * which will be notified every time the REST API receives a request of some type.
 *
 * @param wsUri The base URL of the HTTP REST API
 * @param rl The RestListener object that will be notified when a user sends
 *           an HTTP request to the API
 * @see RestRules
 * @see RestListener
 */

public static void startServer(String wsUri, RestListener rl) {
    // Create a resource config that scans for JAX-RS resources and providers
    ResourceConfig rc = new ResourceConfig()
            .register(RestRules.class)
            .register(JacksonFeature.class);

    // Set the listener for the petitions
    listener = rl;

    // Create a new instance of grizzly http server
    // exposing the Jersey application at BASE_URI
    server = GrizzlyHttpServerFactory.createHttpServer(URI.create(wsUri), rc);

    // start the server
    try {
        server.start();
    } catch (IOException e) {
        log.error(e.getMessage());
    }

    log.info("HTTP server started");
}
 
Example #26
Source File: GrapheneRESTServer.java    From Graphene with GNU General Public License v3.0 6 votes vote down vote up
static ResourceConfig generateResourceConfig(Config config, Graphene graphene) {
	ResourceConfig rc = new ResourceConfig();

	// settings
	rc.property(ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
	rc.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); // TODO: remove in production

	// basic features
	rc.register(CORSFilter.class);
	rc.register(JacksonFeature.class);
	rc.register(ValidationFeature.class);

	// custom resources
	GrapheneResourceFactory factory = new GrapheneResourceFactory(config, graphene);

	rc.register(factory.createResource(AdminResource.class));
	rc.register(factory.createResource(CoreferenceResource.class));
	rc.register(factory.createResource(DiscourseSimplificationResource.class));
	rc.register(factory.createResource(RelationExtractionResource.class));

	return rc;
}
 
Example #27
Source File: DockerRegistry.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
private WebTarget getRegistryWebTarget(ImageRef imageRef) {
	if (!webTargets.containsKey(imageRef.getRegistryUrl())) {

		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new JavaTimeModule());

		ClientConfig clientCOnfig = new ClientConfig();
		clientCOnfig.connectorProvider(new HttpUrlConnectorProvider());

		// TODO : This client doesn't handle mandatory Oauth2 Bearer token imposed by some registries implementations (ie : docker hub)
		Client client = ClientBuilder.newClient(clientCOnfig)
				.register(new JacksonJaxbJsonProvider(mapper, new Annotations[] {Annotations.JACKSON}))
				.register(JacksonFeature.class);
		String auth = config.getAuthFor(imageRef.getRegistryName());
		if (auth != null) {
			String[] credentials = new String(Base64.getDecoder().decode(auth), StandardCharsets.UTF_8).split(":");
			client.register(HttpAuthenticationFeature.basicBuilder().credentials(credentials[0], credentials[1]));
		}
		WebTarget webTarget = client.target(imageRef.getRegistryUrl());
		webTargets.put(imageRef.getRegistryUrl(), webTarget);
	}
	return webTargets.get(imageRef.getRegistryUrl());
}
 
Example #28
Source File: BaseApplicaionConfig.java    From azeroth with Apache License 2.0 6 votes vote down vote up
public BaseApplicaionConfig() {
    //设置默认时区
    System.setProperty("user.timezone", "Asia/Shanghai");

    register(ValidationContextResolver.class);
    property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true);

    this.packages(packages());
    register(ObjectMapperResolver.class);
    register(JacksonFeature.class);
    register(JacksonJsonProvider.class);
    register(new BaseExceptionMapper(createExcetionWrapper()));
    register(RequestContextFilter.class);

    register(DefaultWebFilter.class);

    if (FilterConfig.apiDocEnabled()) {
        register(SwaggerSerializers.class);
    }
}
 
Example #29
Source File: Main.java    From http-server-benchmarks with MIT License 6 votes vote down vote up
public static HttpServer startServer() {
    HttpServer server = new HttpServer();
    server.addListener(new NetworkListener("grizzly", "0.0.0.0", 8080));

    final TCPNIOTransportBuilder transportBuilder = TCPNIOTransportBuilder.newInstance();
    //transportBuilder.setIOStrategy(WorkerThreadIOStrategy.getInstance());
    transportBuilder.setIOStrategy(SameThreadIOStrategy.getInstance());
    server.getListener("grizzly").setTransport(transportBuilder.build());
    final ResourceConfig rc = new ResourceConfig().packages("xyz.muetsch.jersey");
    rc.register(JacksonFeature.class);
    final ServerConfiguration config = server.getServerConfiguration();
    config.addHttpHandler(RuntimeDelegate.getInstance().createEndpoint(rc, GrizzlyHttpContainer.class), "/rest/todo/");

    try {
        server.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return server;
}
 
Example #30
Source File: JWTOrFormAuthenticationFilterTest.java    From shiro-jwt with MIT License 5 votes vote down vote up
@Before
public void setUp() throws MalformedURLException {
    Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
    target = client.target(URI.create(new URL(base, "resources/test").toExternalForm()));

    objectMapper = new ObjectMapper();
    objectMapper.addMixIn(TokenResponse.class, MixInExample.class);
}