Search in sources :

Example 61 with JsonObject

use of javax.json.JsonObject in project sling by apache.

the class JSONRecordingTest method logsWithCaller.

@Test
public void logsWithCaller() throws Exception {
    StringWriter sw = new StringWriter();
    final JSONRecording r = new JSONRecording("abc", request, true);
    TracerConfig config = new TracerConfig(TracerContext.QUERY_LOGGER, Level.INFO, new CallerStackReporter(20));
    r.log(config, Level.INFO, "foo", tuple("foo"));
    r.done();
    r.render(sw);
    JsonObject json = Json.createReader(new StringReader(sw.toString())).readObject();
    JsonObject l1 = json.getJsonArray("logs").getJsonObject(0);
    assertTrue(l1.containsKey("caller"));
    assertTrue(l1.getJsonArray("caller").size() > 0);
}
Also used : StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 62 with JsonObject

use of javax.json.JsonObject in project sling by apache.

the class JSONRecordingTest method logQueries.

@Test
public void logQueries() throws Exception {
    StringWriter sw = new StringWriter();
    when(request.getMethod()).thenReturn("GET");
    JSONRecording r = new JSONRecording("abc", request, true);
    MDC.put(MDC_QUERY_ID, "1");
    r.log(tc, Level.DEBUG, "org.apache.jackrabbit.oak.query.QueryEngineImpl", tuple("Parsing {} statement: {}", "XPATH", "SELECT FOO"));
    r.log(tc, Level.DEBUG, QE_LOGGER, tuple("query plan FOO PLAN"));
    r.done();
    r.render(sw);
    JsonObject json = Json.createReader(new StringReader(sw.toString())).readObject();
    assertEquals("GET", json.getString("method"));
    assertTrue(json.containsKey("time"));
    assertTrue(json.containsKey("timestamp"));
    assertEquals(1, json.getJsonArray("queries").size());
}
Also used : StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 63 with JsonObject

use of javax.json.JsonObject in project sling by apache.

the class LogTracerTest method recordingWithoutTracing.

@Test
public void recordingWithoutTracing() throws Exception {
    activateTracerAndServlet();
    MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(context.bundleContext()) {

        @Override
        public RequestProgressTracker getRequestProgressTracker() {
            return createTracker("x", "y");
        }

        @Override
        public String getRequestURI() {
            return "foo";
        }
    };
    request.setHeader(TracerLogServlet.HEADER_TRACER_RECORDING, "true");
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain chain = new FilterChain() {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            //No TurboFilter should be registered if tracing is not requested
            assertNull(context.getService(TurboFilter.class));
        }
    };
    prepareChain(chain).doFilter(request, response);
    String requestId = getRequestId(response);
    assertNotNull(requestId);
    Recording r = ((TracerLogServlet) context.getService(Servlet.class)).getRecording(requestId);
    assertTrue(r instanceof JSONRecording);
    JSONRecording jr = (JSONRecording) r;
    StringWriter sw = new StringWriter();
    jr.render(sw);
    JsonObject json = Json.createReader(new StringReader(sw.toString())).readObject();
    assertEquals(2, json.getJsonArray("requestProgressLogs").size());
}
Also used : SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockSlingHttpServletRequest(org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonObject(javax.json.JsonObject) StringWriter(java.io.StringWriter) MockSlingHttpServletRequest(org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest) StringReader(java.io.StringReader) Servlet(javax.servlet.Servlet) TurboFilter(ch.qos.logback.classic.turbo.TurboFilter) Test(org.junit.Test)

Example 64 with JsonObject

use of javax.json.JsonObject in project sling by apache.

the class TracerLogServletTest method gzipResponse.

@Test
public void gzipResponse() throws Exception {
    TracerLogServlet logServlet = new TracerLogServlet(context.bundleContext());
    when(request.getMethod()).thenReturn("GET");
    when(request.getHeader(TracerLogServlet.HEADER_TRACER_RECORDING)).thenReturn("true");
    when(request.getHeader("Accept-Encoding")).thenReturn("gzip, deflate");
    Recording recording = logServlet.startRecording(request, response);
    recording.registerTracker(createTracker("x", "y"));
    logServlet.endRecording(request, recording);
    ArgumentCaptor<String> requestIdCaptor = ArgumentCaptor.forClass(String.class);
    verify(response).setHeader(eq(TracerLogServlet.HEADER_TRACER_REQUEST_ID), requestIdCaptor.capture());
    verify(response).setHeader(TracerLogServlet.HEADER_TRACER_PROTOCOL_VERSION, String.valueOf(TracerLogServlet.TRACER_PROTOCOL_VERSION));
    ByteArrayServletOutputStream sos = new ByteArrayServletOutputStream();
    when(response.getOutputStream()).thenReturn(sos);
    when(request.getRequestURI()).thenReturn("/system/console/" + requestIdCaptor.getValue() + ".json");
    logServlet.renderContent(request, response);
    byte[] data = IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(sos.baos.toByteArray())));
    JsonObject json = Json.createReader(new StringReader(new String(data, "UTF-8"))).readObject();
    assertEquals("GET", json.getString("method"));
    assertEquals(2, json.getJsonArray("requestProgressLogs").size());
    verify(response).setHeader("Content-Encoding", "gzip");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Test(org.junit.Test)

Example 65 with JsonObject

use of javax.json.JsonObject in project sling by apache.

the class FsMountHelper method getCurrentConfigurations.

/**
     * Return all file provider configs for this project
     * @param targetUrl The targetUrl of the webconsole
     * @return A map (may be empty) with the pids as keys and the configurations as values
     * @throws MojoExecutionException
     */
public Map<String, FsResourceConfiguration> getCurrentConfigurations(final String targetUrl) throws MojoExecutionException {
    log.debug("Getting current file provider configurations.");
    final Map<String, FsResourceConfiguration> result = new HashMap<>();
    final String getUrl = targetUrl + "/configMgr/(service.factoryPid=" + FS_FACTORY + ").json";
    final GetMethod get = new GetMethod(getUrl);
    try {
        final int status = httpClient.executeMethod(get);
        if (status == 200) {
            String contentType = get.getResponseHeader(HEADER_CONTENT_TYPE).getValue();
            int pos = contentType.indexOf(';');
            if (pos != -1) {
                contentType = contentType.substring(0, pos);
            }
            if (!JsonSupport.JSON_MIME_TYPE.equals(contentType)) {
                log.debug("Response type from web console is not JSON, but " + contentType);
                throw new MojoExecutionException("The Apache Felix Web Console is too old to mount " + "the initial content through file system provider configs. " + "Either upgrade the web console or disable this feature.");
            }
            final String jsonText;
            try (InputStream jsonResponse = get.getResponseBodyAsStream()) {
                jsonText = IOUtils.toString(jsonResponse, CharEncoding.UTF_8);
            }
            try {
                JsonArray array = JsonSupport.parseArray(jsonText);
                for (int i = 0; i < array.size(); i++) {
                    final JsonObject obj = array.getJsonObject(i);
                    final String pid = obj.getString("pid");
                    final JsonObject properties = obj.getJsonObject("properties");
                    final String fsmode = getConfigPropertyValue(properties, PROPERTY_FSMODE);
                    final String path = getConfigPropertyValue(properties, PROPERTY_PATH);
                    final String initialContentImportOptions = getConfigPropertyValue(properties, PROPERTY_INITIAL_CONTENT_IMPORT_OPTIONS);
                    final String fileVaultFilterXml = getConfigPropertyValue(properties, PROPERTY_FILEVAULT_FILTER_XML);
                    String root = getConfigPropertyValue(properties, PROPERTY_ROOTS);
                    if (root == null) {
                        root = getConfigPropertyValue(properties, PROPERTY_ROOT);
                    }
                    if (path != null && path.startsWith(this.project.getBasedir().getAbsolutePath()) && root != null) {
                        FsResourceConfiguration cfg = new FsResourceConfiguration().fsMode(fsmode).providerRootPath(path).contentRootDir(root).initialContentImportOptions(initialContentImportOptions).fileVaultFilterXml(fileVaultFilterXml);
                        log.debug("Found configuration with pid: " + pid + ", " + cfg);
                        result.put(pid, cfg);
                    }
                }
            } catch (JsonException ex) {
                throw new MojoExecutionException("Reading configuration from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
            }
        }
    } catch (HttpException ex) {
        throw new MojoExecutionException("Reading configuration from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Reading configuration from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
    } finally {
        get.releaseConnection();
    }
    return result;
}
Also used : JsonException(javax.json.JsonException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) JsonObject(javax.json.JsonObject) IOException(java.io.IOException) JsonArray(javax.json.JsonArray) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException)

Aggregations

JsonObject (javax.json.JsonObject)302 Test (org.junit.Test)110 JsonArray (javax.json.JsonArray)97 HashMap (java.util.HashMap)68 StringReader (java.io.StringReader)66 ArrayList (java.util.ArrayList)58 Credentials (org.apache.commons.httpclient.Credentials)52 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)52 JsonString (javax.json.JsonString)50 JsonReader (javax.json.JsonReader)49 NameValuePair (org.apache.commons.httpclient.NameValuePair)43 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)41 HashSet (java.util.HashSet)20 Map (java.util.Map)20 JsonException (javax.json.JsonException)20 JsonObjectBuilder (javax.json.JsonObjectBuilder)20 Response (javax.ws.rs.core.Response)19 LinkedHashMap (java.util.LinkedHashMap)17 JsonValue (javax.json.JsonValue)14 StringWriter (java.io.StringWriter)13