Example usage for java.io PrintWriter checkError

List of usage examples for java.io PrintWriter checkError

Introduction

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

Prototype

public boolean checkError() 

Source Link

Document

Flushes the stream if it's not closed and checks its error state.

Usage

From source file:org.liberty.android.fantastischmemo.converter.MnemosyneXMLExporter.java

public void convert(String src, String dest) throws Exception {
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(src);
    String dbName = FilenameUtils.getName(dest);
    PrintWriter outxml = null;
    try {//from   w w w  . j a va2 s  .  c  o m
        final CardDao cardDao = helper.getCardDao();
        final LearningDataDao learningDataDao = helper.getLearningDataDao();
        final CategoryDao categoryDao = helper.getCategoryDao();

        // Populate all category field in a transaction.
        List<Card> cardList = cardDao.callBatchTasks(new Callable<List<Card>>() {
            public List<Card> call() throws Exception {
                List<Card> cards = cardDao.queryForAll();
                for (Card c : cards) {
                    categoryDao.refresh(c.getCategory());
                    learningDataDao.refresh(c.getLearningData());
                }
                return cards;
            }
        });
        if (cardList == null || cardList.size() == 0) {
            throw new IOException("Read empty or corrupted file");
        }

        outxml = new PrintWriter(new BufferedWriter(new FileWriter(dest)));
        if (outxml.checkError()) {
            throw new IOException("Can't open: " + dest);
        }
        int count = 0;
        long timeOfStart = 0L;
        String id, u, gr, e, ac_rp, rt_rp, lps, ac_rp_l, rt_rp_l, l_rp, n_rp, question, answer, category;
        // Now write the xml to the file
        for (Card card : cardList) {
            // At the first item, we write all metadata
            if (count == 0) {
                //timeOfStart = item.getDatelearnUnix();
                // 2000-01-01 12:00
                timeOfStart = 946728000L;
                outxml.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
                outxml.print("<mnemosyne core_version=\"1\" time_of_start=\"" + timeOfStart + "\" >\n");
                outxml.print("<category active=\"1\">\n");
                outxml.print("<name>" + dbName + "</name>\n");
                outxml.print("</category>\n");
            }
            // Convert the learning data
            LearningData ld = card.getLearningData();
            id = "" + card.getOrdinal();
            gr = "" + ld.getGrade();
            e = "" + ld.getEasiness();
            ac_rp = "" + ld.getAcqReps();
            rt_rp = "" + ld.getRetReps();
            lps = "" + ld.getLapses();
            ac_rp_l = "" + ld.getAcqRepsSinceLapse();
            rt_rp_l = "" + ld.getRetRepsSinceLapse();
            ;
            if (ac_rp.equals("0")) {
                u = "1";
            } else {
                u = "0";
            }
            // Add 1 here to avoid rounding problem

            l_rp = Long.toString((ld.getLastLearnDate().getTime() / 1000 - timeOfStart) / 86400);
            n_rp = Long.toString((ld.getNextLearnDate().getTime() / 1000 - timeOfStart) / 86400 + 1);

            // Replace the illegal symbols from the question and answer
            question = card.getQuestion();
            answer = card.getAnswer();
            category = card.getCategory().getName();
            if (question == null) {
                question = "";
            }
            if (answer == null) {
                answer = "";
            }
            if (category == null) {
                category = "";
            }
            question = question.replaceAll("&", "&amp;");
            question = question.replaceAll("<", "&lt;");
            question = question.replaceAll(">", "&gt;");
            question = question.replaceAll("'", "&apos;");
            question = question.replaceAll("\"", "&quot;");
            answer = answer.replaceAll("&", "&amp;");
            answer = answer.replaceAll("<", "&lt;");
            answer = answer.replaceAll(">", "&gt;");
            answer = answer.replaceAll("'", "&apos;");
            answer = answer.replaceAll("\"", "&quot;");
            category = category.replaceAll("&", "&amp;");
            category = category.replaceAll("<", "&lt;");
            category = category.replaceAll(">", "&gt;");
            category = category.replaceAll("'", "&apos;");
            category = category.replaceAll("\"", "&quot;");

            outxml.print("<item id=\"" + id + "\" u=\"" + u + "\" gr=\"" + gr + "\" e=\"" + e + "\" ac_rp=\""
                    + ac_rp + "\" rt_rp=\"" + rt_rp + "\" lps=\"" + lps + "\" ac_rp_l=\"" + ac_rp_l
                    + "\" rt_rp_l=\"" + rt_rp_l + "\" l_rp=\"" + l_rp + "\" n_rp=\"" + n_rp + "\">\n");

            if (category.equals("")) {
                outxml.print("<cat>" + dbName + "</cat>\n");
            } else {
                outxml.print("<cat>" + category + "</cat>\n");
            }

            outxml.print("<Q>" + question + "</Q>\n");
            outxml.print("<A>" + answer + "</A>\n");
            outxml.print("</item>\n");
            if (outxml.checkError()) {
                throw new IOException("Error writing xml on id: " + id);
            }
            count += 1;
        }
        outxml.print("</mnemosyne>");
        outxml.close();
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
        if (outxml != null) {
            outxml.close();
        }
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.util.CgroupsLCEResourcesHandlerGPU.java

private void updateCgroup(String controller, String groupName, String param, String value) throws IOException {
    String path = pathForCgroup(controller, groupName);
    param = controller + "." + param;

    if (LOG.isDebugEnabled()) {
        LOG.debug("updateCgroup: " + path + ": " + param + "=" + value);
    }/*  w w  w  .j a va 2s .  c o m*/

    PrintWriter pw = null;
    try {
        File file = new File(path + "/" + param);
        Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        pw = new PrintWriter(w);
        LOG.info("Writing " + value + " to file at " + file.getAbsolutePath());
        pw.write(value);
    } catch (IOException e) {
        throw new IOException("Unable to set " + param + "=" + value + " for cgroup at: " + path, e);
    } finally {
        if (pw != null) {
            boolean hasError = pw.checkError();
            pw.close();
            if (hasError) {
                throw new IOException("Unable to set " + param + "=" + value + " for cgroup at: " + path);
            }
            if (pw.checkError()) {
                throw new IOException("Error while closing cgroup file " + path);
            }
        }
    }
}

From source file:com.googlecode.jmxtrans.model.output.GraphiteWriter.java

@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
    Socket socket = null;/*from w  ww  .  j  av  a2s . co m*/
    PrintWriter writer = null;

    try {
        socket = pool.borrowObject(address);
        writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true);

        List<String> typeNames = this.getTypeNames();

        for (Result result : results) {
            log.debug("Query result: {}", result);
            Map<String, Object> resultValues = result.getValues();
            for (Entry<String, Object> values : resultValues.entrySet()) {
                Object value = values.getValue();
                if (isValidNumber(value)) {

                    String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix)
                            .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000
                            + "\n";
                    log.debug("Graphite Message: {}", line);
                    writer.write(line);
                } else {
                    onlyOnceLogger.infoOnce(
                            "Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value,
                            result);
                }
            }
        }
    } finally {
        if (writer != null && writer.checkError()) {
            log.error("Error writing to Graphite, clearing Graphite socket pool");
            pool.invalidateObject(address, socket);
        } else {
            pool.returnObject(address, socket);
        }
    }
}

From source file:org.apache.hadoop.mapred.JobHistory.java

/**
 * Log a number of keys and values with record. the array length of keys and values
 * should be same. /* w w w.  j  av  a  2s .co  m*/
 * @param recordType type of log event
 * @param keys type of log event
 * @param values type of log event
 * @param JobID jobid of the job  
 */

static void log(ArrayList<PrintWriter> writers, RecordTypes recordType, Keys[] keys, String[] values,
        JobID id) {

    // First up calculate the length of buffer, so that we are performant
    // enough.
    int length = recordType.name().length() + keys.length * 4 + 2;
    for (int i = 0; i < keys.length; i++) {
        values[i] = escapeString(values[i]);
        length += values[i].length() + keys[i].toString().length();
    }

    // We have the length of the buffer, now construct it.
    StringBuilder builder = new StringBuilder(length);
    builder.append(recordType.name());
    builder.append(DELIMITER);
    for (int i = 0; i < keys.length; i++) {
        builder.append(keys[i]);
        builder.append("=\"");
        builder.append(values[i]);
        builder.append("\"");
        builder.append(DELIMITER);
    }
    builder.append(LINE_DELIMITER_CHAR);

    for (Iterator<PrintWriter> iter = writers.iterator(); iter.hasNext();) {
        PrintWriter out = iter.next();
        out.println(builder.toString());
        if (out.checkError() && id != null) {
            LOG.info("Logging failed for job " + id + "removing PrintWriter from FileManager");
            iter.remove();
        }
    }
}

From source file:com.alvermont.terraj.fracplanet.io.POVExporter.java

/**
 * Protected method to implement the actual data export
 *
 * @param pw The <code>PrintWriter</code> to write the data to
 * @param params The parameters describing the terrain and rendering
 * @param progress The object to use for reporting progress
 * @throws java.io.IOException If there is an error exporting the data
 *///from  w w  w  .  ja va 2  s.  c  om
protected void export(PrintWriter pw, AllFracplanetParameters params, Progress progress) throws IOException {
    final ExportParameters ep = params.getExportParameters();
    final TerrainParameters tp = params.getTerrainParameters();

    try {
        TriangleMesh terrain = meshes.get(0);

        // write the header
        if (terrain instanceof TriangleMeshTerrainPlanet || terrain instanceof Triangle) {
            writeHeaderSphere(terrain, pw, ep, tp);
        } else if (terrain instanceof TriangleMeshTerrainFlat) {
            writeHeaderFlat(terrain, pw, ep, tp);
        }

        // export all meshes, currently there are 2 at most, the second
        // one is clouds
        for (int m = 0; m < meshes.size(); ++m) {
            terrain = meshes.get(m);

            boolean cloudy = false;

            if (m > 0) {
                cloudy = true;
            }

            // export the mesh
            exportMesh(terrain, pw, params, progress, cloudy, cloudy, !cloudy);

            if (pw.checkError()) {
                throw new IOException("Error writing to output stream");
            }
        }
    } catch (IOException ioe) {
        // log the error before rethrowing it
        log.error("IOException in pov export: " + ioe.getMessage(), ioe);

        throw ioe;
    } finally {
        pw.close();
    }
}

From source file:org.apache.struts.examples.mailreader.memory.MemoryUserDatabase.java

public void save() throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Saving database to '" + pathname + "'");
    }/* www .  j  a v a2 s  . c o m*/
    File fileNew = new File(pathnameNew);
    PrintWriter writer = null;

    try {

        // Configure our PrintWriter
        FileOutputStream fos = new FileOutputStream(fileNew);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        writer = new PrintWriter(osw);

        // Print the file prolog
        writer.println("<?xml version='1.0'?>");
        writer.println("<database>");

        // Print entries for each defined user and associated subscriptions
        User users[] = findUsers();
        for (int i = 0; i < users.length; i++) {
            writer.print("  ");
            writer.println(users[i]);
            Subscription subscriptions[] = users[i].getSubscriptions();
            for (int j = 0; j < subscriptions.length; j++) {
                writer.print("    ");
                writer.println(subscriptions[j]);
                writer.print("    ");
                writer.println("</subscription>");
            }
            writer.print("  ");
            writer.println("</user>");
        }

        // Print the file epilog
        writer.println("</database>");

        // Check for errors that occurred while printing
        if (writer.checkError()) {
            writer.close();
            fileNew.delete();
            throw new IOException("Saving database to '" + pathname + "'");
        }
        writer.close();
        writer = null;

    } catch (IOException e) {

        if (writer != null) {
            writer.close();
        }
        fileNew.delete();
        throw e;

    }

    // Perform the required renames to permanently save this file
    File fileOrig = new File(pathname);
    File fileOld = new File(pathnameOld);
    if (fileOrig.exists()) {
        fileOld.delete();
        if (!fileOrig.renameTo(fileOld)) {
            throw new IOException("Renaming '" + pathname + "' to '" + pathnameOld + "'");
        }
    }
    if (!fileNew.renameTo(fileOrig)) {
        if (fileOld.exists()) {
            fileOld.renameTo(fileOrig);
        }
        throw new IOException("Renaming '" + pathnameNew + "' to '" + pathname + "'");
    }
    fileOld.delete();

}

From source file:org.apache.struts.apps.mailreader.dao.impl.memory.MemoryUserDatabase.java

public void save() throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Saving database to '" + pathname + "'");
    }//  w  w w . ja v a  2s  . com
    File fileNew = new File(pathnameNew);
    PrintWriter writer = null;

    try {

        // Configure our PrintWriter
        FileOutputStream fos = new FileOutputStream(fileNew);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        writer = new PrintWriter(osw);

        // Print the file prolog
        writer.println("<?xml version='1.0'?>");
        writer.println("<database>");

        // Print entries for each defined user and associated subscriptions
        User yusers[] = findUsers();
        for (int i = 0; i < yusers.length; i++) {
            writer.print("  ");
            writer.println(yusers[i]);
            Subscription subscriptions[] = yusers[i].getSubscriptions();
            for (int j = 0; j < subscriptions.length; j++) {
                writer.print("    ");
                writer.println(subscriptions[j]);
                writer.print("    ");
                writer.println("</subscription>");
            }
            writer.print("  ");
            writer.println("</user>");
        }

        // Print the file epilog
        writer.println("</database>");

        // Check for errors that occurred while printing
        if (writer.checkError()) {
            writer.close();
            fileNew.delete();
            throw new IOException("Saving database to '" + pathname + "'");
        }
        writer.close();
        writer = null;

    } catch (IOException e) {

        if (writer != null) {
            writer.close();
        }
        fileNew.delete();
        throw e;

    }

    // Perform the required renames to permanently save this file
    File fileOrig = new File(pathname);
    File fileOld = new File(pathnameOld);
    if (fileOrig.exists()) {
        fileOld.delete();
        if (!fileOrig.renameTo(fileOld)) {
            throw new IOException("Renaming '" + pathname + "' to '" + pathnameOld + "'");
        }
    }
    if (!fileNew.renameTo(fileOrig)) {
        if (fileOld.exists()) {
            fileOld.renameTo(fileOrig);
        }
        throw new IOException("Renaming '" + pathnameNew + "' to '" + pathname + "'");
    }
    fileOld.delete();

}

From source file:org.apache.struts.webapp.example2.memory.MemoryUserDatabase.java

/**
 * <p>Save any pending changes to the underlying persistence layer.</p>
 *
 * @exception Exception if a database access error occurs
 */// w ww  .  j  a  va 2 s .  c o  m
public void save() throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Saving database to '" + pathname + "'");
    }
    File fileNew = new File(pathnameNew);
    PrintWriter writer = null;

    try {

        // Configure our PrintWriter
        FileOutputStream fos = new FileOutputStream(fileNew);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        writer = new PrintWriter(osw);

        // Print the file prolog
        writer.println("<?xml version='1.0'?>");
        writer.println("<database>");

        // Print entries for each defined user and associated subscriptions
        User users[] = findUsers();
        for (int i = 0; i < users.length; i++) {
            writer.print("  ");
            writer.println(users[i]);
            Subscription subscriptions[] = users[i].getSubscriptions();
            for (int j = 0; j < subscriptions.length; j++) {
                writer.print("    ");
                writer.println(subscriptions[j]);
                writer.print("    ");
                writer.println("</subscription>");
            }
            writer.print("  ");
            writer.println("</user>");
        }

        // Print the file epilog
        writer.println("</database>");

        // Check for errors that occurred while printing
        if (writer.checkError()) {
            writer.close();
            fileNew.delete();
            throw new IOException("Saving database to '" + pathname + "'");
        }
        writer.close();
        writer = null;

    } catch (IOException e) {

        if (writer != null) {
            writer.close();
        }
        fileNew.delete();
        throw e;

    }

    // Perform the required renames to permanently save this file
    File fileOrig = new File(pathname);
    File fileOld = new File(pathnameOld);
    if (fileOrig.exists()) {
        fileOld.delete();
        if (!fileOrig.renameTo(fileOld)) {
            throw new IOException("Renaming '" + pathname + "' to '" + pathnameOld + "'");
        }
    }
    if (!fileNew.renameTo(fileOrig)) {
        if (fileOld.exists()) {
            fileOld.renameTo(fileOrig);
        }
        throw new IOException("Renaming '" + pathnameNew + "' to '" + pathname + "'");
    }
    fileOld.delete();

}

From source file:catalina.users.MemoryUserDatabase.java

/**
 * Save any updated information to the persistent storage location for
 * this user database.//from  w  w w  . j  a va 2 s  . co  m
 *
 * @exception Exception if any exception is thrown during saving
 */
public void save() throws Exception {

    // Write out contents to a temporary file
    File fileNew = new File(pathnameNew);
    if (!fileNew.isAbsolute()) {
        fileNew = new File(System.getProperty("catalina.base"), pathnameNew);
    }
    PrintWriter writer = null;
    try {

        // Configure our PrintWriter
        FileOutputStream fos = new FileOutputStream(fileNew);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
        writer = new PrintWriter(osw);

        // Print the file prolog
        writer.println("<?xml version='1.0' encoding='utf-8'?>");
        writer.println("<tomcat-users>");

        // Print entries for each defined role, group, and user
        Iterator values = null;
        values = getRoles();
        while (values.hasNext()) {
            writer.print("  ");
            writer.println(values.next());
        }
        values = getGroups();
        while (values.hasNext()) {
            writer.print("  ");
            writer.println(values.next());
        }
        values = getUsers();
        while (values.hasNext()) {
            writer.print("  ");
            writer.println(values.next());
        }

        // Print the file epilog
        writer.println("</tomcat-users>");

        // Check for errors that occurred while printing
        if (writer.checkError()) {
            writer.close();
            fileNew.delete();
            throw new IOException(sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath()));
        }
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
        }
        fileNew.delete();
        throw e;
    }

    // Perform the required renames to permanently save this file
    File fileOld = new File(pathnameNew);
    if (!fileOld.isAbsolute()) {
        fileOld = new File(System.getProperty("catalina.base"), pathnameOld);
    }
    fileOld.delete();
    File fileOrig = new File(pathname);
    if (!fileOrig.isAbsolute()) {
        fileOrig = new File(System.getProperty("catalina.base"), pathname);
    }
    if (fileOrig.exists()) {
        fileOld.delete();
        if (!fileOrig.renameTo(fileOld)) {
            throw new IOException(sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath()));
        }
    }
    if (!fileNew.renameTo(fileOrig)) {
        if (fileOld.exists()) {
            fileOld.renameTo(fileOrig);
        }
        throw new IOException(sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath()));
    }
    fileOld.delete();

}

From source file:org.openmrs.hl7.impl.HL7ServiceImpl.java

/**
 * writes a given hl7 archive to the file system
 *
 * @param hl7InArchive the hl7 archive to write to the file system
 *///  w w  w .  ja v a2  s .  c o  m
private URI writeHL7InArchiveToFileSystem(HL7InArchive hl7InArchive) throws APIException {

    PrintWriter writer = null;
    File destinationDir = HL7Util.getHl7ArchivesDirectory();
    try {
        // number formatter used to format month and day with zero padding
        DecimalFormat df = new DecimalFormat("00");

        //write the archive to a separate file while grouping them according to
        //the year, month and date of month when they were stored in the archives table
        Calendar calendar = Calendar.getInstance(Context.getLocale());
        calendar.setTime(hl7InArchive.getDateCreated());

        //resolve the year folder from the date of creation of the archive
        File yearDir = new File(destinationDir, Integer.toString(calendar.get(Calendar.YEAR)));
        if (!yearDir.isDirectory()) {
            yearDir.mkdirs();
        }

        //resolve the appropriate month folder
        File monthDir = new File(yearDir, df.format(calendar.get(Calendar.MONTH) + 1));
        if (!monthDir.isDirectory()) {
            monthDir.mkdirs();
        }

        //resolve the appropriate day of month folder
        File dayDir = new File(monthDir, df.format(calendar.get(Calendar.DAY_OF_MONTH)));
        if (!dayDir.isDirectory()) {
            dayDir.mkdirs();
        }

        //use the uuid, source id and source key(if present) to generate the file name
        File fileToWriteTo = new File(dayDir,
                hl7InArchive.getUuid() + (StringUtils.isBlank(hl7InArchive.getHL7SourceKey()) ? ""
                        : "_" + hl7InArchive.getHL7SourceKey()) + ".txt");

        //write the hl7 data to the file
        writer = new PrintWriter(fileToWriteTo);
        writer.write(hl7InArchive.getHL7Data());

        //check if there was an error while writing to the current file
        if (writer.checkError()) {
            log.warn("An Error occured while writing hl7 archive with id '" + hl7InArchive.getHL7InArchiveId()
                    + "' to the file system");
            throw new APIException("Hl7Service.write.no.error", (Object[]) null);
        }

        // hand back the URI for the file
        return fileToWriteTo.toURI();

    } catch (FileNotFoundException e) {
        log.warn("Failed to write hl7 archive with id '" + hl7InArchive.getHL7InArchiveId()
                + "' to the file system ", e);
        throw new APIException("Hl7Service.write.error", null, e);

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}