List of usage examples for java.io EOFException EOFException
public EOFException()
EOFException
with null
as its error detail message. From source file:com.bigdata.dastor.io.SSTableReader.java
private PositionSize getDataPositionSize(FileDataInput input, long dataPosition) throws IOException { // if we've reached the end of the index, then the row size is "the rest of the data file" if (input.isEOF()) return new PositionSize(dataPosition, length() - dataPosition); // otherwise, row size is the start of the next row (in next index entry), minus the start of this one. long nextIndexPosition = input.getAbsolutePosition(); // if next index entry would span mmap boundary, get the next row position from the summary instead PositionSize nextPositionSize = indexSummary.getSpannedDataPosition(nextIndexPosition); if (nextPositionSize != null) return new PositionSize(dataPosition, nextPositionSize.position - dataPosition); // read next entry directly int utflen = input.readUnsignedShort(); if (utflen != input.skipBytes(utflen)) throw new EOFException(); return new PositionSize(dataPosition, input.readLong() - dataPosition); }
From source file:org.apache.mele.embedded.HadoopQueueEmbedded.java
private static int readInt(InputStream inputStream) throws IOException { int i1 = inputStream.read(); int i2 = inputStream.read(); int i3 = inputStream.read(); int i4 = inputStream.read(); if ((i1 | i2 | i3 | i4) < 0) { throw new EOFException(); }//w w w . ja v a 2s.c o m return ((i1 << 24) + (i2 << 16) + (i3 << 8) + (i4 << 0)); }
From source file:org.commoncrawl.util.StreamingArcFileReader.java
private boolean readHeader() throws IOException { if (_rawInput.available() == 0 && _eosReached) { throw new EOFException(); }// w w w . j a va 2s . co m switch (_headerReadState) { case ReadingFixedHeader: { if (_rawInput.available() >= FixedHeaderBytes) { _arcFileStartOffset = _streamPos; // reset crc accumulator first ... _crc.reset(); // reset content bytes read counter .. _contentBytesRead = 0; // Check header magic if (readUShort(_checkedInput) != GZIP_MAGIC) { throw new IOException("Not in GZIP format"); } // Check compression method if (readUByte(_checkedInput) != 8) { throw new IOException("Unsupported compression method"); } // Read flags _headerFlags = readUByte(_checkedInput); // Skip MTIME, XFL, and OS fields skipBytes(_checkedInput, 6); _headerReadState = HeaderReadState.ReadingFlagValues; } else { break; } } case ReadingFlagValues: { boolean advanceToNext = true; // Skip optional extra field if ((_headerFlags & FEXTRA) == FEXTRA) { advanceToNext = false; if (_headerExtraBytes == -1) { if (_checkedInput.available() >= 2) { _headerExtraBytes = readUShort(_checkedInput); } } if (_headerExtraBytes != -1) { if (_checkedInput.available() >= _headerExtraBytes) { // skip the requisite bytes skipBytes(_checkedInput, _headerExtraBytes); // mask out current flag value ... _headerFlags &= ~FEXTRA; // set advanceToNext flag advanceToNext = true; } } } while (advanceToNext && (_headerFlags & (FNAME | FCOMMENT)) != 0) { int activeFlag = FCOMMENT; if ((_headerFlags & FNAME) == FNAME) activeFlag = FNAME; advanceToNext = false; while (_checkedInput.available() != 0) { // keep scanning for null terminator if (readUByte(_checkedInput) == 0) { _headerFlags &= ~activeFlag; advanceToNext = true; } } } if (advanceToNext && (_headerFlags & FHCRC) == FHCRC) { if (_checkedInput.available() >= 2) { int v = (int) _crc.getValue() & 0xffff; if (readUShort(_checkedInput) != v) { throw new IOException("Corrupt GZIP header"); } _headerFlags &= ~FHCRC; } } if (_headerFlags == 0 && _headerReadState == HeaderReadState.ReadingFlagValues) { //reset header state variables... _headerReadState = HeaderReadState.ReadingFixedHeader; _headerFlags = 0; _headerExtraBytes = -1; return true; } } break; } return false; }
From source file:com.sxit.crawler.utils.ArchiveUtils.java
/** * Read stream into buf until EOF or buf full. * /* w ww.j a va 2 s. c o m*/ * @param input * @param buf * @throws IOException */ public static int readFully(InputStream input, byte[] buf) throws IOException { int max = buf.length; int ofs = 0; while (ofs < max) { int l = input.read(buf, ofs, max - ofs); if (l == 0) { throw new EOFException(); } ofs += l; } return ofs; }
From source file:org.apache.hadoop.hbase.KeyValueUtil.java
/** * Create a KeyValue reading from the raw InputStream. Named * <code>createKeyValueFromInputStream</code> so doesn't clash with {@link #create(DataInput)} * @param in inputStream to read.//from w w w.j av a2 s.c o m * @param withTags whether the keyvalue should include tags are not * @return Created KeyValue OR if we find a length of zero, we will return null which can be * useful marking a stream as done. * @throws IOException */ public static KeyValue createKeyValueFromInputStream(InputStream in, boolean withTags) throws IOException { byte[] intBytes = new byte[Bytes.SIZEOF_INT]; int bytesRead = 0; while (bytesRead < intBytes.length) { int n = in.read(intBytes, bytesRead, intBytes.length - bytesRead); if (n < 0) { if (bytesRead == 0) { throw new EOFException(); } throw new IOException("Failed read of int, read " + bytesRead + " bytes"); } bytesRead += n; } byte[] bytes = new byte[Bytes.toInt(intBytes)]; IOUtils.readFully(in, bytes, 0, bytes.length); return withTags ? new KeyValue(bytes, 0, bytes.length) : new NoTagsKeyValue(bytes, 0, bytes.length); }
From source file:org.broad.igv.util.HttpUtils.java
/** * Test to see if this client can successfully retrieve a portion of a remote file using the byte-range header. * This is not a test of the server, but the client. In some environments the byte-range header gets removed * by filters after the request is made by IGV. * * @return//from w w w .j av a2 s . com */ public boolean useByteRange(URL url) { if (BYTE_RANGE_DISABLED) return false; // We can test byte-range success for hosts we can reach. synchronized (byteRangeTestMap) { final String host = url.getHost(); if (byteRangeTestMap.containsKey(host)) { return byteRangeTestMap.get(host); } else { SeekableStream str = null; try { boolean byteRangeTestSuccess = true; if (host.contains("broadinstitute.org")) { byteRangeTestSuccess = testBroadHost(host); } else { // Non-broad URL int l = (int) Math.min(1000, HttpUtils.getInstance().getContentLength(url)); if (l > 100) { byte[] firstBytes = new byte[l]; str = new IGVSeekableHTTPStream(url); str.readFully(firstBytes); int end = firstBytes.length; int start = end - 100; str.seek(start); int len = end - start; byte[] buffer = new byte[len]; int n = 0; while (n < len) { int count = str.read(buffer, n, len - n); if (count < 0) throw new EOFException(); n += count; } for (int i = 0; i < len; i++) { if (buffer[i] != firstBytes[i + start]) { byteRangeTestSuccess = false; break; } } } else { // Too small a sample to test, or unknown content length. Return "true" but don't record // this host as tested. return true; } } if (byteRangeTestSuccess) { log.info("Range-byte request succeeded"); } else { log.info("Range-byte test failed -- problem with client network environment."); } byteRangeTestMap.put(host, byteRangeTestSuccess); return byteRangeTestSuccess; } catch (IOException e) { log.error("Error while testing byte range " + e.getMessage()); // We could not reach the test server, so we can't know if this client can do byte-range tests or // not. Take the "optimistic" view. return true; } finally { if (str != null) try { str.close(); } catch (IOException e) { log.error("Error closing stream (" + url.toExternalForm() + ")", e); } } } } }
From source file:com.bdaum.zoom.gps.internal.operations.GeotagOperation.java
protected Waypoint getPlaceInfo(Meta meta, int i, double lat, double lon, IProgressMonitor aMonitor, IAdaptable info) throws UnknownHostException, EOFException { RasterCoordinate coord = new RasterCoordinate(lat, lon, 2); Waypoint place = coord.findClosestMatch(placeMap, 0.06d, 'K'); if (place != null) return place; try {/*from w w w.ja v a 2 s . co m*/ if (!lastAccessFailed && yieldWebservice(aMonitor)) return null; lastAccessFailed = true; place = GpsUtilities.fetchPlaceInfo(lat, lon); if (place != null && !Double.isNaN(place.getLat()) && !Double.isNaN(place.getLon())) { double elevation = getElevation(place.getLat(), place.getLon(), aMonitor); if (!Double.isNaN(elevation)) place.setElevation(elevation); } if (place != null) { placeMap.put(coord, place); lastAccessFailed = false; return place; } } catch (MalformedURLException e) { // should never happen } catch (SocketTimeoutException e) { addError(Messages.getString("GeotagOperation.connection_timed_out"), //$NON-NLS-1$ null); } catch (HttpException e) { String message = e.getMessage(); if (message.indexOf("(503)") >= 0) { //$NON-NLS-1$ addError(Messages.getString("GeotagOperation.geonaming_aborted"), e); //$NON-NLS-1$ if (aMonitor != null) aMonitor.setCanceled(true); } else addError(NLS.bind(Messages.getString("GeotagOperation.http_exception"), message), //$NON-NLS-1$ null); } catch (IOException e) { if (e instanceof UnknownHostException) throw (UnknownHostException) e; addError(Messages.getString("GeotagOperation.IO_Error_parsing_response"), //$NON-NLS-1$ e); } catch (NumberFormatException e) { addError(Messages.getString("GeotagOperation.Number_format_parsing_response"), //$NON-NLS-1$ e); } catch (WebServiceException e) { addWarning(Messages.getString("GeotagOperation.Geoname_signalled_exception"), e); //$NON-NLS-1$ Throwable e2 = e.getCause(); if (e2 instanceof WebServiceException && e2 != e) { try { int code = Integer.parseInt(e2.getMessage()); if (code >= 18 && code <= 20) { handleResume(meta, code, i, info); throw new EOFException(); } } catch (NumberFormatException e1) { // do nothing } addError(Messages.getString("GeotagOperation.geonaming_aborted"), e2); //$NON-NLS-1$ if (aMonitor != null) aMonitor.setCanceled(true); } } catch (SAXException e) { addError(Messages.getString("GeotagOperation.XML_problem_parsing_response"), e); //$NON-NLS-1$ } catch (ParserConfigurationException e) { addError(Messages.getString("GeotagOperation.internal_error_configuring_sax"), e); //$NON-NLS-1$ } return null; }
From source file:org.globus.myproxy.MyProxy.java
private InputStream handleReply(InputStream in, OutputStream out, GSSCredential authzcreds, boolean wantTrustroots) throws IOException, MyProxyException { String tmp = null;/*from www. j a v a 2 s . c o m*/ /* there was something weird here with the received protocol version sometimes. it contains an extra <32 byte. fixed it by using endsWith. now i read extra byte at the end of each message. */ // protocol version tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.endsWith(MyProxyConstants.VERSION)) { throw new MyProxyException("Protocol version mismatch: " + tmp); } // response tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.startsWith(RESPONSE)) { throw new MyProxyException("Invalid reply: no response message"); } boolean error = tmp.charAt(RESPONSE.length()) == '1'; boolean authzchallenge = tmp.charAt(RESPONSE.length()) == '2'; if (error) { StringBuffer errorStr = new StringBuffer(); while ((tmp = readLine(in)) != null) { if (tmp.startsWith(ERROR)) { if (errorStr.length() > 0) errorStr.append(' '); errorStr.append(tmp.substring(ERROR.length())); } } if (errorStr.length() == 0) { errorStr.append("unspecified server error"); } throw new MyProxyException(errorStr.toString()); } if (authzchallenge) { if (authzcreds == null) { throw new MyProxyException( "Unable to respond to server's authentication challenge. No credentials for renewal."); } if (out == null) { throw new MyProxyException("Internal error. Authz challenge but no OutputStream."); } String[] authzdata = null; while ((tmp = readLine(in)) != null) { if (tmp.startsWith(AUTHZ_DATA)) { int pos = tmp.indexOf(':', AUTHZ_DATA.length() + 1); if (pos != -1) { authzdata = new String[2]; authzdata[0] = tmp.substring(AUTHZ_DATA.length(), pos).trim(); authzdata[1] = tmp.substring(pos + 1).trim(); } if (authzdata == null) { throw new MyProxyException("Unable to parse authorization challenge from server."); } if (authzdata[0].equals("X509_certificate")) { GlobusGSSCredentialImpl pkiCred = (GlobusGSSCredentialImpl) authzcreds; try { Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign(pkiCred.getPrivateKey()); sig.update(authzdata[1].getBytes()); byte[] sigbytes = sig.sign(); X509Certificate[] certs = pkiCred.getCertificateChain(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048); buffer.write(2); // AUTHORIZETYPE_CERT buffer.write(0); buffer.write(0); buffer.write(0); // pad DataOutputStream dos = new DataOutputStream(buffer); dos.writeInt(sigbytes.length); dos.flush(); buffer.write(sigbytes); buffer.write((byte) certs.length); for (int i = 0; i < certs.length; i++) { buffer.write(certs[i].getEncoded()); } out.write(buffer.toByteArray()); out.flush(); } catch (Exception e) { throw new MyProxyException("Authz response failed.", e); } } else { authzdata = null; continue; } } } return handleReply(in, out, authzcreds, wantTrustroots); } if (wantTrustroots == true) { while ((tmp = readLine(in)) != null) { if (tmp.startsWith(TRUSTROOTS)) { String filenameList = tmp.substring(TRUSTROOTS.length()); this.trustrootFilenames = filenameList.split(","); this.trustrootData = new String[this.trustrootFilenames.length]; for (int i = 0; i < this.trustrootFilenames.length; i++) { String lineStart = "FILEDATA_" + this.trustrootFilenames[i] + "="; tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.startsWith(lineStart)) { throw new MyProxyException("bad MyProxy protocol RESPONSE: expecting " + lineStart + " but received " + tmp); } this.trustrootData[i] = new String( Base64.decode(tmp.substring(lineStart.length()).getBytes())); } } } } /* always consume the entire message */ int avail = in.available(); byte[] b = new byte[avail]; if (avail > 0) in.read(b); ByteArrayInputStream inn = new ByteArrayInputStream(b); return inn; }
From source file:org.aludratest.service.gui.web.selenium.selenium2.Selenium2Wrapper.java
private String captureScreenshotToString() { // use Selenium1 interface to capture full screen String url = seleniumUrl.toString(); Pattern p = Pattern.compile("(http(s)?://.+)/wd/hub(/?)"); Matcher matcher = p.matcher(url); if (matcher.matches()) { String screenshotUrl = matcher.group(1); screenshotUrl += (screenshotUrl.endsWith("/") ? "" : "/") + "selenium-server/driver/?cmd=captureScreenshotToString"; InputStream in = null;/*w ww.ja v a 2 s . c om*/ try { in = new URL(screenshotUrl).openStream(); // read away "OK," if (in.read(new byte[3]) < 3) { throw new EOFException(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(in, baos); return new String(baos.toByteArray(), "UTF-8"); } catch (IOException e) { // OK, fallthrough to Selenium 2 method } finally { IOUtils.closeQuietly(in); } } WebDriver screenshotDriver; if (RemoteWebDriver.class.isAssignableFrom(driver.getClass())) { screenshotDriver = new Augmenter().augment(driver); } else { screenshotDriver = driver; } if (screenshotDriver instanceof TakesScreenshot) { TakesScreenshot tsDriver = (TakesScreenshot) screenshotDriver; return tsDriver.getScreenshotAs(OutputType.BASE64); } else { throw new UnsupportedOperationException(driver.getClass() + " does not implement TakeScreenshot"); } }
From source file:UI.MainUI.java
private void readDataFromFile(BufferedReader br, int inputCnt, List<Double> inputValues, int currencyCol, String[] tableRowData) throws NumberFormatException, EOFException, IOException { String line;/*w w w. j a v a 2 s .co m*/ String[] cols; int flag = 1; if (inputValues.size() == 0) { for (int i = 0; i < inputCnt; i++) { if ((line = br.readLine()) != null) { // use comma as separator cols = line.split(","); inputValues.add(Utility.normalize(Double.parseDouble(cols[currencyCol]), currencyCol)); } else { throw new EOFException(); } } } else { //shift every input to left and add previous expected output to last //and read expected output from next row. inputValues.remove(0); inputValues.add(Utility.normalize(Double.parseDouble(tableRowData[EXPECTED_OUTPUT_COL]), currencyCol)); } String str; str = "" + Utility.formatDecimal(Utility.denormalize(inputValues.get(0), currencyCol)); Double d; for (int j = 1; j < inputValues.size(); j++) { d = inputValues.get(j); str += ", " + Utility.formatDecimal(Utility.denormalize(d, currencyCol)); } tableRowData[INPUT_COL] = str; // Read expected output to display. if ((line = br.readLine()) != null) { cols = line.split(","); tableRowData[EXPECTED_OUTPUT_COL] = Utility.formatDecimal(Double.parseDouble(cols[currencyCol])); tableRowData[DATE_COL] = cols[0]; } else { throw new EOFException(); } }