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:com.googlecode.jgenhtml.JGenHtmlUtils.java

/**
 * Writes a resource (e.g. CSS file) to the destination directory.
 * @param resourceName The name of a resource (which the classloader can find).
 * @param destDir The destination directory.
 */// w  ww  .j a  v a  2 s.c om
protected static void writeResource(final File resource, final File destDir) {
    try {
        LOGGER.log(Level.FINE, "Copying resource {0}", resource.getName());
        FileUtils.copyFileToDirectory(resource, destDir);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    }
}

From source file:org.jboss.pnc.environment.docker.DockerEnvironmentDriverRemoteTest.java

static private Map<String, Object> getJSONFromString(String str) {
    Map<String, Object> result = new HashMap<String, Object>();
    try {/*from   www.  ja v  a 2  s.com*/
        result = (Map<String, Object>) new ObjectMapper().readValue(str, Map.class);
    } catch (JsonMappingException jme) {
        logger.error("Error while converting container JSON to Map - " + jme.getLocalizedMessage());
    } catch (IOException ioe) {
        logger.error("Error while converting container JSON to Map - " + ioe.getLocalizedMessage());
    }
    return result;
}

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

private static void writeStreamToFileAndReplace(final InputStream in, final File targetFile, String token,
        String substitute) {//from w  w w . j a  v a  2  s  . c  o m
    try {
        OutputStream out = null;
        try {
            out = new FileOutputStream(targetFile);
            if (token != null && substitute != null) {
                String input = IOUtils.toString(in);
                input = input.replace(token, substitute);
                IOUtils.write(input, out);
            } else {
                IOUtils.copy(in, out);
            }
        } finally {
            if (out != null) {
                out.close();
            }
            in.close();
        }
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    }
}

From source file:jmupen.JMupenUpdater.java

public static void installUpdate() {
    try {//ww  w.jav a 2 s  . c o  m
        String digest = MD5ForFile.getDigest(new FileInputStream(updatePackage), 2048);
        System.out.println("DIGEST UPDATED PACK: " + digest);
        System.out.println("DIGEST ONLINE: " + MD5ForFile.getMd5FromUrl(new URL(Md5URL).openConnection()));
        if (!digest.trim().equals(MD5ForFile.getMd5FromUrl(new URL(Md5URL).openConnection()).trim())) {
            System.err.println("Download failed, removing update file.");
            JMupenGUI.getInstance().showError("Download failed - MD5 Check",
                    "MD5 Check failed, not installing the update.");
            boolean isDeleted = updatePackage.delete();
            if (!isDeleted) {
                JMupenGUI.getInstance().showError("Can't delete temp file",
                        "Please manually delete file at " + updatePackage.getAbsolutePath());
            }
            return;
        }
    } catch (FileNotFoundException e) {
        System.err.println("File not found. Nothing to install.");
        return;
    } catch (Exception e) {
        System.err.println(
                "Almost impossible error (malformed MD5 url or IO problem). " + e.getLocalizedMessage());
    }
    boolean deleted = jarFile.delete();
    System.out.println("Deleted jar? " + deleted);

    if (!deleted) {

        JMupenUtils.extractJar(jarFile, tmpDir);
        JMupenUpdater.startWinUpdaterApplication();

    }
    try {
        FileUtils.moveFile(updatePackage, jarFile);
        JMupenUpdater.restartApplication();
    } catch (IOException ex) {
        System.err.println("Error moving file. You can find updated file at " + JMupenUtils.getConfigDir()
                + " Full mess: " + ex.getLocalizedMessage());
        JMupenGUI.getInstance().showError("Error updating JMupen.",
                "I couldn't move update file in place. You can find the app file in "
                        + JMupenUtils.getConfigDir() + " folder.");
    }
}

From source file:de.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java

public static String writeToString(EObject instance) {
    try {//w  ww  .j a  va 2  s. c  om
        String str = writeToString(instance, NonContainmentReferenceHandling.INLINE, null);
        if (MAX_STRING_SIZE > 0 && str.length() > MAX_STRING_SIZE) {
            return str.substring(0, MAX_STRING_SIZE) + " ... ... ... string is too long (length: "
                    + str.length() + " > allowed: " + MAX_STRING_SIZE + ", see MAX_STRING_SIZE)\n";
        }
        return str;
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage());
        e.printStackTrace();
        return "";
    }
}

From source file:com.smartmarmot.dbforbix.DBforBix.java

private static void reinit() {
    //get config instance
    Config config = Config.getInstance();

    // read config file
    try {/*www .ja  v  a  2s .co m*/
        config.readFileConfig();
    } catch (IOException e) {
        System.err.println("Error in config: " + e.getLocalizedMessage());
        System.exit(-1);
    } catch (NullPointerException e) {
        System.err.println("Error while getting config hash file: " + e.getLocalizedMessage());
        System.exit(-1);
    }

    // init logging
    //      try {
    //         String logfile = config.getLogFile();
    //         
    //         if (logfile.startsWith("./"))
    //            logfile = logfile.replaceFirst(".", config.getBasedir());
    //         
    //         PatternLayout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss}] [%-5p] [%t[%M(%F:%L)]]: %m%n");
    //         RollingFileAppender rfa = new RollingFileAppender(layout, logfile, true);
    //         rfa.setMaxFileSize(config.getLogFileSize());
    //         rfa.setMaxBackupIndex(1);
    //         
    //         Logger.getRootLogger().addAppender(rfa);
    //         if (!debug)
    //            Logger.getRootLogger().setLevel(config.getLogLevel());
    //      }
    //      catch (IOException ex) {
    //         System.err.println("Error while configuring logging: " + ex.getLocalizedMessage());
    //         LOG.error(ex.getLocalizedMessage(), ex);
    //      }

    LOG.info("### executing " + Constants.BANNER + ": " + new Date().toString());
    LOG.info("using config file " + config.getConfigFile());
    LOG.debug(config);

    // read config from Zabbix Server
    config.getZabbixConfigurationItems();// fill itemConfigs collection
    config.buildConfigurationElementsAndSchedulers();
}

From source file:com.intuit.tank.proxy.Main.java

/**
 * Returns a proxy selector//  www .  jav a  2 s  .c o  m
 * 
 * @param proxy
 * @return
 */
static ProxySelector getProxySelector(String proxy) {
    final java.net.Proxy upstream;
    if ("DIRECT".equals(proxy)) {
        upstream = java.net.Proxy.NO_PROXY;
    } else {
        java.net.Proxy.Type type = null;
        if (proxy.startsWith("PROXY ")) {
            type = java.net.Proxy.Type.HTTP;
        } else if (proxy.startsWith("SOCKS ")) {
            type = java.net.Proxy.Type.SOCKS;
        } else
            throw new IllegalArgumentException("Unknown Proxy type: " + proxy);
        proxy = proxy.substring(6); // "SOCKS " or "PROXY "
        int c = proxy.indexOf(':');
        if (c == -1)
            throw new IllegalArgumentException("Illegal proxy address: " + proxy);
        InetSocketAddress addr = new InetSocketAddress(proxy.substring(0, c),
                Integer.parseInt(proxy.substring(c + 1)));
        upstream = new java.net.Proxy(type, addr);
    }
    ProxySelector ps = new ProxySelector() {

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            logger.info("Proxy connection to " + uri + " via " + sa + " failed! " + ioe.getLocalizedMessage());
        }

        @Override
        public List<java.net.Proxy> select(URI uri) {
            return Arrays.asList(upstream);
        }
    };
    return ps;
}

From source file:it.geosolutions.geobatch.figis.intersection.Utilities.java

/************
 * Deletes all files and subdirectories under dir.
 * Returns true if all deletions were successful.
 * If a deletion fails, the method stops attempting to delete and returns false.
 * @param dir/*from   www.ja  v a 2 s.  c  o  m*/
 * @return
 * @throws IOException
 */
static boolean deleteDir(File dir) {

    LOGGER.trace("Deleting dir " + dir);
    try {
        if (dir.exists() && dir.isDirectory()) {
            FileUtils.cleanDirectory(dir);
        }
    } catch (IOException e) {
        LOGGER.error("ERRORE ON DELETING DIR: " + dir.getAbsolutePath());
        LOGGER.error(e.getLocalizedMessage(), e);
    }
    // The directory is now empty so delete it
    return !dir.exists();
}

From source file:net.mceoin.cominghome.api.NestUtil.java

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *//*from   ww  w . j a v a  2  s  . c  o  m*/
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

    String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth="
            + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

            //                System.out.println("Redirect to URL : " + newUrl);

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    if (error) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {//from   www  .  j  a  v a  2s  .c  om
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}