List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.eclipse.mylyn.internal.monitor.usage.UsageUploadManager.java
public int getNewUid(StudyParameters studyParameters, IProgressMonitor monitor) throws UsageDataException { // TODO extract url for servlet String url = studyParameters.getUserIdServletUrl(); final PostMethod getUserIdMethod = new PostMethod(url); try {//from ww w .j ava2 s . c o m getUserIdMethod.addParameter(new NameValuePair("MylarUserID", "")); //$NON-NLS-1$//$NON-NLS-2$ AbstractWebLocation location = new WebLocation(url); HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); final int status = WebUtil.execute(httpClient, hostConfiguration, getUserIdMethod, monitor); if (status == HttpStatus.SC_OK) { InputStream inputStream = WebUtil.getResponseBodyAsStream(getUserIdMethod, monitor); try { byte[] buffer = new byte[SIZE_OF_INT]; int numBytesRead = inputStream.read(buffer); int uid = new Integer(new String(buffer, 0, numBytesRead)).intValue(); return uid; } finally { inputStream.close(); } } else { throw new UsageDataException( NLS.bind(Messages.UsageUploadManager_Error_Getting_Uid_Http_Response, status)); } } catch (final IOException e) { if (e instanceof NoRouteToHostException || e instanceof UnknownHostException) { throw new UsageDataException(Messages.UsageUploadManager_Error_Getting_Uid_No_Network, e); } else { throw new UsageDataException( NLS.bind(Messages.UsageUploadManager_Error_Getting_Uid_X, e.getClass().getCanonicalName()), e); } } finally { WebUtil.releaseConnection(getUserIdMethod, monitor); } }
From source file:org.dasein.cloud.google.network.FirewallSupport.java
@Override public Firewall getFirewall(@Nonnull String firewallId) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context has been established for this request"); }//from w w w .ja v a 2 s . com Compute gce = provider.getGoogleCompute(); try { Network firewall = gce.networks().get(ctx.getAccountNumber(), firewallId.split("fw-")[1]).execute(); List<com.google.api.services.compute.model.Firewall> rules = gce.firewalls() .list(ctx.getAccountNumber()).setFilter("network eq " + firewall.getName()).execute() .getItems(); return toFirewall(firewall, rules); } catch (IOException ex) { logger.error("An error occurred while getting firewall " + firewallId + ": " + ex.getMessage()); if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(ex.getMessage()); } }
From source file:gov.nasa.ensemble.core.jscience.csvxml.ProfileLoader.java
/** * Loads profile objects.//from w ww . ja v a 2s.c o m * @param loadDataImmediately -- set to true if the stream can't be reopened and repositioned later on demand when the datapoints are needed. * @return Profiles. * @throws ProfileLoadingException * @throws IOException */ public Collection<ProfileWithLazyDatapointsFromCsv<?>> readProfiles(boolean loadDataImmediately) throws ProfileLoadingException, IOException { InputStream urlStreamWeJustOpened = null; try { final InputStream streamWeAreReading; if (sourceStream != null) { streamWeAreReading = sourceStream; } else { ExtensibleURIConverterImpl converter = new ExtensibleURIConverterImpl(); urlStreamWeJustOpened = converter.createInputStream(sourceURI); streamWeAreReading = urlStreamWeJustOpened; } Document document = loadColumnDefinitions(streamWeAreReading); Node topLevel = document.getElementsByTagName("columns").item(0); String timeFormatName = topLevel.getAttributes().getNamedItem("timeFormat").getNodeValue(); specifiedDateFormat = InterchangeDateFormatFactory.fromName(timeFormatName); NodeList columnElements = document.getElementsByTagName("column"); int nProfiles = columnElements.getLength(); profileAndMetadataInXmlOrder = new ArrayList(nProfiles); for (int i = 0; i < nProfiles; i++) { Node item = columnElements.item(i); ProfileWithLazyDatapointsFromCsv<?> profile = createLazyProfile(item); profile.setValid(true); // see SPF-8162 String datatypeName = item.getAttributes().getNamedItem("type").getTextContent(); Datatype datatype = Datatype.valueOf(datatypeName); Node defaultValueNode = item.getAttributes().getNamedItem("defaultValue"); Object defaultValue = null; if (defaultValueNode != null) { defaultValue = parseValueCell(defaultValueNode.getTextContent(), datatype); } profileAndMetadataInXmlOrder.add(new ProfileAndMetadata(profile, datatype, defaultValue)); } List<ProfileWithLazyDatapointsFromCsv<?>> profiles = new ArrayList<ProfileWithLazyDatapointsFromCsv<?>>(); for (ProfileAndMetadata profileEtc : profileAndMetadataInXmlOrder) { profiles.add(profileEtc.getProfile()); } if (loadDataImmediately) { loadDataFromThisPointInStream(streamWeAreReading); } return profiles; } catch (IOException e) { throw e; } catch (Exception e) { throw new ProfileLoadingException(e.getClass() + ": " + e.getMessage()); } finally { if (urlStreamWeJustOpened != null) { IOUtils.closeQuietly(urlStreamWeJustOpened); } } }
From source file:org.dasein.cloud.google.network.FirewallSupport.java
@Override public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context has been established for this request"); }/*from ww w.j a va 2 s .co m*/ Compute gce = provider.getGoogleCompute(); try { List<com.google.api.services.compute.model.Firewall> rules = gce.firewalls() .list(ctx.getAccountNumber()).setFilter("network eq .*" + firewallId.split("fw-")[1]).execute() .getItems(); if (rules != null) { return toFirewallRules(rules); } else return Collections.emptyList(); } catch (IOException ex) { logger.error("An error occurred while getting firewall " + firewallId + ": " + ex.getMessage()); if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(ex.getMessage()); } }
From source file:edu.ku.brc.specify.tools.schemalocale.LocalizerApp.java
/** * /*from www . j a va 2s . c o m*/ */ protected void indexSourceFiles() { if (INDEX_DIR.exists()) { System.out.println("Cannot save index to '" + INDEX_DIR + "' directory, please delete it first"); System.exit(1); } File SRC_DIR = new File("src"); if (!SRC_DIR.exists()) { System.out.println("Source directory doesn't exist '" + SRC_DIR); System.exit(1); } Date start = new Date(); try { IndexWriter writer = new IndexWriter(FSDirectory.open(INDEX_DIR), new IndexWriterConfig(Version.LUCENE_47, new StandardAnalyzer(Version.LUCENE_47))); System.out.println("Indexing to directory '" + INDEX_DIR + "'..."); indexDocs(writer, SRC_DIR); //System.out.println("Optimizing..."); //writer.optimize(); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:databaseadapter.GenerateMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { initialize();//from w ww . ja va 2 s . com Collection<Table> tables = collectTables(); Map<Table, List<Column>> tablesColumns = collectColumns(tables); for (Map.Entry<Table, List<Column>> entry : tablesColumns.entrySet()) { Table table = entry.getKey(); List<Column> columns = entry.getValue(); table.setColumns(columns); getLog().debug("... table " + table + ":"); for (Column col : columns) getLog().debug(" \\--> column " + col); } for (Template template : templates) { if (template.isForeach()) for (Table table : tables) { String code = generateCode(table, template); File outputDirectory = template.getOutputDirectory(); if (outputDirectory == null) { outputDirectory = new File(project.getBuild().getDirectory(), "generated-sources"); outputDirectory = new File(outputDirectory, "databaseadapter"); } String[] subfolders = StringUtils.split(template.getPackage(), '.'); for (String subfolder : subfolders) outputDirectory = new File(outputDirectory, subfolder); if (!outputDirectory.exists()) outputDirectory.mkdirs(); File outputFile = new File(outputDirectory, tableToClassName(table, template) + ".java"); try { FileUtils.writeStringToFile(outputFile, code); } catch (IOException e) { throw new RuntimeException("Unable to write generated code into file '" + outputFile + "' due to a " + e.getClass().getName() + " with message '" + e.getMessage() + "'", e); } } else { String code = generateCode(tables, template); File outputDirectory = template.getOutputDirectory(); if (outputDirectory == null) { outputDirectory = new File(project.getBuild().getDirectory(), "generated-sources"); outputDirectory = new File(outputDirectory, "databaseadapter"); } String[] subfolders = StringUtils.split(template.getPackage(), '.'); for (String subfolder : subfolders) outputDirectory = new File(outputDirectory, subfolder); if (!outputDirectory.exists()) outputDirectory.mkdirs(); File outputFile = new File(outputDirectory, template.getClassName() + ".java"); try { FileUtils.writeStringToFile(outputFile, code); } catch (IOException e) { throw new RuntimeException("Unable to write generated code into file '" + outputFile + "' due to a " + e.getClass().getName() + " with message '" + e.getMessage() + "'", e); } } } }
From source file:org.runbuddy.libtomahawk.resolver.ScriptAccount.java
@SuppressLint({ "AddJavascriptInterface", "SetJavaScriptEnabled" }) public ScriptAccount(String path, boolean manuallyInstalled) { String prefix = manuallyInstalled ? "file://" : "file:///android_asset"; mPath = prefix + path;//w w w .ja v a2 s . c o m mManuallyInstalled = manuallyInstalled; String[] parts = mPath.split("/"); mName = parts[parts.length - 1]; InputStream inputStream = null; try { if (mManuallyInstalled) { File metadataFile = new File(path + File.separator + "content" + File.separator + "metadata.json"); inputStream = new FileInputStream(metadataFile); } else { inputStream = TomahawkApp.getContext().getAssets() .open(path.substring(1) + "/content/metadata.json"); } String metadataString = IOUtils.toString(inputStream, Charsets.UTF_8); mMetaData = GsonHelper.get().fromJson(metadataString, ScriptResolverMetaData.class); if (mMetaData == null) { Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount."); return; } } catch (IOException e) { Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage()); Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount."); return; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage()); } } } CookieManager.setAcceptFileSchemeCookies(true); mWebView = new WebView(TomahawkApp.getContext()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true); } WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { //noinspection deprecation settings.setDatabasePath(TomahawkApp.getContext().getDir("databases", Context.MODE_PRIVATE).getPath()); } settings.setDomStorageEnabled(true); mWebView.setWebChromeClient(new TomahawkWebChromeClient()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { //initalize WebView String data = "<!DOCTYPE html>" + "<html>" + "<head><title>" + mName + "</title></head>" + "<body>" + "<script src=\"file:///android_asset/js/rsvp-latest.min.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/cryptojs-core.js" + "\" type=\"text/javascript\"></script>"; if (mMetaData.manifest.scripts != null) { for (String scriptPath : mMetaData.manifest.scripts) { data += "<script src=\"" + mPath + "/content/" + scriptPath + "\" type=\"text/javascript\"></script>"; } } try { String[] cryptoJsScripts = TomahawkApp.getContext().getAssets().list("js/cryptojs"); for (String scriptPath : cryptoJsScripts) { data += "<script src=\"file:///android_asset/js/cryptojs/" + scriptPath + "\" type=\"text/javascript\"></script>"; } } catch (IOException e) { Log.e(TAG, "ScriptResolver: " + e.getClass() + ": " + e.getLocalizedMessage()); } data += "<script src=\"file:///android_asset/js/tomahawk_android_pre.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk-infosystem.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk_android_post.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"" + mPath + "/content/" + mMetaData.manifest.main + "\" type=\"text/javascript\"></script>" + "</body></html>"; mWebView.setWebViewClient(new ScriptWebViewClient(ScriptAccount.this)); mWebView.addJavascriptInterface(new ScriptInterface(ScriptAccount.this), SCRIPT_INTERFACE_NAME); mWebView.loadDataWithBaseURL("file:///android_asset/test.html", data, "text/html", null, null); } }); }
From source file:org.openmrs.web.servlet.ShowGraphServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *//*ww w .j a v a2s. c om*/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { JFreeChart chart = getChart(request); // get the height and width of the graph String widthString = request.getParameter("width"); String heightString = request.getParameter("height"); Integer width; Integer height; if (widthString != null && widthString.length() > 0) { width = Integer.parseInt(widthString); } else { width = 500; } if (heightString != null && heightString.length() > 0) { height = Integer.parseInt(heightString); } else { height = 300; } // get the requested mime type of the graph String mimeType = request.getParameter("mimeType"); if (mimeType == null) { mimeType = PNG_MIME_TYPE; } // Modify response to disable caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); // Write chart out to response as image try { if (JPG_MIME_TYPE.equalsIgnoreCase(mimeType)) { response.setContentType(JPG_MIME_TYPE); ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, width, height); } else if (PNG_MIME_TYPE.equalsIgnoreCase(mimeType)) { response.setContentType(PNG_MIME_TYPE); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height); } else { throw new APIException("unsupported.mime.type", (Object[]) null); } } catch (IOException e) { // if its tomcat and the user simply navigated away from the page, don't throw an error if (e.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) { // do nothing } else { log.error("Error class name: " + e.getClass().getName()); log.error("Unable to write chart", e); } } } // Add error handling above and remove this try/catch catch (Exception e) { log.error("An unknown expected exception was thrown while rendering a graph", e); } }
From source file:org.apache.tez.runtime.library.shuffle.common.HttpConnection.java
/** * Connect to source with specific timeout * /*w ww . j av a 2 s . c o m*/ * @param connectionTimeout * @return true if connection was successful * false if connection was previously cleaned up * @throws IOException upon connection failure */ public boolean connect(int connectionTimeout) throws IOException { stopWatch.reset().start(); if (connection == null) { setupConnection(); } int unit = 0; if (connectionTimeout < 0) { throw new IOException("Invalid timeout " + "[timeout = " + connectionTimeout + " ms]"); } else if (connectionTimeout > 0) { unit = Math.min(UNIT_CONNECT_TIMEOUT, connectionTimeout); } // set the connect timeout to the unit-connect-timeout connection.setConnectTimeout(unit); int connectionFailures = 0; while (true) { try { connection.connect(); connectionSucceeed = true; break; } catch (IOException ioe) { // Don't attempt another connect if already cleanedup. if (cleanup) { LOG.info("Cleanup is set to true. Not attempting to" + " connect again. Last exception was: [" + ioe.getClass().getName() + ", " + ioe.getMessage() + "]"); return false; } // update the total remaining connect-timeout connectionTimeout -= unit; // throw an exception if we have waited for timeout amount of time // note that the updated value if timeout is used here if (connectionTimeout <= 0) { throw ioe; } // reset the connect timeout for the last try if (connectionTimeout < unit) { unit = connectionTimeout; // reset the connect time out for the final connect connection.setConnectTimeout(unit); } connectionFailures++; } } if (LOG.isDebugEnabled()) { LOG.debug("Time taken to connect to " + url.toString() + " " + stopWatch.elapsedTime(TimeUnit.MILLISECONDS) + " ms; connectionFailures=" + connectionFailures); } return true; }
From source file:org.ops4j.pax.url.mvn.internal.Connection.java
/** * Returns the input stream denoted by the url.<br/> * If the url does not contain a repository the resource is searched in every repository if available, in the order * provided by the repository setting.//from w ww.ja va 2s .c om * * @return the input stream for the resource denoted by url * * @throws IOException in case of an exception during accessing the resource * @see java.net.URLConnection#getInputStream() */ @Override public InputStream getInputStream() throws IOException { connect(); LOG.debug("Resolving [" + url.toExternalForm() + "]"); final Set<DownloadableArtifact> defaultDownloadables = collectDefaultPossibleDownloads(); if (LOG.isTraceEnabled()) { LOG.trace("Possible default download locations for [" + url.toExternalForm() + "]"); for (DownloadableArtifact artifact : defaultDownloadables) { LOG.trace(" " + artifact); } } for (DownloadableArtifact artifact : defaultDownloadables) { LOG.trace("Downloading [" + artifact + "]"); try { m_configuration.enableProxy(artifact.getArtifactURL()); return artifact.getInputStream(); } catch (IOException ignore) { // go on with next repository LOG.debug(Ix2 + "Could not download [" + artifact + "]"); LOG.trace(Ix2 + "Reason [" + ignore.getClass().getName() + ": " + ignore.getMessage() + "]"); } } final Set<DownloadableArtifact> downloadables = collectPossibleDownloads(); if (LOG.isTraceEnabled()) { LOG.trace("Possible download locations for [" + url.toExternalForm() + "]"); for (DownloadableArtifact artifact : downloadables) { LOG.trace(" " + artifact); } } for (DownloadableArtifact artifact : downloadables) { LOG.trace("Downloading [" + artifact + "]"); try { m_configuration.enableProxy(artifact.getArtifactURL()); return artifact.getInputStream(); } catch (IOException ignore) { // go on with next repository LOG.debug(Ix2 + "Could not download [" + artifact + "]"); LOG.trace(Ix2 + "Reason [" + ignore.getClass().getName() + ": " + ignore.getMessage() + "]"); } } // no artifact found throw new RuntimeException("URL [" + url.toExternalForm() + "] could not be resolved."); }