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.apache.hama.ipc.TestIPC.java

@SuppressWarnings("deprecation")
public void testStandAloneClient() throws Exception {
    testParallel(10, false, 2, 4, 2, 4, 100);
    Client client = new Client(LongWritable.class, conf);
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
    try {//from   w  ww .ja v a 2 s .  com
        client.call(new LongWritable(RANDOM.nextLong()), address);
        fail("Expected an exception to have been thrown");
    } catch (IOException e) {
        String message = e.getMessage();
        String addressText = address.toString();
        assertTrue("Did not find " + addressText + " in " + message, message.contains(addressText));
        Throwable cause = e.getCause();
        assertNotNull("No nested exception in " + e, cause);
        String causeText = cause.getMessage();
        assertTrue("Did not find " + causeText + " in " + message, message.contains(causeText));
    }
}

From source file:org.apache.hawq.pxf.service.ReadVectorizedBridge.java

@Override
public Writable getNext() throws Exception {
    Writable output = null;/*from  w ww.java2s.  c o m*/
    OneRow batch = null;

    if (!outputQueue.isEmpty()) {
        return outputQueue.pop();
    }

    try {
        while (outputQueue.isEmpty()) {
            batch = fileAccessor.readNextObject();
            if (batch == null) {
                output = outputBuilder.getPartialLine();
                if (output != null) {
                    LOG.warn("A partial record in the end of the fragment");
                }
                // if there is a partial line, return it now, otherwise it
                // will return null
                return output;
            }

            // we checked before that outputQueue is empty, so we can
            // override it.
            List<List<OneField>> resolvedBatch = ((ReadVectorizedResolver) fieldsResolver)
                    .getFieldsForBatch(batch);
            outputQueue = outputBuilder.makeVectorizedOutput(resolvedBatch);
            if (!outputQueue.isEmpty()) {
                output = outputQueue.pop();
                break;
            }
        }
    } catch (IOException ex) {
        if (!isDataException(ex)) {
            throw ex;
        }
        output = outputBuilder.getErrorOutput(ex);
    } catch (BadRecordException ex) {
        String row_info = "null";
        if (batch != null) {
            row_info = batch.toString();
        }
        if (ex.getCause() != null) {
            LOG.debug("BadRecordException " + ex.getCause().toString() + ": " + row_info);
        } else {
            LOG.debug(ex.toString() + ": " + row_info);
        }
        output = outputBuilder.getErrorOutput(ex);
    } catch (Exception ex) {
        throw ex;
    }

    return output;
}

From source file:jetbrains.buildServer.torrent.TorrentTransportTest.java

public void testInterrupt() throws IOException, InterruptedException, NoSuchAlgorithmException {
    setTorrentTransportEnabled();//www  .  j  av  a 2s.c o  m
    setDownloadHonestly(true);

    final File storageDir = new File(myTempDir, "storageDir");
    storageDir.mkdir();
    final File downloadDir = new File(myTempDir, "downloadDir");
    downloadDir.mkdir();
    final File torrentsDir = new File(myTempDir, "torrentsDir");
    torrentsDir.mkdir();
    final String fileName = "MyBuild.31.zip";
    final File artifactFile = new File(storageDir, fileName);
    createTempFile(25 * 1024 * 1025).renameTo(artifactFile);

    final File teamcityIvyFile = new File("agent/tests/resources/" + TorrentTransportFactory.TEAMCITY_IVY);
    myDownloadMap.put("/" + TorrentTransportFactory.TEAMCITY_IVY, teamcityIvyFile);
    final String ivyUrl = SERVER_PATH + TorrentTransportFactory.TEAMCITY_IVY;
    final File ivyFile = new File(myTempDir, TorrentTransportFactory.TEAMCITY_IVY);
    myTorrentTransport.downloadUrlTo(ivyUrl, ivyFile);
    Tracker tracker = new Tracker(6969);
    List<Client> clientList = new ArrayList<Client>();
    for (int i = 0; i < TorrentTransportFactory.MIN_SEEDERS_COUNT_TO_TRY; i++) {
        clientList.add(new Client());
    }
    try {
        tracker.start(true);

        myDirectorySeeder.start(new InetAddress[] { InetAddress.getLocalHost() }, tracker.getAnnounceURI(), 5);

        final Torrent torrent = Torrent.create(artifactFile, tracker.getAnnounceURI(), "testplugin");
        final File torrentFile = new File(torrentsDir, fileName + ".torrent");
        torrent.save(torrentFile);
        myDownloadMap.put("/.teamcity/torrents/" + fileName + ".torrent", torrentFile);
        for (Client client : clientList) {
            client.start(InetAddress.getLocalHost());
            client.addTorrent(SharedTorrent.fromFile(torrentFile, storageDir, true));
        }
        final File targetFile = new File(downloadDir, fileName);
        new Thread() {
            @Override
            public void run() {
                try {
                    sleep(400);
                    myTorrentTransport.interrupt();
                } catch (InterruptedException e) {
                    fail("Must not fail here: " + e);
                }
            }
        }.start();
        String digest = null;
        try {
            digest = myTorrentTransport.downloadUrlTo(SERVER_PATH + fileName, targetFile);
        } catch (IOException ex) {
            assertNull(digest);
            assertTrue(ex.getCause() instanceof InterruptedException);
        }
        assertFalse(targetFile.exists());
    } finally {
        for (Client client : clientList) {
            client.stop();
        }
        tracker.stop();
    }
}

From source file:uk.trainwatch.osgb.codepoint.util.CodePointImport.java

private void importer(Connection con, Path path) throws SQLException {
    LOG.log(Level.INFO, () -> "Importing " + path);

    try {/*from ww  w .  j  a va2 s. com*/
        try (CSVParser parser = new CSVParser(new FileReader(path.toFile()), CSVFormat.DEFAULT)) {
            List<CSVRecord> records = parser.getRecords();

            // Do the import in one massive transaction
            con.setAutoCommit(false);

            try (PreparedStatement ps = con.prepareStatement(CP_SQL)) {
                records.stream()
                        .map(r -> new PostCode(r.get(0), Integer.parseInt(r.get(1)), Integer.parseInt(r.get(2)),
                                Integer.parseInt(r.get(3)), r.get(4), r.get(5), r.get(6), r.get(7), r.get(8),
                                r.get(9)))
                        .forEach(SQLConsumer.guard(pc -> {
                            SQL.executeUpdate(ps, pc.getPostCode(), pc.getPqi(), pc.getEastings(),
                                    pc.getNorthings(), codeLookup.getOrDefault(pc.getCountry(), 0),
                                    codeLookup.getOrDefault(pc.getCounty(), 0),
                                    codeLookup.getOrDefault(pc.getDistrict(), 0),
                                    codeLookup.getOrDefault(pc.getWard(), 0),
                                    nhsLookup.getOrDefault(pc.getNhsRegion(), 0),
                                    nhsLookup.getOrDefault(pc.getNhs(), 0));
                        }));
            }

            con.commit();

            int parseCount = records.size();
            lineCount += parseCount;
            LOG.log(Level.INFO, () -> "Parsed " + parseCount);
        }

    } catch (IOException ex) {
        con.rollback();
        LOG.log(Level.SEVERE, null, ex);
        throw new UncheckedIOException(ex);
    } catch (UncheckedSQLException ex) {
        con.rollback();
        LOG.log(Level.SEVERE, null, ex);
        throw ex.getCause();
    } catch (Exception ex) {
        con.rollback();
        LOG.log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}

From source file:eu.musesproject.server.policyrulesselector.PolicySelector.java

private String getFullJSONDevicePolicy() {//TODO This is a sample policy selection, hence the selection of concrete policies based on decisions is yet to be done
    String jsonDevicePolicy = null;
    BufferedReader br = null;/* ww  w .  j a  v  a2 s.  c o  m*/
    InputStream in = null;
    InputStreamReader is = null;
    try {
        in = FileManager.get().open("devpolicies/muses-device-policy-prototype.xml");
        is = new InputStreamReader(in);
        StringBuilder sb = new StringBuilder();
        br = new BufferedReader(is);
        String read = br.readLine();

        while (read != null) {
            sb.append(read);
            read = br.readLine();
        }
        String fileContent = sb.toString();
        JSONObject xmlJSONObj = XML.toJSONObject(fileContent);
        jsonDevicePolicy = xmlJSONObj.toString();
    } catch (JSONException je) {
        logger.error("JSONException:" + je.getCause());
    } catch (IOException e) {
        logger.error("IOException:" + e.getCause());
    } finally {

        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            logger.error("IOException:" + e.getCause());

        }
    }

    return jsonDevicePolicy;
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);//from w  w  w  . j  ava 2  s .  c om
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:fr.univrouen.poste.web.membre.PosteAPourvoirController.java

@RequestMapping(value = "/{id}/{idFile}")
@PreAuthorize("hasPermission(#id, 'viewposte')")
public void downloadPosteFile(@PathVariable("id") Long id, @PathVariable("idFile") Long idFile,
        HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
    try {//from   w  w w  . java 2s  .c  om
        PosteAPourvoir poste = PosteAPourvoir.findPosteAPourvoir(id);
        PosteAPourvoirFile posteFile = PosteAPourvoirFile.findPosteAPourvoirFile(idFile);
        String filename = posteFile.getFilename();
        Long size = posteFile.getFileSize();
        String contentType = posteFile.getContentType();
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setContentLength(size.intValue());
        IOUtils.copy(posteFile.getBigFile().getBinaryFile().getBinaryStream(), response.getOutputStream());

        Calendar cal = Calendar.getInstance();
        Date currentTime = cal.getTime();

        logService.logActionPosteFile(LogService.DOWNLOAD_ACTION, poste, posteFile, request, currentTime);
    } catch (IOException ioe) {
        String ip = request.getRemoteAddr();
        logger.warn("Download IOException, that can be just because the client [" + ip
                + "] canceled the download process : " + ioe.getCause());
    }
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferServer.java

/**
 * This method actually executes the server-side SASL handshake.
 *
 * @param underlyingOut connection output stream
 * @param underlyingIn connection input stream
 * @param saslProps properties of SASL negotiation
 * @param callbackHandler for responding to SASL callbacks
 * @return new pair of streams, wrapped after SASL negotiation
 * @throws IOException for any error//from www. j ava 2 s . c  o m
 */
private IOStreamPair doSaslHandshake(OutputStream underlyingOut, InputStream underlyingIn,
        Map<String, String> saslProps, CallbackHandler callbackHandler) throws IOException {

    DataInputStream in = new DataInputStream(underlyingIn);
    DataOutputStream out = new DataOutputStream(underlyingOut);

    SaslParticipant sasl = SaslParticipant.createServerSaslParticipant(saslProps, callbackHandler);

    int magicNumber = in.readInt();
    if (magicNumber != SASL_TRANSFER_MAGIC_NUMBER) {
        throw new InvalidMagicNumberException(magicNumber, dnConf.getEncryptDataTransfer());
    }
    try {
        // step 1
        byte[] remoteResponse = readSaslMessage(in);
        byte[] localResponse = sasl.evaluateChallengeOrResponse(remoteResponse);
        sendSaslMessage(out, localResponse);

        // step 2 (server-side only)
        List<CipherOption> cipherOptions = Lists.newArrayList();
        remoteResponse = readSaslMessageAndNegotiationCipherOptions(in, cipherOptions);
        localResponse = sasl.evaluateChallengeOrResponse(remoteResponse);

        // SASL handshake is complete
        checkSaslComplete(sasl, saslProps);

        CipherOption cipherOption = null;
        if (sasl.isNegotiatedQopPrivacy()) {
            // Negotiate a cipher option
            cipherOption = negotiateCipherOption(dnConf.getConf(), cipherOptions);
            if (cipherOption != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Server using cipher suite " + cipherOption.getCipherSuite().getName());
                }
            }
        }

        // If negotiated cipher option is not null, wrap it before sending.
        sendSaslMessageAndNegotiatedCipherOption(out, localResponse, wrap(cipherOption, sasl));

        // If negotiated cipher option is not null, we will use it to create 
        // stream pair.
        return cipherOption != null
                ? createStreamPair(dnConf.getConf(), cipherOption, underlyingOut, underlyingIn, true)
                : sasl.createStreamPair(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:com.starit.diamond.server.service.task.DumpConfigInfoTask.java

public List<ConfigInfo> tryLoadLocalDistDumpInfo() {
    List<ConfigInfo> result = new ArrayList<ConfigInfo>();
    log.warn("tryLoadLocalDumpInfo");
    if (checkDumpTs()) {
        try {//from  ww w  .j  av  a2 s.  c o m
            String basePath = WebUtils.getRealPath(this.timerTaskService.getDiskService().getServletContext(),
                    Constants.BASE_DIR);
            File file = new File(basePath);
            if (file.exists()) {
                if (checkDumpTs())
                    for (File group : file.listFiles()) {
                        if (checkDumpTs())
                            for (File dataId : group.listFiles()) {
                                String groupName = group.getName();
                                String dataIdName = dataId.getName();
                                dataIdName = SystemConfig.decodeFnForDataIdIfUnderWin(dataIdName);
                                if (checkDumpTs())
                                    try {
                                        String content = FileUtils.getFileContent(dataId.getAbsolutePath());
                                        ConfigInfo configInfo = new ConfigInfo(dataIdName, groupName, content);
                                        result.add(configInfo);
                                        timerTaskService.getConfigService().updateMD5Cache(configInfo);
                                    } catch (IOException e) {
                                        log.error("ConfigInfo:dataId:" + dataIdName + ":"
                                                + groupName);
                                        log.error(e.getMessage(), e.getCause());
                                    }

                            }
                    }
            }
            timerTaskService.setFirstLoadDumpInfo(false);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e.getCause());
        }
    }
    return result;
}

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

public void testDistributeLargeFile() {

    File f = new File("C:\\Users\\esutdal\\Documents\\test\\cbp14co.txt");
    try {/*from   ww  w  .ja v  a2  s.  c  o m*/
        Future<DFSSResponse> fut = dfss.distribute(f, new DFSSTaskConfig());
        DFSSResponse dfs = fut.get();
        Assert.assertEquals("Record size do not match", 2125362, dfs.getNoOfRecords());
        Assert.assertTrue("error list not empty", dfs.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;
}