org.apache.logging.log4j.core.util.IOUtils Java Examples

The following examples show how to use org.apache.logging.log4j.core.util.IOUtils. 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: HttpClientTransport.java    From servicecomb-saga-actuator with Apache License 2.0 5 votes vote down vote up
private SagaResponse on(Request request) {
  try {
    HttpResponse httpResponse = request.execute().returnResponse();
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String content = IOUtils.toString(new InputStreamReader(httpResponse.getEntity().getContent()));
    if (statusCode >= 200 && statusCode < 300) {
      return new SuccessfulSagaResponse(content);
    }
    throw new TransportFailedException("The remote service returned with status code " + statusCode
        + ", reason " + httpResponse.getStatusLine().getReasonPhrase()
        + ", and content " + content);
  } catch (IOException e) {
    throw new TransportFailedException("Network Error", e);
  }
}
 
Example #2
Source File: CircosConfigWriter.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private String readResource(@NotNull final String resource) throws IOException
{
    InputStream in = getClass().getResourceAsStream(resource);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    return IOUtils.toString(reader);
}
 
Example #3
Source File: ChromosomeRangeExecution.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private String readResource(@NotNull final String resource) throws IOException
{
    InputStream in = getClass().getResourceAsStream(resource);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    return IOUtils.toString(reader);
}
 
Example #4
Source File: MCRServletContextResourceImporter.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private String getStringContent(URL resource) throws IOException {
    try (InputStream resourceAsStream = resource.openStream()) {
        InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8);
        return IOUtils.toString(inputStreamReader);
    }
}
 
Example #5
Source File: CircosCharts.java    From hmftools with GNU General Public License v3.0 4 votes vote down vote up
@NotNull
private String readResource(@NotNull final String resource) throws IOException {
    InputStream in = getClass().getResourceAsStream(resource);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    return IOUtils.toString(reader);
}
 
Example #6
Source File: ScriptFile.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@PluginFactory
public static ScriptFile createScript(
        // @formatter:off
        @PluginAttribute String name,
        @PluginAttribute String language,
        @PluginAttribute("path") final String filePathOrUri,
        @PluginAttribute final Boolean isWatched,
        @PluginAttribute final Charset charset) {
        // @formatter:on
    if (filePathOrUri == null) {
        LOGGER.error("No script path provided for ScriptFile");
        return null;
    }
    if (name == null) {
        name = filePathOrUri;
    }
    final URI uri = NetUtils.toURI(filePathOrUri);
    final File file = FileUtils.fileFromUri(uri);
    if (language == null && file != null) {
        final String fileExtension = FileUtils.getFileExtension(file);
        if (fileExtension != null) {
            final ExtensionLanguageMapping mapping = ExtensionLanguageMapping.getByExtension(fileExtension);
            if (mapping != null) {
                language = mapping.getLanguage();
            }
        }
    }
    if (language == null) {
        LOGGER.info("No script language supplied, defaulting to {}", DEFAULT_LANGUAGE);
        language = DEFAULT_LANGUAGE;
    }

    final Charset actualCharset = charset == null ? Charset.defaultCharset() : charset;
    String scriptText;
    try (final Reader reader = new InputStreamReader(
            file != null ? new FileInputStream(file) : uri.toURL().openStream(), actualCharset)) {
        scriptText = IOUtils.toString(reader);
    } catch (final IOException e) {
        LOGGER.error("{}: language={}, path={}, actualCharset={}", e.getClass().getSimpleName(),
                language, filePathOrUri, actualCharset);
        return null;
    }
    final Path path = file != null ? Paths.get(file.toURI()) : Paths.get(uri);
    if (path == null) {
        LOGGER.error("Unable to convert {} to a Path", uri.toString());
        return null;
    }
    return new ScriptFile(name, path, language, isWatched == null ? Boolean.FALSE : isWatched, scriptText);
}
 
Example #7
Source File: HttpURLConnectionManager.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void send(final Layout<?> layout, final LogEvent event) throws IOException {
    final HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setRequestMethod(method);
    if (connectTimeoutMillis > 0) {
        urlConnection.setConnectTimeout(connectTimeoutMillis);
    }
    if (readTimeoutMillis > 0) {
        urlConnection.setReadTimeout(readTimeoutMillis);
    }
    if (layout.getContentType() != null) {
        urlConnection.setRequestProperty("Content-Type", layout.getContentType());
    }
    for (final Property header : headers) {
        urlConnection.setRequestProperty(
            header.getName(),
            header.isValueNeedsLookup() ? getConfiguration().getStrSubstitutor().replace(event, header.getValue()) : header.getValue());
    }
    if (sslConfiguration != null) {
        ((HttpsURLConnection)urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
    }
    if (isHttps && !verifyHostname) {
        ((HttpsURLConnection)urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
    }

    final byte[] msg = layout.toByteArray(event);
    urlConnection.setFixedLengthStreamingMode(msg.length);
    urlConnection.connect();
    try (OutputStream os = urlConnection.getOutputStream()) {
        os.write(msg);
    }

    final byte[] buffer = new byte[1024];
    try (InputStream is = urlConnection.getInputStream()) {
        while (IOUtils.EOF != is.read(buffer)) {
            // empty
        }
    } catch (final IOException e) {
        final StringBuilder errorMessage = new StringBuilder();
        try (InputStream es = urlConnection.getErrorStream()) {
            errorMessage.append(urlConnection.getResponseCode());
            if (urlConnection.getResponseMessage() != null) {
                errorMessage.append(' ').append(urlConnection.getResponseMessage());
            }
            if (es != null) {
                errorMessage.append(" - ");
                int n;
                while (IOUtils.EOF != (n = es.read(buffer))) {
                    errorMessage.append(new String(buffer, 0, n, CHARSET));
                }
            }
        }
        if (urlConnection.getResponseCode() > -1) {
            throw new IOException(errorMessage.toString());
        } else {
            throw e;
        }
    }
}
 
Example #8
Source File: RollingAppenderDirectWriteWithHtmlLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void checkAppenderWithHtmlLayout(boolean append) throws InterruptedException, IOException {
    String prefix = "testHtml_" + (append ? "append_" : "noAppend_");
    Configuration config = loggerContextRule.getConfiguration();
    RollingFileAppender appender = RollingFileAppender.newBuilder()
            .setName("RollingHtml")
            .setFilePattern(DIR + "/" + prefix + "_-%d{MM-dd-yy-HH-mm}-%i.html")
            .setPolicy(new SizeBasedTriggeringPolicy(500))
            .setStrategy(DirectWriteRolloverStrategy.newBuilder()
                    .setConfig(config)
                    .build())
            .setLayout(HtmlLayout.createDefaultLayout())
            .setAppend(append)
            .build();
    boolean stopped = false;
    try {
        int count = 100;
        for (int i = 0; i < count; ++i) {
            appender.append(Log4jLogEvent.newBuilder()
                    .setMessage(new SimpleMessage("This is test message number " + i))
                    .build()
            );
        }
        appender.getManager().flush();
        appender.stop();
        stopped = true;
        Thread.sleep(50);
        final File dir = new File(DIR);
        assertTrue("Directory not created", dir.exists());
        final File[] files = dir.listFiles();
        assertNotNull(files);
        assertThat(files, hasItemInArray(that(hasName(that(endsWith(".html"))))));

        int foundEvents = 0;
        final Pattern eventMatcher = Pattern.compile("title=\"Message\"");
        for (File file : files) {
            if (!file.getName().startsWith(prefix))
                continue;
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String data = IOUtils.toString(reader).trim();
                // check that every file starts with the header
                assertThat("header in file " + file, data, Matchers.startsWith("<!DOCTYPE"));
                assertThat("footer in file " + file, data, Matchers.endsWith("</html>"));
                final Matcher matcher = eventMatcher.matcher(data);
                while (matcher.find()) {
                    foundEvents++;
                }
            }
        }
        assertEquals("Incorrect number of events read.", count, foundEvents);
    } finally {
        if (!stopped) {
            appender.stop();
        }
    }
}