Java Code Examples for java.io.IOException#getCause()

The following examples show how to use java.io.IOException#getCause() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SearchService.java    From jakduk-api with MIT License 6 votes vote down vote up
public void indexDocumentBoardComment(EsComment esComment) {

		String id = esComment.getId();
		String parentBoardId = esComment.getArticle().getId();

		try {
			IndexResponse response = client.prepareIndex()
					.setIndex(elasticsearchProperties.getIndexBoard())
					.setType(Constants.ES_TYPE_COMMENT)
					.setId(id)
					.setParent(parentBoardId)
					.setSource(ObjectMapperUtils.writeValueAsString(esComment), XContentType.JSON)
					.get();

		} catch (IOException e) {
			throw new ServiceException(ServiceError.ELASTICSEARCH_INDEX_FAILED, e.getCause());
		}
	}
 
Example 2
Source File: StackTraceTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URL url;
    try (ServerSocket ss = new ServerSocket(0)) {  // refusing socket
        url = new URL("http://localhost:" + ss.getLocalPort() + "/");
    }
    URLConnection uc = url.openConnection();

    // Trigger implicit connection by trying to retrieve bogus
    // response header, and force remembered exception
    uc.getHeaderFieldKey(20);

    try {
        uc.getInputStream();  // expect to throw
        throw new RuntimeException("Expected getInputStream to throw");
    } catch (IOException ioe) {
        if (!(ioe instanceof ConnectException))
            throw new RuntimeException("Expect ConnectException, got " + ioe);
        if (ioe.getMessage() == null)
            throw new RuntimeException("Exception message is null");
        if (ioe.getCause() == null)
            throw new RuntimeException("Excepting a chained exception, but got: ",
                                       ioe);
    }
}
 
Example 3
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortRead400() throws Exception {
    System.out.println("Running cbc_shortRead400");

    // Encrypt 400 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 400);
    // Create stream with encrypted data
    CipherInputStream in = getStream("CBC", ct);

    try {
        in.read();
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 4
Source File: FunctionalInterfaceConversionTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();

    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), dc, null, null,
            Arrays.asList(samSourceFile, pkgClassSourceFile, clientSourceFile));
    try {
        ct.analyze();
    } catch (IOException ex) {
        throw new AssertionError("Test failing with cause", ex.getCause());
    }
    if (dc.errorFound == checkSamConversion()) {
        throw new AssertionError(samSourceFile + "\n\n" +
            pkgClassSourceFile + "\n\n" + clientSourceFile);
    }
}
 
Example 5
Source File: StackTraceTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URL url;
    try (ServerSocket ss = new ServerSocket(0)) {  // refusing socket
        url = new URL("http://localhost:" + ss.getLocalPort() + "/");
    }
    URLConnection uc = url.openConnection();

    // Trigger implicit connection by trying to retrieve bogus
    // response header, and force remembered exception
    uc.getHeaderFieldKey(20);

    try {
        uc.getInputStream();  // expect to throw
        throw new RuntimeException("Expected getInputStream to throw");
    } catch (IOException ioe) {
        if (!(ioe instanceof ConnectException))
            throw new RuntimeException("Expect ConnectException, got " + ioe);
        if (ioe.getMessage() == null)
            throw new RuntimeException("Exception message is null");
        if (ioe.getCause() == null)
            throw new RuntimeException("Excepting a chained exception, but got: ",
                                       ioe);
    }
}
 
Example 6
Source File: CipherInputStreamExceptions.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_suppressUnreadCorrupt() throws Exception {
    Cipher c;
    byte[] read = new byte[200];

    System.out.println("Running supressUnreadCorrupt test");

    // Encrypt 100 bytes with AES/GCM/PKCS5Padding
    byte[] ct = encryptedText("GCM", 100);
    // Corrupt the encrypted message
    ct = corruptGCM(ct);
    // Create stream for decryption
    CipherInputStream in = getStream("GCM", ct);

    try {
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail: " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 7
Source File: UpdateBot.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        new UpdateBot().run(args);
    } catch (IOException e) {
        System.err.println("Failed: " + e);
        e.printStackTrace();
        Throwable cause = e.getCause();
        if (cause != e) {
            System.out.println("Caused by: " + cause);
            cause.printStackTrace();
        }
        System.exit(1);
    }
}
 
Example 8
Source File: SnapshotManager.java    From serve with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD")
public Snapshot getSnapshot(String snapshotName) throws SnapshotReadException {
    try {
        return snapshotSerializer.getSnapshot(snapshotName);
    } catch (IOException e) {
        throw new SnapshotReadException(
                "Error while retrieving snapshot details. Cause : " + e.getCause());
    }
}
 
Example 9
Source File: AnnotationModelHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the given callable as a JavaSource user action task. Not private because
 * used in unit tests.
 *
 * @param notify whether to notify <code>JavaContextListener</code>s.
 */
<V> V runJavaSourceTask(final Callable<V> callable, final boolean notify) throws IOException {
    JavaSource existingJavaSource;
    synchronized (this) {
        existingJavaSource = javaSource;
    }
    JavaSource newJavaSource = existingJavaSource != null ? existingJavaSource : JavaSource.create(cpi);
    final List<V> result = new ArrayList<V>();
    try {
        newJavaSource.runUserActionTask(new CancellableTask<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws Exception {
                result.add(runCallable(callable, controller, notify));
            }
            @Override
            public void cancel() {
                // we can't cancel
            }
        }, true);
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause instanceof MetadataModelException) {
            throw (MetadataModelException)cause;
        }
        throw e;
    }
    return result.get(0);
}
 
Example 10
Source File: GrpcCAS.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Override
public void put(Blob blob) throws InterruptedException {
  Chunker chunker = Chunker.builder().setInput(blob.getData()).build();
  try {
    uploader.uploadBlob(HashCode.fromString(blob.getDigest().getHash()), chunker);
  } catch (IOException e) {
    if (e.getCause() instanceof StatusRuntimeException) {
      throw (StatusRuntimeException) e.getCause();
    }
    throw new RuntimeException(e);
  }
}
 
Example 11
Source File: TestOutputOperator.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(Context.OperatorContext context)
{
  try {
    fs = FileSystem.get(new Configuration());
    if (pathSpec == null) {
      throw new IllegalArgumentException("pathSpec not specified.");
    }

    filepath = new Path(pathSpec);

    logger.info("output file: " + filepath);
    if (fs.exists(filepath)) {
      if (append) {
        output = fs.append(filepath);
      } else {
        fs.delete(filepath, true);
        output = fs.create(filepath);
      }
    } else {
      output = fs.create(filepath);
    }
  } catch (IOException iOException) {
    logger.debug(iOException.getLocalizedMessage());
    throw new RuntimeException(iOException.getCause());
  } catch (IllegalArgumentException illegalArgumentException) {
    logger.debug(illegalArgumentException.getLocalizedMessage());
    throw new RuntimeException(illegalArgumentException);
  }
}
 
Example 12
Source File: ObsoleteUrlFactory.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(Call call, IOException e) {
    synchronized (lock) {
        this.callFailure = (e instanceof UnexpectedException) ? e.getCause() : e;
        lock.notifyAll();
    }
}
 
Example 13
Source File: RequestReader.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Extracts the body contents from the request as a List, the JSON can be an array or just a single value without the [] symbols
 *
 * @param req          the request
 * @param jsonHelper   Jackson Helper
 * @param requiredType the type to return (without the List param)
 * @return A List of "Object" as the required type
 */
default <T> List<T> extractJsonContentAsList(WebScriptRequest req, JacksonHelper jsonHelper, Class<T> requiredType)
{
    Reader reader;
    try
    {
        reader = req.getContent().getReader();
        return jsonHelper.constructList(reader, requiredType);
    }
    catch (IOException e)
    {
        throw new ApiException("Could not read content from HTTP request body.", e.getCause());
    }
}
 
Example 14
Source File: ObsoleteUrlFactory.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(Call call, IOException e) {
    synchronized (lock) {
        this.callFailure = (e instanceof UnexpectedException) ? e.getCause() : e;
        lock.notifyAll();
    }
}
 
Example 15
Source File: ShardMapManager.java    From elastic-db-tools-for-java with MIT License 5 votes vote down vote up
/**
 * Upgrades store at specified location.
 *
 * @param location
 *            Store location to upgrade.
 * @param targetVersion
 *            Target version for store to upgrade to.
 */
private void upgradeStoreLocal(ShardLocation location,
        Version targetVersion) {
    try (IStoreOperationLocal op = this.getStoreOperationFactory().createUpgradeStoreLocalOperation(this, location, "UpgradeStoreLocal",
            targetVersion)) {
        op.doLocal();
    }
    catch (IOException e) {
        e.printStackTrace();
        throw (ShardManagementException) e.getCause();
    }
}
 
Example 16
Source File: AbstractServerConnection.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void initSaslServer(String mechanismName) throws SaslException {
  checkState(saslServer == null);
  try {
    this.saslServer = config.getAuthProvider()
        .getAuthenticatorFactory(mechanismName)
        .createSaslServer(UserGroupInformation.getLoginUser(),
            SaslProperties.getSaslProperties(isEncryptionEnabled(), getMaxWrappedSize()));
  } catch (final IOException e) {
    getLogger().debug("Login failed.", e);
    final Throwable cause = e.getCause();
    if (cause instanceof LoginException) {
      throw new SaslException("Failed to login.", cause);
    }
    throw new SaslException("Unexpected failure trying to login.", cause);
  }
  if (saslServer == null) {
    throw new SaslException(String.format("Server cannot initiate authentication using %s mechanism. Insufficient" +
        " parameters or selected mechanism doesn't support configured security layers ?", mechanismName));
  }

  // If encryption is enabled set the backend wrapper instance corresponding to this SaslServer in the connection
  // object. This is later used to do wrap/unwrap in handlers.
  if (isEncryptionEnabled()) {
    saslCodec = new SaslCodec() {

      @Override
      public byte[] wrap(byte[] data, int offset, int len) throws SaslException {
        checkState(saslServer != null);
        return saslServer.wrap(data, offset, len);
      }

      @Override
      public byte[] unwrap(byte[] data, int offset, int len) throws SaslException {
        checkState(saslServer != null);
        return saslServer.unwrap(data, offset, len);
      }
    };
  }
}
 
Example 17
Source File: TestAddIndexes.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
void doBody(int j, Directory[] dirs) throws Throwable {
  switch(j%5) {
  case 0:
    if (VERBOSE) {
      System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[]) then full merge");
    }
    writer2.addIndexes(dirs);
    try {
      writer2.forceMerge(1);
    } catch (IOException ioe) {
      if (ioe.getCause() instanceof MergePolicy.MergeAbortedException) {
        // OK
      } else {
        throw ioe;
      }
    }
    break;
  case 1:
    if (VERBOSE) {
      System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[])");
    }
    writer2.addIndexes(dirs);
    break;
  case 2:
    if (VERBOSE) {
      System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(LeafReader[])");
    }
    TestUtil.addIndexesSlowly(writer2, readers);
    break;
  case 3:
    if (VERBOSE) {
      System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[]) then maybeMerge");
    }
    writer2.addIndexes(dirs);
    writer2.maybeMerge();
    break;
  case 4:
    if (VERBOSE) {
      System.out.println(Thread.currentThread().getName() + ": TEST: commit");
    }
    writer2.commit();
  }
}
 
Example 18
Source File: OpenVidu.java    From openvidu with Apache License 2.0 4 votes vote down vote up
/**
 * Updates every property of every active Session with the current status they
 * have in OpenVidu Server. After calling this method you can access the updated
 * list of active sessions by calling
 * {@link io.openvidu.java.client.OpenVidu#getActiveSessions()}
 * 
 * @return true if any Session status has changed with respect to the server,
 *         false if not. This applies to any property or sub-property of any of
 *         the sessions locally stored in OpenVidu Java Client
 * 
 * @throws OpenViduHttpException
 * @throws OpenViduJavaClientException
 */
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
	HttpGet request = new HttpGet(this.hostname + API_SESSIONS);

	HttpResponse response;
	try {
		response = this.httpClient.execute(request);
	} catch (IOException e) {
		throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
	}

	try {
		int statusCode = response.getStatusLine().getStatusCode();
		if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
			JsonObject jsonSessions = httpResponseToJson(response);
			JsonArray jsonArraySessions = jsonSessions.get("content").getAsJsonArray();

			// Set to store fetched sessionIds and later remove closed sessions
			Set<String> fetchedSessionIds = new HashSet<>();
			// Boolean to store if any Session has changed
			final boolean[] hasChanged = { false };
			jsonArraySessions.forEach(session -> {
				String sessionId = (session.getAsJsonObject()).get("sessionId").getAsString();
				fetchedSessionIds.add(sessionId);
				this.activeSessions.computeIfPresent(sessionId, (sId, s) -> {
					String beforeJSON = s.toJson();
					s = s.resetSessionWithJson(session.getAsJsonObject());
					String afterJSON = s.toJson();
					boolean changed = !beforeJSON.equals(afterJSON);
					hasChanged[0] = hasChanged[0] || changed;
					log.info("Available session '{}' info fetched. Any change: {}", sessionId, changed);
					return s;
				});
				this.activeSessions.computeIfAbsent(sessionId, sId -> {
					log.info("New session '{}' fetched", sessionId);
					hasChanged[0] = true;
					return new Session(this, session.getAsJsonObject());
				});
			});

			// Remove closed sessions from activeSessions map
			this.activeSessions = this.activeSessions.entrySet().stream().filter(entry -> {
				if (fetchedSessionIds.contains(entry.getKey())) {
					return true;
				} else {
					log.info("Removing closed session {}", entry.getKey());
					hasChanged[0] = true;
					return false;
				}
			}).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
			log.info("Active sessions info fetched: {}", this.activeSessions.keySet());
			return hasChanged[0];
		} else {
			throw new OpenViduHttpException(statusCode);
		}
	} finally {
		EntityUtils.consumeQuietly(response.getEntity());
	}
}
 
Example 19
Source File: InstalledOAuth2Authenticator.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
/**
 * Get New Credentials from the user from the command line OAuth2 dance.
 */
private Credential getNewOAuth2Credential() throws OAuthException {
  GoogleAuthorizationCodeFlow authorizationFlow = getAuthorizationFlow();
  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();

  System.out.println("\n**ACTION REQUIRED** Paste this url in your browser"
      + " and authenticate using your **AdWords Admin Email**: \n" + authorizeUrl);

  // Wait for the authorization code.
  System.out.println("\nType the code you received on the web page here: ");
  try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String authorizationCode = reader.readLine();

    // Authorize the OAuth2 token.
    GoogleAuthorizationCodeTokenRequest tokenRequest =
        authorizationFlow.newTokenRequest(authorizationCode);
    tokenRequest.setRedirectUri(CALLBACK_URL);
    GoogleTokenResponse tokenResponse = tokenRequest.execute();

    //  Create the credential.
    Credential credential =
        new GoogleCredential.Builder()
            .setClientSecrets(clientId, clientSecret)
            .setJsonFactory(new JacksonFactory())
            .setTransport(new NetHttpTransport())
            .build()
            .setFromTokenResponse(tokenResponse);

    // Get refresh token and prompt to save in properties file
    refreshToken = credential.getRefreshToken();
    System.out.println("\n**ACTION REQUIRED** Put the following line in your properties file to"
        + " avoid OAuth authentication next time.");
    System.out.printf("refreshToken=%s\n\n", refreshToken);

    System.out.println("Then press enter to continue...");
    reader.readLine();

    return credential;
  } catch (IOException e) {
    throw new OAuthException("An error occured obtaining the OAuth2Credential", e.getCause());
  }
}
 
Example 20
Source File: SlicedFileConsumer.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Adjust timestamp and write to the file.
 * 
 * @param queued
 *            queued data for write
 */
private final void write(QueuedMediaData queued) {
    // get data type
    byte dataType = queued.getDataType();
    // get timestamp
    int timestamp = queued.getTimestamp();
    log.debug("Write - timestamp: {} type: {}", timestamp, dataType);
    // get queued
    ITag tag = queued.getData();
    if (tag != null) {
        // only allow blank tags if they are of audio type
        if (tag.getBodySize() > 0 || dataType == ITag.TYPE_AUDIO) {
            // if the last message was a reset or we just started, use the header timer
            if (startTimestamp == -1) {
                startTimestamp = timestamp;
                timestamp = 0;
            } else {
                timestamp -= startTimestamp;
            }
            // update the timestamp
            tag.setTimestamp(timestamp);
            try {
                if (timestamp >= 0) {
                    if (!writer.writeTag(tag)) {
                        log.warn("Tag was not written");
                    }
                } else {
                    log.warn("Skipping message with negative timestamp.");
                }
            } catch (ClosedChannelException cce) {
                // the channel we tried to write to is closed, we should not try
                // again on that writer
                log.error("The writer is no longer able to write to the file: {} writable: {}", path.getFileName(), path.toFile().canWrite());
            } catch (IOException e) {
                log.warn("Error writing tag", e);
                if (e.getCause() instanceof ClosedChannelException) {
                    // the channel we tried to write to is closed, we should not
                    // try again on that writer
                    log.error("The writer is no longer able to write to the file: {} writable: {}", path.getFileName(), path.toFile().canWrite());
                }
            } finally {
                queued.dispose();
            }
        }
    }
}