List of usage examples for java.io IOException getCause
public synchronized Throwable getCause()
From source file:org.alfresco.utilities.LdtpUtils.java
/** * Execute a command/* ww w . j ava2 s . co m*/ * * @example: execute(new String[] { "killall", getApplicationName() }) for MAC * @param command */ public static void execute(String[] command) { try { Runtime.getRuntime().exec(command); } catch (IOException e) { logger.error("Could not execute command", e.getCause()); } }
From source file:org.alfresco.utilities.LdtpUtils.java
/** * This will a specific process based on command array list passed * It's best to use this alternative rather than Runtime.getRuntime().exec * /*from w ww .j ava 2 s. c o m*/ * @author Paul Brodner * @param command * @return * @throws IOException * @throws InterruptedException */ public static Process runProcess(String... command) { ProcessBuilder pb = new ProcessBuilder(command); Process process; try { process = pb.start(); LdtpUtils.logDebug("Running Process:" + command.toString()); return process; } catch (IOException e) { logger.error("Could not run process", e.getCause()); } return null; }
From source file:com.alibaba.wasp.ipc.WaspRPC.java
/** * @param protocol/* ww w. j ava 2s . com*/ * protocol interface * @param clientVersion * which client version we expect * @param addr * address of remote service * @param conf * configuration * @param maxAttempts * max attempts * @param rpcTimeout * timeout for each RPC * @param timeout * timeout in milliseconds * @return proxy * @throws java.io.IOException * e */ @SuppressWarnings("unchecked") public static VersionedProtocol waitForProxy(Class protocol, long clientVersion, InetSocketAddress addr, Configuration conf, int maxAttempts, int rpcTimeout, long timeout) throws IOException { long startTime = System.currentTimeMillis(); IOException ioe; int reconnectAttempts = 0; while (true) { try { return getProxy(protocol, clientVersion, addr, conf, rpcTimeout); } catch (SocketTimeoutException te) { // namenode is busy LOG.info("Problem connecting to server: " + addr); ioe = te; } catch (IOException ioex) { // We only handle the ConnectException. ConnectException ce = null; if (ioex instanceof ConnectException) { ce = (ConnectException) ioex; ioe = ce; } else if (ioex.getCause() != null && ioex.getCause() instanceof ConnectException) { ce = (ConnectException) ioex.getCause(); ioe = ce; } else if (ioex.getMessage().toLowerCase().contains("connection refused")) { ce = new ConnectException(ioex.getMessage()); ioe = ce; } else { // This is the exception we can't handle. ioe = ioex; } if (ce != null) { handleConnectionException(++reconnectAttempts, maxAttempts, protocol, addr, ce); } } // check if timed out if (System.currentTimeMillis() - timeout >= startTime) { throw ioe; } // wait for retry try { Thread.sleep(1000); } catch (InterruptedException ie) { // IGNORE } } }
From source file:org.dspace.license.CreativeCommons.java
public static String fetchLicenseRdf(String ccResult) { StringWriter result = new StringWriter(); String licenseRdfString = new String(""); try {//from w w w . ja v a2 s . com InputStream inputstream = new ByteArrayInputStream(ccResult.getBytes("UTF-8")); templates.newTransformer().transform(new StreamSource(inputstream), new StreamResult(result)); } catch (TransformerException te) { throw new RuntimeException("Transformer exception " + te.getMessage(), te); } catch (IOException ioe) { throw new RuntimeException("IOexception " + ioe.getCause().toString(), ioe); } finally { return result.getBuffer().toString(); } }
From source file:org.apache.hadoop.hbase.ipc.HBaseClientRPC.java
/** * @param protocol protocol interface * @param addr address of remote service * @param conf configuration//from w w w.java2 s .c o m * @param maxAttempts max attempts * @param rpcTimeout timeout for each RPC * @param timeout timeout in milliseconds * @return proxy * @throws java.io.IOException e */ public static IpcProtocol waitForProxy(Class<? extends IpcProtocol> protocol, InetSocketAddress addr, Configuration conf, int maxAttempts, int rpcTimeout, long timeout) throws IOException { // HBase does limited number of reconnects which is different from hadoop. long startTime = System.currentTimeMillis(); IOException ioe; int reconnectAttempts = 0; while (true) { try { return getProxy(protocol, addr, conf, rpcTimeout); } catch (SocketTimeoutException te) { LOG.info("Problem connecting to server: " + addr); ioe = te; } catch (IOException ioex) { // We only handle the ConnectException. ConnectException ce = null; if (ioex instanceof ConnectException) { ce = (ConnectException) ioex; ioe = ce; } else if (ioex.getCause() != null && ioex.getCause() instanceof ConnectException) { ce = (ConnectException) ioex.getCause(); ioe = ce; } else if (ioex.getMessage().toLowerCase().contains("connection refused")) { ce = new ConnectException(ioex.getMessage()); ioe = ce; } else { // This is the exception we can't handle. ioe = ioex; } if (ce != null) { handleConnectionException(++reconnectAttempts, maxAttempts, protocol, addr, ce); } } // check if timed out if (System.currentTimeMillis() - timeout >= startTime) { throw ioe; } // wait for retry try { Thread.sleep(1000); } catch (InterruptedException ie) { // IGNORE } } }
From source file:org.wildfly.test.integration.elytron.sasl.mgmt.ExternalMgmtSaslTestCase.java
protected static void assertCertAuthenticationFails(String message) { final long startTime = System.currentTimeMillis(); try {/*from w ww.ja va 2s . c o m*/ executeWhoAmI(); fail(message); } catch (IOException e) { assertTrue("Connection reached its timeout (hang).", startTime + CONNECTION_TIMEOUT_IN_MS > System.currentTimeMillis()); Throwable cause = e.getCause(); assertThat("ConnectionException was expected as a cause when certificate authentication fails", cause, is(instanceOf(ConnectException.class))); assertThat("SSLException was expected as the second cause when certificate authentication fails", cause.getCause(), anyOf(is(instanceOf(SSLException.class)), is(instanceOf(IOException.class)))); // JDK-8172163: IOException: Broken pipe needs to be accepted too } }
From source file:org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor.java
/** * Factory method for DNs, where the nonce, keyId, and encryption key are not * yet known. The nonce and keyId will be sent by the client, and the DN * will then use those pieces of info and the secret key shared with the NN * to determine the encryptionKey used for the SASL handshake/encryption. * /*from w ww. j a v a 2 s . co m*/ * Establishes a secure connection assuming that the party on the other end * has the same shared secret. This does a SASL connection handshake, but not * a general-purpose one. It's specific to the MD5-DIGEST SASL mechanism with * auth-conf enabled. In particular, it doesn't support an arbitrary number of * challenge/response rounds, and we know that the client will never have an * initial response, so we don't check for one. * * @param underlyingOut output stream to write to the other party * @param underlyingIn input stream to read from the other party * @param blockPoolTokenSecretManager secret manager capable of constructing * encryption key based on keyId, blockPoolId, and nonce * @return a pair of streams which wrap the given streams and encrypt/decrypt * all data read/written * @throws IOException in the event of error */ public static IOStreamPair getEncryptedStreams(OutputStream underlyingOut, InputStream underlyingIn, BlockPoolTokenSecretManager blockPoolTokenSecretManager, String encryptionAlgorithm) throws IOException { DataInputStream in = new DataInputStream(underlyingIn); DataOutputStream out = new DataOutputStream(underlyingOut); Map<String, String> saslProps = Maps.newHashMap(SASL_PROPS); saslProps.put("com.sun.security.sasl.digest.cipher", encryptionAlgorithm); if (LOG.isDebugEnabled()) { LOG.debug("Server using encryption algorithm " + encryptionAlgorithm); } SaslParticipant sasl = new SaslParticipant(Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, saslProps, new SaslServerCallbackHandler(blockPoolTokenSecretManager))); int magicNumber = in.readInt(); if (magicNumber != ENCRYPTED_TRANSFER_MAGIC_NUMBER) { throw new InvalidMagicNumberException(magicNumber); } try { // step 1 performSaslStep1(out, in, sasl); // step 2 (server-side only) byte[] remoteResponse = readSaslMessage(in); byte[] localResponse = sasl.evaluateChallengeOrResponse(remoteResponse); sendSaslMessage(out, localResponse); // SASL handshake is complete checkSaslComplete(sasl); return sasl.createEncryptedStreamPair(out, in); } catch (IOException ioe) { if (ioe instanceof SaslException && ioe.getCause() != null && ioe.getCause() instanceof InvalidEncryptionKeyException) { // This could just be because the client is long-lived and hasn't gotten // a new encryption key from the NN in a while. Upon receiving this // error, the client will get a new encryption key from the NN and retry // connecting to this DN. sendInvalidKeySaslErrorMessage(out, ioe.getCause().getMessage()); } else { sendGenericSaslErrorMessage(out, ioe.getMessage()); } throw ioe; } }
From source file:dk.netarkivet.common.utils.JMXUtils.java
/** Get a JMXConnector to a given host and port, using login and password. * * @param hostName The host to attempt to connect to. * @param jmxPort The port on the host to connect to * (a non-negative number).//from ww w.j a v a2 s . c o m * @param login The login name to authenticate as (typically "controlRole" * or "monitorRole". * @param password The password for JMX access. * @return A JMX connector to the given host and port, using default RMI. * @throws IOFailure if connecting to JMX fails. */ public static JMXConnector getJMXConnector(String hostName, int jmxPort, final String login, final String password) { ArgumentNotValid.checkNotNullOrEmpty(hostName, "String hostName"); ArgumentNotValid.checkNotNegative(jmxPort, "int jmxPort"); ArgumentNotValid.checkNotNullOrEmpty(login, "String login"); ArgumentNotValid.checkNotNullOrEmpty(password, "String password"); JMXServiceURL rmiurl = getUrl(hostName, jmxPort, -1); Map<String, ?> environment = packageCredentials(login, password); Throwable lastException; int retries = 0; final int maxJmxRetries = getMaxTries(); do { try { return JMXConnectorFactory.connect(rmiurl, environment); } catch (IOException e) { lastException = e; if (retries < maxJmxRetries && e.getCause() != null && (e.getCause() instanceof ServiceUnavailableException || e.getCause() instanceof SocketTimeoutException)) { // Sleep a bit before trying again TimeUtils.exponentialBackoffSleep(retries); /* called exponentialBackoffSleep(retries) which used Calendar.MILLISECOND as time unit, which means we only wait an exponential number of milliseconds. */ continue; } break; } } while (retries++ < maxJmxRetries); throw new IOFailure( "Failed to connect to URL " + rmiurl + " after " + retries + " of " + maxJmxRetries + " attempts.\nException type: " + lastException.getCause().getClass().getName(), lastException); }
From source file:com.liveneo.plat.utils.StringUtil.java
/** * Decodes a string which was encoded using Base64 encoding. * /* w ww. j a v a 2s. co m*/ * @param str * The string to decode * @return Decoded string */ public static String decodeString(String str) { BASE64Decoder dec = new BASE64Decoder(); try { return new String(dec.decodeBuffer(str)); } catch (IOException io) { throw new RuntimeException(io.getMessage(), io.getCause()); } }
From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java
/** * Validates the status of an <code>HttpURLConnection</code> against an expected HTTP * status code. If the current status code is not the expected one it throws an exception * with a detail message using Server side error messages if available. * * @param conn the <code>HttpURLConnection</code>. * @param expected the expected HTTP status code. * @throws IOException thrown if the current status code does not match the expected one. *///from www . j a v a2s.c o m private static void validateResponse(HttpURLConnection conn, int expected) throws IOException { int status = conn.getResponseCode(); if (status != expected) { try { JSONObject json = (JSONObject) jsonParse(conn); throw new IOException(MessageFormat.format("HTTP status [{0}], {1} - {2}", json.get("status"), json.get("reason"), json.get("message"))); } catch (IOException ex) { if (ex.getCause() instanceof IOException) { throw (IOException) ex.getCause(); } throw new IOException( MessageFormat.format("HTTP status [{0}], {1}", status, conn.getResponseMessage())); } } }