List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:tree.love.providers.downloads.DownloadThread.java
/** * Read headers from the HTTP response and store them into local state. *//*from w w w . j a v a 2 s . c o m*/ private void readResponseHeaders(State state, HttpURLConnection conn) throws StopRequestException { state.mContentDisposition = conn.getHeaderField("Content-Disposition"); state.mContentLocation = conn.getHeaderField("Content-Location"); if (state.mMimeType == null) { state.mMimeType = normalizeMimeType(conn.getContentType()); } state.mHeaderETag = conn.getHeaderField("ETag"); final String transferEncoding = conn.getHeaderField("Transfer-Encoding"); if (transferEncoding == null) { state.mContentLength = getHeaderFieldLong(conn, "Content-Length", -1); } else { Log.i(TAG, "Ignoring Content-Length since Transfer-Encoding is also defined"); state.mContentLength = -1; } state.mTotalBytes = state.mContentLength; mInfo.mTotalBytes = state.mContentLength; final boolean noSizeInfo = state.mContentLength == -1 && (transferEncoding == null || !transferEncoding.equalsIgnoreCase("chunked")); if (!mInfo.mNoIntegrity && noSizeInfo) { throw new StopRequestException(STATUS_CANNOT_RESUME, "can't know size of download, giving up"); } }
From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceTest.java
@Test @RunAsClient//from w ww . j a v a 2 s .c o m public void testUpdateAssetFromAtom(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); //System.out.println(GetContent(connection)); InputStream in = connection.getInputStream(); assertNotNull(in); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals(baseURL.getPath() + "rest/packages/restPackage1/assets/model1", entry.getBaseUri().getPath()); assertEquals("model1", entry.getTitle()); assertNotNull(entry.getPublished()); assertNotNull(entry.getAuthor().getName()); assertEquals("desc for model1", entry.getSummary()); //assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(), entry.getContentMimeType().getPrimaryType()); assertEquals(baseURL.getPath() + "rest/packages/restPackage1/assets/model1/binary", entry.getContentSrc().getPath()); ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA); ExtensibleElement archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED); assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE); assertEquals("Draft", stateExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT); assertEquals("model.drl", formatExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement uuidExtension = metadataExtension.getExtension(Translator.UUID); assertNotNull(uuidExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES); assertEquals("AssetPackageResourceTestCategory", categoryExtension.getSimpleExtension(Translator.VALUE)); connection.disconnect(); //Update category. Add a new category tag categoryExtension.addSimpleExtension(Translator.VALUE, "AssetPackageResourceTestCategory2"); //Update state stateExtension.getExtension(Translator.VALUE).setText("Dev"); //Update format formatExtension.getExtension(Translator.VALUE).setText("anotherformat"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML); connection.setDoOutput(true); entry.writeTo(connection.getOutputStream()); assertEquals(204, connection.getResponseCode()); connection.disconnect(); //Verify again connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); //System.out.println(GetContent(connection)); in = connection.getInputStream(); assertNotNull(in); doc = abdera.getParser().parse(in); entry = doc.getRoot(); metadataExtension = entry.getExtension(Translator.METADATA); archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED); assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE)); stateExtension = metadataExtension.getExtension(Translator.STATE); assertEquals("Dev", stateExtension.getSimpleExtension(Translator.VALUE)); formatExtension = metadataExtension.getExtension(Translator.FORMAT); assertEquals("anotherformat", formatExtension.getSimpleExtension(Translator.VALUE)); categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES); List<Element> categoryValues = categoryExtension.getExtensions(Translator.VALUE); assertTrue(categoryValues.size() == 2); boolean foundCategory1 = false; boolean foundCategory2 = false; for (Element cat : categoryValues) { String catgoryValue = cat.getText(); if ("AssetPackageResourceTestCategory".equals(catgoryValue)) { foundCategory1 = true; } if ("AssetPackageResourceTestCategory2".equals(catgoryValue)) { foundCategory2 = true; } } assertTrue(foundCategory1); assertTrue(foundCategory2); }
From source file:com.github.hexocraftapi.updater.updater.Downloader.java
/** * Download the file and save it to the updater folder. */// ww w.j ava2s .c o m private boolean downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { // Init connection HttpURLConnection connection = (HttpURLConnection) initConnection(this.update.getDownloadUrl()); // always check HTTP response code first int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); connection = (HttpURLConnection) initConnection(new URL(newUrl)); responseCode = connection.getResponseCode(); } // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String fileURL = this.update.getDownloadUrl().toString(); String disposition = connection.getHeaderField("Content-Disposition"); String contentType = connection.getContentType(); int fileLength = connection.getContentLength(); // extracts file name from header field if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) fileName = disposition.substring(index + 10, disposition.length() - 1); } // extracts file name from URL else fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); // opens input stream from the HTTP connection in = new BufferedInputStream(connection.getInputStream()); // opens an output stream to save into file fout = new FileOutputStream(new File(this.updateFolder, fileName)); log(Level.INFO, "About to download a new update: " + this.update.getVersion().toString()); final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) fout.write(buffer, 0, bytesRead); log(Level.INFO, "File downloaded: " + fileName); } } catch (Exception ex) { log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful."); return false; } finally { try { if (in != null) in.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } try { if (fout != null) fout.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } return true; } }
From source file:com.bigstep.datalake.DLFileSystem.java
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream) throws IOException { if (c.getContentLength() == 0) { return null; }/*from w ww. j a va2s.c o m*/ final InputStream in = useErrorStream ? c.getErrorStream() : c.getInputStream(); if (in == null) { throw new IOException("The " + (useErrorStream ? "error" : "input") + " stream is null."); } try { final String contentType = c.getContentType(); if (contentType != null) { final MediaType parsed = MediaType.valueOf(contentType); if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) { throw new IOException("Content-Type \"" + contentType + "\" is incompatible with \"" + MediaType.APPLICATION_JSON + "\" (parsed=\"" + parsed + "\")"); } } final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Gson gson = new Gson(); return gson.fromJson(reader, Map.class); } finally { in.close(); } }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a pkcs12 with a clear-text password *///from w ww. j ava2 s. c o m @Test public void test09RequestPKCS12ClearPassword() throws Exception { log.trace(">test01RequestPKCS12()"); // Create a user with a clear-text password setupUser(SecConst.TOKEN_SOFT_P12, true); assertEquals("end entity password wasn't set", "foo123", findPassword(TEST_USERNAME)); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo123&keylength=2048").getBytes("UTF-8")); os.close(); assertEquals("Response code", 200, con.getResponseCode()); // Some appserver (Weblogic) responds with // "application/x-pkcs12; charset=UTF-8" String contentType = con.getContentType(); assertTrue("contentType was " + contentType, contentType.startsWith("application/x-pkcs12")); // First read the response and then close the connection try { con.getInputStream().skip(99999); } catch (EOFException e) { /* Ignore */ } con.disconnect(); assertTrue("password wasn't cleared", StringUtils.isEmpty(findPassword(TEST_USERNAME))); log.trace("<test01RequestPKCS12()"); }
From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java
@Test @RunAsClient/* w w w . j a va2 s . c o m*/ public void testUpdateAssetFromAtom(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model5"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); //System.out.println(GetContent(connection)); InputStream in = connection.getInputStream(); assertNotNull(in); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals(baseURL.getPath() + "rest/packages/restPackage1/assets/model5", entry.getBaseUri().getPath()); assertEquals("model5", entry.getTitle()); assertNotNull(entry.getPublished()); assertNotNull(entry.getAuthor().getName()); assertEquals("desc for model5", entry.getSummary()); //assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(), entry.getContentMimeType().getPrimaryType()); assertEquals(baseURL.getPath() + "rest/packages/restPackage1/assets/model5/binary", entry.getContentSrc().getPath()); ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA); ExtensibleElement archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED); assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE); assertEquals("Draft", stateExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT); assertEquals("model.drl", formatExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement uuidExtension = metadataExtension.getExtension(Translator.UUID); assertNotNull(uuidExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES); assertEquals("AssetPackageResourceTestCategory", categoryExtension.getSimpleExtension(Translator.VALUE)); connection.disconnect(); //Update category. Add a new category tag categoryExtension.addSimpleExtension(Translator.VALUE, "AssetPackageResourceTestCategory2"); //Update state stateExtension.<Element>getExtension(Translator.VALUE).setText("Dev"); //Update format formatExtension.<Element>getExtension(Translator.VALUE).setText("anotherformat"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_ATOM_XML); connection.setDoOutput(true); entry.writeTo(connection.getOutputStream()); assertEquals(204, connection.getResponseCode()); connection.disconnect(); //Verify again connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); //System.out.println(GetContent(connection)); in = connection.getInputStream(); assertNotNull(in); doc = abdera.getParser().parse(in); entry = doc.getRoot(); metadataExtension = entry.getExtension(Translator.METADATA); archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED); assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE)); stateExtension = metadataExtension.getExtension(Translator.STATE); assertEquals("Dev", stateExtension.getSimpleExtension(Translator.VALUE)); formatExtension = metadataExtension.getExtension(Translator.FORMAT); assertEquals("anotherformat", formatExtension.getSimpleExtension(Translator.VALUE)); categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES); List<Element> categoryValues = categoryExtension.getExtensions(Translator.VALUE); assertTrue(categoryValues.size() == 2); boolean foundCategory1 = false; boolean foundCategory2 = false; for (Element cat : categoryValues) { String catgoryValue = cat.getText(); if ("AssetPackageResourceTestCategory".equals(catgoryValue)) { foundCategory1 = true; } if ("AssetPackageResourceTestCategory2".equals(catgoryValue)) { foundCategory2 = true; } } assertTrue(foundCategory1); assertTrue(foundCategory2); url = new URL(baseURL, "rest/packages/restPackage1/assets/model5/source"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.TEXT_PLAIN); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.TEXT_PLAIN, connection.getContentType()); String result = IOUtils.toString(connection.getInputStream()); assertTrue(result.contains("declare Album5")); assertTrue(result.contains("genre5: String")); }
From source file:com.portfolio.data.attachment.XSLService.java
void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { /// Receive answer InputStream in;// w w w. j a v a 2 s . c om try { in = connection.getInputStream(); } catch (Exception e) { System.out.println(e.toString()); in = connection.getErrorStream(); } String ref = null; if (referer != null) { int first = referer.indexOf('/', 7); int last = referer.lastIndexOf('/'); ref = referer.substring(first, last); } response.setContentType(connection.getContentType()); response.setStatus(connection.getResponseCode()); response.setContentLength(connection.getContentLength()); /// Transfer headers Map<String, List<String>> headers = connection.getHeaderFields(); int size = headers.size(); for (int i = 1; i < size; ++i) { String key = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); // response.setHeader(key, value); response.addHeader(key, value); } /// Deal with correct path with set cookie List<String> setValues = headers.get("Set-Cookie"); if (setValues != null) { String setVal = setValues.get(0); int pathPlace = setVal.indexOf("Path="); if (pathPlace > 0) { setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break setVal = setVal + ref; response.setHeader("Set-Cookie", setVal); } } /// Write back data DataInputStream stream = new DataInputStream(in); byte[] buffer = new byte[1024]; // int size; ServletOutputStream out = null; try { out = response.getOutputStream(); while ((size = stream.read(buffer, 0, buffer.length)) != -1) out.write(buffer, 0, size); } catch (Exception e) { System.out.println(e.toString()); System.out.println("Writing messed up!"); } finally { in.close(); out.flush(); // close() should flush already, but Tomcat 5.5 doesn't out.close(); } }
From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java
private int refreshFeed(String feedId, long keepDateBorderTime) { RssAtomParser handler = null;// w w w . ja v a 2 s. c o m ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null); if (cursor.moveToFirst()) { int urlPosition = cursor.getColumnIndex(FeedColumns.URL); int idPosition = cursor.getColumnIndex(FeedColumns._ID); int titlePosition = cursor.getColumnIndex(FeedColumns.NAME); int fetchModePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE); int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE); int iconPosition = cursor.getColumnIndex(FeedColumns.ICON); int retrieveFullscreenPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT); /* ModPrivacyVandaag: if Fetchmode = 99, do not refresh this feed. */ int fetchMode = cursor.getInt(fetchModePosition); if (fetchMode == FETCHMODE_DO_NOT_FETCH) { cursor.close(); return 0; } // end of this added block of code; commented out initialize of fetchmode on line 520 String id = cursor.getString(idPosition); HttpURLConnection connection = null; try { String feedUrl = cursor.getString(urlPosition); connection = NetworkUtils.setupConnection(feedUrl); String contentType = connection.getContentType(); handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), keepDateBorderTime, id, cursor.getString(titlePosition), feedUrl, cursor.getInt(retrieveFullscreenPosition) == 1); handler.setFetchImages(NetworkUtils.needDownloadPictures()); // Log.e (TAG,"feedUrl = "+feedUrl); if (fetchMode == 0) { if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) { BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); String line; int posStart = -1; while ((line = reader.readLine()) != null) { if (line.contains(HTML_BODY)) { break; } else { Matcher matcher = FEED_LINK_PATTERN.matcher(line); if (matcher.find()) { // not "while" as only one link is needed line = matcher.group(); posStart = line.indexOf(HREF); if (posStart > -1) { String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10)) .replace(Constants.AMP_SG, Constants.AMP); ContentValues values = new ContentValues(); if (url.startsWith(Constants.SLASH)) { int index = feedUrl.indexOf('/', 8); if (index > -1) { url = feedUrl.substring(0, index) + url; } else { url = feedUrl + url; } } else if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) { url = feedUrl + '/' + url; } values.put(FeedColumns.URL, url); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); connection.disconnect(); connection = NetworkUtils.setupConnection(url); contentType = connection.getContentType(); break; } } } } // this indicates a badly configured feed if (posStart == -1) { connection.disconnect(); connection = NetworkUtils.setupConnection(feedUrl); contentType = connection.getContentType(); } } if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8)); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException ignored) { fetchMode = FETCHMODE_REENCODE; } } else { fetchMode = FETCHMODE_REENCODE; } } else { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(connection.getInputStream())); char[] chars = new char[20]; int length = bufferedReader.read(chars); String xmlDescription = new String(chars, 0, length); connection.disconnect(); connection = NetworkUtils.setupConnection(connection.getURL()); int start = xmlDescription.indexOf(ENCODING); if (start > -1) { try { Xml.findEncodingByName(xmlDescription.substring(start + 10, xmlDescription.indexOf('"', start + 11))); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException ignored) { fetchMode = FETCHMODE_REENCODE; } } else { // absolutely no encoding information found fetchMode = FETCHMODE_DIRECT; } } ContentValues values = new ContentValues(); values.put(FeedColumns.FETCH_MODE, fetchMode); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); } switch (fetchMode) { default: case FETCHMODE_DIRECT: { if (contentType != null) { int index = contentType.indexOf(CHARSET); int index2 = contentType.indexOf(';', index); InputStream inputStream = connection.getInputStream(); Xml.parse(inputStream, Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8)), handler); } else { InputStreamReader reader = new InputStreamReader(connection.getInputStream()); Xml.parse(reader, handler); } break; } case FETCHMODE_REENCODE: { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = connection.getInputStream(); byte[] byteBuffer = new byte[4096]; int n; while ((n = inputStream.read(byteBuffer)) > 0) { outputStream.write(byteBuffer, 0, n); } String xmlText = outputStream.toString(); int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1; if (start > -1) { Xml.parse(new StringReader(new String(outputStream.toByteArray(), xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler); } else { // use content type if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { StringReader reader = new StringReader(new String(outputStream.toByteArray(), index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8))); Xml.parse(reader, handler); } catch (Exception e) { Log.e("Privacy Vandaag: ", "Error reading string " + e.getMessage()); } } else { StringReader reader = new StringReader(xmlText); Xml.parse(reader, handler); } } } break; } } connection.disconnect(); } catch (FileNotFoundException e) { if (handler == null || (!handler.isDone() && !handler.isCancelled())) { ContentValues values = new ContentValues(); // resets the fetch mode to determine it again later values.put(FeedColumns.FETCH_MODE, 0); values.put(FeedColumns.ERROR, getString(R.string.error_feed_error)); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); } } catch (Throwable e) { if (handler == null || (!handler.isDone() && !handler.isCancelled())) { ContentValues values = new ContentValues(); // resets the fetch mode to determine it again later values.put(FeedColumns.FETCH_MODE, 0); values.put(FeedColumns.ERROR, e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process)); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); handler = null; // If an error has occurred, reset the new articles counter for this feed to avoid notifications. } } finally { /* check and optionally find favicon */ /* No longer needed, because the icons of the feeds are included in the package */ /* try { if (handler != null && cursor.getBlob(iconPosition) == null) { String feedLink = handler.getFeedLink(); if (feedLink != null) { NetworkUtils.retrieveFavicon(this, new URL(feedLink), id); } else { NetworkUtils.retrieveFavicon(this, connection.getURL(), id); } } } catch (Throwable ignored) { } */ if (connection != null) { connection.disconnect(); } } } cursor.close(); int newArticles = (handler != null) ? handler.getNewCount() : 0; //Log.e(TAG, "Test notification is gegeven voor feedID " + feedId); //if (newArticles == 0 ) newArticles =2; // ONLY FOR TESTING !!!! // Check of meldingen voor deze feed aanstaat, anders newArticles op 0 zetten if (newArticles > 0) { boolean notifyFeed = true; switch (Integer.parseInt(feedId)) { case 1: // feedID Privacy Barometer notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYBAROMETER, true); break; case 2: // feedID Bits of Freedom notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_BITSOFFREEDOM, true); break; case 3: // feedID Privacy First notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYFIRST, true); break; case 4: // feedID Autoriteit Persoonsgegevens notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_AUTORITEITPERSOONSGEGEVENS, true); } if (!notifyFeed) newArticles = 0; // geen melding als de meldingen voor deze feed uitstaan. } //Log.e(TAG, "Nieuwe artikelen is " + newArticles); return newArticles; }
From source file:org.apache.slider.core.restclient.UrlConnectionOperations.java
public HttpOperationResponse execHttpOperation(HttpVerb verb, URL url, byte[] payload, String contentType) throws IOException, AuthenticationException { HttpURLConnection conn = null; HttpOperationResponse outcome = new HttpOperationResponse(); int resultCode; byte[] body = null; log.debug("{} {} spnego={}", verb, url, useSpnego); boolean doOutput = verb.hasUploadBody(); if (doOutput) { Preconditions.checkArgument(payload != null, "Null payload on a verb which expects one"); }/*from w ww . j a va 2 s . c om*/ try { conn = openConnection(url); conn.setRequestMethod(verb.getVerb()); conn.setDoOutput(doOutput); if (doOutput) { conn.setRequestProperty("Content-Type", contentType); } // now do the connection conn.connect(); if (doOutput) { OutputStream output = conn.getOutputStream(); IOUtils.write(payload, output); output.close(); } resultCode = conn.getResponseCode(); outcome.lastModified = conn.getLastModified(); outcome.contentType = conn.getContentType(); outcome.headers = conn.getHeaderFields(); InputStream stream = conn.getErrorStream(); if (stream == null) { stream = conn.getInputStream(); } if (stream != null) { // read into a buffer. body = IOUtils.toByteArray(stream); } else { // no body: log.debug("No body in response"); } } catch (SSLException e) { throw e; } catch (IOException e) { throw NetUtils.wrapException(url.toString(), url.getPort(), "localhost", 0, e); } catch (AuthenticationException e) { throw new AuthenticationException("From " + url + ": " + e, e); } finally { if (conn != null) { conn.disconnect(); } } uprateFaults(HttpVerb.GET, url.toString(), resultCode, "", body); outcome.responseCode = resultCode; outcome.data = body; return outcome; }
From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java
public byte[] sendCmpHttp(final byte[] message, final int httpRespCode, String cmpAlias, String host, final String fullURL) throws IOException { String urlString = fullURL;// w w w .jav a 2s .c om if (urlString == null) { if (host == null) { host = "127.0.0.1"; log.info("Using default CMP Server IP address: localhost"); } final String httpReqPath = "http://" + host + ":8080/ejbca"; final String resourceCmp = "publicweb/cmp"; if (cmpAlias == null) { cmpAlias = "cmp"; log.info("Using default CMP alias: " + cmpAlias); } urlString = httpReqPath + '/' + resourceCmp + '/' + cmpAlias; } log.info("Using CMP URL: " + urlString); URL url = new URL(urlString); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/pkixcmp"); con.connect(); // POST it OutputStream os = con.getOutputStream(); os.write(message); os.close(); final int conResponseCode = con.getResponseCode(); if (conResponseCode != httpRespCode) { log.info("Unexpected HTTP response code: " + conResponseCode); } // Only try to read the response if we expected a 200 (ok) response if (httpRespCode != 200) { return null; } // Some appserver (Weblogic) responds with // "application/pkixcmp; charset=UTF-8" final String conContentType = con.getContentType(); if (conContentType == null) { log.error("No content type in response."); System.exit(1); } if (!StringUtils.equals("application/pkixcmp", conContentType)) { log.info("Content type is not 'application/pkixcmp'"); } // Check that the CMP respone has the cache-control headers as specified in // http://tools.ietf.org/html/draft-ietf-pkix-cmp-transport-protocols-14 final String cacheControl = con.getHeaderField("Cache-Control"); if (cacheControl == null) { log.error("'Cache-Control' header is not present."); System.exit(1); } if (!StringUtils.equals("no-cache", cacheControl)) { log.error("Cache-Control is not 'no-cache'"); System.exit(1); } final String pragma = con.getHeaderField("Pragma"); if (pragma == null) { log.error("'Pragma' header is not present."); System.exit(1); } if (!StringUtils.equals("no-cache", pragma)) { log.error("Pragma is not 'no-cache'"); System.exit(1); } // Now read in the bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and CMP requests are small enough InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); if ((respBytes == null) || (respBytes.length <= 0)) { log.error("No response from server"); System.exit(1); } return respBytes; }