List of usage examples for java.io IOException getCause
public synchronized Throwable getCause()
From source file:org.apache.sqoop.mapreduce.db.SQLServerDBRecordReader.java
@Override /**/*from w w w . j a v a 2 s . co m*/ * Read the next key, value pair. * Try to recover failed connections using the configured connection failure * handler before retrying the failed operation */ public boolean nextKeyValue() throws IOException { boolean valueReceived = false; int retryCount = RETRY_MAX; boolean doRetry = true; do { try { // Try to get the next key/value pairs valueReceived = super.nextKeyValue(); doRetry = false; } catch (IOException ioEx) { LOG.warn("Trying to recover from DB read failure: ", ioEx); Throwable cause = ioEx.getCause(); // Use configured connection handler to recover from the connection // failure and use the newly constructed connection. // If the failure cannot be recovered, an exception is thrown if (failureHandler.canHandleFailure(cause)) { // Recover from connection failure Connection conn = failureHandler.recover(); // Configure the new connection before using it configureConnection(conn); setConnection(conn); --retryCount; doRetry = (retryCount >= 0); } else { // Cannot recovered using configured handler, re-throw throw new IOException("Cannection handler cannot recover failure: ", ioEx); } } } while (doRetry); // Rethrow the exception if all retry attempts are consumed if (retryCount < 0) { throw new IOException("Failed to read from database after " + RETRY_MAX + " retries."); } return valueReceived; }
From source file:org.apache.flink.runtime.state.DuplicatingCheckpointOutputStreamTest.java
/** * Tests that in case of unaligned stream positions, the secondary stream is closed and the primary still works. * This is important because some code may rely on seeking to stream offsets in the created state files and if the * streams are not aligned this code could fail. *//*from ww w .ja v a 2 s. c o m*/ @Test public void testUnalignedStreamsException() throws IOException { int streamCapacity = 1024 * 1024; TestMemoryCheckpointOutputStream primaryStream = new TestMemoryCheckpointOutputStream(streamCapacity); TestMemoryCheckpointOutputStream secondaryStream = new TestMemoryCheckpointOutputStream(streamCapacity); primaryStream.write(42); DuplicatingCheckpointOutputStream stream = new DuplicatingCheckpointOutputStream(primaryStream, secondaryStream); Assert.assertNotNull(stream.getSecondaryStreamException()); Assert.assertTrue(secondaryStream.isClosed()); stream.write(23); try { stream.closeAndGetSecondaryHandle(); Assert.fail(); } catch (IOException ignore) { Assert.assertEquals(ignore.getCause(), stream.getSecondaryStreamException()); } StreamStateHandle primaryHandle = stream.closeAndGetPrimaryHandle(); try (FSDataInputStream inputStream = primaryHandle.openInputStream();) { Assert.assertEquals(42, inputStream.read()); Assert.assertEquals(23, inputStream.read()); Assert.assertEquals(-1, inputStream.read()); } }
From source file:adapter.sos.BasicSensorObservationServiceClient.java
public void postXml(String strXML, String serviceURL) throws SOSException { HttpPost httppost = new HttpPost(serviceURL); HttpEntity entity = null;//from ww w . ja va2 s. c o m HttpResponse response = null; try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("request", strXML)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); entity = response.getEntity(); int code = response.getStatusLine().getStatusCode(); if (code != 200) { throw new SOSException("Server replied with http error code: " + code); } examineReponse(entity); } catch (IOException e) { try { EntityUtils.consume(entity); } catch (IOException e1) { e1.printStackTrace(); } throw new SOSException("Cannot execute post: " + e.getCause()); } }
From source file:com.idiro.utils.db.mysql.MySqlUtils.java
public static boolean importTable(JdbcConnection conn, String tableName, Map<String, String> features, File fileIn, File tablePath, char delimiter, boolean header) { boolean ok = true; try {/* www. j a v a 2 s . co m*/ DbChecker dbCh = new DbChecker(conn); if (!dbCh.isTableExist(tableName)) { logger.debug("The table which has to be imported has not been created"); logger.debug("Creation of the table"); Integer ASCIIVal = (int) delimiter; String[] options = { ASCIIVal.toString(), tablePath.getCanonicalPath() }; conn.executeQuery(new MySqlBasicStatement().createExternalTable(tableName, features, options)); } else { //Check if it is the same table if (!dbCh.areFeaturesTheSame(tableName, features.keySet())) { logger.warn("Mismatch between the table to import and the table in the database"); return false; } logger.warn("Have to check if the table is external or not, I do not know how to do that"); } } catch (SQLException e) { logger.debug("Fail to watch the datastore"); logger.debug(e.getMessage()); return false; } catch (IOException e) { logger.warn("Fail to get the output path from a File object"); logger.warn(e.getMessage()); return false; } //Check if the input file has the right number of field FileChecker fChIn = new FileChecker(fileIn); FileChecker fChOut = new FileChecker(tablePath); String strLine = ""; try { if (fChIn.isDirectory() || !fChIn.canRead()) { logger.warn("The file " + fChIn.getFilename() + "is a directory or can not be read"); return false; } BufferedReader br = new BufferedReader(new FileReader(fileIn)); //Read first line strLine = br.readLine(); br.close(); } catch (IOException e1) { logger.debug("Fail to open the file" + fChIn.getFilename()); return false; } if (StringUtils.countMatches(strLine, String.valueOf(delimiter)) != features.size() - 1) { logger.warn("File given does not match with the delimiter '" + delimiter + "' given and the number of fields '" + features.size() + "'"); return false; } BufferedWriter bw = null; BufferedReader br = null; try { bw = new BufferedWriter(new FileWriter(tablePath)); logger.debug("read the file" + fileIn.getAbsolutePath()); br = new BufferedReader(new FileReader(fileIn)); String delimiterStr = "" + delimiter; //Read File Line By Line while ((strLine = br.readLine()) != null) { bw.write("\"" + strLine.replace(delimiterStr, "\",\"") + "\"\n"); } br.close(); bw.close(); } catch (FileNotFoundException e1) { logger.error(e1.getCause() + " " + e1.getMessage()); logger.error("Fail to read " + fileIn.getAbsolutePath()); ok = false; } catch (IOException e1) { logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename() + " to the file " + fChOut.getFilename()); ok = false; } return ok; }
From source file:org.geoserver.csw.DownloadLinkHandler.java
/** * Return an {@link Iterator} containing {@link String}s representing * the downloadLinks associated to the provided {@link CoverageInfo} object. * * @param baseURL/*w ww. java2s.co m*/ * @param coverageInfo * */ protected CloseableIterator<String> linksFromCoverage(String baseURL, CoverageInfo coverageInfo) { GridCoverage2DReader reader; try { reader = (GridCoverage2DReader) coverageInfo.getGridCoverageReader(null, GeoTools.getDefaultHints()); String name = DirectDownload.extractName(coverageInfo); if (reader == null) { throw new IllegalArgumentException("No reader available for the specified coverage: " + name); } ResourceInfo resourceInfo = reader.getInfo(name); if (resourceInfo instanceof FileResourceInfo) { FileResourceInfo fileResourceInfo = (FileResourceInfo) resourceInfo; // Replace the template URL with proper values String baseLink = baseURL.replace("${nameSpace}", coverageInfo.getNamespace().getName()) .replace("${layerName}", coverageInfo.getName()); CloseableIterator<org.geotools.data.FileGroupProvider.FileGroup> dataIterator = fileResourceInfo .getFiles(null); return new CloseableLinksIterator(baseLink, dataIterator); } else { throw new RuntimeException("Donwload links handler need to provide " + "download links to files. The ResourceInfo associated with the store should be a FileResourceInfo instance"); } } catch (IOException e) { throw new RuntimeException("Unable to generate download links", e.getCause()); } }
From source file:org.signserver.client.cli.defaultimpl.KeyStoreOptions.java
public void parseCommandLine(CommandLine line, ConsolePasswordReader passwordReader, PrintStream out) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException { if (line.hasOption(KeyStoreOptions.TRUSTSTORE)) { truststoreFile = new File(line.getOptionValue(KeyStoreOptions.TRUSTSTORE, null)); }/*from w w w .j a v a 2 s . c o m*/ if (line.hasOption(KeyStoreOptions.TRUSTSTOREPWD)) { truststorePassword = line.getOptionValue(KeyStoreOptions.TRUSTSTOREPWD, null); } if (line.hasOption(KeyStoreOptions.KEYSTORE)) { keystoreFile = new File(line.getOptionValue(KeyStoreOptions.KEYSTORE, null)); } if (line.hasOption(KeyStoreOptions.KEYSTOREPWD)) { keystorePassword = line.getOptionValue(KeyStoreOptions.KEYSTOREPWD, null); } if (line.hasOption(KeyStoreOptions.KEYALIAS)) { keyAlias = line.getOptionValue(KeyStoreOptions.KEYALIAS, null); } if (passwordReader != null) { // Prompt for truststore password if not given if (truststoreFile != null && truststorePassword == null) { for (int i = 0; i < 3; i++) { out.print("Password for truststore: "); out.flush(); truststorePassword = new String(passwordReader.readPassword()); try { KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(new FileInputStream(truststoreFile), truststorePassword.toCharArray()); break; } catch (IOException ex) { if (ex.getCause() instanceof UnrecoverableKeyException) { if (i >= 2) { throw ex; } continue; } else { throw ex; } } } } // Prompt for keystore password if not given if (keystoreFile != null && keystorePassword == null) { for (int i = 0; i < 3; i++) { out.print("Password for keystore: "); out.flush(); keystorePassword = new String(passwordReader.readPassword()); try { KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray()); break; } catch (IOException ex) { if (ex.getCause() instanceof UnrecoverableKeyException) { if (i >= 2) { throw ex; } continue; } else { throw ex; } } } } } }
From source file:org.fishwife.jrugged.spring.PerformanceMonitorFilter.java
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException { try {/* ww w .j a v a 2s . c o m*/ invoke(new Runnable() { public void run() { try { chain.doFilter(req, resp); } catch (IOException e) { throw new WrappedException(e); } catch (ServletException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { Throwable wrapped = e.getCause(); if (wrapped instanceof IOException) { throw (IOException) wrapped; } else if (wrapped instanceof ServletException) { throw (ServletException) wrapped; } else { throw new IllegalStateException("unknown wrapped exception", wrapped); } } catch (Exception e) { throw new IllegalStateException("unknown checked exception", e); } }
From source file:org.apache.bookkeeper.bookie.BookieInitializationTest.java
/** * Verify the bookie registration, it should throw * KeeperException.NodeExistsException if the znode still exists even after * the zk session timeout./*from w w w . j a v a 2 s . co m*/ */ @Test(timeout = 30000) public void testRegNodeExistsAfterSessionTimeOut() throws Exception { File tmpDir = createTempDir("bookie", "test"); ServerConfiguration conf = new ServerConfiguration().setZkServers(null).setJournalDirName(tmpDir.getPath()) .setLedgerDirNames(new String[] { tmpDir.getPath() }); String bkRegPath = conf.getZkAvailableBookiesPath() + "/" + InetAddress.getLocalHost().getHostAddress() + ":" + conf.getBookiePort(); MockBookie b = new MockBookie(conf); b.initialize(); b.zk = zkc; b.testRegisterBookie(conf); Stat bkRegNode1 = zkc.exists(bkRegPath, false); Assert.assertNotNull("Bookie registration node doesn't exists!", bkRegNode1); // simulating bookie restart, on restart bookie will create new // zkclient and doing the registration. createNewZKClient(); b.zk = newzk; try { b.testRegisterBookie(conf); fail("Should throw NodeExistsException as the znode is not getting expired"); } catch (IOException e) { Throwable t = e.getCause(); if (t instanceof KeeperException) { KeeperException ke = (KeeperException) t; Assert.assertTrue("ErrorCode:" + ke.code() + ", Registration node doesn't exists", ke.code() == KeeperException.Code.NODEEXISTS); // verify ephemeral owner of the bkReg znode Stat bkRegNode2 = newzk.exists(bkRegPath, false); Assert.assertNotNull("Bookie registration has been failed", bkRegNode2); Assert.assertTrue("Bookie wrongly registered. Old registration znode:" + bkRegNode1 + ", New znode:" + bkRegNode2, bkRegNode1.getEphemeralOwner() == bkRegNode2.getEphemeralOwner()); return; } throw e; } }
From source file:org.openhab.tools.analysis.utils.CachingHttpClientTest.java
@Test public void testFailureAndSuccess() throws Exception { URL url = getUniqueURL(PATH_TO_RESOURCE); // The server stops responding Mockito.doNothing().when(server.getHandler()).handle(any(), any(), any(), any()); // First request throws exception, because a get request is sent try {// ww w . j ava 2 s. c o m testClient.get(url); } catch (IOException e) { assertThat(e, instanceOf(IOException.class)); assertThat(e.getMessage(), equalTo("Unable to get " + url.toString())); assertThat(e.getCause(), instanceOf(FileNotFoundException.class)); } mockHandler(server.getHandler()); // Next requests do not throw exception assertNull(testClient.get(url)); assertNull(testClient.get(url)); verify(server.getHandler(), times(1)).handle(any(), any(), any(), any()); }
From source file:com.appcel.core.converter.locator.ConverterLocator.java
@Override public ConverterExecutor createConverterExecutor(ConverterExecutorEnum executorEnum) { ConverterExecutor converterExcutor = null; String os = System.getProperty("os.name").toLowerCase(); // Windows?//from w w w . jav a 2 s . c o m boolean isWindows = (os.indexOf("windows") != -1) ? true : false; // Need a chmod? //String archexe = executorEnum.getValue(); // Temp dir? // File temp = new File(System.getProperty("java.io.tmpdir"), archexe + myEXEversion); // if (!temp.exists()) { // temp.mkdirs(); // temp.deleteOnExit(); // } // converter executable export on disk. // String suffix = isWindows ? ".exe" : ""; // File exeFile = new File(temp, archexe + suffix); //String executableCmdPath = exeFile.getAbsolutePath(); // if (!exeFile.exists()) { // // copyFile(archexe + suffix, exeFile); // } ConverterConfiguration converterConf = ConverterConfiguration.getMe(); String openofficeHome = null; String swftoolsHome = null; String swftoolsExecutor = null; String swftoolsFontHome = null; if (ConverterExecutorEnum.OPENOFFICE_EXECUTOR.equals(executorEnum)) { openofficeHome = isWindows ? converterConf.getConverterOpenofficeWinHome() : converterConf.getConverterOpenofficeLinuxHome(); converterExcutor = new OpenofficeConverterExecutor(openofficeHome, ConverterConfiguration.getMe().getConverterOpenofficePort(), !isWindows); LOGGER.info("Converter openoffice home Path ??==========>>> " + openofficeHome); } else if (ConverterExecutorEnum.SWFTOOLS_EXECUTOR.equals(executorEnum)) { swftoolsHome = isWindows ? converterConf.getConverterSwftoolsWinHome() : converterConf.getConverterSwftoolsLinuxHome(); swftoolsFontHome = isWindows ? converterConf.getConverterSwftoolsFontWinHome() : converterConf.getConverterSwftoolsFontLinuxHome(); swftoolsExecutor = isWindows ? converterConf.getConverterSwftoolsWinExecutor() : converterConf.getConverterSwftoolsLinuxExecutor(); converterExcutor = new SwftoolsConverterExecutor(swftoolsHome, swftoolsFontHome, swftoolsExecutor, !isWindows); LOGGER.info("Converter swftools home Path ??==========>>> " + swftoolsHome); LOGGER.info("Converter swfls font home Path ??==========>>> " + swftoolsFontHome); LOGGER.info("Converter swftools executor ?==========>>> " + swftoolsExecutor); } else { throw new ConverterException( "Illegal The encoder paramter executor error : " + executorEnum + " is not support."); } if (!isWindows) { Runtime runtime = Runtime.getRuntime(); try { if (StringUtils.isNotBlank(swftoolsFontHome)) { runtime.exec(new String[] { "/bin/chmod", "755", swftoolsFontHome }); } if (StringUtils.isNotBlank(swftoolsExecutor)) { runtime.exec(new String[] { "/bin/chmod", "755", swftoolsExecutor }); } } catch (IOException e) { e.printStackTrace(); LOGGER.info(" Linux chmod 755 error. ==========>>>" + e.getCause()); } } return converterExcutor; }