Search in sources :

Example 1 with JacksonJsonProvider

use of com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider in project kafka by apache.

the class RestServer method start.

public void start(Herder herder) {
    log.info("Starting REST server");
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(new JacksonJsonProvider());
    resourceConfig.register(RootResource.class);
    resourceConfig.register(new ConnectorsResource(herder));
    resourceConfig.register(new ConnectorPluginsResource(herder));
    resourceConfig.register(ConnectExceptionMapper.class);
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
        FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
        filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler(), requestLogHandler });
    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);
    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new ConnectException("Unable to start REST server", e);
    }
    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}
Also used : Slf4jRequestLog(org.eclipse.jetty.server.Slf4jRequestLog) ConnectorsResource(org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ConnectorPluginsResource(org.apache.kafka.connect.runtime.rest.resources.ConnectorPluginsResource) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) ConnectRestException(org.apache.kafka.connect.runtime.rest.errors.ConnectRestException) IOException(java.io.IOException) ConnectException(org.apache.kafka.connect.errors.ConnectException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ConnectException(org.apache.kafka.connect.errors.ConnectException)

Example 2 with JacksonJsonProvider

use of com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider in project dropwizard by dropwizard.

the class ResourceTestRule method apply.

@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            DropwizardTestResourceConfig.CONFIGURATION_REGISTRY.put(configuration.getId(), configuration);
            try {
                test = new JerseyTest() {

                    @Override
                    protected TestContainerFactory getTestContainerFactory() {
                        return configuration.testContainerFactory;
                    }

                    @Override
                    protected DeploymentContext configureDeployment() {
                        return ServletDeploymentContext.builder(new DropwizardTestResourceConfig(configuration)).initParam(ServletProperties.JAXRS_APPLICATION_CLASS, DropwizardTestResourceConfig.class.getName()).initParam(DropwizardTestResourceConfig.CONFIGURATION_ID, configuration.getId()).build();
                    }

                    @Override
                    protected void configureClient(ClientConfig clientConfig) {
                        final JacksonJsonProvider jsonProvider = new JacksonJsonProvider();
                        jsonProvider.setMapper(configuration.mapper);
                        configuration.clientConfigurator.accept(clientConfig);
                        clientConfig.register(jsonProvider);
                    }
                };
                test.setUp();
                base.evaluate();
            } finally {
                DropwizardTestResourceConfig.CONFIGURATION_REGISTRY.remove(configuration.getId());
                test.tearDown();
            }
        }
    };
}
Also used : DeploymentContext(org.glassfish.jersey.test.DeploymentContext) ServletDeploymentContext(org.glassfish.jersey.test.ServletDeploymentContext) JerseyTest(org.glassfish.jersey.test.JerseyTest) Statement(org.junit.runners.model.Statement) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ClientConfig(org.glassfish.jersey.client.ClientConfig) TestContainerFactory(org.glassfish.jersey.test.spi.TestContainerFactory) InMemoryTestContainerFactory(org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory)

Example 3 with JacksonJsonProvider

use of com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider in project druid by druid-io.

the class JettyServerModule method getJacksonJsonProvider.

@Provides
@Singleton
public JacksonJsonProvider getJacksonJsonProvider(@Json ObjectMapper objectMapper) {
    final JacksonJsonProvider provider = new JacksonJsonProvider();
    provider.setMapper(objectMapper);
    return provider;
}
Also used : JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) LazySingleton(io.druid.guice.LazySingleton) Singleton(com.google.inject.Singleton) Provides(com.google.inject.Provides)

Example 4 with JacksonJsonProvider

use of com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider in project tika by apache.

the class JoshuaNetworkTranslator method translate.

/**
   * <p>Initially then check if the source language has been provided.
   * If no source language (or a null value) has been provided then
   * we make an attempt to guess the source using Tika's
   * {@link org.apache.tika.langdetect.OptimaizeLangDetector}. If we
   * are still unable to guess the language then we return the source
   * text.</p>
   * 
   * <p>We then process the input text into a new string consisting of 
   * sentences, one per line e.g. insert \n between the presence of '.'</p>
   * 
   * @see org.apache.tika.language.translate.Translator#translate
   * (java.lang.String, java.lang.String, java.lang.String)
   */
@Override
public String translate(String text, String sourceLanguage, String targetLanguage) throws TikaException, IOException {
    //create networkURI
    if (!networkServer.endsWith("/")) {
        networkURI = networkServer + "/" + targetLanguage;
    } else {
        networkURI = networkServer + targetLanguage;
    }
    if (!this.isAvailable())
        return text;
    //make an attempt to guess language if one is not provided.
    if (sourceLanguage == null)
        sourceLanguage = detectLanguage(text).getLanguage();
    //process input text into sentences, one per line 
    // e.g. insert \n between the presence of '.'
    StringBuilder sb = new StringBuilder(text);
    int i = 0;
    while ((i = sb.indexOf(".", i + 1)) != -1) {
        sb.replace(i, i + 1, "\n");
    }
    String inputText = sb.toString();
    WebClient client;
    final List<Object> providers = new ArrayList<>();
    JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
    providers.add(jacksonJsonProvider);
    client = WebClient.create(networkURI, providers);
    ObjectMapper requestMapper = new ObjectMapper();
    ObjectNode jsonNode = requestMapper.createObjectNode();
    jsonNode.put("inputLanguage", sourceLanguage);
    jsonNode.put("inputText", inputText);
    //make the reuest
    Response response = client.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(jsonNode);
    BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) response.getEntity(), UTF_8));
    String line;
    StringBuilder responseText = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        responseText.append(line);
    }
    try {
        ObjectMapper responseMapper = new ObjectMapper();
        JsonNode jsonResp = responseMapper.readTree(responseText.toString());
        if (jsonResp.findValuesAsText("outputText") != null) {
            return jsonResp.findValuesAsText("outputText").get(0);
        } else {
            throw new TikaException(jsonResp.findValue("message").get(0).asText());
        }
    } catch (JsonParseException e) {
        throw new TikaException("Error requesting translation from '" + sourceLanguage + "' to '" + targetLanguage + "', JSON response " + "from Joshua REST Server is not well formatted: " + responseText.toString());
    }
}
Also used : TikaException(org.apache.tika.exception.TikaException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(com.fasterxml.jackson.core.JsonParseException) WebClient(org.apache.cxf.jaxrs.client.WebClient) Response(javax.ws.rs.core.Response) BufferedReader(java.io.BufferedReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with JacksonJsonProvider

use of com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider in project cxf by apache.

the class RxJava2ObservableServer method run.

protected void run() {
    Bus bus = BusFactory.getDefaultBus();
    // Make sure default JSONProvider is not loaded
    bus.setProperty("skip.default.json.provider.registration", true);
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setInvoker(new ReactiveIOInvoker());
    sf.setProvider(new JacksonJsonProvider());
    sf.getOutInterceptors().add(new LoggingOutInterceptor());
    sf.setResourceClasses(RxJava2ObservableService.class);
    sf.setResourceProvider(RxJava2ObservableService.class, new SingletonResourceProvider(new RxJava2ObservableService(), true));
    sf.setAddress("http://localhost:" + PORT + "/");
    server = sf.create();
}
Also used : Bus(org.apache.cxf.Bus) ReactiveIOInvoker(org.apache.cxf.jaxrs.rx2.server.ReactiveIOInvoker) LoggingOutInterceptor(org.apache.cxf.ext.logging.LoggingOutInterceptor) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider)

Aggregations

JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)217 WebClient (org.apache.cxf.jaxrs.client.WebClient)149 Response (javax.ws.rs.core.Response)127 ArrayList (java.util.ArrayList)109 HashMap (java.util.HashMap)104 URL (java.net.URL)103 Book (org.apache.cxf.systest.jaxrs.security.Book)76 Test (org.junit.Test)66 JwtAuthenticationClientFilter (org.apache.cxf.rs.security.jose.jaxrs.JwtAuthenticationClientFilter)50 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)50 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)45 ClientBuilder (javax.ws.rs.client.ClientBuilder)28 Number (org.apache.coheigea.cxf.jaxrs.json.common.Number)28 List (java.util.List)27 JwsWriterInterceptor (org.apache.cxf.rs.security.jose.jaxrs.JwsWriterInterceptor)27 LinkedList (java.util.LinkedList)26 GenericType (javax.ws.rs.core.GenericType)26 MediaType (javax.ws.rs.core.MediaType)26 AbstractResourceInfo (org.apache.cxf.jaxrs.model.AbstractResourceInfo)26 AbstractBusClientServerTestBase (org.apache.cxf.testutil.common.AbstractBusClientServerTestBase)26