Example usage for java.io IOException getLocalizedMessage

List of usage examples for java.io IOException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:controlador.Red.java

/**
 * Borrado de un elemento en remoto mediante FTP.
 * @param element Elemento a borrar./*www.java2 s.  c o m*/
 * @return Estado de la operacion.
 */
public static boolean borrarFTP(String element) {
    try {
        boolean res = false;
        if (element.contains("(Directorio)")) {
            element = element.substring(0, element.indexOf('('));
            res = ftp.removeDirectory(element); //Para quitar [...](Directorio)
            if (res)
                System.out.println("Directorio remoto Borrado con Exito.");
        } else {
            res = ftp.deleteFile(element);
            if (res)
                System.out.println("Fichero remoto Borrado con Exito.");
        }

        if (!res)
            System.out
                    .println("Problemas para encontrar o borrar el elemento remoto. Comprueba que no exista.");

        return res;
    } catch (IOException ex) {
        System.out.println("Problemas para borrar en remoto: " + ex.getLocalizedMessage());
    }

    return false;
}

From source file:controlador.Red.java

/**
 * Creacion de un directorio con el nombre pasado como parametro.
 * @param name String que sera el nombre del directorio.
 * @return Resultado de la operacion.//from w  w  w  . j a v a2 s  . co  m
 */
public static boolean mkdirFTP(String name) {
    try {
        boolean res = ftp.makeDirectory(name);

        if (res)
            System.out.println("Directorio remoto Creado con Exito!");
        else
            System.out.println("Problema para crear el Directorio remoto.");

        return res;
    } catch (IOException ex) {
        System.out.println("Problemas para crear el directorio remoto: " + ex.getLocalizedMessage());
    }

    return false;
}

From source file:de.marius_oe.cfs.cryption.Crypter.java

/**
 * Decrypts the given input stream and stores the decrypted bytes in the
 * destinationFile. If compressStream is <code>true</code>, the given stream
 * has been compressed and is uncompressed after decryption.
 *
 * @param inStream/*from   ww  w  .  j av a  2  s  .com*/
 *            source stream with encrypted data and iv at the beginning
 * @param destinationStream
 *            stream for the decrypted data
 * @param compressStream
 *            whether the stream was compressed before encryption
 */
public static void decrypt(InputStream inStream, OutputStream destinationStream, boolean compressStream) {
    logger.debug("decrypting inputstream - compressed: {}", compressStream);

    try {
        // reading iv of stream
        int ivLength = inStream.read();
        byte[] iv = new byte[ivLength];
        inStream.read(iv);

        logger.debug("Decrypt InputStream.");
        inStream = new CipherInputStream(inStream, getCipher(Cipher.DECRYPT_MODE, iv));

        if (compressStream) {
            logger.debug("Decompress InputStream.");

            try {
                inStream = new ZipInputStream(inStream);
                ((ZipInputStream) inStream).getNextEntry();
            } catch (IOException e) {
                logger.debug("Error occured during unzipping - Reason: {}", e.getLocalizedMessage());
                throw new RuntimeException(e);
            }
        }

        // copy stream
        int bytesCopied = IOUtils.copy(inStream, destinationStream);

        logger.debug("decryption done. copied {} decrypted bytes to the outputstream", bytesCopied);

        inStream.close();
        destinationStream.close();
    } catch (IOException e) {
        logger.error("Decryption failed - Reason: {}", e.getLocalizedMessage());
        throw new RuntimeException(e);
    }
}

From source file:controlador.Red.java

/**
 * Get de un fichero desde el Server al Cliente Local.
 * @param rutaLocal Ruta en la cual se creara el fichero.
 * @param name Nombre con el cual se busca el fichero en el server y se crea en local.
 * @return Estado de la operacion.//  www  .j  a v a2s  . c  o  m
 */
public static boolean getFile(String rutaLocal, String name) {
    try {
        url = new URL(conexion + name);
        URLConnection urlConn = url.openConnection();
        InputStream is = urlConn.getInputStream();
        FileOutputStream fos = new FileOutputStream(rutaLocal + name);
        byte[] buffer = new byte[BUFFER_LENGTH];

        int count;
        while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
        }
        fos.flush();

        is.close();
        fos.close();

        return true;
    } catch (IOException ex) {
        System.out.println("Problema al recibir un fichero desde el Server: " + ex.getLocalizedMessage());
    }

    return false;
}

From source file:android.databinding.tool.MakeCopy.java

private static void addFromFile(File resDir, File resTarget) {
    for (File layoutDir : resDir.listFiles(LAYOUT_DIR_FILTER)) {
        if (layoutDir.isDirectory()) {
            File targetDir = new File(resTarget, layoutDir.getName());
            for (File layoutFile : layoutDir.listFiles(XML_FILENAME_FILTER)) {
                File targetFile = new File(targetDir, layoutFile.getName());
                FileWriter appender = null;
                try {
                    appender = new FileWriter(targetFile, true);
                    appender.write("<!-- From: " + layoutFile.toURI().toString() + " -->\n");
                } catch (IOException e) {
                    System.err.println("Could not update " + layoutFile + ": " + e.getLocalizedMessage());
                } finally {
                    IOUtils.closeQuietly(appender);
                }/*from  w  w  w. j  a v a2s.c  om*/
            }
        }
    }
}

From source file:mcp.tools.nmap.parser.NmapXmlParser.java

public static void parse(File xmlResultsFile, String scanDescription, String commandLine) {
    Pattern endTimePattern = Pattern.compile("<runstats><finished time=\"(\\d+)");
    String xmlResults;/*from ww w. j  a v a  2 s  .  c  om*/
    try {
        xmlResults = FileUtils.readFileToString(xmlResultsFile);
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }

    Matcher m = endTimePattern.matcher(xmlResults);
    Instant scanTime = null;
    if (m.find()) {
        int t;
        try {
            t = Integer.parseInt(m.group(1));
            scanTime = Instant.ofEpochSecond(t);
        } catch (NumberFormatException e) {

        }
    }

    if (scanTime == null) {
        logger.debug("Failed to find scan completion time in nmap results. Using current time.");
        scanTime = Instant.now();
    }
    String path;
    try {
        path = xmlResultsFile.getCanonicalPath();
    } catch (IOException e1) {
        logger.debug("Why did the canonical path fail?");
        path = xmlResultsFile.getAbsolutePath();
    }

    NmapScanSource source = new NmapScanSourceImpl(path, scanDescription, commandLine);

    NMapXmlHandler nmxh = new NMapXmlHandler(scanTime, source);
    SAXParserFactory spf = SAXParserFactory.newInstance();

    SAXParser sp;
    try {
        sp = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    } catch (SAXException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    }

    try {
        sp.parse(xmlResultsFile, nmxh);
    } catch (SAXException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }
}

From source file:controlador.Red.java

/**
 * Envio de un fichero desde el Cliente Local al Server FTP.
 * @param rutaLocal Ruta del Cliente donde se buscara el fichero.
 * @param name Nombre con el cual se buscara y creara el fichero.
 * @return Estado de la operacion./* w  ww.  java  2 s . c o m*/
 */
public static boolean sendFile(String rutaLocal, String name) {
    try {
        url = new URL(conexion + name);
        URLConnection urlConn = url.openConnection();
        OutputStream os = urlConn.getOutputStream();
        FileInputStream fis = new FileInputStream(new File(rutaLocal + name));
        byte[] buffer = new byte[BUFFER_LENGTH];

        int count;
        while ((count = fis.read(buffer)) > 0) {
            os.write(buffer, 0, count);
        }
        os.flush();
        os.close();
        fis.close();

        return true;
    } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("Problema al enviar un fichero al server: " + ex.getLocalizedMessage());
    }

    return false;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.zookeeper.ZKConfigInit.java

/**
 * Loads all bytes from provided file./* w w w .  j ava  2s  .c o m*/
 * 
 * @param cfgFileName
 *            path string of file to read data
 * @return a byte array containing the bytes read from the file, or {@code null} if path is {@code null}/empty or
 *         {@link java.io.IOException} occurs
 */
public static byte[] loadDataFromFile(String cfgFileName) {
    LOGGER.log(OpLevel.INFO,
            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ZKConfigInit.loading.cfg.data"),
            cfgFileName);

    if (StringUtils.isEmpty(cfgFileName)) {
        return null;
    }

    try {
        return Files.readAllBytes(Paths.get(cfgFileName));
    } catch (IOException exc) {
        LOGGER.log(OpLevel.ERROR, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ZKConfigInit.loading.cfg.failed"), exc.getLocalizedMessage(), exc);
        return null;
    }
}

From source file:de.huberlin.german.korpling.laudatioteitool.App.java

private static void validate(String arg, String corpusSchemeURL, String documentSchemeURL,
        String prepartionSchemeURL) {
    File f = new File(arg);
    if (!f.exists()) {
        System.err.println("File " + f.getAbsolutePath() + " does not exist");
        System.exit(-2);//from   ww w  .  ja  v a  2s .c om
    }

    if (f.isDirectory()) {
        try {
            File out = File.createTempFile("tmpvalidation", ".xml");
            out.deleteOnExit();
            MergeTEI merge = new MergeTEI(f, out, corpusSchemeURL, documentSchemeURL, prepartionSchemeURL);
            merge.merge();

            out.delete();

            // if we got until there without exception the document is valid
            System.out.println("Validation successfull");
            System.exit(0);
        } catch (IOException ex) {
            log.error("Could not create temporary file", ex);
        } catch (LaudatioException ex) {
            System.err.println(ex.getLocalizedMessage());
        }
    } else {
        try {
            File out = Files.createTempDir();

            SplitTEI split = new SplitTEI(f, out, corpusSchemeURL, documentSchemeURL, prepartionSchemeURL);
            split.split();

            deleteTemporaryDirectory(out);

            // if we got until there without exception the document is valid
            System.out.println("Validation successfull");
            System.exit(0);
        } catch (IOException ex) {
            log.error("Could not create temporary file", ex);
        } catch (LaudatioException ex) {
            System.err.println(ex.getLocalizedMessage());
        }
    }

    // non-valid per default
    System.exit(1);
}

From source file:SigningProcess.java

public static String sign(String base64, HashMap map) {
    String base64string = null;/*from   w w w .ja va  2 s .c  om*/
    try {
        System.out.println("map :" + map);
        // Getting a set of the entries
        Set set = map.entrySet();
        System.out.println("set :" + set);
        // Get an iterator
        Iterator it = set.iterator();
        // Display elements
        while (it.hasNext()) {
            Entry me = (Entry) it.next();
            String key = (String) me.getKey();
            if ("privateKey".equalsIgnoreCase(key)) {
                privateKey = (PrivateKey) me.getValue();
            }
            if ("certificateChain".equalsIgnoreCase(key)) {
                certificateChain = (X509Certificate[]) me.getValue();
            }
        }

        OcspClient ocspClient = new OcspClientBouncyCastle();
        TSAClient tsaClient = null;
        for (int i = 0; i < certificateChain.length; i++) {
            X509Certificate cert = (X509Certificate) certificateChain[i];
            String tsaUrl = CertificateUtil.getTSAURL(cert);
            if (tsaUrl != null) {
                tsaClient = new TSAClientBouncyCastle(tsaUrl);
                break;
            }
        }
        List<CrlClient> crlList = new ArrayList<CrlClient>();
        crlList.add(new CrlClientOnline(certificateChain));

        String property = System.getProperty("java.io.tmpdir");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] FileByte = decoder.decodeBuffer(base64);
        writeByteArraysToFile(property + "_unsigned.pdf", FileByte);

        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(property + "_unsigned.pdf");
        FileOutputStream os = new FileOutputStream(property + "_signed.pdf");
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        //            appearance.setReason(reason);
        //            appearance.setLocation(location);
        appearance.setAcro6Layers(false);
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig1");
        // Creating the signature
        ExternalSignature pks = new PrivateKeySignature((PrivateKey) privateKey, DigestAlgorithms.SHA256,
                providerMSCAPI.getName());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, pks, certificateChain, crlList, ocspClient, tsaClient, 0,
                MakeSignature.CryptoStandard.CMS);

        InputStream docStream = new FileInputStream(property + "_signed.pdf");
        byte[] encodeBase64 = Base64.encodeBase64(IOUtils.toByteArray(docStream));
        base64string = new String(encodeBase64);
    } catch (IOException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (DocumentException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (GeneralSecurityException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    }
    return base64string;
}