List of usage examples for java.net URL getContent
public final Object getContent() throws java.io.IOException
From source file:ca.licef.lompad.Classification.java
private void initModel(boolean isInferenceNeeded) throws IOException, MalformedURLException { URL tmpUrl = new URL(this.url); InputStream is = (InputStream) tmpUrl.getContent(); Model model = null;// w ww .j a v a 2 s. com try { model = ModelFactory.createDefaultModel(); model.read(is, null); } finally { try { is.close(); } catch (java.io.IOException e) { e.printStackTrace(); } } this.model = model; if (isInferenceNeeded) computeInference(); }
From source file:com.sip.pwc.sipphone.service.Downloader.java
@Override protected void onHandleIntent(Intent intent) { HttpGet getMethod = new HttpGet(intent.getData().toString()); int result = Activity.RESULT_CANCELED; String outPath = intent.getStringExtra(EXTRA_OUTPATH); boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false); int icon = intent.getIntExtra(EXTRA_ICON, 0); String title = intent.getStringExtra(EXTRA_TITLE); boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title)); // Build notification Builder nb = new Builder(this); nb.setWhen(System.currentTimeMillis()); nb.setContentTitle(title);/*from ww w . j a v a 2 s . c o m*/ nb.setSmallIcon(android.R.drawable.stat_sys_download); nb.setOngoing(true); Intent i = new Intent(this, SipHome.class); nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)); RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif); contentView.setImageViewResource(R.id.status_icon, icon); contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text)); contentView.setProgressBar(R.id.status_progress, 50, 0, false); contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE); nb.setContent(contentView); final Notification notification = showNotif ? nb.build() : null; notification.contentView = contentView; if (!TextUtils.isEmpty(outPath)) { try { File output = new File(outPath); if (output.exists()) { output.delete(); } if (notification != null) { notificationManager.notify(NOTIF_DOWNLOAD, notification); } ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() { private int oldState = 0; @Override public void run(long progress, long total) { //Log.d(THIS_FILE, "Progress is "+progress+" on "+total); int newState = (int) Math.round(progress * 50.0f / total); if (oldState != newState) { notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false); notificationManager.notify(NOTIF_DOWNLOAD, notification); oldState = newState; } } }); boolean hasReply = client.execute(getMethod, responseHandler); if (hasReply) { if (checkMd5) { URL url = new URL(intent.getData().toString().concat(".md5sum")); InputStream content = (InputStream) url.getContent(); if (content != null) { BufferedReader br = new BufferedReader(new InputStreamReader(content)); String downloadedMD5 = ""; try { downloadedMD5 = br.readLine().split(" ")[0]; } catch (NullPointerException e) { throw new IOException("md5_verification : no sum on server"); } if (!MD5.checkMD5(downloadedMD5, output)) { throw new IOException("md5_verification : incorrect"); } } } PendingIntent pendingIntent = (PendingIntent) intent .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT); try { Runtime.getRuntime().exec("chmod 644 " + outPath); } catch (IOException e) { Log.e(THIS_FILE, "Unable to make the apk file readable", e); } Log.d(THIS_FILE, "Download finished of : " + outPath); if (pendingIntent != null) { notification.contentIntent = pendingIntent; notification.flags = Notification.FLAG_AUTO_CANCEL; notification.icon = android.R.drawable.stat_sys_download_done; notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE); notification.contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.done) // TODO should be a parameter of this class + " - Click to install"); notificationManager.notify(NOTIF_DOWNLOAD, notification); /* try { pendingIntent.send(); notificationManager.cancel(NOTIF_DOWNLOAD); } catch (CanceledException e) { Log.e(THIS_FILE, "Impossible to start pending intent for download finish"); } */ } else { Log.w(THIS_FILE, "Invalid pending intent for finish !!!"); } result = Activity.RESULT_OK; } } catch (IOException e) { Log.e(THIS_FILE, "Exception in download", e); } } if (result == Activity.RESULT_CANCELED) { notificationManager.cancel(NOTIF_DOWNLOAD); } }
From source file:com.csipsimple.service.Downloader.java
@Override protected void onHandleIntent(Intent intent) { HttpGet getMethod = new HttpGet(intent.getData().toString()); int result = Activity.RESULT_CANCELED; String outPath = intent.getStringExtra(EXTRA_OUTPATH); boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false); int icon = intent.getIntExtra(EXTRA_ICON, 0); String title = intent.getStringExtra(EXTRA_TITLE); boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title)); // Build notification Builder nb = new NotificationCompat.Builder(this); nb.setWhen(System.currentTimeMillis()); nb.setContentTitle(title);// w ww . j a v a 2 s . co m nb.setSmallIcon(android.R.drawable.stat_sys_download); nb.setOngoing(true); Intent i = new Intent(this, SipHome.class); nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)); RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif); contentView.setImageViewResource(R.id.status_icon, icon); contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text)); contentView.setProgressBar(R.id.status_progress, 50, 0, false); contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE); nb.setContent(contentView); final Notification notification = showNotif ? nb.build() : null; notification.contentView = contentView; if (!TextUtils.isEmpty(outPath)) { try { File output = new File(outPath); if (output.exists()) { output.delete(); } if (notification != null) { notificationManager.notify(NOTIF_DOWNLOAD, notification); } ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() { private int oldState = 0; @Override public void run(long progress, long total) { //Log.d(THIS_FILE, "Progress is "+progress+" on "+total); int newState = (int) Math.round(progress * 50.0f / total); if (oldState != newState) { notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false); notificationManager.notify(NOTIF_DOWNLOAD, notification); oldState = newState; } } }); boolean hasReply = client.execute(getMethod, responseHandler); if (hasReply) { if (checkMd5) { URL url = new URL(intent.getData().toString().concat(".md5sum")); InputStream content = (InputStream) url.getContent(); if (content != null) { BufferedReader br = new BufferedReader(new InputStreamReader(content)); String downloadedMD5 = ""; try { downloadedMD5 = br.readLine().split(" ")[0]; } catch (NullPointerException e) { throw new IOException("md5_verification : no sum on server"); } if (!MD5.checkMD5(downloadedMD5, output)) { throw new IOException("md5_verification : incorrect"); } } } PendingIntent pendingIntent = (PendingIntent) intent .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT); try { Runtime.getRuntime().exec("chmod 644 " + outPath); } catch (IOException e) { Log.e(THIS_FILE, "Unable to make the apk file readable", e); } Log.d(THIS_FILE, "Download finished of : " + outPath); if (pendingIntent != null) { notification.contentIntent = pendingIntent; notification.flags = Notification.FLAG_AUTO_CANCEL; notification.icon = android.R.drawable.stat_sys_download_done; notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE); notification.contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.done) // TODO should be a parameter of this class + " - Click to install"); notificationManager.notify(NOTIF_DOWNLOAD, notification); /* try { pendingIntent.send(); notificationManager.cancel(NOTIF_DOWNLOAD); } catch (CanceledException e) { Log.e(THIS_FILE, "Impossible to start pending intent for download finish"); } */ } else { Log.w(THIS_FILE, "Invalid pending intent for finish !!!"); } result = Activity.RESULT_OK; } } catch (IOException e) { Log.e(THIS_FILE, "Exception in download", e); } } if (result == Activity.RESULT_CANCELED) { notificationManager.cancel(NOTIF_DOWNLOAD); } }
From source file:com.sonetel.service.Downloader.java
@Override protected void onHandleIntent(Intent intent) { HttpGet getMethod = new HttpGet(intent.getData().toString()); int result = Activity.RESULT_CANCELED; String outPath = intent.getStringExtra(EXTRA_OUTPATH); boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false); int icon = intent.getIntExtra(EXTRA_ICON, 0); String title = intent.getStringExtra(EXTRA_TITLE); boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title)); // Build notification Builder nb = new NotificationCompat.Builder(this); nb.setWhen(System.currentTimeMillis()); nb.setContentTitle(title);/* w ww.ja v a2s. com*/ nb.setSmallIcon(android.R.drawable.stat_sys_download); nb.setOngoing(true); Intent i = new Intent(this, SipHome.class); nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)); RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif); contentView.setImageViewResource(R.id.status_icon, icon); contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text)); contentView.setProgressBar(R.id.status_progress, 50, 0, false); contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE); nb.setContent(contentView); final Notification notification = showNotif ? nb.getNotification() : null; notification.contentView = contentView; if (!TextUtils.isEmpty(outPath)) { try { File output = new File(outPath); if (output.exists()) { output.delete(); } if (notification != null) { notificationManager.notify(NOTIF_DOWNLOAD, notification); } ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() { private int oldState = 0; @Override public void run(long progress, long total) { //Log.d(THIS_FILE, "Progress is "+progress+" on "+total); int newState = (int) Math.round(progress * 50.0f / total); if (oldState != newState) { notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false); notificationManager.notify(NOTIF_DOWNLOAD, notification); oldState = newState; } } }); boolean hasReply = client.execute(getMethod, responseHandler); if (hasReply) { if (checkMd5) { URL url = new URL(intent.getData().toString().concat(".md5sum")); InputStream content = (InputStream) url.getContent(); if (content != null) { BufferedReader br = new BufferedReader(new InputStreamReader(content)); String downloadedMD5 = ""; try { downloadedMD5 = br.readLine().split(" ")[0]; } catch (NullPointerException e) { throw new IOException("md5_verification : no sum on server"); } if (!MD5.checkMD5(downloadedMD5, output)) { throw new IOException("md5_verification : incorrect"); } } } PendingIntent pendingIntent = (PendingIntent) intent .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT); try { Runtime.getRuntime().exec("chmod 644 " + outPath); } catch (IOException e) { Log.e(THIS_FILE, "Unable to make the apk file readable", e); } Log.d(THIS_FILE, "Download finished of : " + outPath); if (pendingIntent != null) { notification.contentIntent = pendingIntent; notification.flags = Notification.FLAG_AUTO_CANCEL; notification.icon = android.R.drawable.stat_sys_download_done; notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE); notification.contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.done) // TODO should be a parameter of this class + " - Click to install"); notificationManager.notify(NOTIF_DOWNLOAD, notification); /* try { pendingIntent.send(); notificationManager.cancel(NOTIF_DOWNLOAD); } catch (CanceledException e) { Log.e(THIS_FILE, "Impossible to start pending intent for download finish"); } */ } else { Log.w(THIS_FILE, "Invalid pending intent for finish !!!"); } result = Activity.RESULT_OK; } } catch (IOException e) { Log.e(THIS_FILE, "Exception in download", e); } } if (result == Activity.RESULT_CANCELED) { notificationManager.cancel(NOTIF_DOWNLOAD); } }
From source file:org.chililog.server.workbench.WorkbenchServiceTest.java
/** * We should get back a 404 file not found when we cannot route to a service * // w w w . j ava 2s.com * @throws IOException */ @Test(expected = FileNotFoundException.class) public void testNotFound() throws IOException { // Create a URL for the desired page URL url = new URL("http://localhost:8989/not/found"); url.getContent(); }
From source file:com.adwhirl.AdWhirlManager.java
private Drawable fetchImage(String urlString) { try {// w ww. ja va 2 s . c om URL url = new URL(urlString); InputStream is = (InputStream) url.getContent(); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (Exception e) { Log.e(AdWhirlUtil.ADWHIRL, "Unable to fetchImage(): ", e); return null; } }
From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java
/** * Creates JenkinsBuild if no authorization is required * @return JenkinsBuild//w w w.j a v a 2s. c o m */ private JenkinsBuild createBuild(String urlJenkinsServer, String jobName, BuildType type, I18nHelper i18nHelper) { JenkinsBuild build = new JenkinsBuild(); build.setI18nHelper(i18nHelper); String encodedJobName = URLEncoder.encodeForURL(jobName); try { URL urlBuildNumber = new URL( urlJenkinsServer + "job/" + encodedJobName + "/" + type.toString() + "/buildNumber"); build.setNumber(IOUtils.toString((InputStream) urlBuildNumber.getContent())); build.setUrl(urlJenkinsServer + "job/" + encodedJobName + "/" + build.getNumber()); } catch (MalformedURLException e) { return JenkinsBuild.UNKNOWN; } catch (IOException e) { return JenkinsBuild.UNKNOWN; } // if we were able to obtain a build number, there should also a date // and time exist ... try { URL urlTimestamp = new URL(urlJenkinsServer + "job/" + encodedJobName + "/" + type.toString() + "/buildTimestamp?format=" + DATE_FORMAT); build.setTimestamp(SIMPLE_DATE_FORMAT.parse(IOUtils.toString((InputStream) urlTimestamp.getContent()))); } catch (MalformedURLException e) { return JenkinsBuild.UNKNOWN; } catch (IOException e) { return JenkinsBuild.UNKNOWN; } catch (ParseException e) { return JenkinsBuild.UNKNOWN; } return build; }
From source file:org.kuali.ole.common.Languages.java
private Languages(String encoding) { try {//from w w w . j a v a2 s .c o m String file = null; if (ISO_639_1_CC.equals(encoding)) { file = "languages-iso-639-1-cc.xml"; } else if (ISO_639_3.equals(encoding)) { file = "languages-iso-639-3.xml"; } URL url = this.getClass().getClassLoader().getResource(file); XStream xStream = new XStream(); xStream.alias("languages", Languages.class); xStream.alias("lang", Language.class); xStream.addImplicitCollection(Languages.class, "languages", Language.class); xStream.registerConverter(new LanguageConverter()); Languages langs = (Languages) xStream.fromXML(IOUtils.toString((InputStream) url.getContent())); this.setLanguages(Collections.unmodifiableList(langs.getLanguages())); } catch (Exception e) { LOG.error(e.getMessage(), e); } }
From source file:org.languagetool.server.HTTPServerTest.java
@Test public void testHealthcheck() throws Exception { HTTPServerConfig config = new HTTPServerConfig(HTTPTools.getDefaultPort(), false); HTTPServer server = new HTTPServer(config, false); try {//from www . j a va2 s .c om server.run(); URL url = new URL("http://localhost:<PORT>/v2/healthcheck".replace("<PORT>", String.valueOf(HTTPTools.getDefaultPort()))); InputStream stream = (InputStream) url.getContent(); String response = StringTools.streamToString(stream, "UTF-8"); assertThat(response, is("OK")); } finally { server.stop(); } }
From source file:org.icefaces.samples.showcase.util.SourceCodeLoaderConnection.java
/** * Returns formatted source located in the cache, or adds to the cache and * returns the source found at sourceCodePath, removing oldest cached files * if MAX_CACHE_SIZE exceeded. * //from w ww . j av a2s. c o m * Implementing the map interface method `get` to allow parameter passing * in EL versions prior to 2.0 * * @param sourceCodePathObj The String location of the source file relative * to the web application root. * @return The XHTML formatted source code or a stack trace if the URL * could not be UTF-8 encoded. */ public String get(Object sourceCodePathObj) { if (SOURCE_SERVLET_URL == null || MAX_CACHE_SIZE == null || !(sourceCodePathObj instanceof String)) { return null; } String sourceCodePath; // Try encoding sourceCodePathObj parameter, return a stack trace // instead of source if it fails. try { sourceCodePath = URLEncoder.encode((String) sourceCodePathObj, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.severe("UTF-8 is not supported by this platform."); return ""; } CachedSource cs; // Only allow the cache to be accessed by a single user when being used // within one of these blocks. synchronized (cache) { // Search the cache for formatted source code from this path. If it is // found, update the formatted source code with the current timestamp // and return the cached source. if ((cs = (CachedSource) cache.get(sourceCodePath)) != null) { logger.finer("Source Cache Hit."); logger.finest("Hit: " + sourceCodePath); cs.timestamp = System.currentTimeMillis() / 1000; cache.put(cs.path, cs); return cs.source; } } logger.finer("Source Cache Miss."); logger.finest("Miss: " + sourceCodePath); URL servletUrl = null; InputStream inputStream = null; InputStreamReader inputReader = null; try { if (!IS_SECURE) { servletUrl = new URL(SOURCE_SERVLET_URL + sourceCodePath); inputStream = (InputStream) servletUrl.getContent(); } else { // don't use a connection, just access methods directly inputStream = SourceCodeLoaderServlet.getServlet().getSource((String) sourceCodePathObj); } brokenUrl = false; } catch (Exception e) { e.printStackTrace(); logger.severe( "Broken URL for the source code loader (" + SOURCE_SERVLET_URL + "), check your web.xml."); brokenUrl = true; } if (!brokenUrl) { try { // Set up streams and buffers for source servlet reading inputReader = new InputStreamReader(inputStream, "UTF-8"); StringBuilder buf = new StringBuilder(16384); // Read into stringBuilder until EOF int readChar; while ((readChar = inputReader.read()) != -1) { buf.append((char) readChar); } // Extract page content from <body> tag and fix nbsp for valid XHTML String ret = buf.indexOf(" ") != -1 ? buf.substring(buf.indexOf("<body>") + 6, buf.lastIndexOf("</body>")).replace(" ", " ") : buf.toString(); synchronized (cache) { // If cache is full, remove files until the newly loaded string // will fit and add it to the cache while ((ret.length() * 16) + cacheSize > MAX_CACHE_SIZE) { OrderedBidiMap iCache = cache.inverseOrderedBidiMap(); CachedSource c = (CachedSource) iCache.firstKey(); cache.remove(c.path); cacheSize -= c.source.length() * 16; logger.finer("Cache Oversized. Removing oldest file."); logger.finest("Removed: " + c.path); } cache.put(sourceCodePath, new CachedSource(sourceCodePath, ret)); cacheSize += ret.length() * 16; } // Return newly loaded and cached source return ret; } catch (MalformedURLException e) { logger.severe("Attempted to connect to malformed URL."); logger.severe("Likely either EL param or web.xml SOURCE_SERVLET_URL param is incorrectly set"); e.printStackTrace(); } catch (UnsupportedEncodingException e) { logger.severe("UTF-8 is not supported by this platform."); e.printStackTrace(); } catch (IOException e) { logger.severe("IOException raised while reading characters from Servlet response stream."); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception ignoredClose) { } } if (inputReader != null) { try { inputReader.close(); } catch (Exception ignoredClose) { } } } } return ""; }