List of usage examples for java.net URLConnection connect
public abstract void connect() throws IOException;
From source file:org.wattdepot.client.http.api.collector.EGaugeCollector.java
@Override public void run() { Measurement meas = null;/*from ww w. j av a 2 s . com*/ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); // Have to make HTTP connection manually so we can set proper timeouts URL url = new URL(eGaugeUri); URLConnection httpConnection; httpConnection = url.openConnection(); // Set both connect and read timeouts to 15 seconds. No point in long // timeouts since the // sensor will retry before too long anyway. httpConnection.setConnectTimeout(15 * 1000); httpConnection.setReadTimeout(15 * 1000); httpConnection.connect(); // Record current time as close approximation to time for reading we are // about to make Date timestamp = new Date(); Document doc = builder.parse(httpConnection.getInputStream()); XPathFactory factory = XPathFactory.newInstance(); XPath powerXpath = factory.newXPath(); XPath energyXpath = factory.newXPath(); // Path to get the current power consumed measured by the meter in watts String exprPowerString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/i/text()"; XPathExpression exprPower = powerXpath.compile(exprPowerString); // Path to get the energy consumed month to date in watt seconds String exprEnergyString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/v/text()"; XPathExpression exprEnergy = energyXpath.compile(exprEnergyString); Object powerResult = exprPower.evaluate(doc, XPathConstants.NUMBER); Object energyResult = exprEnergy.evaluate(doc, XPathConstants.NUMBER); Double value = null; // power is given in W Amount<?> power = Amount.valueOf((Double) powerResult, SI.WATT); // energy given in Ws Amount<?> energy = Amount.valueOf((Double) energyResult, SI.WATT.times(SI.SECOND)); if (isPower()) { value = power.to(measUnit).getEstimatedValue(); } else { value = energy.to(measUnit).getEstimatedValue(); } meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit); } catch (MalformedURLException e) { System.err.format("URI %s was invalid leading to malformed URL%n", eGaugeUri); } catch (XPathExpressionException e) { System.err.println("Bad XPath expression, this should never happen."); } catch (ParserConfigurationException e) { System.err.println("Unable to configure XML parser, this is weird."); } catch (SAXException e) { System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } catch (IOException e) { System.err.format( "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } if (meas != null) { try { this.client.putMeasurement(depository, meas); } catch (MeasurementTypeException e) { System.err.format("%s does not store %s measurements%n", depository.getName(), meas.getMeasurementType()); } if (debug) { System.out.println(meas); } } }
From source file:com.bt.heliniumstudentapp.UpdateClass.java
@Override protected String doInBackground(Void... Void) { try {//from w w w .j a v a2 s . co m URLConnection connection = new URL(HeliniumStudentApp.URL_UPDATE_CHANGELOG).openConnection(); connection.setConnectTimeout(HeliniumStudentApp.TIMEOUT_CONNECT); connection.setReadTimeout(HeliniumStudentApp.TIMEOUT_READ); connection.setRequestProperty("Accept-Charset", HeliniumStudentApp.CHARSET); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + HeliniumStudentApp.CHARSET); connection.connect(); final Scanner line = new Scanner(connection.getInputStream()).useDelimiter("\\A"); final String html = line.hasNext() ? line.next() : ""; ((HttpURLConnection) connection).disconnect(); if (((HttpURLConnection) connection).getResponseCode() == 200) return html; else return null; } catch (IOException e) { return null; } }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
/** * @throws Exception/*w w w.j a v a2 s. c om*/ */ @Test public void testResponseHeader() throws Exception { final String headerValue = "bla blah"; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, Response response) throws HandlerException { log.info("handling testResponseHeader"); response.setHeader(HeaderName.COOKIE, headerValue); } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); URLConnection connection = serverURL.openConnection(); connection.connect(); assertEquals(headerValue, connection.getHeaderField("Cookie")); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
/** * @throws Exception//from w ww .j av a 2s . c o m */ @Test public void testScheme() throws Exception { final URIScheme[] schemes = new URIScheme[1]; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, Response response) throws HandlerException { log.info("handling scheme-test"); schemes[0] = request.getScheme(); } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); URLConnection connection = serverURL.openConnection(); connection.connect(); //this is for the connection to get real connection.getHeaderField("Cookie"); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } assertEquals(URIScheme.HTTP, schemes[0]); }
From source file:org.gephi.streaming.impl.StreamingControllerImpl.java
private void sendEvent(final StreamingEndpoint endpoint, GraphEvent event) { logger.log(Level.FINE, "Sending event {0}", event.toString()); try {/*from www . ja v a2 s.c om*/ URL url = new URL(endpoint.getUrl(), endpoint.getUrl().getFile() + "?operation=updateGraph&format=" + endpoint.getStreamType().getType()); URLConnection connection = url.openConnection(); // Workaround for Bug https://issues.apache.org/jira/browse/CODEC-89 String base64Encoded = Base64 .encodeBase64String((endpoint.getUser() + ":" + endpoint.getPassword()).getBytes()); base64Encoded = base64Encoded.replaceAll("\r\n?", ""); connection.setRequestProperty("Authorization", "Basic " + base64Encoded); connection.setDoOutput(true); connection.connect(); StreamWriterFactory writerFactory = Lookup.getDefault().lookup(StreamWriterFactory.class); OutputStream out = null; try { out = connection.getOutputStream(); } catch (UnknownServiceException e) { // protocol doesn't support output return; } StreamWriter writer = writerFactory.createStreamWriter(endpoint.getStreamType(), out); writer.handleGraphEvent(event); out.flush(); out.close(); connection.getInputStream().close(); } catch (IOException ex) { logger.log(Level.FINE, null, ex); } }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
@Test public void testHeaderAddedInMessageBody() throws Exception { final String serverHeaderValue = "Ad-Hoc testing server"; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, final Response response) throws HandlerException { response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { try { response.setHeader(HeaderName.SERVER, serverHeaderValue); } catch (HandlerException ex) { throw new RuntimeException(ex); }/* w ww .j a v a 2 s.c o m*/ ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes()); out.write(bb); } }); } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); URLConnection connection = serverURL.openConnection(); connection.connect(); // for the handler to be invoked, something of the response has to // be asked assertEquals(serverHeaderValue, connection.getHeaderField("server")); connection.getContentLength(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } }
From source file:GridFDock.DataDistribute.java
public int getFileSize1(String server, String user, String pswd, String path, String filename, int port) { URL url = null;//from ww w . j a v a 2 s . c o m URLConnection con = null; int c; int t = 0; BufferedInputStream bis; try { url = new URL("ftp://" + user + ":" + pswd + "@" + server + ":" + port + path + "/" + filename); url.getFile().length(); con = url.openConnection(); con.connect(); InputStream urlfs = con.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((c = urlfs.read()) != -1) out.write((byte) c); urlfs.close(); t = out.size(); // return loadmap (new ByteArrayInputStream(out.toByteArray()); } catch (MalformedURLException e) { System.out.println("When get the size of file from site, the url is wrong."); } catch (IOException e) { System.out.println( "When get the size of file from site, it can not open site or the file does not exist."); } return t; }
From source file:com.twitterdev.rdio.app.RdioApp.java
private void next(final boolean manualPlay) { if (player != null) { player.stop();//from ww w. j a va 2s . co m 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]; final String trackName = track.artistName; final String artist = track.trackName; try { player = rdio.getPlayerForTrack(track.key, null, manualPlay); player.prepare(); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { next(false); } }); player.start(); new getSearch().execute(track.trackName); runOnUiThread(new Runnable() { @Override public void run() { TextView a = (TextView) findViewById(R.id.artist); //a.setText(artist); TextView t = (TextView) findViewById(R.id.track); //t.setText(trackName); } }); } 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) { int imageWidth = artwork.getWidth(); int imageHeight = artwork.getHeight(); DisplayMetrics dimension = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dimension); int newWidth = dimension.widthPixels; float scaleFactor = (float) newWidth / (float) imageWidth; int newHeight = (int) (imageHeight * scaleFactor); artwork = Bitmap.createScaledBitmap(artwork, newWidth, newHeight, true); //albumArt.setImageBitmap(bitmap); albumArt.setAdjustViewBounds(true); 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:CB_Utils.Util.Downloader.java
/** * Start downloading the remote resource. The target object should not be accessed until after calling waitUntilCompleted(). *///w ww . ja va 2 s . c o m @Override public void run() { synchronized (stateLock) { if (started) { return; } else { started = true; running = true; } } BufferedInputStream bis = null; BufferedOutputStream bos = null; BufferedReader br = null; try { /* open connection to the URL */ checkState(); progressString = "Opening connection to remote resource"; progressUpdated = true; final URLConnection link; try { link = url.openConnection(); link.connect(); } catch (Exception e) { progressString = "Failed to open connection to remote resource"; progressUpdated = true; throw e; } /* get length of the remote resource */ checkState(); progressString = "Getting length of remote resource"; progressUpdated = true; /* get size of webpage in bytes; -1 if unknown */ final int length = link.getContentLength(); synchronized (lengthLock) { totalLength = length; } progressUpdated = true; /* open input stream to remote resource */ checkState(); progressString = "Opening input stream to remote resource"; progressUpdated = true; InputStream input = null; try { if (totalLength < 1) { // load with http Request HttpGet httppost = new HttpGet(url.toString()); // Execute HTTP Post Request try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, HttpUtils.conectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, HttpUtils.socketTimeout); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httppost); input = response.getEntity().getContent(); } catch (ConnectTimeoutException e1) { e1.printStackTrace(); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } else { input = link.getInputStream(); } if (target instanceof File) { bis = new BufferedInputStream(input); } else if (target instanceof StringBuilder) { final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH); /* look for charset, if specified */ String charset = null; final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType); if (m.find()) { charset = m.group(1).trim(); } if ((charset != null) && charset.length() > 0) { try { br = new BufferedReader(new InputStreamReader(input, charset)); } catch (Exception e) { br = null; } } if (br == null) { br = new BufferedReader(new InputStreamReader(input)); } } } catch (Exception e) { progressString = "Failed to open input stream to remote resource"; progressUpdated = true; throw e; } /* open output stream, if necessary */ if (target instanceof File) { checkState(); progressString = "Opening output stream to local file"; progressUpdated = true; try { /* create parent directories, if necessary */ final File f = (File) target; final File parent = f.getParentFile(); if ((parent != null) && !parent.exists()) { parent.mkdirs(); } bos = new BufferedOutputStream(f.getFileOutputStream()); } catch (Exception e) { progressString = "Failed to open output stream to local file"; progressUpdated = true; throw e; } } /* download remote resource iteratively */ progressString = "Downloading"; progressUpdated = true; try { if (target instanceof File) { final byte[] byteBuffer = new byte[BUFFER_SIZE]; while (true) { checkState(); final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE); /* check for end-of-stream */ if (byteCount == -1) { break; } bos.write(byteBuffer, 0, byteCount); synchronized (lengthLock) { downloadedLength += byteCount; } progressUpdated = true; } } else if (target instanceof StringBuilder) { final char[] charBuffer = new char[BUFFER_SIZE]; final StringBuilder sb = (StringBuilder) target; while (true) { checkState(); final int charCount = br.read(charBuffer, 0, BUFFER_SIZE); /* check for end-of-stream */ if (charCount == -1) { break; } sb.append(charBuffer, 0, charCount); synchronized (lengthLock) { downloadedLength += charCount; /* may be inaccurate because byte != char */ } progressUpdated = true; } } } catch (Exception e) { progressString = "Failed to download remote resource"; progressUpdated = true; throw e; } /* download completed successfully */ progressString = "Download completed"; progressUpdated = true; } catch (Exception e) { error = e; } finally { /* clean-up */ for (Closeable c : new Closeable[] { bis, br, bos }) { if (c != null) { try { c.close(); } catch (Exception e) { /* ignore */ } } } synchronized (stateLock) { running = false; completed = true; } } }
From source file:edu.harvard.i2b2.eclipse.LoginView.java
private void getCellStatus(StatusLabelPaintListener statusLabelPaintListener2, Label statusLabel) { StringBuffer result = new StringBuffer(); boolean coreDown = false; if (userInfoBean.getCellList() == null) { statusLabelPaintListener.setOvalColor(badColor); return;//w w w. j a va 2 s . c om } for (String cellID : userInfoBean.getCellList()) { try { URL url = new URL(userInfoBean.getCellDataUrl(cellID)); URLConnection connection = url.openConnection(); connection.connect(); } catch (MalformedURLException e) { // new URL() failed log.debug(e.getMessage()); if (userInfoBean.isCoreCell(cellID)) coreDown = true; result.append(userInfoBean.getCellName(cellID)); result.append("\n"); //$NON-NLS-1$ } catch (IOException e) { // openConnection() failed log.debug(e.getMessage()); if (userInfoBean.isCoreCell(cellID)) coreDown = true; result.append(userInfoBean.getCellName(cellID)); result.append("\n"); //$NON-NLS-1$ } } if (result.length() > 0) { statusOvalLabel .setToolTipText(Messages.getString("LoginView.TooltipCellUnavailable") + result.toString()); //$NON-NLS-1$ if (coreDown) statusLabelPaintListener.setOvalColor(badColor); else statusLabelPaintListener.setOvalColor(warningColor); } }