Java Code Examples for java.io.PrintStream#checkError()

The following examples show how to use java.io.PrintStream#checkError() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IOUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Copies from one stream to another.
 *
 * @param in
 *        InputStream to read from
 * @param out
 *        OutputStream to write to
 * @param buffSize
 *        the size of the buffer
 * @param close
 *        whether or not close the InputStream and OutputStream at the end. The streams are closed in the finally
 *        clause.
 * @throws IOException
 *         thrown if an error occurred while writing to the output stream
 */
public static void copyBytes(final InputStream in, final OutputStream out, final int buffSize, final boolean close)
		throws IOException {

	@SuppressWarnings("resource")
	final PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
	final byte[] buf = new byte[buffSize];
	try {
		int bytesRead = in.read(buf);
		while (bytesRead >= 0) {
			out.write(buf, 0, bytesRead);
			if ((ps != null) && ps.checkError()) {
				throw new IOException("Unable to write to output stream.");
			}
			bytesRead = in.read(buf);
		}
	} finally {
		if (close) {
			out.close();
			in.close();
		}
	}
}
 
Example 2
Source File: IOUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Copies from one stream to another.
 *
 * @param in
 *        InputStream to read from
 * @param out
 *        OutputStream to write to
 * @param buffSize
 *        the size of the buffer
 * @param close
 *        whether or not close the InputStream and OutputStream at the end. The streams are closed in the finally
 *        clause.
 * @throws IOException
 *         thrown if an error occurred while writing to the output stream
 */
public static void copyBytes(final InputStream in, final OutputStream out, final int buffSize, final boolean close)
		throws IOException {

	@SuppressWarnings("resource")
	final PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
	final byte[] buf = new byte[buffSize];
	try {
		int bytesRead = in.read(buf);
		while (bytesRead >= 0) {
			out.write(buf, 0, bytesRead);
			if ((ps != null) && ps.checkError()) {
				throw new IOException("Unable to write to output stream.");
			}
			bytesRead = in.read(buf);
		}
	} finally {
		if (close) {
			out.close();
			in.close();
		}
	}
}
 
Example 3
Source File: ScanUtil.java    From fluo with Apache License 2.0 6 votes vote down vote up
/**
 * Generate JSON format as result of the scan.
 *
 * @since 1.2
 */
private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,
    PrintStream out) throws JsonIOException {
  Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)
      .create();

  Map<String, String> json = new LinkedHashMap<>();
  for (RowColumnValue rcv : cellScanner) {
    json.put(FLUO_ROW, encoder.apply(rcv.getRow()));
    json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));
    json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));
    json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));
    json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));
    gson.toJson(json, out);
    out.append("\n");

    if (out.checkError()) {
      break;
    }
  }
  out.flush();
}
 
Example 4
Source File: Diagnostic.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Write a throwable to the log stream. If writing to the log stream fails
 * and the log stream differs from <code>System.err</code>, then an attempt
 * is made to redirect the message to <code>System.err</code>.
 *
 * @param t throwable to write
 */
public static synchronized void userLog(final Throwable t) {
  final PrintStream log = getLogStream();
  if (log != null) {
    t.printStackTrace(log);
    log.flush();
    if (log.checkError()) {
      // The call to checkError forces a flush and returns true if the stream
      // is in an unusable state.  This should not happen in ordinary usage,
      // but could happen if for example logging is going to a file and the
      // disk runs out of space.  Therefore, if the current logging stream is
      // not System.err, we make an effort to redirect the log message to
      // that stream.
      if (!log.equals(System.err)) {
        if (!sLogRedirect) {
          sLogRedirect = true;
          System.err.println(now() + "Logging problem: redirecting logging to System.err.");
        }
        t.printStackTrace(System.err);
        System.err.flush();
      }
    }
  }
}
 
Example 5
Source File: Diagnostic.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Write a message to the progress stream if a log file exists.
 * @param message to write
 */
public static synchronized void progress(final String message) {
  sLastProgress = message;
  final PrintStream prog = getProgressStream();
  if (prog != null) {
    prog.println(now() + message);
    prog.flush();
    if (prog.checkError()) {
      // The call to checkError forces a flush and returns true if the stream
      // is in an unusable state.  This should not happen in ordinary usage,
      // but could happen if for example logging is going to a file and the
      // disk runs out of space.
      sProgressStream = null;
    }
  }
}
 
Example 6
Source File: IOUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Copies from one stream to another.
 *
 * @param in
 *        InputStream to read from
 * @param out
 *        OutputStream to write to
 * @param buffSize
 *        the size of the buffer
 * @param close
 *        whether or not close the InputStream and OutputStream at the end. The streams are closed in the finally
 *        clause.
 * @throws IOException
 *         thrown if an error occurred while writing to the output stream
 */
public static void copyBytes(final InputStream in, final OutputStream out, final int buffSize, final boolean close)
		throws IOException {

	@SuppressWarnings("resource")
	final PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
	final byte[] buf = new byte[buffSize];
	try {
		int bytesRead = in.read(buf);
		while (bytesRead >= 0) {
			out.write(buf, 0, bytesRead);
			if ((ps != null) && ps.checkError()) {
				throw new IOException("Unable to write to output stream.");
			}
			bytesRead = in.read(buf);
		}
	} finally {
		if (close) {
			out.close();
			in.close();
		}
	}
}
 
Example 7
Source File: ScanUtil.java    From fluo with Apache License 2.0 6 votes vote down vote up
private static void scan(ScanOpts options, PrintStream out, CellScanner cellScanner) {
  Function<Bytes, String> encoder = getEncoder(options);

  if (options.exportAsJson) {
    generateJson(cellScanner, encoder, out);
  } else {
    for (RowColumnValue rcv : cellScanner) {
      out.print(encoder.apply(rcv.getRow()));
      out.print(' ');
      out.print(encoder.apply(rcv.getColumn().getFamily()));
      out.print(' ');
      out.print(encoder.apply(rcv.getColumn().getQualifier()));
      out.print(' ');
      out.print(encoder.apply(rcv.getColumn().getVisibility()));
      out.print("\t");
      out.print(encoder.apply(rcv.getValue()));
      out.println();
      if (out.checkError()) {
        break;
      }
    }
  }
}
 
Example 8
Source File: IOUtils.java    From stratosphere with Apache License 2.0 6 votes vote down vote up
/**
 * Copies from one stream to another.
 * 
 * @param in
 *        InputStream to read from
 * @param out
 *        OutputStream to write to
 * @param buffSize
 *        the size of the buffer
 * @param close
 *        whether or not close the InputStream and OutputStream at the end. The streams are closed in the finally
 *        clause.
 * @throws IOException
 *         thrown if an error occurred while writing to the output stream
 */
public static void copyBytes(final InputStream in, final OutputStream out, final int buffSize, final boolean close)
		throws IOException {

	final PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
	final byte[] buf = new byte[buffSize];
	try {
		int bytesRead = in.read(buf);
		while (bytesRead >= 0) {
			out.write(buf, 0, bytesRead);
			if ((ps != null) && ps.checkError()) {
				throw new IOException("Unable to write to output stream.");
			}
			bytesRead = in.read(buf);
		}
	} finally {
		if (close) {
			out.close();
			in.close();
		}
	}
}
 
Example 9
Source File: Utils.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * Copies from one stream to another.
 *
 * @param in       InputStream to read from
 * @param out      OutputStream to write to
 * @param buffSize the size of the buffer
 */
public static void copyBytes(InputStream in, OutputStream out, int buffSize)
        throws IOException {
    PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
    byte buf[] = new byte[buffSize];
    int bytesRead = in.read(buf);
    while (bytesRead >= 0) {
        out.write(buf, 0, bytesRead);
        if ((ps != null) && ps.checkError()) {
            throw new IOException("Unable to write to output stream.");
        }
        bytesRead = in.read(buf);
    }
}
 
Example 10
Source File: DfaRun.java    From monqjfa with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>reads and filters input, copying it to the output
 * until EOF is hit.</p>
 */
public void filter(PrintStream out)
  throws java.io.IOException
{
  StringBuilder sb = new StringBuilder(500);
  while( read(sb) ) {
    out.print(sb);
    sb.setLength(0);
    if( out.checkError() ) return;
  }
  out.print(sb);
  out.flush();
}
 
Example 11
Source File: DeploymentGroupWatchCommand.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
int run(Namespace options, HeliosClient client, PrintStream out, boolean json,
        BufferedReader stdin) throws ExecutionException, InterruptedException, IOException {
  final String name = options.getString(nameArg.getDest());
  final boolean full = options.getBoolean(fullArg.getDest());
  final Integer interval = options.getInt(intervalArg.getDest());
  final DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_TIME_PATTERN);

  if (!json) {
    out.println("Control-C to stop");
    out.println("STATUS               HOST                           STATE");
  }

  final int timestampLength = String.format("[%s UTC]", DATE_TIME_PATTERN).length();

  int rc = 0;
  while (rc == 0) {
    final Instant now = new Instant();
    if (!json) {
      out.printf(Strings.repeat("-", MAX_WIDTH - timestampLength - 1)
                 + " [%s UTC]%n", now.toString(formatter));
    }

    rc = DeploymentGroupStatusCommand.run0(client, out, json, name, full);
    if (out.checkError()) {
      break;
    }

    Thread.sleep(1000 * interval);
  }
  return 0;
}
 
Example 12
Source File: JobWatchCommand.java    From helios with Apache License 2.0 5 votes vote down vote up
static void watchJobsOnHosts(final PrintStream out, final boolean exact,
                             final List<String> prefixes, final Set<JobId> jobIds,
                             final int interval, final List<TargetAndClient> clients)
    throws InterruptedException, ExecutionException {
  out.println("Control-C to stop");
  out.println("JOB                  HOST                           STATE    THROTTLED?");
  final DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
  while (true) {

    final Instant now = new Instant();
    out.printf("-------------------- ------------------------------ -------- "
               + "---------- [%s UTC]%n", now.toString(formatter));
    for (final TargetAndClient cc : clients) {
      final Optional<Target> target = cc.getTarget();
      if (clients.size() > 1) {
        final String header;
        if (target.isPresent()) {
          final List<URI> endpoints = target.get().getEndpointSupplier().get();
          header = format(" %s (%s)", target.get().getName(), endpoints);
        } else {
          header = "";
        }
        out.printf("---%s%n", header);
      }
      showReport(out, exact, prefixes, jobIds, formatter, cc.getClient());
    }
    if (out.checkError()) {
      break;
    }
    Thread.sleep(1000 * interval);
  }
}
 
Example 13
Source File: Diagnostic.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Write a message to the log stream.  If writing to the log stream fails
 * and the log stream differs from <code>System.err</code>, then an attempt
 * is made to redirect the message to <code>System.err</code>.
 *
 * @param message to write
 * @param prefix a prefix to include before the message
 */
private static synchronized void userLog(final String message, final String prefix) {
  final PrintStream log = getLogStream();
  if (log != null) {
    log.println(now() + prefix + message);
    final long currentTimeMillis = System.currentTimeMillis();
    if (currentTimeMillis - sLastFlushTime > FLUSH_INTERVAL) {
      log.flush();
      sLastFlushTime = currentTimeMillis;
    }
    if (log.checkError()) {
      // The call to checkError forces a flush and returns true if the stream
      // is in an unusable state.  This should not happen in ordinary usage,
      // but could happen if for example logging is going to a file and the
      // disk runs out of space.  Therefore, if the current logging stream is
      // not System.err, we make an effort to redirect the log message to
      // that stream.
      if (!log.equals(System.err)) {
        if (!sLogRedirect) {
          sLogRedirect = true;
          System.err.println("Logging problem: redirecting logging to System.err.");
          setLogStream(System.err);
        }
        System.err.println(now() + message);
        System.err.flush();
      }
    }
  }
}
 
Example 14
Source File: IOUtils.java    From gadtry with Apache License 2.0 5 votes vote down vote up
/**
 * Copies from one stream to another.
 *
 * @param in InputStrem to read from
 * @param out OutputStream to write to
 * @param buffSize the size of the buffer
 * @throws IOException IOException
 */
public static void copyBytes(InputStream in, OutputStream out, int buffSize)
        throws IOException
{
    PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
    byte[] buf = new byte[buffSize];
    int bytesRead = -1;
    while ((bytesRead = in.read(buf)) >= 0) {
        out.write(buf, 0, bytesRead);
        if ((ps != null) && ps.checkError()) {
            throw new IOException("Unable to write to output stream.");
        }
    }
}
 
Example 15
Source File: SSTableExport.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
/**
 * Checks if PrintStream error and throw exception
 *
 * @param out The PrintStream to be check
 */
private static void checkStream(PrintStream out) throws IOException
{
    if (out.checkError())
        throw new IOException("Error writing output stream");
}
 
Example 16
Source File: MaxrankOutputFormatter.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static void flushAndCheckError(PrintStream printStream) throws IOException {
  if (printStream.checkError()) {
    throw new IOException("PrintStream encountered an error");
  }
}
 
Example 17
Source File: MinrankOutputFormatter.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static void flushAndCheckError(PrintStream printStream) throws IOException {
  if (printStream.checkError()) {
    throw new IOException("PrintStream encountered an error");
  }
}
 
Example 18
Source File: ViewSam.java    From picard with MIT License 4 votes vote down vote up
/**
 * This is factored out of doWork only for unit testing.
 */
int writeSamText(PrintStream printStream) {
    try {
        final CloseableIterator<SAMRecord> samRecordsIterator;
        final SamReader samReader = SamReaderFactory.makeDefault()
                .referenceSequence(REFERENCE_SEQUENCE)
                .open(SamInputResource.of(INPUT));

        // if we are only using the header or we aren't using intervals, then use the reader as the iterator.
        // otherwise use the SamRecordIntervalIteratorFactory to make an interval-ed iterator
        if (HEADER_ONLY || INTERVAL_LIST == null) {
            samRecordsIterator = samReader.iterator();
        } else {
            IOUtil.assertFileIsReadable(INTERVAL_LIST);

            final List<Interval> intervals = IntervalList.fromFile(INTERVAL_LIST).uniqued().getIntervals();
            samRecordsIterator = new SamRecordIntervalIteratorFactory().makeSamRecordIntervalIterator(samReader, intervals, samReader.hasIndex());
        }
        final AsciiWriter writer = new AsciiWriter(printStream);
        final SAMFileHeader header = samReader.getFileHeader();
        if (!RECORDS_ONLY) {
            if (header.getTextHeader() != null) {
                writer.write(header.getTextHeader());
            } else {
                // Headers that are too large are not retained as text, so need to regenerate text
                new SAMTextHeaderCodec().encode(writer, header, true);
            }
        }
        if (!HEADER_ONLY) {
            while (samRecordsIterator.hasNext()) {
                final SAMRecord rec = samRecordsIterator.next();

                if (printStream.checkError()) {
                    return 1;
                }

                if (this.ALIGNMENT_STATUS == AlignmentStatus.Aligned && rec.getReadUnmappedFlag()) continue;
                if (this.ALIGNMENT_STATUS == AlignmentStatus.Unaligned && !rec.getReadUnmappedFlag()) continue;

                if (this.PF_STATUS == PfStatus.PF && rec.getReadFailsVendorQualityCheckFlag()) continue;
                if (this.PF_STATUS == PfStatus.NonPF && !rec.getReadFailsVendorQualityCheckFlag()) continue;
                writer.write(rec.getSAMString());
            }
        }
        writer.flush();
        if (printStream.checkError()) {
            return 1;
        }
        CloserUtil.close(writer);
        CloserUtil.close(samRecordsIterator);
        return 0;
    } catch (IOException e) {
        throw new PicardException("Exception writing SAM text", e);
    }
}
 
Example 19
Source File: MultiPrintStream.java    From JarShrink with Apache License 2.0 3 votes vote down vote up
@Override
public boolean checkError() {
	
	for (PrintStream out : streams) {
		
		if (out.checkError()) { return true; }
	}
	
	return false;
}