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:com.reactive.hzdfs.TestRunner.java

@Test
public void testDistributeSimpleFile() {

    try {/*from  w  ww . ja va 2s .  c  om*/
        File f = ResourceLoaderHelper.loadFromFileOrClassPath("vp-client.log");
        Future<DFSSResponse> fut = dfss.distribute(f, new DFSSTaskConfig());
        resp = fut.get();
        Assert.assertEquals("Records do not match", 48, resp.getNoOfRecords());
        Assert.assertTrue("error list not empty", resp.getErrorNodes().isEmpty());
        return;
    } catch (IOException e) {
        Assert.fail("Job did not start - " + e);
    } catch (InterruptedException e) {
        Assert.fail("InterruptedException - " + e);
    } catch (ExecutionException e) {
        Assert.fail("File distribution error - " + e.getCause());
    }
    return;
}

From source file:ss.udapi.sdk.services.HttpServices.java

public ServiceRequest processLogin(ServiceRequest loginReq, String relation, String name) throws Exception {

    if (loginReq == null)
        throw new IllegalArgumentException("loginReq must be a valid request");

    logger.info("Preparing request for: " + name);
    CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(loginTimeout).build();
    List<RestItem> serviceRestItems = null;
    ServiceRequest serviceRequest = new ServiceRequest();

    RestItem loginDetails = getRestItems(loginReq, name);
    if (loginDetails == null) {
        logger.error("Link not found for request " + name);
        return null;
    }/*from   ww w. jav a 2  s  .c o m*/

    RestLink link = getLink(loginDetails, relation);
    if (link == null) {
        logger.error("Relation not found for relation: " + relation + " for " + name);
        return null;
    }

    CloseableHttpResponse response = null;
    try {

        HttpUriRequest httpAction = new HttpPost(link.getHref());
        if (compressionEnabled == true) {
            httpAction.setHeader("Accept-Encoding", "gzip");
        }

        httpAction.setHeader("X-Auth-User", SystemProperties.get("ss.username"));
        httpAction.setHeader("X-Auth-Key", SystemProperties.get("ss.password"));
        httpAction.setHeader("Content-Type", "application/json");

        // Send the request of to retrieve the Authentication Token and the
        // list of available services.
        response = httpClient.execute(httpAction);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ClientProtocolException("Unexpected response status: "
                    + response.getStatusLine().getStatusCode() + " while retrieving services for: " + name);
        }

        if (response.getFirstHeader("X-Auth-Token") == null)
            throw new ClientProtocolException("Unexpected response: no auth token found");

        serviceAuthToken = response.getFirstHeader("X-Auth-Token").getValue();

        serviceRequest.setAuthToken(serviceAuthToken);
        HttpEntity entity = response.getEntity();
        String jsonResponse = new String(EntityUtils.toByteArray(entity));
        serviceRestItems = JsonHelper.toRestItems(jsonResponse);
        serviceRequest.setServiceRestItems(serviceRestItems);

        return serviceRequest;

    } catch (ClientProtocolException protEx) {
        logger.error(
                "Invalid Client Protocol: " + protEx.getMessage() + " while retrieving services for: " + name);
        throw protEx;
    } catch (IOException ioEx) {
        logger.error("Communication error" + ioEx.getCause() + " while retrieving services for: " + name);
        throw ioEx;
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            // Can safely be ignored, either the server closed the
            // connection or we didn't open it so there's nothing to do
        }
    }
}

From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java

@Override
public ProcessTask call() throws CommandExecException {
    List<String> command = commandLine.getCommand();
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(commandLine.getWorkingDir());
    builder.redirectOutput(Redirect.PIPE);
    builder.redirectError(Redirect.PIPE);
    builder.redirectInput(Redirect.PIPE);
    try {//from   ww  w .  java  2s.c  o  m
        startProcess(builder);
    } catch (IOException e) {
        throw log.errorStartCommand(this, e, commandLine);
    } catch (InterruptedException e) {
        throw log.commandInterrupted(this, e, commandLine);
    } catch (ExecutionException e) {
        throw log.errorStartCommand(this, e.getCause(), commandLine);
    }
    return this;
}

From source file:uk.ac.ucl.excites.sapelli.collector.load.ProjectLoader.java

/**
 * Extract the given sapelli file (provided as an InputStream) and parses the PROJECT.xml; returns the resulting Project object.
 * /*ww w.  j a va  2  s .co m*/
 * @param sapelliFileInputStream
 * @return the loaded Project
 * @throws Exception
 */
public Project load(InputStream sapelliFileInputStream) throws Exception {
    clearWarnings();
    Project project = null;
    File extractFolder = null;
    try {
        // STEP 0 - Create the extraction folder:
        extractFolder = new File(fileStorageProvider.getTempFolder(true), "" + System.currentTimeMillis());
        if (!FileHelpers.createDirectory(extractFolder))
            throw new FileStorageException("Could not create folder to extract project file into.");

        // STEP 1 - Extract the content of the Sapelli file to a new subfolder of the temp folder:
        try {
            if (Unzipper.unzip(sapelliFileInputStream, extractFolder) == 0)
                throw new Exception("Sapelli file is not a valid ZIP archive or does not contain any files.");
        } catch (IOException ioe) {
            throw new Exception("Error on extracting contents of Sapelli file.", ioe.getCause());
        }

        // STEP 2 - Parse PROJECT.xml:
        try {
            project = parser
                    .parseProject(new File(extractFolder.getAbsolutePath() + File.separator + PROJECT_FILE));
        } catch (Exception e) {
            throw new Exception("Error on parsing " + PROJECT_FILE, e);
        }
        // Copy parser warnings:
        addWarnings(parser.getWarnings());

        // STEP 3 - Check if project is acceptable:
        checkProject(project); // throws IllegalArgumentException if something is wrong

        // STEP 4 - Create move extracted files to project folder:
        try {
            File installFolder = fileStorageProvider.getProjectInstallationFolder(project, true);
            FileHelpers.moveDirectory(extractFolder, installFolder);
            extractFolder = installFolder;
        } catch (Exception e) {
            throw new Exception("Error on moving extracted files to project folder.", e);
        }

        // STEP 5 - Run post-processing tasks:
        List<PostProcessTask> tasks = parser.getPostProcessingTasks();
        if (!tasks.isEmpty()) {
            if (postProcessor != null) {
                postProcessor.initialise(project);
                for (PostProcessTask task : tasks) {
                    try {
                        task.execute(postProcessor, project, this);
                    } catch (Exception e) {
                        throw new Exception("Error on executing post-processing task", e);
                    }
                }

                postProcessor.freeResources();
            } else
                addWarning("Unable to perform " + tasks.size() + " post-processing");
        }
    } catch (Exception e) {
        // Delete temp or install folder:
        FileUtils.deleteQuietly(extractFolder);

        // Re-throw Exception:
        throw e;
    }

    // Return project object:
    return project;
}

From source file:com.reactive.hzdfs.TestRunner.java

@Test
public void testDistributedSimpleFileRecords() {
    try {//from ww w .  j av a  2  s.c  o m
        File f = ResourceLoaderHelper.loadFromFileOrClassPath("AirPassengers.csv");
        Future<DFSSResponse> fut = dfss.distribute(f, new DFSSTaskConfig());
        resp = fut.get();
        Assert.assertNotNull(resp);
        Assert.assertEquals("Records do not match", 145, resp.getNoOfRecords());
        Assert.assertTrue("error list not empty", resp.getErrorNodes().isEmpty());

    } catch (IOException e) {
        Assert.fail("Job did not start - " + e);
    } catch (InterruptedException e) {
        Assert.fail("InterruptedException - " + e);
    } catch (ExecutionException e) {
        Assert.fail("File distribution error - " + e.getCause());
    }

    Assert.assertNotNull(resp.getRecordMap());
    Object record = hzService.get(48, resp.getRecordMap());
    Assert.assertEquals("\"47\",1952.83333333333,172", record);
    record = hzService.get(1, resp.getRecordMap());
    Assert.assertEquals("\"\",\"time\",\"AirPassengers\"", record);
    record = hzService.get(145, resp.getRecordMap());
    Assert.assertEquals("\"144\",1960.91666666667,432", record);
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private void execute(HttpUriRequest request, EntityGetter getter) throws Exception {
    try {/*from  ww w .  jav  a  2s  .co  m*/
        SharingHttpContext context = new SharingHttpContext(state);
        prepare(request, context);
        HttpResponse response = client.execute(server, request, context);
        try {
            context.close();
            handleStatus(response);
            if (getter != null) {
                getter.handle(response);
            }
        } finally {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    } catch (IOException e) {
        if (e.getCause() instanceof TransferCancelledException) {
            throw (Exception) e.getCause();
        }
        throw e;
    }
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public Entities analyseText(String modelSetId, String contextArtifactId, String userId, String title,
        String text) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/analysetext", DefaultRestResource.REST_URI,
            modelSetId);//from   ww w.ja  v  a  2  s  .co  m
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);

    NameValuePair[] queryString = new NameValuePair[4];
    queryString[0] = new NameValuePair("modelsetid", modelSetId);
    queryString[1] = new NameValuePair("contextArtifactId", contextArtifactId);
    queryString[2] = new NameValuePair("userid", userId);
    queryString[3] = new NameValuePair("title", title);
    postMethod.setQueryString(queryString);

    RequestEntity requestEntity;
    InputStream entitiesAsStream = null;
    try {
        requestEntity = new StringRequestEntity(text, MediaType.APPLICATION_XML, "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);
        entitiesAsStream = postMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    Entities entities = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(Entities.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        entities = (Entities) unmarshaller.unmarshal(entitiesAsStream);
    } catch (JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
    return entities;
}

From source file:org.apache.hadoop.hbase.catalog.CatalogTracker.java

/**
 * @param sn ServerName to get a connection against.
 * @return The AdminProtocol we got when we connected to <code>sn</code>
 * May have come from cache, may not be good, may have been setup by this
 * invocation, or may be null.//w  w  w  . j a va2 s. c om
 * @throws IOException
 */
@SuppressWarnings("deprecation")
private AdminService.BlockingInterface getCachedConnection(ServerName sn) throws IOException {
    if (sn == null) {
        return null;
    }
    AdminService.BlockingInterface service = null;
    try {
        service = connection.getAdmin(sn);
    } catch (RetriesExhaustedException e) {
        if (e.getCause() != null && e.getCause() instanceof ConnectException) {
            // Catch this; presume it means the cached connection has gone bad.
        } else {
            throw e;
        }
    } catch (SocketTimeoutException e) {
        LOG.debug("Timed out connecting to " + sn);
    } catch (NoRouteToHostException e) {
        LOG.debug("Connecting to " + sn, e);
    } catch (SocketException e) {
        LOG.debug("Exception connecting to " + sn);
    } catch (UnknownHostException e) {
        LOG.debug("Unknown host exception connecting to  " + sn);
    } catch (FailedServerException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Server " + sn + " is in failed server list.");
        }
    } catch (IOException ioe) {
        Throwable cause = ioe.getCause();
        if (ioe instanceof ConnectException) {
            // Catch. Connect refused.
        } else if (cause != null && cause instanceof EOFException) {
            // Catch. Other end disconnected us.
        } else if (cause != null && cause.getMessage() != null
                && cause.getMessage().toLowerCase().contains("connection reset")) {
            // Catch. Connection reset.
        } else {
            throw ioe;
        }

    }
    return service;
}

From source file:org.apache.nifi.controller.state.providers.zookeeper.ZooKeeperStateProvider.java

@Override
public boolean replace(final StateMap oldValue, final Map<String, String> newValue, final String componentId)
        throws IOException {
    verifyEnabled();//from   w  w w . j a  v a 2 s .co  m

    try {
        setState(newValue, (int) oldValue.getVersion(), componentId, false);
        return true;
    } catch (final NoNodeException nne) {
        return false;
    } catch (final IOException ioe) {
        final Throwable cause = ioe.getCause();
        if (cause != null && cause instanceof KeeperException) {
            final KeeperException ke = (KeeperException) cause;
            if (Code.BADVERSION == ke.code()) {
                return false;
            }
        }

        throw ioe;
    }
}

From source file:com.reactive.hzdfs.TestRunner.java

@Test
public void testMapReduceSimpleFileRecords() {

    try {/*from w  ww .  j a  v a  2  s .com*/
        File f = ResourceLoaderHelper.loadFromFileOrClassPath("AirPassengers.csv");
        Future<DFSSResponse> fut = dfss.distribute(f, new DFSSTaskConfig());
        resp = fut.get();
        Assert.assertNotNull(resp);
        Assert.assertEquals("Records do not match", 145, resp.getNoOfRecords());
        Assert.assertTrue("error list not empty", resp.getErrorNodes().isEmpty());

    } catch (IOException e) {
        Assert.fail("Job did not start - " + e);
    } catch (InterruptedException e) {
        Assert.fail("InterruptedException - " + e);
    } catch (ExecutionException e) {
        Assert.fail("File distribution error - " + e.getCause());
    }

    Assert.assertNotNull(resp.getRecordMap());
    Object record = hzService.get(48, resp.getRecordMap());
    Assert.assertEquals("\"47\",1952.83333333333,172", record);
    record = hzService.get(1, resp.getRecordMap());
    Assert.assertEquals("\"\",\"time\",\"AirPassengers\"", record);
    record = hzService.get(145, resp.getRecordMap());
    Assert.assertEquals("\"144\",1960.91666666667,432", record);

    JobTracker tracker = hzService.newJobTracker("default");
    JobRunner runner = new JobRunner(resp, tracker);
    runner.run();

    try {
        Map<String, Integer> result = runner.future.get(60, TimeUnit.SECONDS);
        Assert.assertTrue(!result.isEmpty());
        Assert.assertTrue(result.containsKey("461"));
        Assert.assertEquals(2, (int) result.get("461"));
    } catch (InterruptedException e) {
        Assert.fail("InterruptedException");
    } catch (ExecutionException e) {
        Assert.fail("ExecutionException - " + e.getCause());
    } catch (TimeoutException e) {
        Assert.fail("TimeoutException");
    }

}