public void writeAsAttachment(Object obj, OutputStream out) throws IOException { try { if (obj instanceof StreamSource) { StreamSource source = (StreamSource) obj; InputSource inputSource = null; InputStream is = source.getInputStream(); Reader reader = source.getReader(); String systemId = source.getSystemId(); if (is != null) inputSource = new InputSource(is); else if (reader != null) inputSource = new InputSource(reader); else if (systemId != null) inputSource = new InputSource(systemId); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(_entityResolver); SAXSource saxSource = new SAXSource(xmlReader, inputSource); _transformer.transform(saxSource, new StreamResult(out)); } else _transformer.transform((Source) obj, new StreamResult(out)); } catch (TransformerException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } catch (SAXException saxe) { IOException ioe = new IOException(); ioe.initCause(saxe); throw ioe; } }
/** {@inheritDoc} */ public <V, T extends Throwable> V call(Callable<V, T> callable) throws IOException, T, InterruptedException { UserRequest<V, T> request = null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V, T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); // re-wrap the exception so that we can capture the stack trace of the caller. } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on " + name + " failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on " + name + " failed"); x.initCause(e); throw x; } finally { // since this is synchronous operation, when the round trip is over // we assume all the exported objects are out of scope. // (that is, the operation shouldn't spawn a new thread or altter // global state in the remote system. if (request != null) request.releaseExports(); } }
/** * Deserialize a {@link RealMatrix} field in a class. * * <p>This method is intended to be called from within a private <code>readObject</code> method * (after a call to <code>ois.defaultReadObject()</code>) in a class that has a {@link RealMatrix} * field, which should be declared <code>transient</code>. This way, the default handling does not * deserialize the matrix (the {@link RealMatrix} interface is not serializable by default) but * this method does deserialize it specifically. * * @param instance instance in which the field must be set up * @param fieldName name of the field within the class (may be private and final) * @param ois stream from which the real matrix should be read * @exception ClassNotFoundException if a class in the stream cannot be found * @exception IOException if object cannot be read from the stream * @see #serializeRealMatrix(RealMatrix, ObjectOutputStream) */ public static void deserializeRealMatrix( final Object instance, final String fieldName, final ObjectInputStream ois) throws ClassNotFoundException, IOException { try { // read the matrix data final int n = ois.readInt(); final int m = ois.readInt(); final double[][] data = new double[n][m]; for (int i = 0; i < n; ++i) { final double[] dataI = data[i]; for (int j = 0; j < m; ++j) { dataI[j] = ois.readDouble(); } } // create the instance final RealMatrix matrix = new Array2DRowRealMatrix(data, false); // set up the field final java.lang.reflect.Field f = instance.getClass().getDeclaredField(fieldName); f.setAccessible(true); f.set(instance, matrix); } catch (NoSuchFieldException nsfe) { IOException ioe = new IOException(); ioe.initCause(nsfe); throw ioe; } catch (IllegalAccessException iae) { IOException ioe = new IOException(); ioe.initCause(iae); throw ioe; } }
public void get(String source, File destination) throws IOException { fireTransferInitiated(getResource(source), TransferEvent.REQUEST_GET); ChannelSftp c = getSftpChannel(source); try { String path = getPath(source); c.get(path, destination.getAbsolutePath(), new MyProgressMonitor()); } catch (SftpException e) { IOException ex = new IOException( "impossible to get " + source + " on " + getHost() + (e.getMessage() != null ? ": " + e.getMessage() : "")); ex.initCause(e); throw ex; } catch (URISyntaxException e) { IOException ex = new IOException( "impossible to get " + source + " on " + getHost() + (e.getMessage() != null ? ": " + e.getMessage() : "")); ex.initCause(e); throw ex; } }
public List list(String parent) throws IOException { try { ChannelSftp c = getSftpChannel(parent); String path = getPath(parent); Collection r = c.ls(path); if (r != null) { if (!path.endsWith("/")) { path = parent + "/"; } List result = new ArrayList(); for (Iterator iter = r.iterator(); iter.hasNext(); ) { Object obj = iter.next(); if (obj instanceof LsEntry) { LsEntry entry = (LsEntry) obj; if (".".equals(entry.getFilename()) || "..".equals(entry.getFilename())) { continue; } result.add(path + entry.getFilename()); } } return result; } } catch (SftpException e) { IOException ex = new IOException("Failed to return a listing for '" + parent + "'"); ex.initCause(e); throw ex; } catch (URISyntaxException usex) { IOException ex = new IOException("Failed to return a listing for '" + parent + "'"); ex.initCause(usex); throw ex; } return null; }
public InputStream openStream(SFTPResource resource) throws IOException { ChannelSftp c = getSftpChannel(resource.getName()); try { String path = getPath(resource.getName()); return c.get(path); } catch (SftpException e) { IOException ex = new IOException( "impossible to open stream for " + resource + " on " + getHost() + (e.getMessage() != null ? ": " + e.getMessage() : "")); ex.initCause(e); throw ex; } catch (URISyntaxException e) { IOException ex = new IOException( "impossible to open stream for " + resource + " on " + getHost() + (e.getMessage() != null ? ": " + e.getMessage() : "")); ex.initCause(e); throw ex; } }
private Object readSetting(java.io.Reader input, Object inst) throws IOException { try { java.lang.reflect.Method m = inst.getClass() .getDeclaredMethod("readProperties", new Class[] {Properties.class}); // NOI18N m.setAccessible(true); XMLPropertiesConvertor.Reader r = new XMLPropertiesConvertor.Reader(); r.parse(input); m.setAccessible(true); Object ret = m.invoke(inst, new Object[] {r.getProperties()}); if (ret == null) { ret = inst; } return ret; } catch (NoSuchMethodException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } catch (IllegalAccessException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } catch (java.lang.reflect.InvocationTargetException ex) { Throwable t = ex.getTargetException(); IOException ioe = new IOException(ex.getMessage()); ioe.initCause(t); throw ioe; } }
public void write(SecureItemTable tbl, char[] password) throws IOException { OutputStream os = new FileOutputStream(file); OutputStream xmlout; if (password.length == 0) { xmlout = os; os = null; } else { PBEKeySpec keyspec = new PBEKeySpec(password); Cipher c; try { SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = fac.generateSecret(keyspec); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.ENCRYPT_MODE, key, pbeSpec); } catch (java.security.GeneralSecurityException exc) { os.close(); IOException ioe = new IOException("Security exception during write"); ioe.initCause(exc); throw ioe; } CipherOutputStream out = new CipherOutputStream(os, c); xmlout = out; } try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource src = new DOMSource(tbl.getDocument()); StringWriter writer = new StringWriter(); StreamResult sr = new StreamResult(writer); t.transform(src, sr); OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8); osw.write(writer.toString()); osw.close(); } catch (Exception exc) { IOException ioe = new IOException("Unable to serialize XML"); ioe.initCause(exc); throw ioe; } finally { xmlout.close(); if (os != null) os.close(); } tbl.setDirty(false); return; }
/** * Load weights and values from the given file * * @param joinFileName the file from which to read join cost features * @param joinPdfFileName the file from which to read the Gaussian models in the leaves of the * tree * @param joinTreeFileName the file from which to read the Tree, in HTS format. */ public void load( String joinFileName, InputStream joinPdfStream, InputStream joinTreeStream, String trickyPhonesFile) throws IOException, MaryConfigurationException { jcf = new JoinCostFeatures(joinFileName); assert featureDef != null : "Expected to have a feature definition, but it is null!"; /* Load Trees */ HTSCARTReader htsReader = new HTSCARTReader(); int numStates = 1; // just one state in the joinModeller // Check if there are tricky phones, and create a PhoneTranslator object PhoneTranslator phTranslator = new PhoneTranslator(new FileInputStream(trickyPhonesFile)); try { // joinTree.loadTreeSetGeneral(joinTreeFileName, 0, featureDef); joinTree = htsReader.load( numStates, joinTreeStream, joinPdfStream, PdfFileFormat.join, featureDef, phTranslator); } catch (Exception e) { IOException ioe = new IOException("Cannot load join model trees"); ioe.initCause(e); throw ioe; } }
static Throwable wrapWithAddendum(Throwable ex, String addendum, boolean after) { if (ex instanceof AssertionFailedError) { AssertionFailedError ne = new AssertionFailedError(combineMessages(ex, addendum, after)); if (ex.getCause() != null) { ne.initCause(ex.getCause()); } ne.setStackTrace(ex.getStackTrace()); return ne; } if (ex instanceof AssertionError) { // preferred in JUnit 4 AssertionError ne = new AssertionError(combineMessages(ex, addendum, after)); if (ex.getCause() != null) { ne.initCause(ex.getCause()); } ne.setStackTrace(ex.getStackTrace()); return ne; } if (ex instanceof IOException) { // #66208 IOException ne = new IOException(combineMessages(ex, addendum, after)); if (ex.getCause() != null) { ne.initCause(ex.getCause()); } ne.setStackTrace(ex.getStackTrace()); return ne; } if (ex instanceof Exception) { return new InvocationTargetException(ex, combineMessages(ex, addendum, after)); } return ex; }
/** * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code * BloomFilter<T>}. * * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here. * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate * the original Bloom filter! * * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not * appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method. */ public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<T> funnel) throws IOException { checkNotNull(in, "InputStream"); checkNotNull(funnel, "Funnel"); int strategyOrdinal = -1; int numHashFunctions = -1; int dataLength = -1; try { DataInputStream din = new DataInputStream(in); // currently this assumes there is no negative ordinal; will have to be updated if we // add non-stateless strategies (for which we've reserved negative ordinals; see // Strategy.ordinal()). strategyOrdinal = din.readByte(); numHashFunctions = UnsignedBytes.toInt(din.readByte()); dataLength = din.readInt(); Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal]; long[] data = new long[dataLength]; for (int i = 0; i < data.length; i++) { data[i] = din.readLong(); } return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); } catch (RuntimeException e) { IOException ioException = new IOException( "Unable to deserialize BloomFilter from InputStream." + " strategyOrdinal: " + strategyOrdinal + " numHashFunctions: " + numHashFunctions + " dataLength: " + dataLength); ioException.initCause(e); throw ioException; } }
/** * Provides an implementation of the <code>readProductNodes</code> interface method. Clients * implementing this method can be sure that the input object and eventually the subset * information has already been set. * * <p> * * <p>This method is called as a last step in the <code>readProductNodes(input, subsetInfo)</code> * method. * * @throws java.io.IOException if an I/O error occurs */ @Override protected Product readProductNodesImpl() throws IOException { Product product; try { final File fileFromInput = ReaderUtils.getFileFromInput(getInput()); dataDir = createDirectory(fileFromInput); dataDir.readProductDirectory(); product = dataDir.createProduct(); addCalibrationLUT(product, fileFromInput.getParentFile()); product.getGcpGroup(); product.setFileLocation(fileFromInput); product.setProductReader(this); product.setModified(false); final MetadataElement absRoot = AbstractMetadata.getAbstractedMetadata(product); isAscending = absRoot.getAttributeString(AbstractMetadata.PASS).equals("ASCENDING"); isAntennaPointingRight = absRoot.getAttributeString(AbstractMetadata.antenna_pointing).equals("right"); } catch (Exception e) { Debug.trace(e.toString()); final IOException ioException = new IOException(e.getMessage()); ioException.initCause(e); throw ioException; } return product; }
/** * Checks that the certificate is compatible with the enabled cipher suites. If we don't check * now, the JIoEndpoint can enter a nasty logging loop. See bug 45528. */ private void checkConfig() throws IOException { // Create an unbound server socket ServerSocket socket = sslProxy.createServerSocket(); initServerSocket(socket); try { // Set the timeout to 1ms as all we care about is if it throws an // SSLException on accept. socket.setSoTimeout(1); socket.accept(); // Will never get here - no client can connect to an unbound port } catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString("jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; } catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ } finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } } }
private static Codec readCodec(DataInput input, boolean unsupportedAllowed) throws IOException { final String name = input.readString(); try { return Codec.forName(name); } catch (IllegalArgumentException e) { // give better error messages if we can, first check if this is a legacy codec if (unsupportedCodecs.contains(name)) { // We should only get here on pre-5.3 indices, but we can't test this until 7.0 when 5.x // indices become too old: assert unsupportedAllowed; IOException newExc = new IndexFormatTooOldException(input, "Codec '" + name + "' is too old"); newExc.initCause(e); throw newExc; } // or maybe it's an old default codec that moved if (name.startsWith("Lucene")) { throw new IllegalArgumentException( "Could not load codec '" + name + "'. Did you forget to add lucene-backward-codecs.jar?", e); } throw e; } }
/** * Rename file. If file can't be renamed in standard way the coping data will be used instead. * * @param srcFile source file * @param dstFile destination file * @throws IOException if any exception occurred */ public static void renameFile(File srcFile, File dstFile) throws IOException { // Rename the srcFile file to the new one. Unfortunately, the renameTo() // method does not work reliably under some JVMs. Therefore, if the // rename fails, we manually rename by copying the srcFile file to the new one if (!srcFile.renameTo(dstFile)) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(dstFile); transfer(in, out); } catch (IOException ioe) { IOException newExc = new IOException("Cannot rename " + srcFile + " to " + dstFile); newExc.initCause(ioe); throw newExc; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } // delete the srcFile file. srcFile.delete(); } }
private final byte[] uncompress(final byte[] input) throws IOException { Inflater decompressor = new Inflater(); decompressor.setInput(input); // Create an expandable byte array to hold the decompressed data ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); // Decompress the data byte[] buf = new byte[1024]; while (!decompressor.finished()) { try { int count = decompressor.inflate(buf); bos.write(buf, 0, count); } catch (DataFormatException e) { // this will happen if the field is not compressed IOException newException = new IOException("field data are in wrong format: " + e.toString()); newException.initCause(e); throw newException; } } decompressor.end(); // Get the decompressed data return bos.toByteArray(); }
public Destination getDestination(EndpointInfo ei, Bus bus) throws IOException { String address = ei.getAddress(); BindingInfo bi = ei.getBinding(); String transId = ei.getTransportId(); if (bi instanceof SoapBindingInfo) { transId = ((SoapBindingInfo) bi).getTransportURI(); if (transId == null) { transId = ei.getTransportId(); } } DestinationFactory destinationFactory; try { DestinationFactoryManager mgr = bus.getExtension(DestinationFactoryManager.class); if (StringUtils.isEmpty(address) || address.startsWith("http") || address.startsWith("jms") || address.startsWith("soap.udp") || address.startsWith("/")) { destinationFactory = mgr.getDestinationFactory(mapTransportURI(transId, address)); } else { destinationFactory = mgr.getDestinationFactoryForUri(address); } if (destinationFactory == null) { throw new IOException("Could not find destination factory for transport " + transId); } return destinationFactory.getDestination(ei, bus); } catch (BusException e) { IOException ex = new IOException("Could not find destination factory for transport " + transId); ex.initCause(e); throw ex; } }
private void dumpBinary(DirectedGraph graph, DataOutput os) throws IOException { try { int numLeafNodes = setUniqueLeafNodeIds(graph); int numDecNodes = setUniqueDecisionNodeIds(graph); int numGraphNodes = setUniqueDirectedGraphNodeIds(graph); int maxNum = 1 << 30; if (numLeafNodes > maxNum || numDecNodes > maxNum || numGraphNodes > maxNum) { throw new UnsupportedOperationException( "Cannot write more than " + maxNum + " nodes of one type in this format"); } // write the number of decision nodes os.writeInt(numDecNodes); printDecisionNodes(graph, os, null); // write the number of leaves. os.writeInt(numLeafNodes); printLeafNodes(graph, os, null); // write the number of directed graph nodes os.writeInt(numGraphNodes); printDirectedGraphNodes(graph, os, null); } catch (IOException ioe) { IOException newIOE = new IOException("Error dumping CART to output stream"); newIOE.initCause(ioe); throw newIOE; } }
public void toTextOut(DirectedGraph graph, PrintWriter pw) throws IOException { try { int numLeafNodes = setUniqueLeafNodeIds(graph); int numDecNodes = setUniqueDecisionNodeIds(graph); int numGraphNodes = setUniqueDirectedGraphNodeIds(graph); pw.println( "Num decision nodes= " + numDecNodes + " Num leaf nodes= " + numLeafNodes + " Num directed graph nodes= " + numGraphNodes); printDecisionNodes(graph, null, pw); pw.println("\n----------------\n"); printLeafNodes(graph, null, pw); pw.println("\n----------------\n"); printDirectedGraphNodes(graph, null, pw); pw.flush(); pw.close(); } catch (IOException ioe) { IOException newIOE = new IOException("Error dumping graph to standard output"); newIOE.initCause(ioe); throw newIOE; } }
@Override public Object resolveObject(Object obj) throws IOException { // Until we've identified a remote object, we can't assume the orb is // available in the container. If the orb is not present, this will be null. ProtocolManager protocolMgr = getProtocolManager(); try { if ((protocolMgr != null) && protocolMgr.isStub(obj)) { protocolMgr.connectObject((Remote) obj); return obj; } else if (obj instanceof SerializableObjectFactory) { return ((SerializableObjectFactory) obj).createObject(); } else { return obj; } } catch (IOException ioEx) { _ejbLogger.log(Level.SEVERE, "ejb.resolve_object_exception", ioEx); throw ioEx; } catch (Exception ex) { _ejbLogger.log(Level.SEVERE, "ejb.resolve_object_exception", ex); IOException ioe = new IOException(); ioe.initCause(ex); throw ioe; } }
@SuppressWarnings("unchecked") public static <T> T unmarshal(final InputStream in) throws IOException { final Unmarshaller unmarshaller = SardineUtil.createUnmarshaller(); try { final XMLReader reader = XMLReaderFactory.createXMLReader(); try { reader.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE); } catch (final SAXException e) {; // Not all parsers will support this attribute } try { reader.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE); } catch (final SAXException e) {; // Not all parsers will support this attribute } try { reader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); } catch (final SAXException e) {; // Not all parsers will support this attribute } try { reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); } catch (final SAXException e) {; // Not all parsers will support this attribute } return (T) unmarshaller.unmarshal(new SAXSource(reader, new InputSource(in))); } catch (final SAXException e) { throw new RuntimeException(e.getMessage(), e); } catch (final JAXBException e) { // Server does not return any valid WebDAV XML that matches our JAXB context final IOException failure = new IOException("Not a valid DAV response"); // Backward compatibility failure.initCause(e); throw failure; } }
/* * (non-Javadoc) * * @see org.apache.ivy.repository.Repository#list(java.lang.String) */ public List list(String parent) throws IOException { Message.debug("SShRepository:list called: " + parent); ArrayList result = new ArrayList(); Session session = null; ChannelExec channel = null; session = getSession(parent); channel = getExecChannel(session); URI parentUri = null; try { parentUri = new URI(parent); } catch (URISyntaxException e) { IOException ioe = new IOException("The uri '" + parent + "' is not valid!"); ioe.initCause(e); throw ioe; } String fullCmd = replaceArgument(listCommand, parentUri.getPath()); channel.setCommand(fullCmd); StringBuffer stdOut = new StringBuffer(); StringBuffer stdErr = new StringBuffer(); readSessionOutput(channel, stdOut, stdErr); if (channel.getExitStatus() != 0) { Message.error("Ssh ListCommand exited with status != 0"); Message.error(stdErr.toString()); return null; } else { BufferedReader br = new BufferedReader(new StringReader(stdOut.toString())); String line = null; while ((line = br.readLine()) != null) { result.add(line); } } return result; }
/** * Process in the request in some fashion * * @param session the HttpSession. */ public synchronized void processRequest(HttpSession session) throws IOException, IllegalStateException { try { HttpMessage request = session.getRequestMessage(); HttpHeaders header = request.getHeaders(); logR.debug("Read \n" + header.toString()); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (header.getContentLength() > 0) { StreamUtil.copyStream(request.getInputStream(), out, header.getContentLength()); } logR.debug("Read Data portion\n" + out); HttpResponse httpResponse = session.getResponseLine(); httpResponse.setResponseCode(HttpURLConnection.HTTP_OK); httpResponse.setResponseMessage("OK"); HttpMessage msg = session.getResponseMessage(); msg.getOutputStream().write(responseBytes); msg.getOutputStream().flush(); } catch (HttpException e) { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } return; }
/* * (non-Javadoc) * * @see org.apache.ivy.repository.Repository#get(java.lang.String, java.io.File) */ public void get(String source, File destination) throws IOException { Message.debug("SShRepository:get called: " + source + " to " + destination.getCanonicalPath()); if (destination.getParentFile() != null) { destination.getParentFile().mkdirs(); } Session session = getSession(source); URI sourceUri = null; try { sourceUri = new URI(source); } catch (URISyntaxException e) { IOException ioe = new IOException("The uri '" + source + "' is not valid!"); ioe.initCause(e); throw ioe; } try { Scp myCopy = new Scp(session); myCopy.get(sourceUri.getPath(), destination.getCanonicalPath()); } catch (IOException e) { if (session != null) { releaseSession(session, source); } throw e; } catch (RemoteScpException e) { throw new IOException(e.getMessage()); } }
/** * Save the base state of the instance. This method performs step finalization if it has not been * done before. * * @param out stream where to save the state * @exception IOException in case of write error */ protected void writeBaseExternal(final ObjectOutput out) throws IOException { if (currentState == null) { out.writeInt(-1); } else { out.writeInt(currentState.length); } out.writeDouble(globalPreviousTime); out.writeDouble(globalCurrentTime); out.writeDouble(softPreviousTime); out.writeDouble(softCurrentTime); out.writeDouble(h); out.writeBoolean(forward); if (currentState != null) { for (int i = 0; i < currentState.length; ++i) { out.writeDouble(currentState[i]); } } out.writeDouble(interpolatedTime); // we do not store the interpolated state, // it will be recomputed as needed after reading // finalize the step (and don't bother saving the now true flag) try { finalizeStep(); } catch (DerivativeException e) { IOException ioe = new IOException(e.getLocalizedMessage()); ioe.initCause(e); throw ioe; } }
/** Extract a resource from jar, mark it for deletion upon exit, and return its location. */ private static File extractFromJar( String resource, String fileName, String suffix, File directory) throws IOException { URL res = Main.class.getResource(resource); if (res == null) throw new IOException("Unable to find the resource: " + resource); // put this jar in a file system so that we can load jars from there File tmp; try { tmp = File.createTempFile(fileName, suffix, directory); } catch (IOException e) { String tmpdir = (directory == null) ? System.getProperty("java.io.tmpdir") : directory.getAbsolutePath(); IOException x = new IOException("Jenkins has failed to create a temporary file in " + tmpdir); x.initCause(e); throw x; } InputStream is = res.openStream(); try { OutputStream os = new FileOutputStream(tmp); try { copyStream(is, os); } finally { os.close(); } } finally { is.close(); } tmp.deleteOnExit(); return tmp; }
public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if (buffer == null) return null; Object retval = null; try { // to read the object as an Externalizable ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer, offset, length); ObjectInputStream in = new ObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval = in.readObject(); in.close(); } catch (StreamCorruptedException sce) { // try { // is it Streamable? // ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, // length); // DataInputStream in=new DataInputStream(in_stream); // retval=readGenericStreamable(in); // in.close(); // } // catch(Exception ee) { IOException tmp = new IOException("unmarshalling failed"); tmp.initCause(sce); throw tmp; // } } if (retval == null) return null; return retval; }
/** * Copy sourceURL to destinationFile without doing any byte conversion. * * @param sourceURL The source URL * @param destinationFile The destination File. * @return true if the file was copied, false if the file was not copied because the sourceURL and * the destinationFile refer to the same file. * @exception IOException If the source file does not exist. */ public static boolean binaryCopyURLToFile(URL sourceURL, File destinationFile) throws IOException { URL destinationURL = destinationFile.getCanonicalFile().toURI().toURL(); if (sourceURL.sameFile(destinationURL)) { return false; } // If sourceURL is of the form file:./foo, then we need to try again. File sourceFile = new File(sourceURL.getFile()); // If the sourceURL is not a jar URL, then check to see if we // have the same file. // FIXME: should we check for !/ and !\ everywhere? if ((sourceFile.getPath().indexOf("!/") == -1) && (sourceFile.getPath().indexOf("!\\") == -1)) { try { if (sourceFile.getCanonicalFile().toURI().toURL().sameFile(destinationURL)) { return false; } } catch (IOException ex) { // JNLP Jar urls sometimes throw an exception here. // IOException constructor does not take a cause IOException ioException = new IOException("Cannot find canonical file name of '" + sourceFile + "'"); ioException.initCause(ex); throw ioException; } } _binaryCopyStream(sourceURL.openStream(), destinationFile); return true; }
/** Parses the XML contained in the given InputStream using the specified XML handler. */ public static void parseXML(InputStream xml, DefaultHandler handler) throws IOException { try { // Java XML factories are not declared to be thread safe SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(xml, handler); } catch (ParserConfigurationException exc) { IOException e = new IOException(); e.initCause(exc); throw e; } catch (SAXException exc) { IOException e = new IOException(); e.initCause(exc); throw e; } }
@SuppressWarnings({"unchecked"}) public <T> T deserialize(InputStream stream, Class<T> clazz) throws IOException { if (isValid(clazz) == false) throw new IllegalArgumentException("Not a JSONAware class: " + clazz); try { JSONTokener tokener = createTokener(stream); JSONArray value = new JSONArray(tokener); T instance = clazz.newInstance(); Collection<JSONAware> collection = (Collection<JSONAware>) instance; for (int i = 0; i < value.length(); i++) { JSONAware ja = instanceProvider.createInstance(i); ja.readJSONObject(value.getJSONObject(i)); collection.add(ja); } return instance; } catch (IOException e) { throw e; } catch (Exception e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } finally { stream.close(); } }