List of usage examples for java.io IOException initCause
public synchronized Throwable initCause(Throwable cause)
From source file:com.gc.iotools.stream.is.TeeInputStreamOutputStream.java
/** * {@inheritDoc}//from w w w. jav a 2 s . c om * * <p> * This method is called when the method {@link #close()} is invoked. It * copies all the data eventually remaining in the source * <code>InputStream</code> passed in the constructor to the destination * <code>OutputStream</code>. * </p> * <p> * The standard behavior is to close both the underlying * <code>InputStream</code> and <code>OutputStream(s)</code>. When the * class was constructed with the parameter * {@link TeeInputStreamOutputStream#closeCalled closeCalled} set to false * the underlying streams must be closed externally. * @see #close() */ @Override public void closeOnce() throws IOException { IOException e1 = null; try { final byte[] buffer = new byte[EasyStreamConstants.SKIP_BUFFER_SIZE]; while (innerRead(buffer, 0, buffer.length) > 0) { // empty block: just throw bytes away } } catch (final IOException e) { e1 = new IOException("Incomplete data was written to the destination " + "OutputStream(s)."); e1.initCause(e); } if (this.closeStreams) { final long startr = System.currentTimeMillis(); this.source.close(); this.readTime += System.currentTimeMillis() - startr; for (int i = 0; i < this.destinations.length; i++) { final long start = System.currentTimeMillis(); this.destinations[i].close(); this.writeTime[i] += System.currentTimeMillis() - start; } } if (e1 != null) { throw e1; } }
From source file:com.scvngr.levelup.core.net.LevelUpResponse.java
@NonNull @TargetApi(Build.VERSION_CODES.GINGERBREAD) private IOException getInvalidErrorResponseIOException(@NonNull final JSONException e) { final IOException wrappingException; if (EnvironmentUtil.isSdk9OrGreater()) { wrappingException = new IOException(INVALID_ERROR_RESPONSE_MESSAGE, e); } else {/*from ww w. jav a 2s.co m*/ wrappingException = new IOException(INVALID_ERROR_RESPONSE_MESSAGE); wrappingException.initCause(e); } return wrappingException; }
From source file:com.granule.json.utils.internal.JSONObject.java
/** * Internal method to write out all children JSON objects attached to this JSON object. * @param writer The writer to use while writing the JSON text. * @param depth The indention depth of the JSON text. * @param compact Flag to denote whether or not to write in nice indent format, or compact format. * @throws IOException Trhown if an error occurs on write. */// ww w .ja v a 2 s . com private void writeChildren(Writer writer, int depth, boolean compact) throws IOException { if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeChildren(Writer, int, boolean)"); if (!jsonObjects.isEmpty()) { Enumeration keys = jsonObjects.keys(); while (keys.hasMoreElements()) { String objName = (String) keys.nextElement(); Vector vect = (Vector) jsonObjects.get(objName); if (vect != null && !vect.isEmpty()) { /** * Non-array versus array elements. */ if (vect.size() == 1) { if (logger.isLoggable(Level.FINEST)) logger.logp(Level.FINEST, className, "writeChildren(Writer, int, boolean)", "Writing child object: [" + objName + "]"); JSONObject obj = (JSONObject) vect.elementAt(0); obj.writeObject(writer, depth + 1, false, compact); if (keys.hasMoreElements()) { try { if (!compact) { if (!obj.isTextOnlyObject() && !obj.isEmptyObject()) { writeIndention(writer, depth + 1); } writer.write(",\n"); } else { writer.write(","); } } catch (Exception ex) { IOException iox = new IOException("Error occurred on serialization of JSON text."); iox.initCause(ex); throw iox; } } else { if (obj.isTextOnlyObject() && !compact) { writer.write("\n"); } } } else { if (logger.isLoggable(Level.FINEST)) logger.logp(Level.FINEST, className, "writeChildren(Writer, int, boolean)", "Writing array of JSON objects with attribute name: [" + objName + "]"); try { if (!compact) { writeIndention(writer, depth + 1); writer.write("\"" + objName + "\""); writer.write(" : [\n"); } else { writer.write("\"" + objName + "\""); writer.write(":["); } for (int i = 0; i < vect.size(); i++) { JSONObject obj = (JSONObject) vect.elementAt(i); obj.writeObject(writer, depth + 2, true, compact); /** * Still more we haven't handled. */ if (i != (vect.size() - 1)) { if (!compact) { if (!obj.isTextOnlyObject() && !obj.isEmptyObject()) { writeIndention(writer, depth + 2); } writer.write(",\n"); } else { writer.write(","); } } } if (!compact) { writer.write("\n"); writeIndention(writer, depth + 1); } writer.write("]"); if (keys.hasMoreElements()) { writer.write(","); } if (!compact) { writer.write("\n"); } } catch (Exception ex) { IOException iox = new IOException("Error occurred on serialization of JSON text."); iox.initCause(ex); throw iox; } } } } } if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeChildren(Writer, int, boolean)"); }
From source file:phex.download.DownloadEngine.java
public void startDownload() throws IOException { String snapshotOfSegment;// w w w. j a va 2 s . c o m NLogger.debug(NLoggerNames.Download_Engine, "Download Engine starts download."); DirectByteBuffer directByteBuffer = null; LengthLimitedInputStream downloadStream = null; try { ManagedFile destFile = downloadFile.getIncompleteDownloadFile(); directByteBuffer = DirectByteBufferProvider.requestBuffer(DirectByteBufferProvider.BUFFER_SIZE_64K); segment.downloadStartNotify(); snapshotOfSegment = segment.toString(); // determine the length to download, we start with the MAX // which would cause a download until the stream ends. long downloadLengthLeft = Long.MAX_VALUE; // maybe we know the file size if (replyContentRange != null && replyContentRange.totalLength != -1) { downloadLengthLeft = replyContentRange.totalLength; } // maybe we know a reply content length if (replyContentLength != -1) { downloadLengthLeft = Math.min(replyContentLength, downloadLengthLeft); } // maybe the segment has a smaler length (usually not the case) long segmentDataSizeLeft = segment.getTransferDataSizeLeft(); if (segmentDataSizeLeft != -1) { downloadLengthLeft = Math.min(segmentDataSizeLeft, downloadLengthLeft); } downloadStream = new LengthLimitedInputStream(inStream, downloadLengthLeft); long fileOffset = segment.getStart() + segment.getTransferredDataSize(); long lengthDownloaded = segment.getTransferredDataSize(); int len; byte[] buffer = new byte[BUFFER_LENGTH]; while ((len = downloadStream.read(buffer, 0, BUFFER_LENGTH)) > 0) { synchronized (segment) { long tmpCheckLength = lengthDownloaded + len; if (tmpCheckLength < segment.getTransferredDataSize()) { NLogger.error(NLoggerNames.Download_Engine, "TransferredDataSize would be going down! " + " ll " + downloadLengthLeft + " l " + len + " ld " + lengthDownloaded + " gtds " + segment.getTransferredDataSize() + " seg: " + segment + " originally: " + snapshotOfSegment); throw new IOException("TransferredDataSize would be going down!"); } else if (segment.getTransferDataSize() > -1 && tmpCheckLength > segment.getTransferDataSize()) { NLogger.error(NLoggerNames.Download_Engine, "TransferredDataSize would be larger then segment! " + " ll " + downloadLengthLeft + " l " + len + " ld " + lengthDownloaded + " gtds " + segment.getTransferredDataSize() + " seg: " + segment + " originally: " + snapshotOfSegment); throw new IOException("TransferredDataSize would be larger then segment!"); } directByteBuffer.put(buffer, 0, len); directByteBuffer.flip(); destFile.write(directByteBuffer, fileOffset); fileOffset += directByteBuffer.limit(); directByteBuffer.clear(); lengthDownloaded += len; segment.setTransferredDataSize(lengthDownloaded); candidate.incTotalDownloadSize(len); // get transfer size since it might have changed in the meantime. segmentDataSizeLeft = segment.getTransferDataSizeLeft(); if (segmentDataSizeLeft != -1) { downloadLengthLeft = Math.min(segmentDataSizeLeft, downloadLengthLeft); downloadStream.setLengthLimit(downloadLengthLeft); } } } isDownloadSuccessful = true; // if we successful downloaded and we still dont know the total file size, // we can assume that the file was completly downloaded. if (downloadFile.getTotalDataSize() == SWDownloadConstants.UNKNOWN_FILE_SIZE) { // we have a file with an unknown data size. For aditional check assert // certain parameters assert (segment.getTotalDataSize() == -1); downloadFile.setFileSize(segment.getTransferredDataSize()); } } catch (FileHandlingException exp) { NLogger.error(NLoggerNames.Download_Engine, exp, exp); IOException ioExp = new IOException(exp.getMessage()); ioExp.initCause(exp); throw ioExp; } catch (ManagedFileException exp) { if (Thread.currentThread().isInterrupted()) { return; } NLogger.error(NLoggerNames.Download_Engine, exp, exp); IOException ioExp = new IOException(exp.getMessage()); ioExp.initCause(exp); throw ioExp; } finally {// dont close managed file since it might be used by parallel threads. if (directByteBuffer != null) { directByteBuffer.release(); } boolean isAcceptingNextSegment = isAcceptingNextSegment(); candidate.addToCandidateLog("Is accepting next segment: " + isAcceptingNextSegment); // this is for keep alive support... if (isAcceptingNextSegment) { // only need to close and consume left overs if we plan to // continue using this connection. downloadStream.close(); } else { stopDownload(); } } }
From source file:org.apache.hadoop.hbase.util.FSUtils.java
/** * Checks to see if the specified file system is available * * @param fs filesystem/* w w w.j a va2 s. c om*/ * @throws IOException e */ public static void checkFileSystemAvailable(final FileSystem fs) throws IOException { if (!(fs instanceof DistributedFileSystem)) { return; } IOException exception = null; DistributedFileSystem dfs = (DistributedFileSystem) fs; try { if (dfs.exists(new Path("/"))) { return; } } catch (IOException e) { exception = RemoteExceptionHandler.checkIOException(e); } try { fs.close(); } catch (Exception e) { LOG.error("file system close failed: ", e); } IOException io = new IOException("File system is not available"); io.initCause(exception); throw io; }
From source file:org.esa.nest.dataio.cosmo.CosmoSkymedReader.java
/** * {@inheritDoc}/*from w w w .j a va 2s .c om*/ */ @Override protected void readBandRasterDataImpl(int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight, int sourceStepX, int sourceStepY, Band destBand, int destOffsetX, int destOffsetY, int destWidth, int destHeight, ProductData destBuffer, ProgressMonitor pm) throws IOException { Guardian.assertTrue("sourceStepX == 1 && sourceStepY == 1", sourceStepX == 1 && sourceStepY == 1); Guardian.assertTrue("sourceWidth == destWidth", sourceWidth == destWidth); Guardian.assertTrue("sourceHeight == destHeight", sourceHeight == destHeight); final int sceneHeight = product.getSceneRasterHeight(); final int y0 = yFlipped ? (sceneHeight - 1) - sourceOffsetY : sourceOffsetY; final Variable variable = bandMap.get(destBand); final int rank = variable.getRank(); final int[] origin = new int[rank]; final int[] shape = new int[rank]; for (int i = 0; i < rank; i++) { shape[i] = 1; origin[i] = 0; } shape[0] = 1; shape[1] = destWidth; origin[1] = sourceOffsetX; if (isComplex && destBand.getUnit().equals(Unit.IMAGINARY)) { origin[2] = 1; } pm.beginTask("Reading data from band " + destBand.getName(), destHeight); try { for (int y = 0; y < destHeight; y++) { origin[0] = yFlipped ? y0 - y : y0 + y; final Array array; synchronized (netcdfFile) { array = variable.read(origin, shape); } System.arraycopy(array.getStorage(), 0, destBuffer.getElems(), y * destWidth, destWidth); pm.worked(1); if (pm.isCanceled()) { throw new IOException("Process terminated by user."); /*I18N*/ } } } catch (InvalidRangeException e) { final IOException ioException = new IOException(e.getMessage()); ioException.initCause(e); throw ioException; } finally { pm.done(); } }
From source file:it.geosolutions.imageio.plugins.nitronitf.NITFImageWriter.java
@Override public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException { // Headers and segments initialization NITFImageWriteParam nitfParam = null; HeaderWrapper header = null;/* w w w . j a v a 2 s.c om*/ Map<String, Map<String, String>> extensionsMap = null; ShapeFileWrapper shape = null; List<TextWrapper> texts = null; WriteCompression compression = null; List<ImageWrapper> inputImages = null; if (param != null && param instanceof NITFImageWriteParam) { nitfParam = (NITFImageWriteParam) param; NITFProperties nitfMetadata = nitfParam.getNitfProperties(); if (nitfMetadata != null) { header = nitfMetadata.getHeader(); shape = nitfMetadata.getShape(); texts = nitfMetadata.getTextsWrapper(); inputImages = nitfMetadata.getImagesWrapper(); } compression = nitfParam.getWriteCompression(); } ImageWrapper imageW = inputImages.get(0); RenderedImage ri = imageW.getImage(); final boolean isJP2 = (compression != null && compression != WriteCompression.UNCOMPRESSED); FileImageInputStreamExt jp2Stream = null; File tempFile = null; try { Record record = new Record(Version.NITF_21); if (isJP2) { // Proceeding with jp2 compression if (JP2_TEMP_FOLDER != null) { tempFile = File.createTempFile("jp2compressed", ".jpc", new File(JP2_TEMP_FOLDER)); } String parentPath = outputFile.getParent(); String name = FilenameUtils.getBaseName(outputFile.getCanonicalPath()); tempFile = new File(parentPath + File.separatorChar + name + ".j2c"); prepareJP2Image(ri, tempFile, compression); jp2Stream = new FileImageInputStreamExtImpl(tempFile); } // populating the file header initFileHeader(record, header); // adding an image segment to the record addImageSegment(record, inputImages, jp2Stream, compression); if (texts != null && !texts.isEmpty()) { // adding a text segment if present addTextSegment(record, texts); } if (!writeNITF(record, inputImages, shape, jp2Stream, texts)) { throw new IOException("Unable to successfully write"); } } catch (Throwable t) { IOException ioe = new IOException(); ioe.initCause(t); throw ioe; } finally { // Releasing resources if (jp2Stream != null) { try { jp2Stream.close(); } catch (Throwable thr) { // Eat exception } } if (tempFile != null) { try { tempFile.delete(); } catch (Throwable thr) { } } } // record.destruct(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Successfully wrote NITF: " + outputFile); } }
From source file:org.apache.hadoop.hbase.regionserver.wal.AbstractFSWAL.java
private IOException convertInterruptedExceptionToIOException(final InterruptedException ie) { Thread.currentThread().interrupt(); IOException ioe = new InterruptedIOException(); ioe.initCause(ie); return ioe;/*from ww w. j a v a 2s .co m*/ }
From source file:org.apache.axis2.addressing.EndpointReference.java
/** * Write the EPR to the specified OutputStream. Because of potential * OMElements/Attributes, we need to actually serialize the OM structures * (at least in some cases.)//from w ww . java 2 s .co m */ public synchronized void writeExternal(java.io.ObjectOutput o) throws IOException { SafeObjectOutputStream out = SafeObjectOutputStream.install(o); // revision ID out.writeInt(revisionID); // Correlation ID String logCorrelationIDString = getLogCorrelationIDString(); // String object id out.writeObject(logCorrelationIDString); // Write out the content as xml out.writeUTF("start xml"); // write marker OMElement om = EndpointReferenceHelper.toOM(OMAbstractFactory.getOMFactory(), this, new QName("urn:axis2", "omepr", "ser"), AddressingConstants.Final.WSA_NAMESPACE); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { om.serialize(baos); } catch (Exception e) { IOException ioe = new IOException("Unable to serialize the EndpointReference with logCorrelationID [" + logCorrelationIDString + "]"); ioe.initCause(e); if (log.isDebugEnabled()) { log.debug("writeObject(): Unable to serialize the EPR with logCorrelationID [" + logCorrelationIDString + "] original error [" + e.getClass().getName() + "] message [" + e.getMessage() + "]", e); } throw ioe; } out.writeInt(baos.size()); out.write(baos.toByteArray()); out.writeUTF("end xml"); // write marker if (log.isDebugEnabled()) { byte[] buffer = baos.toByteArray(); String content = new String(buffer); log.debug("writeObject(): EPR logCorrelationID [" + logCorrelationIDString + "] " + " EPR content size [" + baos.size() + "]" + " EPR content [" + content + "]"); } }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page./*from ww w. j a v a2 s .com*/ */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }