List of usage examples for java.io IOException initCause
public synchronized Throwable initCause(Throwable cause)
From source file:morphy.utils.FileUtils.java
/** * This code was obtained from://from w w w .j a v a 2 s . co m * http://www.dreamincode.net/code/snippet1443.htm * * This function will copy files or directories from one location to * another. note that the source and the destination must be mutually * exclusive. This function can not be used to copy a directory to a sub * directory of itself. The function will also have problems if the * destination files already exist. * * @param src * -- A File object that represents the source for the copy * @param dest * -- A File object that represents the destination for the copy. * @throws IOException * if unable to copy. */ public static void copyFiles(File src, File dest) throws IOException { if (src.getName().startsWith(".")) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring " + src.getAbsolutePath() + " because name started with ."); } return; } // Check to ensure that the source is valid... if (!src.exists()) { throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + "."); } else if (!src.canRead()) { // check to ensure we have rights to the // source... throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + "."); } // is this a directory copy? if (src.isDirectory()) { if (!dest.exists()) { // does the destination already exist? // if not we need to make it exist if possible (note this is // mkdirs not mkdir) if (!dest.mkdirs()) { throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + "."); } if (LOG.isDebugEnabled()) { LOG.debug("Created directory " + dest.getAbsolutePath()); } } // get a listing of files... String list[] = src.list(); // copy all the files in the list. for (String element : list) { File dest1 = new File(dest, element); File src1 = new File(src, element); copyFiles(src1, dest1); } } else { // This was not a directory, so lets just copy the file FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; // Buffer 4K at a time (you can // change this). int bytesRead; try { // open the files for input and output fin = new FileInputStream(src); fout = new FileOutputStream(dest); // while bytesRead indicates a successful read, lets write... while ((bytesRead = fin.read(buffer)) >= 0) { fout.write(buffer, 0, bytesRead); } if (LOG.isDebugEnabled()) { LOG.debug("Copied " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); } } catch (IOException e) { // Error copying file... IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath() + "to" + dest.getAbsolutePath() + "."); wrapper.initCause(e); wrapper.setStackTrace(e.getStackTrace()); throw wrapper; } finally { // Ensure that the files are closed (if they were open). if (fin != null) { try { fin.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } } }
From source file:org.pixmob.fm2.util.HttpUtils.java
/** * Setup SSL connection./*from w w w . j a v a 2 s . com*/ */ private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException { if (DEBUG) { Log.d(TAG, "Load custom SSL certificates"); } final SSLContext sslContext; try { // Load SSL certificates: // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html // Earlier Android versions do not have updated root CA // certificates, resulting in connection errors. final KeyStore keyStore = loadCertificates(context); final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore); final TrustManager[] tms = new TrustManager[] { customTrustManager }; // Init SSL connection with custom certificates. // The same SecureRandom instance is used for every connection to // speed up initialization. sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tms, SECURE_RANDOM); } catch (GeneralSecurityException e) { final IOException ioe = new IOException("Failed to initialize SSL engine"); ioe.initCause(e); throw ioe; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Fix slow read: // http://code.google.com/p/android/issues/detail?id=13117 // Prior to ICS, the host name is still resolved even if we already // know its IP address, for each connection. final SSLSocketFactory delegate = sslContext.getSocketFactory(); final SSLSocketFactory socketFactory = new SSLSocketFactory() { @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { InetAddress addr = InetAddress.getByName(host); injectHostname(addr, host); return delegate.createSocket(addr, port); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return delegate.createSocket(host, port, localHost, localPort); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } private void injectHostname(InetAddress address, String host) { try { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(address, host); } catch (Exception ignored) { } } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { injectHostname(s.getInetAddress(), host); return delegate.createSocket(s, host, port, autoClose); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } }; conn.setSSLSocketFactory(socketFactory); } else { conn.setSSLSocketFactory(sslContext.getSocketFactory()); } conn.setHostnameVerifier(new BrowserCompatHostnameVerifier()); }
From source file:tectonicus.util.FileUtils.java
/** * This function will copy files or directories from one location to * another. note that the source and the destination must be mutually * exclusive. This function can not be used to copy a directory to a sub * directory of itself. The function will also have problems if the * destination files already exist./*ww w . j a v a2s. com*/ * * @param src * -- A File object that represents the source for the copy * @param dest * -- A File object that represnts the destination for the copy. * @throws IOException * if unable to copy. */ public static void copyFiles(File src, File dest, Set<String> excludeExtensions) throws IOException { // Check to ensure that the source is valid... if (!src.exists()) { throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + "."); } else if (!src.canRead()) { // check to ensure we have rights to the source... throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + "."); } // is this a directory copy? if (src.isDirectory()) { if (!dest.exists()) { // does the destination already exist? // if not we need to make it exist if possible (note this is // mkdirs not mkdir) if (!dest.mkdirs()) { throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + "."); } } // get a listing of files... String list[] = src.list(); // copy all the files in the list. for (int i = 0; i < list.length; i++) { File dest1 = new File(dest, list[i]); File src1 = new File(src, list[i]); copyFiles(src1, dest1, excludeExtensions); } } else { String extension = getExtension(src.getName()); if (!excludeExtensions.contains(extension)) { // This was not a directory, so lets just copy the file FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; // Buffer 4K at a time int bytesRead; try { // open the files for input and output fin = new FileInputStream(src); fout = new FileOutputStream(dest); // while bytesRead indicates a successful read, lets write... while ((bytesRead = fin.read(buffer)) >= 0) { fout.write(buffer, 0, bytesRead); } } catch (IOException e) { // Error copying file... IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath() + "to" + dest.getAbsolutePath() + "."); wrapper.initCause(e); wrapper.setStackTrace(e.getStackTrace()); throw wrapper; } finally { // Ensure that the files are closed (if they were open). if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } } else { System.out.println("Skipping " + src.getAbsolutePath()); } } }
From source file:com.adito.vfs.webdav.DAVServlet.java
protected static AuthenticationScheme configureAuthenticationScheme(HttpServletRequest request, HttpServletResponse response) throws IOException { AuthenticationScheme seq = AuthenticationModuleManager.getInstance() .getSchemeForAuthenticationModuleInUse(WebDAVAuthenticationModule.MODULE_NAME); if (seq == null || !seq.getEnabled()) { log.error(//from w ww . j a v a2 s. c om "User cannot authenticate via WebDAV using only HTTP BASIC authentication as the current policy does not allow this."); response.sendError(DAVStatus.SC_FORBIDDEN, "You cannot authenticate via WebDAV using only HTTP BASIC authentication as the current policy does not allow this."); return seq; } seq.addModule(WebDAVAuthenticationModule.MODULE_NAME); try { seq.init(request.getSession()); } catch (Exception e) { IOException ioe = new IOException("Failed to authentication scheme."); ioe.initCause(e); throw ioe; } seq.nextAuthenticationModule(); request.getSession().setAttribute(Constants.AUTH_SENT, Boolean.TRUE); request.getSession().setAttribute(Constants.AUTH_SESSION, seq); return seq; }
From source file:com.examples.with.different.packagename.concolic.MathRuntimeException.java
/** * Constructs a new <code>IOException</code> with specified nested * <code>Throwable</code> root cause. * <p>This factory method allows chaining of other exceptions within an * <code>IOException</code> even for Java 5. The constructor for * <code>IOException</code> with a cause parameter was introduced only * with Java 6.</p>/* w w w . j ava 2s . c o m*/ * @param rootCause the exception or error that caused this exception * to be thrown. * @return built exception */ public static IOException createIOException(final Throwable rootCause) { IOException ioe = new IOException(rootCause.getLocalizedMessage()); ioe.initCause(rootCause); return ioe; }
From source file:org.infosec.ismp.collectd.snmp.castor.CastorUtils.java
/** * Unmarshal a Castor XML configuration file. Uses Java 5 generics for * return type. //w w w. j a v a 2s.com * * @param <T> the class representing the marshalled XML configuration * file. This will be the return time form the method. * @param clazz the class representing the marshalled XML configuration * file * @param resource the marshalled XML configuration file to unmarshal * @return Unmarshalled object representing XML file * @throws MarshalException if the underlying Castor * Unmarshaller.unmarshal() call throws a MarshalException * @throws ValidationException if the underlying Castor * Unmarshaller.unmarshal() call throws a ValidationException * @throws IOException if the resource could not be opened */ public static <T> T unmarshal(Class<T> clazz, Resource resource) throws MarshalException, ValidationException, IOException { InputStream in; try { in = resource.getInputStream(); } catch (IOException e) { IOException newE = new IOException( "Failed to open XML configuration file for resource '" + resource + "': " + e); newE.initCause(e); throw newE; } try { InputSource source = new InputSource(in); try { source.setSystemId(resource.getURL().toString()); } catch (Throwable t) { // ignore } return unmarshal(clazz, source); } finally { IOUtils.closeQuietly(in); } }
From source file:SocketFetcher.java
/** * Start TLS on an existing socket./*from w ww.ja v a2s. com*/ * Supports the "STARTTLS" command in many protocols. */ public static Socket startTLS(Socket socket, Properties props, String prefix) throws IOException { InetAddress a = socket.getInetAddress(); String host = a.getHostName(); int port = socket.getPort(); //System.out.println("SocketFetcher: startTLS host " + host + ", port " + port); try { SSLSocketFactory ssf; String sfClass = props.getProperty(prefix + ".socketFactory.class", null); SocketFactory sf = getSocketFactory(sfClass); if (sf != null && sf instanceof SSLSocketFactory) ssf = (SSLSocketFactory) sf; else ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); socket = ssf.createSocket(socket, host, port, true); configureSSLSocket(socket, props, prefix); } catch (Exception ex) { if (ex instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException) ex).getTargetException(); if (t instanceof Exception) ex = (Exception) t; } if (ex instanceof IOException) throw (IOException) ex; // wrap anything else before sending it on IOException ioex = new IOException( "Exception in startTLS: host " + host + ", port " + port + "; Exception: " + ex); ioex.initCause(ex); throw ioex; } return socket; }
From source file:org.cloudata.core.common.ipc.CRPC.java
/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. */ public static CVersionedProtocol getProxy(Class<?> protocol, long clientVersion, InetSocketAddress addr, CloudataConf conf, SocketFactory factory) throws IOException { CVersionedProtocol proxy = (CVersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(addr, conf, factory)); Long serverVersion = null;/*from w w w . j av a 2s . co m*/ try { synchronized (versionCheckMap) { if ((serverVersion = versionCheckMap.get(addr)) == null) { serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion); versionCheckMap.put(addr, serverVersion); } } } catch (IOException e) { LOG.warn("Error proxy.getProtocolVersion:" + addr + "," + e.getMessage()); throw e; } catch (Exception e) { IOException err = new IOException(e.getMessage()); err.initCause(e); throw err; } if (serverVersion == clientVersion) { return proxy; } else { throw new VersionMismatch(protocol.getName(), clientVersion, serverVersion); } }
From source file:org.geoserver.data.util.IOUtils.java
/** * @param len /*ww w .j a v a 2 s . c om*/ * @param stream * @param fos * @return * @throws IOException */ public static void saveCompressedStream(final byte[] buffer, final OutputStream out, final int len) throws IOException { try { out.write(buffer, 0, len); } catch (Exception e) { out.flush(); out.close(); IOException ioe = new IOException("Not valid archive file type."); ioe.initCause(e); throw ioe; } }
From source file:org.apache.hadoop.mapred.pipes.Submitter.java
private static void setupPipesJob(JobConf conf) throws IOException { // default map output types to Text if (!getIsJavaMapper(conf)) { conf.setMapRunnerClass(PipesMapRunner.class); // Save the user's partitioner and hook in our's. setJavaPartitioner(conf, conf.getPartitionerClass()); conf.setPartitionerClass(PipesPartitioner.class); }//from w ww . jav a2 s . c o m if (!getIsJavaReducer(conf)) { conf.setReducerClass(PipesReducer.class); if (!getIsJavaRecordWriter(conf)) { conf.setOutputFormat(NullOutputFormat.class); } } String textClassname = Text.class.getName(); setIfUnset(conf, "mapred.mapoutput.key.class", textClassname); setIfUnset(conf, "mapred.mapoutput.value.class", textClassname); setIfUnset(conf, "mapred.output.key.class", textClassname); setIfUnset(conf, "mapred.output.value.class", textClassname); // Use PipesNonJavaInputFormat if necessary to handle progress reporting // from C++ RecordReaders ... if (!getIsJavaRecordReader(conf) && !getIsJavaMapper(conf)) { conf.setClass("mapred.pipes.user.inputformat", conf.getInputFormat().getClass(), InputFormat.class); conf.setInputFormat(PipesNonJavaInputFormat.class); } String exec = getExecutable(conf); if (exec == null) { throw new IllegalArgumentException("No application program defined."); } // add default debug script only when executable is expressed as // <path>#<executable> if (exec.contains("#")) { DistributedCache.createSymlink(conf); // set default gdb commands for map and reduce task String defScript = "$HADOOP_HOME/src/c++/pipes/debug/pipes-default-script"; setIfUnset(conf, "mapred.map.task.debug.script", defScript); setIfUnset(conf, "mapred.reduce.task.debug.script", defScript); } URI[] fileCache = DistributedCache.getCacheFiles(conf); if (fileCache == null) { fileCache = new URI[1]; } else { URI[] tmp = new URI[fileCache.length + 1]; System.arraycopy(fileCache, 0, tmp, 1, fileCache.length); fileCache = tmp; } try { fileCache[0] = new URI(exec); } catch (URISyntaxException e) { IOException ie = new IOException("Problem parsing execable URI " + exec); ie.initCause(e); throw ie; } DistributedCache.setCacheFiles(fileCache, conf); }