类org.apache.logging.log4j.core.util.IOUtils源码实例Demo

下面列出了怎么用org.apache.logging.log4j.core.util.IOUtils的API类实例代码及写法,或者点击链接到github查看源代码。

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);
  }
}
 
源代码2 项目: hmftools   文件: CircosConfigWriter.java
@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);
}
 
源代码3 项目: hmftools   文件: ChromosomeRangeExecution.java
@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);
}
 
private String getStringContent(URL resource) throws IOException {
    try (InputStream resourceAsStream = resource.openStream()) {
        InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8);
        return IOUtils.toString(inputStreamReader);
    }
}
 
源代码5 项目: hmftools   文件: CircosCharts.java
@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);
}
 
源代码6 项目: logging-log4j2   文件: ScriptFile.java
@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);
}
 
源代码7 项目: logging-log4j2   文件: HttpURLConnectionManager.java
@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;
        }
    }
}
 
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();
        }
    }
}
 
 类所在包
 类方法
 同包方法