List of usage examples for java.net URLConnection connect
public abstract void connect() throws IOException;
From source file:org.geosdi.geoplatform.gui.server.service.impl.LayerService.java
@Override public boolean checkWmsGetMapUrl(String urlString) throws GeoPlatformException { try {/*w w w . j a v a 2 s . co m*/ URL url = new URL(urlString); URLConnection myURLConnection = url.openConnection(); myURLConnection.connect(); logger.debug("#################RESPONSE : {}\n\n", IOUtils.toString(myURLConnection.getInputStream())); String contentType = myURLConnection.getContentType(); logger.info("#####################CONTENT_TYPE : {}\n", contentType); if (!contentType.contains("xml")) { return true; } } catch (IOException ex) { logger.error("Error on executing Check url: {}", ex.getMessage()); throw new GeoPlatformException("Error on executing ParseURLServlet."); } return false; }
From source file:org.adaway.service.ApplyService.java
/** * Downloads files from hosts sources/* w ww .j a v a 2 s. co m*/ * * @return return code */ private int download() { Cursor enabledHostsSourcesCursor; byte data[]; int count; long currentLastModifiedOnline; int returnCode = StatusCodes.SUCCESS; // default return code if (Utils.isAndroidOnline(mService)) { showApplyNotification(mService, mService.getString(R.string.download_dialog), mService.getString(R.string.download_dialog), mService.getString(R.string.download_dialog)); // output to write into FileOutputStream out = null; try { out = mService.openFileOutput(Constants.DOWNLOADED_HOSTS_FILENAME, Context.MODE_PRIVATE); mNumberOfFailedDownloads = 0; mNumberOfDownloads = 0; // get cursor over all enabled hosts source enabledHostsSourcesCursor = ProviderHelper.getEnabledHostsSourcesCursor(mService); // iterate over all hosts sources in db with cursor if (enabledHostsSourcesCursor.moveToFirst()) { do { mNumberOfDownloads++; InputStream is = null; BufferedInputStream bis = null; String currentUrl = enabledHostsSourcesCursor .getString(enabledHostsSourcesCursor.getColumnIndex("url")); try { Log.v(Constants.TAG, "Downloading hosts file: " + currentUrl); /* change URL in download dialog */ updateApplyNotification(mService, mService.getString(R.string.download_dialog), currentUrl); /* build connection */ URL mURL = new URL(currentUrl); URLConnection connection = mURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); /* connect */ connection.connect(); is = connection.getInputStream(); bis = new BufferedInputStream(is); if (is == null) { Log.e(Constants.TAG, "Stream is null"); } /* download with progress */ data = new byte[1024]; count = 0; // run while only when thread is not cancelled while ((count = bis.read(data)) != -1) { out.write(data, 0, count); } // add line seperator to add files together in one file out.write(Constants.LINE_SEPERATOR.getBytes()); // save last modified online for later use currentLastModifiedOnline = connection.getLastModified(); ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), currentLastModifiedOnline); } catch (IOException e) { Log.e(Constants.TAG, "Exception while downloading from " + currentUrl, e); mNumberOfFailedDownloads++; // set last_modified_online of failed download to 0 (not available) ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), 0); } finally { // flush and close streams try { if (out != null) { out.flush(); } if (bis != null) { bis.close(); } if (is != null) { is.close(); } } catch (Exception e) { Log.e(Constants.TAG, "Exception on flush and closing streams.", e); } } } while (enabledHostsSourcesCursor.moveToNext()); } // close cursor in the end if (enabledHostsSourcesCursor != null && !enabledHostsSourcesCursor.isClosed()) { enabledHostsSourcesCursor.close(); } // if all downloads failed return download_fail error if (mNumberOfDownloads == mNumberOfFailedDownloads && mNumberOfDownloads != 0) { returnCode = StatusCodes.DOWNLOAD_FAIL; } } catch (Exception e) { Log.e(Constants.TAG, "Private File can not be created, Exception: " + e); returnCode = StatusCodes.PRIVATE_FILE_FAIL; } finally { try { if (out != null) { out.close(); } } catch (Exception e) { Log.e(Constants.TAG, "Exception on close of out.", e); } } } else { returnCode = StatusCodes.NO_CONNECTION; } return returnCode; }
From source file:com.music.mybarr.activities.ExampleActivity.java
private void next(final boolean manualPlay) { if (player != null) { player.stop();//from w w w. j a va 2 s. c om player.release(); player = null; } final Track track = trackQueue.poll(); if (trackQueue.size() < 3) { Log.i(TAG, "Track queue depleted, loading more tracks"); LoadMoreTracks(); } if (track == null) { Log.e(TAG, "Track is null! Size of queue: " + trackQueue.size()); return; } // Load the next track in the background and prep the player (to start buffering) // Do this in a bkg thread so it doesn't block the main thread in .prepare() AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() { @Override protected Track doInBackground(Track... params) { Track track = params[0]; try { player = rdio.getPlayerForTrack(track.key, null, manualPlay); player.prepare(); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { next(false); } }); player.start(); } catch (Exception e) { Log.e("Test", "Exception " + e); } return track; } @Override protected void onPostExecute(Track track) { updatePlayPause(true); } }; task.execute(track); // Fetch album art in the background and then update the UI on the main thread AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() { @Override protected Bitmap doInBackground(Track... params) { Track track = params[0]; try { String artworkUrl = track.albumArt.replace("square-200", "square-600"); Log.i(TAG, "Downloading album art: " + artworkUrl); Bitmap bm = null; try { URL aURL = new URL(artworkUrl); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); } catch (IOException e) { Log.e(TAG, "Error getting bitmap", e); } return bm; } catch (Exception e) { Log.e(TAG, "Error downloading artwork", e); return null; } } @Override protected void onPostExecute(Bitmap artwork) { if (artwork != null) { albumArt.setImageBitmap(artwork); } else albumArt.setImageResource(R.drawable.blank_album_art); } }; artworkTask.execute(track); Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName, track.albumName, track.artistName), Toast.LENGTH_LONG).show(); }
From source file:ubic.gemma.core.loader.entrez.EutilFetch.java
/** * see <a href="http://www.ncbi.nlm.nih.gov/corehtml/query/static/esummary_help.html">ncbi help</a> * * @param db e.g., gds./* www . ja va 2s .c o m*/ * @param searchString search string * @param mode HTML,TEXT or XML FIXME only provides XML. * @param limit - Maximum number of records to return. * @return XML * @throws IOException if there is a problem while manipulating the file */ @SuppressWarnings("SameParameterValue") // Only TEXT is used, also observe the parameter javadoc fix me note private static String fetch(String db, String searchString, Mode mode, int limit) throws IOException { URL searchUrl = new URL(EutilFetch.ESEARCH + db + "&usehistory=y&term=" + searchString + (StringUtils.isNotBlank(APIKEY) ? "&api_key=" + APIKEY : "")); URLConnection conn = null; int numTries = 0; while (conn == null && numTries < MAX_TRIES) { try { numTries++; EutilFetch.factory.setIgnoringComments(true); EutilFetch.factory.setValidating(false); Document document = EutilFetch.parseSUrlInputStream(searchUrl); NodeList countNode = document.getElementsByTagName("Count"); Node countEl = countNode.item(0); int count; try { count = Integer.parseInt(XMLUtils.getTextValue((Element) countEl)); } catch (NumberFormatException e) { throw new IOException("Could not parse count from: " + searchUrl); } if (count == 0) throw new IOException("Got no records from: " + searchUrl); NodeList qnode = document.getElementsByTagName("QueryKey"); Element queryIdEl = (Element) qnode.item(0); NodeList cknode = document.getElementsByTagName("WebEnv"); Element cookieEl = (Element) cknode.item(0); String queryId = XMLUtils.getTextValue(queryIdEl); String cookie = XMLUtils.getTextValue(cookieEl); URL fetchUrl = new URL(EutilFetch.EFETCH + db + "&mode=" + mode.toString().toLowerCase() + "&query_key=" + queryId + "&WebEnv=" + cookie + "&retmax=" + limit + (StringUtils.isNotBlank(APIKEY) ? "&api_key=" + APIKEY : "")); conn = fetchUrl.openConnection(); conn.connect(); } catch (ParserConfigurationException | SAXException e1) { throw new RuntimeException("Failed to parse XML: " + e1.getMessage(), e1); } catch (IOException e2) { if (numTries == MAX_TRIES) throw e2; log.warn(e2.getMessage()); try { Thread.sleep(500); } catch (InterruptedException e) { } } } if (conn == null) throw new IllegalStateException("Connection was null"); try (InputStream is = conn.getInputStream()) { try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) { StringBuilder buf = new StringBuilder(); String line; while ((line = br.readLine()) != null) { buf.append(line); } return buf.toString(); } } }
From source file:hudson.remoting.Launcher.java
/** * Parses the connection arguments from JNLP file given in the URL. *//* www. ja v a 2s. co m*/ public List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException { while (true) { try { URLConnection con = slaveJnlpURL.openConnection(); if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) { HttpURLConnection http = (HttpURLConnection) con; String userPassword = slaveJnlpCredentials; String encoding = new String(Base64.encodeBase64(userPassword.getBytes())); http.setRequestProperty("Authorization", "Basic " + encoding); } con.connect(); if (con instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) con; if (http.getResponseCode() >= 400) // got the error code. report that (such as 401) throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " " + http.getResponseMessage()); } Document dom; // check if this URL points to a .jnlp file String contentType = con.getHeaderField("Content-Type"); if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) { // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with. try { dom = loadDom(slaveJnlpURL, con); } catch (SAXException e) { throw new IOException( slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType); } catch (IOException e) { throw new IOException( slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType); } } else { dom = loadDom(slaveJnlpURL, con); } // exec into the JNLP launcher, to fetch the connection parameter through JNLP. NodeList argElements = dom.getElementsByTagName("argument"); List<String> jnlpArgs = new ArrayList<String>(); for (int i = 0; i < argElements.getLength(); i++) jnlpArgs.add(argElements.item(i).getTextContent()); if (slaveJnlpCredentials != null) { jnlpArgs.add("-credentials"); jnlpArgs.add(slaveJnlpCredentials); } // force a headless mode jnlpArgs.add("-headless"); return jnlpArgs; } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) { // invalid SSL certificate. One reason this happens is when the certificate is self-signed IOException x = new IOException( "Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check."); x.initCause(e); throw x; } else throw e; } catch (IOException e) { System.err.println("Failing to obtain " + slaveJnlpURL); e.printStackTrace(System.err); System.err.println("Waiting 10 seconds before retry"); Thread.sleep(10 * 1000); // retry } } }
From source file:org.openqa.selenium.server.ProxyHandler.java
protected void wireUpSslWithRemoteService(String host, SslRelay listener) throws IOException { // grab a keystore that has been signed by a CA cert that has already been imported in to the browser // note: this logic assumes the tester is using *custom and has imported the CA cert in to IE/Firefox/etc // the CA cert can be found at http://dangerous-certificate-authority.openqa.org File keystore = File.createTempFile("selenium-rc-" + host, "keystore"); String urlString = "http://dangerous-certificate-authority.openqa.org/genkey.jsp?padding=" + _sslMap.size() + "&domain=" + host; URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; int length;//from w w w .j a va 2 s . c o m FileOutputStream fos = new FileOutputStream(keystore); while ((length = is.read(buffer)) != -1) { fos.write(buffer, 0, length); } fos.close(); is.close(); listener.setKeystore(keystore.getAbsolutePath()); //listener.setKeystore("c:\\" + (_sslMap.size() + 1) + ".keystore"); listener.setNukeDirOrFile(keystore); }
From source file:com.cxic.ip.WebUrl.java
public ArrayList<String> getData() { ArrayList<String> data = new ArrayList<String>(); String line = null;/*from w w w . j a v a 2 s . c o m*/ URL address = null; try { address = new URL(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } URLConnection urlconn = null; if (useProxy) { SocketAddress addr = new InetSocketAddress(ip, port); java.net.Proxy httpProxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, addr); try { urlconn = address.openConnection(httpProxy); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { urlconn = address.openConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { urlconn.connect(); } catch (IOException e) { // TODO Auto-generated catch block return null; } BufferedReader buffreader = null; try { buffreader = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { line = buffreader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } while (line != null) { data.add(line); try { line = buffreader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return data; }
From source file:com.pk.wallpapermanager.PkWallpaperManager.java
/** * Downloads the wallpaper. May throw an exception. * <p>/*from ww w .j a v a 2 s.co m*/ * You can see download progress for the wallpaper passed * through the interface. * <p> * Note: Do NOT call this from the main UI thread! Call * downloadWallpaperAsync instead. * * @param mWall * @throws IOException */ public void downloadWallpaper(Wallpaper mWall, NotificationManager notification, Builder builder) throws IOException { // Returns and does nothing if the wallpaper is null or local if (mWall == null || mWall.isLocal()) { if (debugEnabled) Log.d(LOG_TAG, "Unable to download image. " + mWall == null ? "Wallpaper object is null." : "Wallpaper object is local."); return; } // Loop through all listeners notifying them for (WallpaperDownloadListener mListener : mWallpaperDownloadListeners) { mListener.onWallpaperDownloading(mWall, 0); } // Connect to the server URL url = new URL( mSettings.getStorageURL() + "/" + mSettings.getWallpaperPath() + "/" + mWall.getRelativeFullURL()); URLConnection connection = url.openConnection(); connection.connect(); InputStream input = new BufferedInputStream(url.openStream(), 8192); // Output stream String fileName = mWall.getTitle().length() > 0 ? mWall.getTitle() + mWall.getRelativeFullURL().substring(mWall.getRelativeFullURL().lastIndexOf(".")) : mWall.getRelativeFullURL(); File file = new File(mSettings.getSaveLocation() + "/" + fileName); file.getParentFile().mkdirs(); OutputStream output = new FileOutputStream(file); byte data[] = new byte[mSettings.getByteBuffer()]; int count, progress, total = 0; while ((count = input.read(data)) != -1) { total += count; progress = (int) ((total * 100) / mWall.getFileSize()); Log.d(LOG_TAG, "Download Progress: " + progress); // Loop through all listeners notifying them for (WallpaperDownloadListener mListener : mWallpaperDownloadListeners) { mListener.onWallpaperDownloading(mWall, progress); } // Writing data to file output.write(data, 0, count); } // Flushing output output.flush(); // Closing streams output.close(); input.close(); // Scan media for newly downloaded image new SingleMediaScanner(mContext, file).scanMedia(); // Loop through all listeners notifying them for (WallpaperDownloadListener mListener : mWallpaperDownloadListeners) { mListener.onWallpaperDownloaded(mWall); } if (debugEnabled) Log.d(LOG_TAG, "Finished downloading wallpaper!"); }
From source file:org.latticesoft.util.common.FileUtil.java
/** * Uploads a file content to an url/* w ww. ja v a 2s . c om*/ * @param url the url to upload to * @param input filename the input file to read from */ public static void uploadToURL(URL url, String inputFilename) { if (url == null || inputFilename == null) { return; } InputStream is = null; OutputStream os = null; Reader r = null; BufferedReader br = null; PrintWriter pw = null; String line = null; URLConnection conn = null; try { conn = url.openConnection(); conn.connect(); os = conn.getOutputStream(); is = FileUtil.getInputStream(inputFilename); r = new InputStreamReader(is); br = new BufferedReader(r); pw = new PrintWriter(os); do { line = br.readLine(); if (line != null) { pw.println(line); } } while (line != null); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } finally { try { br.close(); } catch (Exception e) { } try { r.close(); } catch (Exception e) { } try { is.close(); } catch (Exception e) { } try { pw.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } }