Example usage for java.io UncheckedIOException UncheckedIOException

List of usage examples for java.io UncheckedIOException UncheckedIOException

Introduction

In this page you can find the example usage for java.io UncheckedIOException UncheckedIOException.

Prototype

public UncheckedIOException(IOException cause) 

Source Link

Document

Constructs an instance of this class.

Usage

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

public static void writeLineToChannel(final WritableByteChannel destChannel, final String line,
        final Charset charset) {
    try {/*  ww  w .java  2 s  . co m*/
        String tmpLine = line.endsWith(SystemUtils.LINE_SEPARATOR) ? line : line + SystemUtils.LINE_SEPARATOR;
        CharBuffer buffer = CharBuffer.wrap(tmpLine);
        CharsetEncoder encoder = charset.newEncoder();
        ByteBuffer bb = encoder.encode(buffer);
        writeToChannel(destChannel, bb);
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get a base64-encoded image for inclusion in an img tag with a chart with message flight times.
 *
 * @return chart as base64 string./*from www  . j  a  va 2  s .  co m*/
 */
public String getBase64EncodedFlightTimeMetricsImage() {
    TimeSeries timeSeries50p = new TimeSeries("Median");
    TimeSeries timeSeries95p = new TimeSeries("95 percentile");
    TimeSeries timeSeriesMax = new TimeSeries("Max");
    for (FlightTimeMetrics m : getFlightTimeMetrics()) {
        Minute minute = new Minute(m.getPeriod());
        timeSeries50p.add(minute, m.getMedian());
        timeSeries95p.add(minute, m.getPercentile95());
        timeSeriesMax.add(minute, m.getMax());
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeries50p);
    timeSeriesCollection.addSeries(timeSeries95p);
    timeSeriesCollection.addSeries(timeSeriesMax);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Flight time", "Time", "ms",
                timeSeriesCollection);
        chart.getPlot().setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(bos, chart, 1024, 500);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}

From source file:org.everit.jetty.server.ecm.tests.JettyComponentTest.java

@Test
public void testForwardRequestCustomizer() {
    try {//from   w w  w .j  a v a2 s  .co m
        InetAddress localHost = InetAddress.getLocalHost();
        URL url = new URL("http://" + localHost.getHostName() + ":" + port + "/sample/echoremote");
        HttpURLConnection urlConnection = openConnection(url);
        JSONObject jsonObject = readJSONResponse(urlConnection);
        Assert.assertEquals(localHost.getHostName(), jsonObject.getString("serverName"));
        Assert.assertEquals(String.valueOf(port), jsonObject.get("serverPort").toString());

        final String testClientName = "11.11" + ".11.11";
        final String testServerName = "mytest.com";
        final int testServerPort = 888;

        urlConnection = openConnection(url);
        urlConnection.setRequestProperty(HttpHeader.X_FORWARDED_FOR.asString(), testClientName);

        urlConnection.setRequestProperty(HttpHeader.X_FORWARDED_HOST.asString(),
                testServerName + ":" + testServerPort);
        urlConnection.setRequestProperty(HttpHeader.X_FORWARDED_PROTO.asString(), "https");

        jsonObject = readJSONResponse(urlConnection);
        Assert.assertEquals(testClientName, jsonObject.getString("remoteAddr"));
        Assert.assertEquals(testServerName, jsonObject.getString("serverName"));
        Assert.assertEquals(String.valueOf(testServerPort), jsonObject.get("serverPort").toString());
        Assert.assertEquals(true, Boolean.valueOf(jsonObject.get("secure").toString()));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

}

From source file:com.github.horrorho.inflatabledonkey.chunk.engine.ChunkListDecrypter.java

Optional<InputStream> positionedStream(InputStream inputStream, int position, int chunkOffset,
        int chunkLength) {
    // Align stream offset with chunk offset, although we cannot back track nor should we need to.
    try {/*from  ww w . jav a2s.c  o m*/
        if (chunkOffset < position) {
            logger.warn("-- positionedStream() - bad stream position: {} chunk offset: {}", position,
                    chunkOffset);
            return Optional.empty();
        }
        if (chunkOffset > position) {
            int bytes = chunkOffset - position;
            logger.debug("-- positionedStream() - skipping: {}", bytes);
            inputStream.skip(bytes);
        }
        return Optional.of(inputStream);

    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:jvmoptions.OptionAnalyzer.java

static Map<String, Map<String, String>> parse(Path hpp) {
    System.out.printf("process %s %n", hpp);
    String file = hpp.subpath(4, hpp.getNameCount()).toString().replace(File.separatorChar, '/');
    try {/* w w w. ja  va2 s  .com*/
        String all = preprocess(hpp);

        String categories = "(?<kind>develop|develop_pd|product|product_pd|diagnostic|experimental|notproduct|manageable|product_rw|lp64_product)";

        // detect Regex bugs.
        List<String> names = parseNames(all, categories);
        Set<String> nameSet = new HashSet<>();

        Pattern descPtn = Pattern.compile("\"((\\\\\"|[^\"])+)\"");
        Pattern pattern = Pattern.compile(categories
                + "\\((?<type>\\w+?),[ ]*(?<name>\\w+)[ ]*(,[ ]*(?<default>[\\w ()\\-+/*.\"]+))?,[ ]*(?<desc>("
                + descPtn.pattern() + "[ ]*)+)\\)");

        Map<String, Map<String, String>> result = new HashMap<>();

        int times = 0;
        for (Matcher matcher = pattern.matcher(all); matcher.find(); times++) {
            String name = matcher.group("name");
            verify(names, nameSet, times, name);

            String def = Objects.toString(matcher.group("default"), "");

            String d = matcher.group("desc");
            StringBuilder desc = new StringBuilder();
            for (Matcher m = descPtn.matcher(d); m.find();) {
                desc.append(m.group(1).replaceAll("\\\\", ""));
            }

            Map<String, String> m = new HashMap<>();
            m.put("kind", matcher.group("kind"));
            m.put("type", matcher.group("type"));
            m.put("default", def);
            m.put("description", desc.toString());
            m.put("file", file);
            result.put(name, m);
        }
        System.out.printf("        %s contains %d options%n", hpp, times);

        return result;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:edu.umd.umiacs.clip.tools.io.AllFiles.java

public static Stream<String> lines(Path path) {
    try {//w w w  . ja v  a2 s  .  co m
        String p = path.toString();
        if (!p.contains("*")) {
            return p.endsWith(".gz") ? GZIPFiles.lines(path)
                    : p.endsWith(".bz2") ? BZIP2Files.lines(path) : overridenLines(path);
        } else {
            File file = path.toFile();
            return Stream
                    .of(file.getParentFile().listFiles(
                            (dir, name) -> name.matches(file.getName().replace(".", "\\.").replace("*", ".+"))))
                    .sorted().flatMap(AllFiles::lines);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java

protected String createCheckSum(final File file) {
    Preconditions.checkArgument(file != null);

    try {//w  ww.  j  ava  2  s .  c o  m
        return DigestUtils.md5Hex(Files.toByteArray(file));
    } catch (final IOException ex) {
        LOG.error("Failed to create checksum.", ex);
        throw new UncheckedIOException(ex);
    }
}

From source file:org.codice.ddf.catalog.content.monitor.DavEntry.java

/**
 * Return a local cache of the file being monitored. This file is invalidated if necessary when
 * refresh() is called.// w  w w. j  a v  a  2s.c  o m
 *
 * @param sardine
 * @return the file being monitored
 */
public File getFile(Sardine sardine) throws IOException {
    if (file == null || !file.exists()) {
        Path dav = Files.createTempDirectory("dav");
        File dest = new File(dav.toFile(), URLDecoder.decode(FilenameUtils.getName(getLocation()), "UTF-8"));
        try (OutputStream os = new FileOutputStream(dest)) {
            IOUtils.copy(sardine.get(getLocation()), os);
            setFile(dest);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    return file;
}

From source file:org.opendatakit.briefcase.reused.UncheckedFiles.java

public static long checksumOf(Path file) {
    try {/*from ww  w  .  j av a2 s  .  c om*/
        return FileUtils.checksumCRC32(file.toFile());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.travis4j.TravisClient.java

@Override
public Log getLog(long logId) {
    JsonResponse log = client.query("logs/" + logId);

    long jobId = log.getJson().getJSONObject("log").getLong("job_id");

    // FIXME there must be a better way, but the travis API doesn't seem to work as documented
    URI logResource = URI.create("https://s3.amazonaws.com/archive.travis-ci.org/jobs/" + jobId + "/log.txt");

    LOG.debug("Got log from Travis {}, now fetching log from s3 for job {}", log, jobId);
    HttpUriRequest logRequest = RequestBuilder.get(logResource).addHeader("Accept", "text/plain")
            .addHeader("Content-Type", "text/plain").build();

    HttpResponse response;/*  w  ww.j  ava  2 s. c o m*/
    try {
        response = client.getHttpClient().execute(logRequest);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    LOG.debug("Got response for jobId {}, getting entity", jobId);
    HttpEntity body = null;
    if (response.getStatusLine().getStatusCode() == 200) {
        body = response.getEntity();
    } else {
        LOG.warn("Couldn't get log body: {}", response.getStatusLine());
    }
    LOG.debug("Done getting log {}, creating log object", logId);
    return factory.createLog(log, body);
}