Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.omegat.core.data.RealProject.java

/**
 * Set up and execute the user-specified external command.
 * @param command Command to execute//ww  w.  j  a va 2  s  .  c o m
 */
private void doExternalCommand(String command) {

    if (StringUtil.isEmpty(command)) {
        return;
    }

    Core.getMainWindow().showStatusMessageRB("CT_START_EXTERNAL_CMD");

    CommandVarExpansion expander = new CommandVarExpansion(command);
    command = expander.expandVariables(m_config);
    Log.log("Executing command: " + command);
    try {
        Process p = Runtime.getRuntime().exec(StaticUtils.parseCLICommand(command));
        processCache.push(p);
        CommandMonitor stdout = CommandMonitor.newStdoutMonitor(p);
        CommandMonitor stderr = CommandMonitor.newStderrMonitor(p);
        stdout.start();
        stderr.start();
    } catch (IOException e) {
        String message;
        Throwable cause = e.getCause();
        if (cause == null) {
            message = e.getLocalizedMessage();
        } else {
            message = cause.getLocalizedMessage();
        }
        Core.getMainWindow().showStatusMessageRB("CT_ERROR_STARTING_EXTERNAL_CMD", message);
    }
}

From source file:org.apache.jxtadoop.fs.FsShell.java

int runCmdHandler(CmdHandler handler, String[] args, int startIndex, boolean recursive) throws IOException {
    int errors = 0;

    for (int i = startIndex; i < args.length; i++) {
        Path srcPath = new Path(args[i]);
        FileSystem srcFs = srcPath.getFileSystem(getConf());
        Path[] paths = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath);
        for (Path path : paths) {
            try {
                FileStatus file = srcFs.getFileStatus(path);
                if (file == null) {
                    System.err.println(handler.getName() + ": could not get status for '" + path + "'");
                    errors++;// w w w  .  j a  v a2  s. c  o m
                } else {
                    errors += runCmdHandler(handler, file, srcFs, recursive);
                }
            } catch (IOException e) {
                String msg = (e.getMessage() != null ? e.getLocalizedMessage()
                        : (e.getCause().getMessage() != null ? e.getCause().getLocalizedMessage() : "null"));
                System.err.println(
                        handler.getName() + ": could not get status for '" + path + "': " + msg.split("\n")[0]);
            }
        }
    }

    return (errors > 0 || handler.getErrorCode() != 0) ? 1 : 0;
}

From source file:org.apache.hadoop.mapreduce.security.TestJHSSecurity.java

@Test
public void testDelegationToken() throws IOException, InterruptedException {

    Logger rootLogger = LogManager.getRootLogger();
    rootLogger.setLevel(Level.DEBUG);

    final YarnConfiguration conf = new YarnConfiguration(new JobConf());
    // Just a random principle
    conf.set(JHAdminConfig.MR_HISTORY_PRINCIPAL, "RandomOrc/localhost@apache.org");

    conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    UserGroupInformation.setConfiguration(conf);

    final long initialInterval = 10000l;
    final long maxLifetime = 20000l;
    final long renewInterval = 10000l;

    JobHistoryServer jobHistoryServer = null;
    MRClientProtocol clientUsingDT = null;
    long tokenFetchTime;
    try {/* w w  w . j  a v  a 2  s .co  m*/
        jobHistoryServer = new JobHistoryServer() {
            protected void doSecureLogin(Configuration conf) throws IOException {
                // no keytab based login
            };

            @Override
            protected JHSDelegationTokenSecretManager createJHSSecretManager(Configuration conf,
                    HistoryServerStateStoreService store) {
                return new JHSDelegationTokenSecretManager(initialInterval, maxLifetime, renewInterval, 3600000,
                        store);
            }

            @Override
            protected HistoryClientService createHistoryClientService() {
                return new HistoryClientService(historyContext, this.jhsDTSecretManager) {
                    @Override
                    protected void initializeWebApp(Configuration conf) {
                        // Don't need it, skip.;
                    }
                };
            }
        };
        //      final JobHistoryServer jobHistoryServer = jhServer;
        jobHistoryServer.init(conf);
        jobHistoryServer.start();
        final MRClientProtocol hsService = jobHistoryServer.getClientService().getClientHandler();

        // Fake the authentication-method
        UserGroupInformation loggedInUser = UserGroupInformation.createRemoteUser("testrenewer@APACHE.ORG");
        Assert.assertEquals("testrenewer", loggedInUser.getShortUserName());
        // Default realm is APACHE.ORG
        loggedInUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);

        Token token = getDelegationToken(loggedInUser, hsService, loggedInUser.getShortUserName());
        tokenFetchTime = System.currentTimeMillis();
        LOG.info("Got delegation token at: " + tokenFetchTime);

        // Now try talking to JHS using the delegation token
        clientUsingDT = getMRClientProtocol(token, jobHistoryServer.getClientService().getBindAddress(),
                "TheDarkLord", conf);

        GetJobReportRequest jobReportRequest = Records.newRecord(GetJobReportRequest.class);
        jobReportRequest.setJobId(MRBuilderUtils.newJobId(123456, 1, 1));
        try {
            clientUsingDT.getJobReport(jobReportRequest);
        } catch (IOException e) {
            Assert.assertEquals("Unknown job job_123456_0001", e.getMessage());
        }

        // Renew after 50% of token age.
        while (System.currentTimeMillis() < tokenFetchTime + initialInterval / 2) {
            Thread.sleep(500l);
        }
        long nextExpTime = renewDelegationToken(loggedInUser, hsService, token);
        long renewalTime = System.currentTimeMillis();
        LOG.info("Renewed token at: " + renewalTime + ", NextExpiryTime: " + nextExpTime);

        // Wait for first expiry, but before renewed expiry.
        while (System.currentTimeMillis() > tokenFetchTime + initialInterval
                && System.currentTimeMillis() < nextExpTime) {
            Thread.sleep(500l);
        }
        Thread.sleep(50l);

        // Valid token because of renewal.
        try {
            clientUsingDT.getJobReport(jobReportRequest);
        } catch (IOException e) {
            Assert.assertEquals("Unknown job job_123456_0001", e.getMessage());
        }

        // Wait for expiry.
        while (System.currentTimeMillis() < renewalTime + renewInterval) {
            Thread.sleep(500l);
        }
        Thread.sleep(50l);
        LOG.info("At time: " + System.currentTimeMillis() + ", token should be invalid");
        // Token should have expired.      
        try {
            clientUsingDT.getJobReport(jobReportRequest);
            fail("Should not have succeeded with an expired token");
        } catch (IOException e) {
            assertTrue(e.getCause().getMessage().contains("is expired"));
        }

        // Test cancellation
        // Stop the existing proxy, start another.
        if (clientUsingDT != null) {
            //        RPC.stopProxy(clientUsingDT);
            clientUsingDT = null;
        }
        token = getDelegationToken(loggedInUser, hsService, loggedInUser.getShortUserName());
        tokenFetchTime = System.currentTimeMillis();
        LOG.info("Got delegation token at: " + tokenFetchTime);

        // Now try talking to HSService using the delegation token
        clientUsingDT = getMRClientProtocol(token, jobHistoryServer.getClientService().getBindAddress(),
                "loginuser2", conf);

        try {
            clientUsingDT.getJobReport(jobReportRequest);
        } catch (IOException e) {
            fail("Unexpected exception" + e);
        }
        cancelDelegationToken(loggedInUser, hsService, token);

        // Testing the token with different renewer to cancel the token
        Token tokenWithDifferentRenewer = getDelegationToken(loggedInUser, hsService, "yarn");
        cancelDelegationToken(loggedInUser, hsService, tokenWithDifferentRenewer);
        if (clientUsingDT != null) {
            //        RPC.stopProxy(clientUsingDT);
            clientUsingDT = null;
        }

        // Creating a new connection.
        clientUsingDT = getMRClientProtocol(token, jobHistoryServer.getClientService().getBindAddress(),
                "loginuser2", conf);
        LOG.info("Cancelled delegation token at: " + System.currentTimeMillis());
        // Verify cancellation worked.
        try {
            clientUsingDT.getJobReport(jobReportRequest);
            fail("Should not have succeeded with a cancelled delegation token");
        } catch (IOException e) {
        }

    } finally {
        jobHistoryServer.stop();
    }
}

From source file:ch.cyberduck.core.Session.java

/**
 * Assert that the connection to the remote host is still alive.
 * Open connection if needed./*from   ww w .  j  av  a 2s. c om*/
 *
 * @throws IOException The connection to the remote host failed.
 */
public void check() throws IOException {
    try {
        try {
            if (!this.isConnected()) {
                if (StringUtils.isBlank(host.getHostname())) {
                    if (StringUtils.isBlank(host.getProtocol().getDefaultHostname())) {
                        log.warn(String.format("No default hostname configured for protocol %s",
                                host.getProtocol()));
                        throw new ConnectionCanceledException();
                    }
                    // If hostname is missing update with default
                    host.setHostname(host.getProtocol().getDefaultHostname());
                }
                // If not connected anymore, reconnect the session
                this.connect();
            } else {
                // The session is still supposed to be connected
                try {
                    // Send a 'no operation command' to make sure the session is alive
                    this.noop();
                } catch (IOException e) {
                    // Close the underlying socket first
                    this.interrupt();
                    // Try to reconnect once more
                    this.connect();
                }
            }
        } catch (SocketException e) {
            if (e.getMessage().equals("Software caused connection abort")) {
                // Do not report as failed if socket opening interrupted
                log.warn("Supressed socket exception:" + e.getMessage());
                throw new ConnectionCanceledException(e.getMessage(), e);
            }
            if (e.getMessage().equals("Socket closed")) {
                // Do not report as failed if socket opening interrupted
                log.warn("Supressed socket exception:" + e.getMessage());
                throw new ConnectionCanceledException(e.getMessage(), e);
            }
            throw e;
        } catch (SSLHandshakeException e) {
            log.error(String.format("SSL Handshake failed for host %s", host), e);
            if (e.getCause() instanceof sun.security.validator.ValidatorException) {
                throw e;
            }
            // Most probably caused by user dismissing ceritifcate. No trusted certificate found.
            throw new ConnectionCanceledException(e.getMessage(), e);
        }
    } catch (IOException e) {
        this.interrupt();
        this.error("Connection failed", e);
        throw e;
    }
}

From source file:net.pms.io.SimpleProcessWrapper.java

/**
 * Runs a process with the given command {@link List}.
 *
 * @param command an array of {@link String} used to build the command line.
 * @param timeoutMS the process timeout in milliseconds after which the
 *            process is terminated. Use zero for no timeout, but be aware
 *            of the <a href=/*from   w w w. j  a  va  2 s  .co m*/
 *            "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9"
 *            >pitfalls</a>
 * @param terminateTimeoutMS the timeout in milliseconds to wait for each
 *            termination attempt.
 * @return The {@link ProcessWrapperResult} from running the process.
 * @throws InterruptedException If the operation is interrupted.
 * @throws IllegalArgumentException If {@code command} is {@code null} or
 *             empty.
 */
@Nonnull
public R runProcess(@Nonnull List<String> command, long timeoutMS, long terminateTimeoutMS)
        throws InterruptedException {
    if (command == null || command.isEmpty()) {
        throw new IllegalArgumentException("command can't be null or empty");
    }
    final String executableName;
    if (isNotBlank(command.get(0))) {
        Path executable = Paths.get(command.get(0)).getFileName();
        if (executable != null) {
            executableName = executable.toString();
        } else {
            executableName = command.get(0);
        }
    } else {
        executableName = command.get(0);
    }
    boolean manageProcess = timeoutMS > 0;
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    if (LOGGER.isTraceEnabled()) {
        //XXX: Replace with String.join() in Java 8
        LOGGER.trace("Executing \"{}\"", StringUtils.join(command, " "));
    }
    Process process;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        LOGGER.debug("IOException when trying to start \"{}\" process: {}", executableName, e.getMessage());
        LOGGER.trace("", e);
        return consumer.createResult(null, Integer.MIN_VALUE, e);
    }
    Future<T> output = consumer.consume(process.getInputStream(), "SPW \"" + executableName + "\" consumer");
    if (manageProcess) {
        Services.processManager().addProcess(process, command.get(0), timeoutMS, terminateTimeoutMS);
    }
    int exitCode = Integer.MIN_VALUE;
    boolean interrupted = false;
    boolean shutdown = false;
    do {
        interrupted = false;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            interrupted = Thread.interrupted();
            if (!shutdown) {
                if (manageProcess) {
                    Services.processManager().shutdownProcess(process, executableName);
                    manageProcess = false;
                } else {
                    Services.processManager().addProcess(process, executableName, 0, terminateTimeoutMS);
                }
                shutdown = true;
            }
        }
    } while (interrupted);
    if (manageProcess) {
        Services.processManager().removeProcess(process, command.get(0));
    }
    try {
        return consumer.createResult(output.get(), exitCode, null);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        LOGGER.error("ExecutionException in \"{}\" consumer, no output will be returned: {}", executableName,
                cause.getMessage());
        LOGGER.trace("", e);
        return consumer.createResult(null, exitCode, cause);
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.AbstractWritableContentRepository.java

/**
 * {@inheritDoc}//from w w  w . j av  a2s  . c om
 * 
 * @see ch.entwine.weblounge.common.repository.WritableContentRepository#index()
 */
public void index() throws ContentRepositoryException {

    if (indexing || indexingOffsite) {
        logger.warn("Ignoring additional index request for {}", this);
        return;
    }

    boolean oldReadOnly = readOnly;
    readOnly = true;
    logger.info("Switching site '{}' to read only mode", site);

    ContentRepositoryIndex newIndex = null;

    // Clear previews directory
    logger.info("Removing cached preview images");
    File previewsDir = new File(
            PathUtils.concat(System.getProperty("java.io.tmpdir"), "sites", site.getIdentifier(), "images"));
    FileUtils.deleteQuietly(previewsDir);

    // Create the new index
    try {
        newIndex = new ContentRepositoryIndex(site, resourceSerializer, false);
        indexingOffsite = true;
        rebuildIndex(newIndex);
    } catch (IOException e) {
        indexingOffsite = false;
        throw new ContentRepositoryException("Error creating index " + site.getIdentifier(), e);
    } finally {
        try {
            if (newIndex != null)
                newIndex.close();
        } catch (IOException e) {
            throw new ContentRepositoryException("Error closing new index " + site.getIdentifier(), e);
        }
    }

    try {
        indexing = true;
        index.close();
        logger.info("Loading new index");
        index = new ContentRepositoryIndex(site, resourceSerializer, oldReadOnly);
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new ContentRepositoryException("Error during reindex of '" + site.getIdentifier() + "'", cause);
    } finally {
        indexing = false;
        indexingOffsite = false;
        logger.info("Switching site '{}' back to write mode", site);
        readOnly = oldReadOnly;
    }

}

From source file:net.sf.clirr.cli.Clirr.java

private void run(String[] args) {
    Options options = defineOptions();/*from   w w  w .  j a v a  2s.  c om*/

    CommandLine cmdline = parseCommandLine(args, options);

    String oldPath = cmdline.getOptionValue('o');
    String newPath = cmdline.getOptionValue('n');
    String oldClassPath = cmdline.getOptionValue("ocp");
    String newClassPath = cmdline.getOptionValue("ncp");
    String style = cmdline.getOptionValue('s', "text");
    String outputFileName = cmdline.getOptionValue('f');
    String[] includePkgs = cmdline.getOptionValues('i');
    boolean showAll = cmdline.hasOption('a');
    boolean showPkg = cmdline.hasOption('p');

    if ((oldPath == null) || (newPath == null)) {
        printUsage(options, System.err);
        System.exit(-1);
    }

    Checker checker = new Checker();
    if (showAll) {
        checker.getScopeSelector().setScope(Scope.PRIVATE);
    } else if (showPkg) {
        checker.getScopeSelector().setScope(Scope.PACKAGE);
    }

    ClassSelector classSelector;
    if ((includePkgs != null) && (includePkgs.length > 0)) {
        classSelector = new ClassSelector(ClassSelector.MODE_IF);
        for (int i = 0; i < includePkgs.length; ++i) {
            classSelector.addPackageTree(includePkgs[i]);
        }
    } else {
        // a selector that selects everything
        classSelector = new ClassSelector(ClassSelector.MODE_UNLESS);
    }

    DiffListener diffListener = null;
    if (style.equals("text")) {
        try {
            diffListener = new PlainDiffListener(outputFileName);
        } catch (IOException ex) {
            System.err.println("Invalid output file name.");
        }
    } else if (style.equals("xml")) {
        try {
            diffListener = new XmlDiffListener(outputFileName);
        } catch (IOException ex) {
            System.err.println("Invalid output file name.");
        }
    } else {
        System.err.println("Invalid style option. Must be one of 'text', 'xml'.");
        printUsage(options, System.err);
        System.exit(-1);
    }

    File[] origClassPathEntries = pathToFileArray(oldPath);
    File[] newClassPathEntries = pathToFileArray(newPath);

    checker.addDiffListener(diffListener);

    try {
        ClassLoader loader1 = new URLClassLoader(convertFilesToURLs(pathToFileArray(oldClassPath)));
        ClassLoader loader2 = new URLClassLoader(convertFilesToURLs(pathToFileArray(newClassPath)));

        DefaultTypeArrayBuilderFactory tabFactory = new DefaultTypeArrayBuilderFactory();

        TypeArrayBuilder tab1 = tabFactory.build();
        TypeArrayBuilder tab2 = tabFactory.build();

        final JavaType[] origClasses = tab1.createClassSet(origClassPathEntries, loader1, classSelector);

        final JavaType[] newClasses = tab2.createClassSet(newClassPathEntries, loader2, classSelector);

        checker.reportDiffs(origClasses, newClasses);

        System.exit(0);
    } catch (CheckerException ex) {
        System.err.println("Unable to complete checks: " + ex.getMessage());
        System.exit(1);
    } catch (MalformedURLException ex) {
        System.err.println("Unable to create classloader for 3rd party classes: " + ex.getMessage());
        System.err.println("old classpath: " + oldClassPath);
        System.err.println("new classpath: " + newClassPath);
        System.exit(1);
    } catch (RuntimeException ex) {
        System.err.println("Unable to complete checks: " + ex.toString());
        Throwable cause = ex.getCause();
        if (cause != null) {
            System.err.println("  caused by : " + cause.toString());
        }
        System.exit(2);
    }
}

From source file:com.mwebster.exchange.EasSyncService.java

@Override
public void validateAccount(String hostAddress, String userName, String password, int port, boolean ssl,
        boolean trustCertificates, Context context) throws MessagingException {
    try {//  w w w . j  a  va  2s. c om
        userLog("Testing EAS: ", hostAddress, ", ", userName, ", ssl = ", ssl ? "1" : "0");
        EasSyncService svc = new EasSyncService("%TestAccount%");
        svc.mContext = context;
        svc.mHostAddress = hostAddress;
        svc.mUserName = userName;
        svc.mPassword = password;
        svc.mSsl = ssl;
        svc.mTrustSsl = trustCertificates;
        // We mustn't use the "real" device id or we'll screw up current accounts
        // Any string will do, but we'll go for "validate"
        svc.mDeviceId = "validate";
        HttpResponse resp = svc.sendHttpClientOptions();
        int code = resp.getStatusLine().getStatusCode();
        userLog("Validation (OPTIONS) response: " + code);
        if (code == HttpStatus.SC_OK) {
            // No exception means successful validation
            Header commands = resp.getFirstHeader("MS-ASProtocolCommands");
            Header versions = resp.getFirstHeader("ms-asprotocolversions");
            if (commands == null || versions == null) {
                userLog("OPTIONS response without commands or versions; reporting I/O error");
                throw new MessagingException(MessagingException.IOERROR);
            }

            // Make sure we've got the right protocol version set up
            setupProtocolVersion(svc, versions);

            // Run second test here for provisioning failures...
            Serializer s = new Serializer();
            userLog("Try folder sync");
            s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text("0").end().end().done();
            resp = svc.sendHttpClientPost("FolderSync", s.toByteArray());
            code = resp.getStatusLine().getStatusCode();
            // We'll get one of the following responses if policies are required by the server
            if (code == HttpStatus.SC_FORBIDDEN || code == HTTP_NEED_PROVISIONING) {
                // Get the policies and see if we are able to support them
                if (svc.canProvision() != null) {
                    // If so, send the advisory Exception (the account may be created later)
                    throw new MessagingException(MessagingException.SECURITY_POLICIES_REQUIRED);
                } else
                    // If not, send the unsupported Exception (the account won't be created)
                    throw new MessagingException(MessagingException.SECURITY_POLICIES_UNSUPPORTED);
            } else if (code == HttpStatus.SC_NOT_FOUND) {
                // We get a 404 from OWA addresses (which are NOT EAS addresses)
                throw new MessagingException(MessagingException.PROTOCOL_VERSION_UNSUPPORTED);
            } else if (code != HttpStatus.SC_OK) {
                // Fail generically with anything other than success
                userLog("Unexpected response for FolderSync: ", code);
                throw new MessagingException(MessagingException.UNSPECIFIED_EXCEPTION);
            }
            userLog("Validation successful");
            return;
        }
        if (isAuthError(code)) {
            userLog("Authentication failed");
            throw new AuthenticationFailedException("Validation failed");
        } else {
            // TODO Need to catch other kinds of errors (e.g. policy) For now, report the code.
            userLog("Validation failed, reporting I/O error: ", code);
            throw new MessagingException(MessagingException.IOERROR);
        }
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof CertificateException) {
            userLog("CertificateException caught: ", e.getMessage());
            throw new MessagingException(MessagingException.GENERAL_SECURITY);
        }
        userLog("IOException caught: ", e.getMessage());
        throw new MessagingException(MessagingException.IOERROR);
    }

}

From source file:org.opendaylight.sfc.bootstrap.SfcProviderBootstrapRestAPITest.java

@Test
public void testReadJsonFiles() {
    String configOriginalPath = "sfc-provider/src/test/resources/SfcProviderConfig/sfc_provider_config_test.json";
    String jsonConfigString = null;
    JSONObject configFile = null;//ww w  .j  a  va 2  s  . c om
    byte[] encoded = null;

    // create json file. File is slightly changed because original path in bootstrapDataDir does
    // not exists
    Path providerPath = Paths.get(configOriginalPath);

    try {
        encoded = Files.readAllBytes(providerPath);
        jsonConfigString = new String(encoded, StandardCharsets.UTF_8);
    } catch (IOException e) {
        LOG.error("Failed to...", e);
    }

    if (encoded != null) {
        try {
            configFile = new JSONObject(jsonConfigString);
        } catch (JSONException e) {
            LOG.error("Error instantiating {}", jsonConfigString, e);
        }
    }

    if (configFile != null) {
        try {
            configFile = configFile.getJSONObject("bootstrap");
        } catch (JSONException e) {
            LOG.error("Error retrieving bootstrap object", e);
        }
    }

    // first mock returns true when method tries to find json file (is does not exists), second
    // puts created json as a result
    PowerMockito.stub(PowerMockito.method(SfcProviderConfig.class, "readConfigFile")).toReturn(true);
    PowerMockito.stub(PowerMockito.method(SfcProviderConfig.class, "getJsonBootstrapObject"))
            .toReturn(configFile);

    /*
     * Actual test. It checks, if both json files has been read successfully, contain all
     * necessary data and if
     * the rest json file has been created. If so, this file is then PUT to url address location
     * - this step needs running
     * sfc-karaf (or any server for test purposes). It is not running - so method should throw
     * ClientHandlerException.
     * If so, test catch that exception, check it and consider test to pass (all steps like
     * reading json etc. were successful).
     * If some other exception is thrown (or none), test will fail.
     */

    try {
        // SfcProviderBootstrapRestAPI.getPutBootstrapData(new Object[0], new Class[0]);
        SfcProviderBootstrapRestAPI sfcProviderBootstrapRestAPI = new SfcProviderBootstrapRestAPI(new Object[0],
                new Class[0], "param");
        sfcProviderBootstrapRestAPI.putBootstrapData();
    } catch (Exception e) {
        if (e.getClass() == ClientHandlerException.class) {
            assertEquals("Must be equal", e.getClass(), (ClientHandlerException.class));
            assertTrue("Must be true", e.getCause().getMessage().toLowerCase().contains("connection refused"));
        } else
            // test is ok in IDE, build throws null pointer, don't know why
            assertEquals("Must be equal", e.getClass(), (NullPointerException.class));
    }
}

From source file:com.android.exchange.EasSyncService.java

@Override
public void validateAccount(String hostAddress, String userName, String password, int port, boolean ssl,
        boolean trustCertificates, Context context) throws MessagingException {
    try {/*  w ww.  j  a  v  a2  s  . c om*/
        userLog("Testing EAS: ", hostAddress, ", ", userName, ", ssl = ", ssl ? "1" : "0");
        EasSyncService svc = new EasSyncService("%TestAccount%");
        svc.mContext = context;
        svc.mHostAddress = hostAddress;
        svc.mUserName = userName;
        svc.mPassword = password;
        svc.mSsl = ssl;
        svc.mTrustSsl = trustCertificates;
        // We mustn't use the "real" device id or we'll screw up current accounts
        // Any string will do, but we'll go for "validate"
        svc.mDeviceId = "validate";
        HttpResponse resp = svc.sendHttpClientOptions();
        int code = resp.getStatusLine().getStatusCode();
        userLog("Validation (OPTIONS) response: " + code);
        if (code == HttpStatus.SC_OK) {
            // No exception means successful validation
            Header commands = resp.getFirstHeader("MS-ASProtocolCommands");
            Header versions = resp.getFirstHeader("ms-asprotocolversions");
            if (commands == null || versions == null) {
                userLog("OPTIONS response without commands or versions; reporting I/O error");
                throw new MessagingException(MessagingException.IOERROR);
            }

            // Make sure we've got the right protocol version set up
            setupProtocolVersion(svc, versions);

            // Run second test here for provisioning failures...
            Serializer s = new Serializer();
            userLog("Validate: try folder sync");
            s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text("0").end().end().done();
            resp = svc.sendHttpClientPost("FolderSync", s.toByteArray());
            code = resp.getStatusLine().getStatusCode();
            // We'll get one of the following responses if policies are required by the server
            if (code == HttpStatus.SC_FORBIDDEN || code == HTTP_NEED_PROVISIONING) {
                // Get the policies and see if we are able to support them
                userLog("Validate: provisioning required");
                if (svc.canProvision() != null) {
                    // If so, send the advisory Exception (the account may be created later)
                    userLog("Validate: provisioning is possible");
                    throw new MessagingException(MessagingException.SECURITY_POLICIES_REQUIRED);
                } else
                    userLog("Validate: provisioning not possible");
                // If not, send the unsupported Exception (the account won't be created)
                throw new MessagingException(MessagingException.SECURITY_POLICIES_UNSUPPORTED);
            } else if (code == HttpStatus.SC_NOT_FOUND) {
                userLog("Wrong address or bad protocol version");
                // We get a 404 from OWA addresses (which are NOT EAS addresses)
                throw new MessagingException(MessagingException.PROTOCOL_VERSION_UNSUPPORTED);
            } else if (code != HttpStatus.SC_OK) {
                // Fail generically with anything other than success
                userLog("Unexpected response for FolderSync: ", code);
                throw new MessagingException(MessagingException.UNSPECIFIED_EXCEPTION);
            }
            userLog("Validation successful");
            return;
        }
        if (isAuthError(code)) {
            userLog("Authentication failed");
            throw new AuthenticationFailedException("Validation failed");
        } else {
            // TODO Need to catch other kinds of errors (e.g. policy) For now, report the code.
            userLog("Validation failed, reporting I/O error: ", code);
            throw new MessagingException(MessagingException.IOERROR);
        }
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof CertificateException) {
            userLog("CertificateException caught: ", e.getMessage());
            throw new MessagingException(MessagingException.GENERAL_SECURITY);
        }
        userLog("IOException caught: ", e.getMessage());
        throw new MessagingException(MessagingException.IOERROR);
    }

}