List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.runbuddy.libtomahawk.utils.parser.XspfParser.java
public static Playlist parse(String url) { String xspfString = null;/*from w ww .ja v a 2s . c om*/ Response response = null; try { response = NetworkUtils.httpRequest(null, url, null, null, null, null, true, null); xspfString = response.body().string(); } catch (IOException e) { Log.e(TAG, "parse: " + e.getClass() + ": " + e.getLocalizedMessage()); } finally { if (response != null) { try { response.body().close(); } catch (IOException e) { Log.e(TAG, "parse: " + e.getClass() + ": " + e.getLocalizedMessage()); } } } return parseXspf(xspfString); }
From source file:wvw.utils.pc.HttpHelper.java
public static String post(String url, JSONArray headers, String data) { HttpPost httpPost = new HttpPost(url); for (int i = 0; i < headers.length(); i++) { JSONArray header = headers.getJSONArray(i); httpPost.addHeader(header.getString(0), header.getString(1)); }/*w w w . jav a2 s . c o m*/ String ret = null; try { httpPost.setEntity(new StringEntity(data)); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(httpPost); StatusLine status = response.getStatusLine(); switch (status.getStatusCode()) { case 200: ret = IOUtils.readFromStream(response.getEntity().getContent()); break; default: ret = genError(status.getReasonPhrase()); break; } } catch (IOException e) { // e.printStackTrace(); ret = genError(e.getClass() + ": " + e.getMessage()); } return ret; }
From source file:com.samczsun.helios.utils.Utils.java
public static String readProcess(Process process) { StringBuilder result = new StringBuilder(); result.append("--- BEGIN PROCESS DUMP ---").append("\n"); result.append("---- STDOUT ----").append("\n"); InputStream inputStream = process.getInputStream(); byte[] inputStreamBytes = new byte[0]; try {//from w ww. j a v a 2 s . co m inputStreamBytes = IOUtils.toByteArray(inputStream); } catch (IOException e) { result.append("An error occured while reading from stdout").append("\n"); result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n"); } finally { if (inputStreamBytes.length > 0) { result.append(new String(inputStreamBytes, StandardCharsets.UTF_8)); } } result.append("---- STDERR ----").append("\n"); inputStream = process.getErrorStream(); inputStreamBytes = new byte[0]; try { inputStreamBytes = IOUtils.toByteArray(inputStream); } catch (IOException e) { result.append("An error occured while reading from stderr").append("\n"); result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n"); } finally { if (inputStreamBytes.length > 0) { result.append(new String(inputStreamBytes, StandardCharsets.UTF_8)); } } result.append("---- EXIT VALUE ----").append("\n"); int exitValue = -0xCAFEBABE; try { exitValue = process.waitFor(); } catch (InterruptedException e) { result.append("An error occured while obtaining the exit value").append("\n"); result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n"); } finally { if (exitValue != -0xCAFEBABE) { result.append("Process finished with exit code ").append(exitValue).append("\n"); } } return result.toString(); }
From source file:com.emental.mindraider.core.search.SearchCommander.java
/** * Generate search index./* www .j a v a2s . co m*/ * * @param directory * the directory * @param rebuildSearchIndexJDialog * the rebuild search index JDialog * @throws IOException * the I/O exception */ public static void rebuild(String directory) throws IOException { if (StringUtils.isNotEmpty(directory)) { Date start = new Date(); try { // experiment in here with analyzers // SearchEngine searchEngine = new // SearchEngine(getSearchIndexPath()); // searchEngine.rebuildIndex(); IndexWriter writer = new IndexWriter(getSearchIndexPath(), new StandardAnalyzer(), true); // infiltrated tags - remove the tag information MindRaider.tagCustodian.clear(); SearchCommander.indexDocs(writer, new File(directory)); writer.optimize(); writer.close(); Date end = new Date(); String finalMessage = "FTS index rebuilt in " + (end.getTime() - start.getTime()) + " milliseconds"; StatusBar.setText(finalMessage); } catch (IOException e) { System.err.println(e.getClass() + ": " + e.getMessage()); } finally { try { MindRaider.tagCustodian.redraw(); MindRaider.tagCustodian.toRdf(); } catch (MindRaiderException e) { logger.error("Unable to save tag ontology!", e); } } } }
From source file:org.apache.hcatalog.cli.HCatCli.java
private static int processCmd(String cmd) { SessionState ss = SessionState.get(); long start = System.currentTimeMillis(); cmd = cmd.trim();/* w ww. jav a2s. co m*/ String firstToken = cmd.split("\\s+")[0].trim(); if (firstToken.equalsIgnoreCase("set")) { return new SetProcessor().run(cmd.substring(firstToken.length()).trim()).getResponseCode(); } else if (firstToken.equalsIgnoreCase("dfs")) { return new DfsProcessor(ss.getConf()).run(cmd.substring(firstToken.length()).trim()).getResponseCode(); } HCatDriver driver = new HCatDriver(); int ret = driver.run(cmd).getResponseCode(); if (ret != 0) { driver.close(); System.exit(ret); } ArrayList<String> res = new ArrayList<String>(); try { while (driver.getResults(res)) { for (String r : res) { ss.out.println(r); } res.clear(); } } catch (IOException e) { ss.err.println("Failed with exception " + e.getClass().getName() + ":" + e.getMessage() + "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); ret = 1; } catch (CommandNeedRetryException e) { ss.err.println("Failed with exception " + e.getClass().getName() + ":" + e.getMessage() + "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); ret = 1; } int cret = driver.close(); if (ret == 0) { ret = cret; } long end = System.currentTimeMillis(); if (end > start) { double timeTaken = (end - start) / 1000.0; ss.err.println("Time taken: " + timeTaken + " seconds"); } return ret; }
From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java
/** * Check if a string appear in the html page * * @param url/*from w w w . j a v a 2 s . c om*/ * URL to test * @param token * String that must be in html page * @return Cookie that identifies the was or null if the test failed. An * empty string means that no cookie was found in the request, but * the check succeeded. */ private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost, int httpProxyPort) { InputStream is = null; String cookie = null; try { HttpURLConnection connection; if (httpProxyHost != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod("GET"); is = connection.getInputStream(); // check http status code if (connection.getResponseCode() == 200) { DataInputStream dis = new DataInputStream(new BufferedInputStream(is)); StringWriter writer = new StringWriter(); IOUtils.copy(dis, writer, "UTF-8"); if (writer.toString().contains(token)) { cookie = connection.getHeaderField("Set-Cookie"); if (cookie == null) cookie = ""; } else { logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token + "'"); logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000)); } } else { logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : " + connection.getResponseMessage()); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } } catch (IOException e) { logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " (" + e.getClass().getName() + ")"); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { // just going to ignore this one } } return cookie; }
From source file:org.apache.hive.hcatalog.cli.HCatCli.java
private static int processCmd(String cmd) { SessionState ss = SessionState.get(); long start = System.currentTimeMillis(); cmd = cmd.trim();/*from w ww.j av a2s. co m*/ String firstToken = cmd.split("\\s+")[0].trim(); if (firstToken.equalsIgnoreCase("set")) { return new SetProcessor().run(cmd.substring(firstToken.length()).trim()).getResponseCode(); } else if (firstToken.equalsIgnoreCase("dfs")) { return new DfsProcessor(ss.getConf()).run(cmd.substring(firstToken.length()).trim()).getResponseCode(); } HCatDriver driver = new HCatDriver(); int ret = driver.run(cmd).getResponseCode(); if (ret != 0) { driver.close(); sysExit(ss, ret); } ArrayList<String> res = new ArrayList<String>(); try { while (driver.getResults(res)) { for (String r : res) { ss.out.println(r); } res.clear(); } } catch (IOException e) { ss.err.println("Failed with exception " + e.getClass().getName() + ":" + e.getMessage() + "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); ret = 1; } catch (CommandNeedRetryException e) { ss.err.println("Failed with exception " + e.getClass().getName() + ":" + e.getMessage() + "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); ret = 1; } int cret = driver.close(); if (ret == 0) { ret = cret; } long end = System.currentTimeMillis(); if (end > start) { double timeTaken = (end - start) / 1000.0; ss.err.println("Time taken: " + timeTaken + " seconds"); } return ret; }
From source file:org.tranche.users.UserZipFileUtil.java
/** <p>Log in. Sends an HTTP POST to the Log In URL to retrieve a valid UserZipFile.</p> * @param username/*from ww w .j av a2 s .c om*/ * @param passphrase * @return * @throws org.tranche.users.InvalidSignInException * @throws java.lang.Exception */ public static UserZipFile getUserZipFile(String username, String passphrase) throws InvalidSignInException, Exception { // check local directory File userZipFileFile = new File(usersDirectory, username + ".zip.encrypted"); File userEmailFile = new File(usersDirectory, username + "-email"); if (usersDirectory != null) { try { if (userZipFileFile.exists() && userEmailFile.exists()) { UserZipFile uzf = new UserZipFile(userZipFileFile); try { uzf.setPassphrase(passphrase); if (uzf.getCertificate() == null) { uzf.setPassphrase(SecurityUtil.SHA1(passphrase)); } } catch (Exception e) { uzf.setPassphrase(SecurityUtil.SHA1(passphrase)); } uzf.setEmail(new String(IOUtil.getBytes(userEmailFile))); if (uzf.getCertificate() != null && uzf.isValid()) { return uzf; } } } catch (Exception e) { } } // go to web site String url = ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_USER_LOG_IN_URL); if (url == null || url.equals("")) { return null; } HttpClient hc = new HttpClient(); PostMethod pm = new PostMethod(url); try { // set up the posting parameters ArrayList buf = new ArrayList(); buf.add(new NameValuePair("name", username)); buf.add(new NameValuePair("password", passphrase)); // set the request body pm.setRequestBody((NameValuePair[]) buf.toArray(new NameValuePair[0])); int returnCode = 0; try { returnCode = hc.executeMethod(pm); } catch (SSLException ssle) { throw ssle; } catch (IOException ioe) { throw new Exception("Could not connect. Please try again later. " + ioe.getClass().getSimpleName() + ": " + ioe.getMessage()); } // if not 200 (OK), there is a scripting or connection problem if (returnCode != 200) { if (returnCode == 506) { throw new InvalidSignInException(); } else { throw new Exception( "There was a problem logging in. Please try again later. (status=" + returnCode + ")"); } } else { // wait for headers to load ThreadUtil.sleep(250); // try to get the email String email = null; for (Header header : pm.getResponseHeaders("User Email")) { if (header.getName().equals("User Email")) { email = header.getValue(); } } // get the log in success for (Header header : pm.getResponseHeaders("Log In Success")) { if (header.getName().equals("Log In Success")) { if (header.getValue().equals("true")) { if (!userZipFileFile.exists()) { userZipFileFile.createNewFile(); } // read the response (a user zip file) FileOutputStream fos = null; InputStream is = null; try { fos = new FileOutputStream(userZipFileFile); is = pm.getResponseBodyAsStream(); byte[] buffer = new byte[1000]; for (int bytesRead = is.read(buffer); bytesRead > -1; bytesRead = is.read(buffer)) { fos.write(buffer, 0, bytesRead); } } finally { IOUtil.safeClose(fos); IOUtil.safeClose(is); } if (!userEmailFile.exists()) { userEmailFile.createNewFile(); } if (email != null) { try { fos = new FileOutputStream(userEmailFile); fos.write(email.getBytes()); } finally { IOUtil.safeClose(fos); } } UserZipFile userZipFile = new UserZipFile(userZipFileFile); try { userZipFile.setPassphrase(passphrase); if (userZipFile.getCertificate() == null) { userZipFile.setPassphrase(SecurityUtil.SHA1(passphrase)); } } catch (Exception e) { userZipFile.setPassphrase(SecurityUtil.SHA1(passphrase)); } userZipFile.setEmail(email); // make sure the passphrase was correct - should always be if (userZipFile.getCertificate() == null) { throw new Exception("There was a problem loading your user zip file."); } // check not yet valid if (userZipFile.isNotYetValid()) { throw new Exception("The user zip file retrieved is not yet valid."); } // check expired if (userZipFile.isExpired()) { throw new Exception("The user zip file retrieved is expired."); } return userZipFile; } } } // fallen through when login failed for (Header header : pm.getResponseHeaders("User Approved")) { if (header.getName().equals("User Approved")) { if (header.getValue().equals("true")) { throw new Exception("The password you provided is incorrect."); } else if (header.getValue().equals("false")) { throw new Exception("Your account has not yet been approved."); } } } throw new InvalidSignInException(); } } finally { pm.releaseConnection(); } }
From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuator.java
/** * Determine whether an {@link IOException} indicates a fatal issue or not. Shamelessly plagiarized from {@link * org.apache.http.impl.client.DefaultHttpRequestRetryHandler}. * * @param ex the exception to check/*from w w w.j av a2s. co m*/ * @return whether or not the caller should retry their request */ private static boolean isRecoverable(final IOException ex) { if (EXCEPTIONS_FATAL.contains(ex.getClass())) { return false; } for (final Class<? extends IOException> exceptionClass : EXCEPTIONS_FATAL) { if (exceptionClass.isInstance(ex)) { return false; } } return true; }
From source file:org.apache.hadoop.hdfs.server.datanode.BlockSender.java
/** * Converts an IOExcpetion (not subclasses) to SocketException. * This is typically done to indicate to upper layers that the error * was a socket error rather than often more serious exceptions like * disk errors./* w ww.java 2 s . c om*/ */ private static IOException ioeToSocketException(IOException ioe) { if (ioe.getClass().equals(IOException.class)) { // "se" could be a new class in stead of SocketException. IOException se = new SocketException("Original Exception : " + ioe); se.initCause(ioe); /* Change the stacktrace so that original trace is not truncated * when printed.*/ se.setStackTrace(ioe.getStackTrace()); return se; } // otherwise just return the same exception. return ioe; }