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:ProfileManager.java

/**
 * <p>Runs during first-time setup.  Creates a new configuration file, who's
 * name was previously determined by <code>DATA_FILE_NAME</code>.</p>
 * //from  w ww.jav a 2  s .  co m
 * <p>Parameters beginning with a '<code>@</code>' are place holders.</p>
 * 
 * @param file     Configuration file, whose name is determined by
 *                 <code>DATA_FILE_NAME</code>.
 * 
 * @param name     Name of active profile, need to fix this.
 */
//private static void initConfig (File file, String name) {
private static void initConfig(File file) {

    System.out.println("\nInitializing configuration settings...");

    //  DEBUG:
    characters.get(0).setIdentified(true);
    characters.get(0).setName("Test Name");

    if (verifyScannedBackups() > 0) {
        //OLD: while (unidentifiedCharacters.size() > 0) {
        while (unidentifiedCharacters) {

            identifyCharacter();

        } //  while unidentifiedCharacters (has objects within)

    } //  if there is at least one unverified character

    //  =================================================================

    System.out.println("Initializing " + DATA_FILE_NAME);
    System.out.println("Writing JSON file...");

    //  Root
    JSONObject rootJSON = new JSONObject();
    rootJSON.put("Active Character", "@Not_Selected");
    rootJSON.put("Active Profile", "@Not_Selected");
    JSONObject charactersJSON = new JSONObject();

    //  TODO:  This is just to make it work, for now...
    int increment = 0;

    for (Character character : characters) {

        //System.out.println("\nCreating character in JSON (" + character.getId() + ")...");

        JSONObject characterJSON = new JSONObject();
        characterJSON.put("ID", character.getId());
        String name = character.getName() != null ? character.getName() : "@Unknown_" + increment++;

        //  TODO:  Implement this:
        //characterJSON.put("Active Profile", character.getActiveProfile().name);

        /*
        //  Add profiles/backups:
        JSONArray profileJSON = new JSONArray();
        profileJSON.add("Backup1 Timestamp");
        profileJSON.add("Backup2 Timestamp");
        characterJSON.put("MyProfile", myProfile);
        */

        charactersJSON.put(name, characterJSON);

        //System.out.println("\nJSON Snapshot:\n" + charactersJSON);

    }

    rootJSON.put("Characters", charactersJSON);

    // try-with-resources statement based on post comment below :)
    try (FileWriter fileWriter = new FileWriter(DATA_FILE_NAME)) {
        fileWriter.write(rootJSON.toJSONString());
        System.out.println("Successfully Copied JSON Object to File...");
        System.out.println("\nJSON Object: " + rootJSON);
    } catch (IOException e) {
        System.out.println("IOException: " + e.getLocalizedMessage());
    }

}

From source file:net.sf.jabref.exporter.FileActions.java

/**
 * Saves the database to file, including only the entries included in the
 * supplied input array bes.//from  ww w.j  ava  2 s  .co  m
 *
 * @return A List containing warnings, if any.
 */
public static SaveSession savePartOfDatabase(BibDatabase database, MetaData metaData, File file,
        JabRefPreferences prefs, BibEntry[] bes, Charset encoding, DatabaseSaveType saveType)
        throws SaveException {

    BibEntry be = null;
    boolean backup = prefs.getBoolean(JabRefPreferences.BACKUP);

    SaveSession session;
    try {
        session = new SaveSession(file, encoding, backup);
    } catch (IOException e) {
        throw new SaveException(e.getMessage(), e.getLocalizedMessage());
    }

    // Map to collect entry type definitions
    // that we must save along with entries using them.
    Map<String, EntryType> types = new TreeMap<>();

    // Define our data stream.
    try (VerifyingWriter fw = session.getWriter()) {

        if (saveType != DatabaseSaveType.PLAIN_BIBTEX) {
            // Write signature.
            FileActions.writeBibFileHeader(fw, encoding);
        }

        // Write preamble if there is one.
        FileActions.writePreamble(fw, database.getPreamble());

        // Write strings if there are any.
        FileActions.writeStrings(fw, database);

        // Write database entries. Take care, using CrossRefEntry-
        // Comparator, that referred entries occur after referring
        // ones. Apart from crossref requirements, entries will be
        // sorted as they appear on the screen.
        List<Comparator<BibEntry>> comparators = FileActions.getSaveComparators(true, metaData);

        // Use glazed lists to get a sorted view of the entries:
        List<BibEntry> sorter = new ArrayList<>(bes.length);
        Collections.addAll(sorter, bes);
        Collections.sort(sorter, new FieldComparatorStack<>(comparators));

        BibEntryWriter bibtexEntryWriter = new BibEntryWriter(new LatexFieldFormatter(), true);

        for (BibEntry aSorter : sorter) {
            be = aSorter;

            // Check if we must write the type definition for this
            // entry, as well. Our criterion is that all non-standard
            // types (*not* customized standard types) must be written.
            EntryType tp = be.getType();
            if (EntryTypes.getStandardType(tp.getName()) == null) {
                types.put(tp.getName(), tp);
            }

            bibtexEntryWriter.write(be, fw);
            //only append newline if the entry has changed
            if (!be.hasChanged()) {
                fw.write(Globals.NEWLINE);
            }
        }

        // Write meta data.
        if ((saveType != DatabaseSaveType.PLAIN_BIBTEX) && (metaData != null)) {
            metaData.writeMetaData(fw);
        }

        // Write type definitions, if any:
        if (!types.isEmpty()) {
            for (Map.Entry<String, EntryType> stringBibtexEntryTypeEntry : types.entrySet()) {
                CustomEntryType tp = (CustomEntryType) stringBibtexEntryTypeEntry.getValue();
                CustomEntryTypesManager.save(tp, fw);
                fw.write(Globals.NEWLINE);
            }

        }
    } catch (Throwable ex) {
        session.cancel();
        //repairAfterError(file, backup, status);
        throw new SaveException(ex.getMessage(), ex.getLocalizedMessage(), be);
    }

    return session;

}

From source file:com.example.rtobase2.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/*from   www.  ja  v  a 2 s . c  o m*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }

            if (request instanceof PUT) {
                byte[] payload = ((PUT) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                conn.setRequestMethod("PUT");
                JSONObject jsonobj = getJSONObject(s);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");
                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();
            }

            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

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

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {

                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:com.massabot.codesender.utils.FirmwareUtils.java

public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();//from  w w w.j a  va 2 s . c  o  m
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            // ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java

public static Document parseXmlText(InputSource input_data) {
    //get the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {//from  w  w w . jav  a 2 s  .  c  om

        //Using factory get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //InputSource is = new InputSource();
        //is.setCharacterStream(new StringReader(data));
        //parse using builder to get DOM representation of the data
        Document doc = db.parse(input_data);
        // normalize text representation
        doc.getDocumentElement().normalize();
        System.out.println("Root element of the doc is " + doc.getDocumentElement().getNodeName());

        return doc;

    } catch (ParserConfigurationException pce) {
        System.out.println("Exception is " + pce.getLocalizedMessage());
        pce.printStackTrace();
        return null;
    } catch (SAXException se) {
        System.out.println("Exception is " + se.getLocalizedMessage());
        System.out.println("line " + se.getMessage());
        se.printStackTrace();
        return null;
    } catch (IOException ioe) {
        System.out.println("Exception is " + ioe.getLocalizedMessage());
        ioe.printStackTrace();
        return null;
    } catch (Exception ex) {
        System.out.println("Exception is " + ex.getLocalizedMessage());
        //    ioe.printStackTrace();
        return null;
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static Document readXMLConfigurationFile() {
    Document xmlFile;//www  . j av a  2s .  c  o m

    InputStream xmlFileStream = PanelSettings.class.getClassLoader()
            .getResourceAsStream(CONFIGURATION_FILE_PATH);

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        xmlFile = db.parse(xmlFileStream);
    } catch (IOException e) {
        log.error("Error al leer el archivo de configuracion. Detalle: " + e.getLocalizedMessage());
        e.printStackTrace();
        xmlFile = null;
    } catch (ParserConfigurationException e) {
        log.error("Error al parsear el archivo de configuracion. Detalle: " + e.getLocalizedMessage());
        e.printStackTrace();
        xmlFile = null;
    } catch (SAXException e) {
        log.error("Error al parsear el archivo de configuracion. Detalle: " + e.getLocalizedMessage());
        e.printStackTrace();
        xmlFile = null;
    }

    return xmlFile;
}

From source file:im.vector.util.BugReporter.java

/**
 * Retrieves the logs/*  ww  w  .j av a 2  s .co  m*/
 * @return the logs.
 */
private static String getLogCatError() {
    Process logcatProc;

    try {
        logcatProc = Runtime.getRuntime().exec(LOGCAT_CMD);
    } catch (IOException e1) {
        return "";
    }

    BufferedReader reader = null;
    String response = "";
    try {
        String separator = System.getProperty("line.separator");
        StringBuilder sb = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), BUFFER_SIZE);
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            sb.append(separator);
        }
        response = sb.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "getLog fails with " + e.getLocalizedMessage());
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, "getLog fails with " + e.getLocalizedMessage());
            }
        }
    }
    return response;
}

From source file:internal.static_util.scorer.TermRelatednessScorer.java

/**
 * Gets the number of documents word appears in the document index.
 *
 * @param words The word(s) to do a documentSearch for.
 * @return The number of documents containing (all of) #words#
 *//*from  w  ww.  ja va 2s  .  com*/
private static int getNumOfDocuments(String... words) {
    // Handle idiot cases
    if (words == null || words.length == 0) {
        return 0;
    }

    Query q = QueryUtils.mustContainWords(words);

    // Get the search call
    Callable<Integer> search = () -> {
        try {
            return searcher.count(q);
        } catch (IOException e) {
            log.error(TermRelatednessScorer.class.toString() + ": ERROR: Could not get term count for query "
                    + q.toString() + ".");
            return 0; // Assume no documents then.
        }
    };

    // Get the number of documents from the cache.
    int numDocuments = 0;
    try {
        numDocuments = cache.get(q.toString(), search);
    } catch (ExecutionException e) {
        log.error("[TermRelatednessScorer] ERROR: There was an error while populating the cache: "
                + e.getLocalizedMessage());
        log.debug(e.getStackTrace());
    }
    return numDocuments;
}

From source file:com.sabdroidex.controllers.couchpotato.CouchPotatoController.java

/**
 * Makes a call to mark the snatched results as ignored and try the next best release.
 *
 * @param messageHandler Handler//from  w ww.j  a v  a 2s.c o m
 * @param releaseId ID of release to download
 */
public static void snatchNextMovieRelease(final Handler messageHandler, final int releaseId) {
    if (!Preferences.isSet(Preferences.COUCHPOTATO_URL)) {
        return;
    }

    Thread thread = new Thread() {

        @Override
        public void run() {

            try {
                String result = makeApiCall(MESSAGE.SEARCHER_TRY_NEXT.toString().toLowerCase(),
                        "id=" + releaseId);
                JSONObject jsonObject = new JSONObject(result);
                Log.d(TAG, jsonObject.toString());
            } catch (IOException e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            } catch (Throwable e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            }
        }
    };
    thread.start();
}

From source file:com.sabdroidex.controllers.couchpotato.CouchPotatoController.java

/**
 * Download a release of a movie//from  w w w  . j a v a  2  s .c o  m
 * 
 * @param messageHandler Handler
 * @param releaseId ID of release to download
 */
public static void downloadRelease(final Handler messageHandler, final int releaseId) {
    if (!Preferences.isSet(Preferences.COUCHPOTATO_URL)) {
        return;
    }

    Thread thread = new Thread() {

        @Override
        public void run() {

            try {
                String result = makeApiCall(MESSAGE.RELEASE_DOWNLOAD.toString().toLowerCase(),
                        "id=" + releaseId);
                JSONObject jsonObject = new JSONObject(result);

                Message message = new Message();
                message.setTarget(messageHandler);
                message.what = MESSAGE.RELEASE_DOWNLOAD.hashCode();
                message.obj = jsonObject.getBoolean("success");
                message.sendToTarget();
            } catch (IOException e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            } catch (Throwable e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            }
        }
    };
    thread.start();
}