List of usage examples for java.io InputStream skip
public long skip(long n) throws IOException
n
bytes of data from this input stream. From source file:cd.education.data.collector.android.utilities.WebUtils.java
/** * Utility to ensure that the entity stream of a response is drained of * bytes./*from w ww. j av a 2 s . co m*/ * * @param response */ public static final void discardEntityBytes(HttpResponse response) { // may be a server that does not handle HttpEntity entity = response.getEntity(); if (entity != null) { try { // have to read the stream in order to reuse the connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.jenkinsci.plugins.workflow.job.WorkflowRun.java
/** * Equivalent to calling {@link LargeText#writeLogTo(long, OutputStream)} without the unwanted override in {@link AnnotatedLargeText} that wraps in a {@link PlainTextConsoleOutputStream}. * TODO replace with {@code AnnotatedLargeText#writeRawLogTo} in 1.577 *///from w ww. j a v a 2 s . co m private static long writeLogTo(AnnotatedLargeText<?> text, long position, OutputStream os) throws IOException { Charset c; try { Field f = LargeText.class.getDeclaredField("charset"); f.setAccessible(true); c = (Charset) f.get(text); } catch (Exception x) { LOGGER.log(Level.WARNING, null, x); return text.writeLogTo(position, os); // give up } Reader r = text.readAll(); try { InputStream is = new ReaderInputStream(r, c); is.skip(position); return position + IOUtils.copyLarge(is, os); } finally { r.close(); } }
From source file:Main.java
private static byte[] readBiggerStream(final InputStream in, final long streamlength) throws IOException { byte[] bytes = new byte[PART_SIZE * 3]; int readed = -1; int patchsize = -1; long skiped = -1; long patchskip = -1; long pointpos = 0; readed = in.read(bytes, 0, PART_SIZE); patchsize = readed;/*from ww w . j av a2 s . c o m*/ while (patchsize > 0 && readed != PART_SIZE) { patchsize = in.read(bytes, readed, PART_SIZE - readed); if (patchsize > 0) { readed += patchsize; } } pointpos = streamlength / 3 - PART_SIZE; skiped = in.skip(pointpos); patchskip = skiped; while (patchskip > 0 && skiped != pointpos) { patchskip = in.skip(pointpos - skiped); if (patchskip > 0) { skiped += patchskip; } } readed = in.read(bytes, PART_SIZE, PART_SIZE); patchsize = readed; while (patchsize > 0 && readed != PART_SIZE) { patchsize = in.read(bytes, PART_SIZE + readed, PART_SIZE - readed); if (patchsize > 0) { readed += patchsize; } } pointpos = streamlength - streamlength / 3 - PART_SIZE * 2; skiped = in.skip(pointpos); patchskip = skiped; while (patchskip > 0 && skiped != pointpos) { patchskip = in.skip(pointpos - skiped); if (patchskip > 0) { skiped += patchskip; } } readed = in.read(bytes, PART_SIZE * 2, PART_SIZE); patchsize = readed; while (patchsize > 0 && readed != PART_SIZE) { patchsize = in.read(bytes, PART_SIZE * 2 + readed, PART_SIZE - readed); if (patchsize > 0) { readed += patchsize; } } return bytes; }
From source file:Hash.Hash.java
private static boolean skipBytes(InputStream in, long pointer) throws IOException { do {//from w w w . java2 s . c o m long skip = in.skip(pointer); if (skip < 0) return false; pointer -= skip; } while (pointer > 0); return true; }
From source file:com.mpower.mintel.android.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * //from www .j a v a2 s.c om * @param urlString * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient, String auth) { URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase() .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) { try { // don't really care about the stream... InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (Exception e) { e.printStackTrace(); } } if (statusCode != 200) { String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); } finally { if (isr != null) { try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { e.printStackTrace(); String cause; if (e.getCause() != null) { cause = e.getCause().getMessage(); } else { cause = e.getMessage(); } String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:com.mpower.daktar.android.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString//from ww w . ja v a 2 s. c o m * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(final String urlString, final HttpContext localContext, final HttpClient httpclient, final String auth) { URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + "while accessing" + urlString, 0); } // set up request... final HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth); HttpResponse response = null; try { response = httpclient.execute(req, localContext); final int statusCode = response.getStatusLine().getStatusCode(); final HttpEntity entity = response.getEntity(); if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase() .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) { try { // don't really care about the stream... final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final Exception e) { e.printStackTrace(); } } if (statusCode != 200) { final String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { final String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { final String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); final KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); } finally { if (isr != null) { try { isr.close(); } catch (final Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (final Exception e) { // no-op } } } } catch (final Exception e) { e.printStackTrace(); final String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; final Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; final StringBuilder b = new StringBuilder(); for (final Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (final Exception e) { e.printStackTrace(); String cause; if (e.getCause() != null) { cause = e.getCause().getMessage(); } else { cause = e.getMessage(); } final String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:com.mycompany.rproject.runnableClass.java
public static void write() { try {/*from w w w. j av a2s .c o m*/ System.out.println("Loading models..."); Configuration configuration = new Configuration(); // Load model from the jar configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us"); //diccionario que usamos configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict"); //languagemodel configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp"); // //creo un reconozcedor StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration); System.out.println("wuhu"); InputStream stream = TranscriberDemo.class .getResourceAsStream("/edu/cmu/sphinx/demo/aligner/outpone.wav"); System.out.println("holotuhu"); // stream.skip(44); System.out.println("wuhuluhutuhu"); // Simple recognition with generic model recognizer.startRecognition(stream); SpeechResult result; String outputFilePath = "/Users/paulamontojo/Downloads/rproject/src/main/resources/edu/cmu/sphinx/demo/aligner/prueba.txt"; PrintWriter pw = null; try { pw = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath, false))); // Loop until last utterance in the audio file has been decoded, in which case the recognizer will return null. while ((result = recognizer.getResult()) != null) { //get hypothesis System.out.format("Hypothesis: %s\n", result.getHypothesis()); for (WordResult res : result.getWords()) { if (res.toString().contains("<sil>")) { System.out.println(" "); pw.println(" "); } else { System.out.print(res); pw.print(res); } } System.out.println("Best hypothesis:"); for (String s : result.getNbest(1)) { System.out.println(s); System.out.println("holi"); } } } catch (IOException ex) { } finally { if (pw != null) { pw.close(); pw.flush(); } } recognizer.stopRecognition(); try { File archivo = new File( "/Users/paulamontojo/Downloads/rproject/src/main/resources/edu/cmu/sphinx/demo/aligner/prueba.txt"); fr = new FileReader(archivo); br = new BufferedReader(fr); sbu = new StringBuilder(); // Lectura del fichero String linea; while ((linea = br.readLine()) != null) { System.out.println(linea); sbu.append(linea); sbu.append("\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) { fr.close(); } } catch (Exception e2) { e2.printStackTrace(); } } System.out.println(sbu.toString()); } catch (IOException ex) { Logger.getLogger(runnableClass.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.olat.core.gui.media.ServletUtil.java
protected static IOException copyRange(InputStream istream, OutputStream ostream, long start, long end) { try {/*from ww w.j a v a 2 s. c o m*/ istream.skip(start); } catch (IOException e) { return e; } IOException exception = null; long bytesToRead = end - start + 1; byte buffer[] = new byte[2048]; int len = buffer.length; while ((bytesToRead > 0) && (len >= buffer.length)) { try { len = istream.read(buffer); if (bytesToRead >= len) { ostream.write(buffer, 0, len); bytesToRead -= len; } else { ostream.write(buffer, 0, (int) bytesToRead); bytesToRead = 0; } } catch (IOException e) { exception = e; len = -1; } if (len < buffer.length) break; } return exception; }
From source file:org.opendatakit.briefcase.util.AggregateUtils.java
private static final void flushEntityBytes(HttpEntity entity) { if (entity != null) { // something is amiss -- read and discard any response body. try {//from w ww . j a va 2 s . co m // don't really care about the stream... InputStream is = entity.getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (Exception e) { log.error("failed to flush http content", e); } } }
From source file:com.swingtech.apps.filemgmt.controller.StreamingViewRenderer.java
/** * Copy the given byte range of the given input to the given output. * //from w w w .j av a 2s . c o m * @param input * The input to copy the given range to the given output for. * @param output * The output to copy the given range from the given input for. * @param start * Start of the byte range. * @param length * Length of the byte range. * @throws IOException * If something fails at I/O level. */ private static void copy(InputStream input, OutputStream output, long inputSize, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int read; if (inputSize == length) { // Write full range. while ((read = input.read(buffer)) > 0) { output.write(buffer, 0, read); output.flush(); } } else { input.skip(start); long toRead = length; while ((read = input.read(buffer)) > 0) { if ((toRead -= read) > 0) { output.write(buffer, 0, read); output.flush(); } else { output.write(buffer, 0, (int) toRead + read); output.flush(); break; } } } }