Example usage for java.io IOException IOException

List of usage examples for java.io IOException IOException

Introduction

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

Prototype

public IOException(Throwable cause) 

Source Link

Document

Constructs an IOException with the specified cause and a detail message of (cause==null ?

Usage

From source file:Main.java

/**
 * Serialize XML Document to string using Transformer
 * //  w  ww  .j  a  v a2s.  c o m
 * @param doc XML Document
 * @return String representation of the the Document
 * @throws IOException
 */
public static String serializeToString(Node node, String encoding) throws IOException {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new IOException("Unable to serialize XML document");
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    DOMSource source = new DOMSource(node);
    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    try {
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new IOException("Unable to serialize XML document");
    }
    writer.flush();

    return writer.toString();
}

From source file:com.datasingularity.http.asyncget.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*from   w w  w.  j  a  v  a  2s.c  om*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new VeryTrustingTrustManager() }, new SecureRandom());
        return context;
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.wormsim.data.SimulationConditions.java

public static SimulationConditions read(String str) throws IOException {
    RealDistribution food = null;/*from w w w.ja  v a2s.  c  o m*/
    HashMap<Integer, RealDistribution> pheromones = new HashMap<>();
    HashMap<String, IntegerDistribution> groups = new HashMap<>();

    if (Utils.MULTIBRACKET_VALIDITY_PATTERN.matcher(str).matches()) {
        Matcher m = Utils.SAMPLER_PATTERN.matcher(str);
        while (m.find()) {
            String match = m.group();
            String[] keyvalue = match.split("~");
            if (keyvalue[0].matches("\\s*food\\s*")) {
                food = Utils.readRealDistribution(keyvalue[1].trim());
            } else if (keyvalue[0].matches("\\s*pheromone\\[\\d+\\]\\s*")) {
                int leftbracket = keyvalue[0].indexOf('[') + 1;
                int rightbracket = keyvalue[0].indexOf(']');
                int id = 0;
                try {
                    id = Integer.valueOf(keyvalue[0].substring(leftbracket, rightbracket));
                    if (id < 0) {
                        throw new IOException("Invalid pheromone reference " + id + ", must be positive!");
                    }
                } catch (NumberFormatException ex) {
                    throw new IOException(ex);
                }
                if (pheromones.putIfAbsent(id, Utils.readRealDistribution(keyvalue[1].trim())) != null) {
                    throw new IOException("Duplicate pheromone id " + id);
                }
            } else { // Group Distribution
                groups.put(keyvalue[0].trim(), Utils.readIntegerDistribution(keyvalue[1].trim()));
            }
        }
    } else {
        throw new IOException("Brackets are missing on simulation conditions definition.");
    }
    if (food == null || groups.isEmpty()) {
        throw new IOException("Incomplete Data! Missing food or groups.");
    }

    // Convert pheromones into array
    Optional<Integer> max = pheromones.keySet().stream().max(Integer::max);

    RealDistribution[] pheromone_arr = new RealDistribution[max.orElse(0)];
    pheromones.forEach((k, v) -> pheromone_arr[k - 1] = v);
    for (int i = 0; i < pheromone_arr.length; i++) {
        if (pheromone_arr[i] == null) {
            pheromone_arr[i] = Utils.ZERO_REAL_DISTRIBUTION;
        }
    }

    return new SimulationConditions(food, pheromone_arr, groups);
}

From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java

public static void checkExistsCanRead(File element) throws IOException, NullPointerException {
    if (element == null) {
        throw new NullPointerException("element is null");
    }//from  w  ww  . j av a 2 s  .  c  o m
    if (element.exists() == false) {
        throw new FileNotFoundException("\"" + element.getPath() + "\" in filesytem");
    }
    if (element.canRead() == false) {
        throw new IOException("Can't read element \"" + element.getPath() + "\"");
    }
}

From source file:com.amazonaws.services.iot.client.shadow.AwsIotJsonDeserializer.java

public static long deserializeVersion(AbstractAwsIotDevice device, String jsonState) throws IOException {
    ObjectMapper jsonObjectMapper = device.getJsonObjectMapper();

    JsonNode node = jsonObjectMapper.readTree(jsonState);
    if (node == null) {
        throw new IOException("Invalid shadow document received for " + device.getThingName());
    }//from  w w w . j a v a2 s  . com

    JsonNode versionNode = node.get("version");
    if (versionNode == null) {
        throw new IOException("Missing version field from shadow document for " + device.getThingName());
    }

    return versionNode.asLong();
}

From source file:Main.java

/**
 * This will parse an XML stream and create a DOM document.
 *
 * @param fileName The file to get the XML from.
 * @return The DOM document./*from   ww w.ja va2 s.  c  o m*/
 * @throws IOException It there is an error creating the dom.
 */
public static Document parse(String fileName) throws IOException {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        return builder.parse(fileName);
    } catch (Exception e) {
        IOException thrown = new IOException(e.getMessage());
        throw thrown;
    }
}

From source file:ImageUtilities.java

/**
 * Returns the format of an image (as string).
 * //from w ww .  j a v a  2 s. c o  m
 * @param stream
 *            image source stream
 * 
 * @return format stream (e.g. "JPEG")
 * 
 * @throws IOException
 *             if an I/O error occured
 */
public static String getFormat(InputStream stream) throws IOException {
    ImageInputStream iis = ImageIO.createImageInputStream(stream);
    Iterator iter = ImageIO.getImageReaders(iis);
    if (!iter.hasNext()) {
        throw new IOException("Unsupported image format!");
    }
    ImageReader reader = (ImageReader) iter.next();
    iis.close();
    return reader.getFormatName();
}

From source file:com.excelsiorjet.api.util.Utils.java

public static void cleanDirectory(File f) throws IOException {
    Files.walkFileTree(f.toPath(), new FileVisitor<Path>() {
        @Override/*from  w  ww .  j ava 2s . c  o m*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        private void deleteFile(File f) throws IOException {
            if (!f.delete()) {
                if (f.exists()) {
                    throw new IOException(Txt.s("JetApi.UnableToDelete.Error", f.getAbsolutePath()));
                }
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            deleteFile(file.toFile());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            if (file.toFile().exists()) {
                throw new IOException(Txt.s("JetApi.UnableToDelete.Error", f.getAbsolutePath()));
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            deleteFile(dir.toFile());
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:ie.aib.nbp.aibssl.AibHostVerifier.java

@Override
public void verify(String host, SSLSocket ssl) throws IOException {
    String sslHost = ssl.getInetAddress().getHostName();
    System.out.println("Host=" + host);
    System.out.println("SSL Host=" + sslHost);
    if (host.equals(sslHost)) {
        return;/*from  www  . ja v  a  2 s .  c  om*/
    } else {
        throw new IOException("hostname in certificate didn't match: " + host + " != " + sslHost);
    }
}

From source file:org.commonjava.maven.firth.client.ArtifactClient.java

public static ArtifactClient load(final String baseUrl, final String mapsBasePath,
        final String packagePathFormat, final String source, final String version) throws IOException {
    final HttpClient http = HttpClientBuilder.create().build();

    // Assume something like: http://download.devel.redhat.com/brewroot/artifact-maps/rcm-mw-tools-build/1234/composition.json
    final String compsUrl = PathUtils.normalize(baseUrl, mapsBasePath, source, version, "composition.json");

    final ObjectMapper om = new ObjectMapper();

    HttpGet request = new HttpGet(compsUrl);
    HttpResponse response = http.execute(request);

    SourceComposition comp;/*from  w ww. j  ava  2s. co  m*/
    if (response.getStatusLine().getStatusCode() == 200) {
        comp = om.readValue(response.getEntity().getContent(), SourceComposition.class);
    } else {
        throw new IOException("Failed to read composition from: " + compsUrl);
    }

    final List<String> manifestSources = new ArrayList<String>();
    manifestSources.add(source);
    manifestSources.addAll(comp.getComposedOf());

    final List<SourceManifest> manifests = new ArrayList<SourceManifest>();
    for (final String src : manifestSources) {
        // Assume something like: http://download.devel.redhat.com/brewroot/artifact-maps/rcm-mw-tools-build/1234/manifest.json
        final String manifestUrl = PathUtils.normalize(baseUrl, mapsBasePath, src, version, "manifest.json");
        request = new HttpGet(manifestUrl);
        response = http.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            final SourceManifest manifest = om.readValue(response.getEntity().getContent(),
                    SourceManifest.class);

            manifests.add(manifest);
        } else {
            throw new IOException("Failed to read manifest from: " + manifestUrl);
        }
    }

    final ArtifactMap am = new ArtifactMap(packagePathFormat, manifests);

    return new ArtifactClient(baseUrl, am, http);
}