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.tmpotter.preferences.PreferencesTest.java

/**
* Test that if an error is encountered when loading the preferences file, the
* original file is backed up.// ww w  . j  av  a  2  s .  c  om
* <p>
* Note that this test can spuriously fail if run in a situation where the
* Preferences class has already been initialized, for instance when running
* the entire suite of tests in Eclipse. It behaves correctly when run
* individually, or with ant.
*/
public void testPreferencesBackup() throws Exception {
    File tmpDir = FileUtil.createTempDir();
    try {
        assertTrue(tmpDir.isDirectory());

        Utilities.setConfigDir(tmpDir.getAbsolutePath());

        File prefs = new File(tmpDir, Preferences.FILE_PREFERENCES);

        // Write anything that is malformed XML, to force a parsing error.
        PrintWriter out = new PrintWriter(prefs, "UTF-8");
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
        out.println("<tmpotter>");
        out.println("<preference version=\"1.0\">");
        out.close();
        assertFalse(out.checkError());

        // Load bad prefs file.
        Preferences pref = Preferences.getPreferences();
        pref.doLoad();

        // The actual backup file will have a timestamp in the filename,
        // so we have to loop through looking for it.
        File backup = null;
        for (File f : tmpDir.listFiles()) {
            String name = f.getName();
            if (name.startsWith("tmpotter.prefs") && name.endsWith(".bak")) {
                backup = f;
                break;
            }
        }

        assertNotNull(backup);
        assertTrue(backup.isFile());

        assertTrue(FileUtils.contentEquals(prefs, backup));
    } finally {
        assertTrue(FileUtil.deleteTree(tmpDir));
    }
}

From source file:org.openmrs.util.DatabaseUpdater.java

/**
 * This method writes the given text to the database updates log file located in the application
 * data directory.//  w ww  .j a v a 2 s.  c  om
 *
 * @param text text to be written to the file
 */
public static void writeUpdateMessagesToFile(String text) {
    PrintWriter writer = null;
    File destFile = new File(OpenmrsUtil.getApplicationDataDirectory(),
            DatabaseUpdater.DATABASE_UPDATES_LOG_FILE);
    try {
        String lineSeparator = System.getProperty("line.separator");
        Date date = Calendar.getInstance().getTime();

        writer = new PrintWriter(new BufferedWriter(new FileWriter(destFile, true)));
        writer.write("********** START OF DATABASE UPDATE LOGS AS AT " + date + " **********");
        writer.write(lineSeparator);
        writer.write(lineSeparator);
        writer.write(text);
        writer.write(lineSeparator);
        writer.write(lineSeparator);
        writer.write("*********** END OF DATABASE UPDATE LOGS AS AT " + date + " ***********");
        writer.write(lineSeparator);
        writer.write(lineSeparator);

        //check if there was an error while writing to the file
        if (writer.checkError()) {
            log.warn("An Error occured while writing warnings to the database update log file'");
        }

        writer.close();
    } catch (FileNotFoundException e) {
        log.warn("Failed to find the database update log file", e);
    } catch (IOException e) {
        log.warn("Failed to write to the database update log file", e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

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

@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
    Socket socket = null;// w w  w . j  av a 2 s  .  c o  m
    PrintWriter writer = null;

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

        for (String formattedResult : messageFormatter.formatResults(results, server)) {
            log.debug("OpenTSDB Message: {}", formattedResult);
            writer.write("put " + formattedResult + "\n");
        }

    } catch (ConnectException e) {
        log.error("Error while connecting to OpenTSDB", e);
    } finally {
        if (writer != null && writer.checkError()) {
            log.error("Error writing to OpenTSDB, clearing OpenTSDB socket pool");
            pool.invalidateObject(address, socket);
        } else {
            pool.returnObject(address, socket);
        }
    }
}

From source file:org.apache.ranger.audit.destination.HDFSAuditDestination.java

@Override
synchronized public boolean logJSON(final Collection<String> events) {
    logStatusIfRequired();/*from  ww  w. ja v a 2s.  c  om*/
    addTotalCount(events.size());

    if (!initDone) {
        addDeferredCount(events.size());
        return false;
    }
    if (isStopped) {
        addDeferredCount(events.size());
        logError("log() called after stop was requested. name=" + getName());
        return false;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("UGI=" + MiscUtil.getUGILoginUser() + ". Will write to HDFS file=" + currentFileName);
        }

        final PrintWriter out = MiscUtil.executePrivilegedAction(new PrivilegedExceptionAction<PrintWriter>() {
            @Override
            public PrintWriter run() throws Exception {
                PrintWriter out = getLogFileStream();
                for (String event : events) {
                    out.println(event);
                }
                return out;
            };
        });

        // flush and check the stream for errors
        if (out.checkError()) {
            // In theory, this count may NOT be accurate as part of the messages may have been successfully written.
            // However, in practice, since client does buffering, either all of none would succeed.
            addDeferredCount(events.size());
            out.close();
            logWriter = null;
            return false;
        }
    } catch (Throwable t) {
        addDeferredCount(events.size());
        logError("Error writing to log file.", t);
        return false;
    }
    addSuccessCount(events.size());
    return true;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.util.CgroupsLCEResourcesHandler.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  2 s . 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);
        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:org.ourgrid.common.executor.vbox.VirtualBoxEnvironment.java

public Process executeRemoteCommand(String dirName, String command, Map<String, String> envVars)
        throws ExecutorException {
    try {// ww  w.j av  a2  s .  co m

        //         String env_storage = envVars.get(WorkerConstants.ENV_STORAGE);

        //         command = command.replace(env_storage, vmStorage.getName());
        getLogger().info("Asked to run command " + command);

        //Defining new environment variables
        Map<String, String> clone = CommonUtils.createSerializableMap();
        clone.putAll(envVars);
        clone.remove(WorkerConstants.ENV_PLAYPEN);
        clone.remove(WorkerConstants.ENV_STORAGE);
        clone.put(WorkerConstants.PROP_STORAGE_DIR, vmStorage.getName());

        //Creating application script
        File script = unixFolderUtil.createScript(command, dirName, clone);

        //Writing virtual environment variables
        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(virtualEnvPropertiesFile)));
        writer.println(VIRTUAL_ENV_APP_SCRIPT_PROP + "=" + execFile.getName());
        writer.println(VIRTUAL_ENV_APP_EXIT_PROP + "=" + exitStatus.getName());
        writer.println(VIRTUAL_ENV_APP_STDOUT_PROP + "=" + stdOut.getName());
        writer.println(VIRTUAL_ENV_APP_STDERR_PROP + "=" + stdErr.getName());
        writer.println(VIRTUAL_ENV_TERMINATION_FILE_PROP + "=" + terminationFile.getName());
        writer.println(VIRTUAL_ENV_STORAGE_NAME_PROP + "=" + vmStorage.getName());

        try {
            if (writer.checkError()) {
                throw new IOException("Unable to create Virtual environment");
            }
        } finally {
            writer.close();
        }

        //Copying files to needed location
        FileUtils.copyFile(script, execFile);
        unixFolderUtil.copyStorageFiles(storage, vmStorage);

    } catch (IOException e) {
        throw new ExecutorException("Unable to create remote execution script", e);
    }

    getLogger().debug("About to start secure environment");

    //Executing command that will initiate virtual environment and execute the process
    Process execProcess = buildAndRunProcessNoWait(createStartVmAndExecuteCmd(), "Could not execute command");
    setExecProcess(execProcess);

    getLogger().debug("About to wait for secure environment to exit");

    return execProcess;
}

From source file:org.ourgrid.common.executor.vmachine.VirtualMachineExecutor.java

private void executeRemoteCommand(String dirName, String command, Map<String, String> envVars)
        throws ExecutorException {
    try {/*from  ww w  .j a  va 2 s. c  om*/

        String env_storage = envVars.get(WorkerConstants.ENV_STORAGE);

        command = command.replace(env_storage, vmStorage.getName());
        logger.info("Asked to run command " + command);

        //Defining new environment variables
        Map<String, String> clone = new HashMap<String, String>();
        clone.putAll(envVars);
        clone.remove(WorkerConstants.ENV_PLAYPEN);
        clone.remove(WorkerConstants.ENV_STORAGE);

        //Creating application script
        File script = unixFolderUtil.createScript(command, dirName, clone);

        //Writing virtual environment variables
        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(virtualEnvPropertiesFile)));
        writer.println(VIRTUAL_ENV_APP_SCRIPT_PROP + "=" + execFile.getName());
        writer.println(VIRTUAL_ENV_APP_EXIT_PROP + "=" + exitStatus.getName());
        writer.println(VIRTUAL_ENV_APP_STDOUT_PROP + "=" + stdOut.getName());
        writer.println(VIRTUAL_ENV_APP_STDERR_PROP + "=" + stdErr.getName());
        writer.println(VIRTUAL_ENV_TERMINATION_FILE_PROP + "=" + terminationFile.getName());
        writer.println(VIRTUAL_ENV_STORAGE_NAME_PROP + "=" + vmStorage.getName());

        try {
            if (writer.checkError()) {
                throw new IOException("Unable to create Virtual environment");
            }
        } finally {
            writer.close();
        }

        //Copying files to needed location
        vmStorage.mkdirs();
        FileUtils.copyFile(script, execFile);
        unixFolderUtil.copyStorageFiles(envVars, vmStorage);
    } catch (IOException e) {
        throw new ExecutorException("Unable to create remote execution script", e);
    }

    logger.debug("About to start secure environment");

    //Executing command that will initiate virtual environment
    ExecutorHandle internalHandle = this.executor.execute(dirName, startvmCmd + " " + vBoxLocation + " "
            + machineName + " " + ("\"" + playpen.getAbsolutePath() + "\""));
    ExecutorResult result = this.executor.getResult(internalHandle);

    logger.debug("Result: " + result);

    if (result.getExitValue() != 0) {
        cleanup();
        throw new ExecutorException("Unable to start virtual environment \n" + result);
    }
}

From source file:org.jnegre.android.osmonthego.service.ExportService.java

/**
 * Handle export in the provided background thread
 *//* w  w  w  .  j  av  a2  s  . c om*/
private void handleOsmExport(boolean includeAddress, boolean includeFixme) {
    //TODO handle empty survey
    //TODO handle bounds around +/-180

    if (!isExternalStorageWritable()) {
        notifyUserOfError();
        return;
    }

    int id = 0;
    double minLat = 200;
    double minLng = 200;
    double maxLat = -200;
    double maxLng = -200;
    StringBuilder builder = new StringBuilder();

    if (includeAddress) {
        Uri uri = AddressTableMetaData.CONTENT_URI;
        Cursor cursor = getContentResolver().query(uri, new String[] { //projection
                AddressTableMetaData.LATITUDE, AddressTableMetaData.LONGITUDE, AddressTableMetaData.NUMBER,
                AddressTableMetaData.STREET }, null, //selection string
                null, //selection args array of strings
                null); //sort order

        if (cursor == null) {
            notifyUserOfError();
            return;
        }

        try {
            int iLat = cursor.getColumnIndex(AddressTableMetaData.LATITUDE);
            int iLong = cursor.getColumnIndex(AddressTableMetaData.LONGITUDE);
            int iNumber = cursor.getColumnIndex(AddressTableMetaData.NUMBER);
            int iStreet = cursor.getColumnIndex(AddressTableMetaData.STREET);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                //Gather values
                double lat = cursor.getDouble(iLat);
                double lng = cursor.getDouble(iLong);
                String number = cursor.getString(iNumber);
                String street = cursor.getString(iStreet);

                minLat = Math.min(minLat, lat);
                maxLat = Math.max(maxLat, lat);
                minLng = Math.min(minLng, lng);
                maxLng = Math.max(maxLng, lng);
                builder.append("<node id=\"-").append(++id).append("\" lat=\"").append(lat).append("\" lon=\"")
                        .append(lng).append("\" version=\"1\" action=\"modify\">\n");
                addOsmTag(builder, "addr:housenumber", number);
                addOsmTag(builder, "addr:street", street);
                builder.append("</node>\n");
            }
        } finally {
            cursor.close();
        }
    }

    if (includeFixme) {
        Uri uri = FixmeTableMetaData.CONTENT_URI;
        Cursor cursor = getContentResolver().query(uri, new String[] { //projection
                FixmeTableMetaData.LATITUDE, FixmeTableMetaData.LONGITUDE, FixmeTableMetaData.COMMENT }, null, //selection string
                null, //selection args array of strings
                null); //sort order

        if (cursor == null) {
            notifyUserOfError();
            return;
        }

        try {
            int iLat = cursor.getColumnIndex(FixmeTableMetaData.LATITUDE);
            int iLong = cursor.getColumnIndex(FixmeTableMetaData.LONGITUDE);
            int iComment = cursor.getColumnIndex(FixmeTableMetaData.COMMENT);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                //Gather values
                double lat = cursor.getDouble(iLat);
                double lng = cursor.getDouble(iLong);
                String comment = cursor.getString(iComment);

                minLat = Math.min(minLat, lat);
                maxLat = Math.max(maxLat, lat);
                minLng = Math.min(minLng, lng);
                maxLng = Math.max(maxLng, lng);
                builder.append("<node id=\"-").append(++id).append("\" lat=\"").append(lat).append("\" lon=\"")
                        .append(lng).append("\" version=\"1\" action=\"modify\">\n");
                addOsmTag(builder, "fixme", comment);
                builder.append("</node>\n");
            }
        } finally {
            cursor.close();
        }
    }

    try {
        File destinationFile = getDestinationFile();
        destinationFile.getParentFile().mkdirs();
        PrintWriter writer = new PrintWriter(destinationFile, "UTF-8");

        writer.println("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>");
        writer.println("<osm version=\"0.6\" generator=\"OsmOnTheGo\">");
        writer.print("<bounds minlat=\"");
        writer.print(minLat - MARGIN);
        writer.print("\" minlon=\"");
        writer.print(minLng - MARGIN);
        writer.print("\" maxlat=\"");
        writer.print(maxLat + MARGIN);
        writer.print("\" maxlon=\"");
        writer.print(maxLng + MARGIN);
        writer.println("\" />");

        writer.println(builder);

        writer.print("</osm>");
        writer.close();

        if (writer.checkError()) {
            notifyUserOfError();
        } else {
            //FIXME i18n the subject and content
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            emailIntent.setType(HTTP.OCTET_STREAM_TYPE);
            //emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"johndoe@exemple.com"});
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "OSM On The Go");
            emailIntent.putExtra(Intent.EXTRA_TEXT, "Your last survey.");
            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(destinationFile));
            startActivity(emailIntent);
        }
    } catch (IOException e) {
        Log.e(TAG, "Could not write to file", e);
        notifyUserOfError();
    }

}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandlerImpl.java

@Override
public void updateCGroupParam(CGroupController controller, String cGroupId, String param, String value)
        throws ResourceHandlerException {
    String cGroupParamPath = getPathForCGroupParam(controller, cGroupId, param);
    PrintWriter pw = null;

    if (LOG.isDebugEnabled()) {
        LOG.debug("updateCGroupParam for path: " + cGroupParamPath + " with value " + value);
    }/*from   ww w . j  ava2  s.  c  om*/

    try {
        File file = new File(cGroupParamPath);
        Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        pw = new PrintWriter(w);
        pw.write(value);
    } catch (IOException e) {
        throw new ResourceHandlerException(new StringBuffer("Unable to write to ").append(cGroupParamPath)
                .append(" with value: ").append(value).toString(), e);
    } finally {
        if (pw != null) {
            boolean hasError = pw.checkError();
            pw.close();
            if (hasError) {
                throw new ResourceHandlerException(new StringBuffer("Unable to write to ")
                        .append(cGroupParamPath).append(" with value: ").append(value).toString());
            }
            if (pw.checkError()) {
                throw new ResourceHandlerException("Error while closing cgroup file" + " " + cGroupParamPath);
            }
        }
    }
}

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

/**
 * Log a number of keys and values with record. the array length of keys and values
 * should be same. //  w ww  .  ja  va  2s.  c  o  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, JobHistoryKeys[] 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();
        }
    }
}