List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.example.prathik1.drfarm.OCRRestAPI.java
private static void DownloadConvertedFile(String outputFileUrl) throws IOException { URL downloadUrl = new URL(outputFileUrl); HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection(); if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = downloadConnection.getInputStream(); // opens an output stream to save into file FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc"); int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); }// w w w . j a v a 2 s.c om outputStream.close(); inputStream.close(); } downloadConnection.disconnect(); }
From source file:com.fluidops.iwb.HTMLProvider.HTMLProvider.java
/** * HINT: The gather(List<Statement> res) method collects the statements * extracted by the provider. Use the following guidelinges: * //from ww w . j a v a2 s. co m * 1.) Make sure to have a clear documentation, structure, and * modularization. Use helper methods wherever possible to increase * readability of the method. * * 2.) Whenever there is a need to create statements, use the helper methods * in {@link ProviderUtils}. This class helps you in generating "safe" URIs, * replacing invalid characters etc. It also offers common functionality for * filtering statements, e.g. removing statements containing null values. * * 3.) Re-use existing ontologies! The {@link Vocabulary} class provides a * mix of vocabulary from common ontologies and can be easily extended. You * should not define URIs inside the provider itself, except these URIs are * absolutely provider-specific. * * 4.) Concerning exception handling, it is best practice to throw * exceptions whenever the provider run cannot be finished in a regular way. * Since these exception will be propagated to the UI, it is recommended to * catch Exceptions locally first, log them, and wrap them into * (Runtime)Exceptions with a human-readable description. When logging * exceptions, the log level "warn" is appropriate. */ @Override public void gather(List<Statement> res) throws Exception { URL registryUrl = new URL(config.location); HttpURLConnection registryConnection = (HttpURLConnection) registryUrl.openConnection(); registryConnection.setRequestMethod("GET"); // ////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////// STEP // 1 logger.info("Retrieving packages from CKAN..."); if (registryConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { String msg = "Connection with the registry could not be established. (" + registryConnection.getResponseCode() + ", " + registryConnection.getResponseMessage() + ")"; logger.warn(msg); throw new RuntimeException(msg); // propagate to UI } String siteContent = GenUtil.readUrl(registryConnection.getInputStream()); JSONObject groupAsJson = null; JSONArray packageListJsonArray = null; try { groupAsJson = new JSONObject(new JSONTokener(siteContent)); packageListJsonArray = groupAsJson.getJSONArray("packages"); } catch (JSONException e) { String msg = "Returned content " + siteContent + " is not valid JSON. Check if the registry URL is valid."; logger.warn(msg); throw new RuntimeException(msg); // propagate to UI } logger.info("-> found " + packageListJsonArray.length() + " packages"); // ////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////// STEP // 2 logger.info("Registering LOD catalog in metadata repository"); /** * HINT: the method createStatement allows to create statements if * subject, predicate and object are all known; use this method instead * of opening a value factory */ res.add(ProviderUtils.createStatement(CKANVocabulary.CKAN_CATALOG, RDF.TYPE, Vocabulary.DCAT.CATALOG)); res.add(ProviderUtils.createStatement(CKANVocabulary.CKAN_CATALOG, RDFS.LABEL, CKANVocabulary.CKAN_CATALOG_LABEL)); logger.info("-> done"); // ////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////// STEP // 3 logger.info("Extracting metdata for the individual data sets listed in CKAN"); /** * HINT: Set up an Apache HTTP client with a manager for multiple * threads; as a general guideline, use parallelization whenever * crawling web sources! */ MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(connectionManager); ExecutorService pool = Executors.newFixedThreadPool(10); // we store the data in a temporary memory store, which allows us // to perform transformation on the result set Repository repository = null; RepositoryConnection connection = null; try { // initialize repository and connection repository = new SailRepository(new MemoryStore()); repository.initialize(); connection = repository.getConnection(); // Fire up a thread for every package logger.info("-> Fire up threads for the individual packages..."); for (int i = 0; i < packageListJsonArray.length(); i++) { // we use the JSON representation to get a base URI to resolve // relative // URIs in the XML later on. (and a fallback solution) String host = "http://www.ckan.net/package/" + packageListJsonArray.get(i).toString(); String baseUri = findBaseUri( "http://www.ckan.net/api/rest/package/" + packageListJsonArray.get(i).toString()); baseUri = (baseUri == null) ? host : baseUri; pool.execute(new MetadataReader(client, host, baseUri, CKANVocabulary.CKAN_CATALOG, connection)); } logger.info("-> Waiting for all tasks to complete (" + packageListJsonArray.length() + "tasks/data sources)..."); pool.shutdown(); pool.awaitTermination(4, TimeUnit.HOURS); /** * Now the extraction has finished, all statements are available in * our temporary repository. We apply some conversions and * transformations to align the extracted statements with our target * ontology. * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * !!!!!!!!!!!!! !!! NOTE: this code is /NOT/ best practice, we * should eventually extend !!! !!! ProviderUtils to deal with at * least lightweight transformations !!! !!! (such as changing * property names) or realize such tasks using !!! !!! an integrated * mapping framework. !!! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ // Extraction from temporary repository, phase 1: logger.info( "-> Extract dcterms:title AS rdfs:label, dcterms:contributor AS dcterms:creator, and dcterms:rights AS dcterms:license"); String mappingQuery = mappingQuery(); GraphQuery mappingGraphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, mappingQuery); GraphQueryResult result = mappingGraphQuery.evaluate(); logger.info("-> Appending extracted result to statement list"); ProviderUtils.appendGraphQueryResultToListAndClose(result, res); // Label the distribution nodes logger.info("-> Generate labels for distributions"); String labelDistributionQuery = labelDistributionQuery(); GraphQuery labelDistributionGraphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, labelDistributionQuery); GraphQueryResult result2 = labelDistributionGraphQuery.evaluate(); logger.info("-> Appending extracted result to statement list"); ProviderUtils.appendGraphQueryResultToListAndClose(result2, res); // Extraction from temporary repository, phase 2: logger.info("-> Deleting previously extracted triples and additional, not required information..."); String deleteQuery = deleteQuery(); Update deleteGraphQuery = connection.prepareUpdate(QueryLanguage.SPARQL, deleteQuery); deleteGraphQuery.execute(); // Extraction from temporary repository, phase 3: logger.info("-> Deleting dcat:distribution and dcat:accessUrl information from" + "temp repository for which format information is missing..."); String cleanDistQuery = cleanDistQuery(); Update cleanupGraphQuery = connection.prepareUpdate(QueryLanguage.SPARQL, cleanDistQuery); cleanupGraphQuery.execute(); logger.info("-> Appending remaining statements to result..."); connection.getStatements(null, null, null, false).addTo(res); logger.info("Provider run finished successfully"); } catch (Exception e) { logger.warn(e.getMessage()); throw new RuntimeException(e); } finally { if (connection != null) connection.close(); if (repository != null) repository.shutDown(); } // in the end, make sure there are no statements containing null in // any of the position (did not take special care when creating // statements) logger.info("-> cleaning up null statements"); res = ProviderUtils.filterNullStatements(res); }
From source file:com.versobit.weatherdoge.WeatherUtil.java
private static WeatherResult getWeatherFromOWM(double latitude, double longitude, String location) { try {/*from ww w . ja v a 2 s . c o m*/ String query; if (latitude == Double.MIN_VALUE && longitude == Double.MIN_VALUE) { if (location == null) { return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, "No valid location parameters.", new IllegalArgumentException()); } query = "q=" + URLEncoder.encode(location, "UTF-8"); } else { query = "lat=" + URLEncoder.encode(String.valueOf(latitude), "UTF-8") + "&lon=" + URLEncoder.encode(String.valueOf(longitude), "UTF-8"); } query += "&APPID=" + URLEncoder.encode(BuildConfig.OWM_APPID, "UTF-8"); URL url = new URL("http://api.openweathermap.org/data/2.5/weather?" + query); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { JSONObject response = new JSONObject(IOUtils.toString(connection.getInputStream())); if (response.getInt("cod") != HttpURLConnection.HTTP_OK) { // OWM has HTTP error codes that are passed through an API field, the actual HTTP // error code is always 200... return new WeatherResult(null, WeatherResult.ERROR_API, response.getString("cod") + ": " + response.getString("message"), null); } JSONObject weather = response.getJSONArray("weather").getJSONObject(0); JSONObject main = response.getJSONObject("main"); double temp = main.getDouble("temp") - 273.15d; String condition = WordUtils.capitalize(weather.getString("description").trim()); String image = weather.getString("icon"); if (location == null || location.isEmpty()) { location = response.getString("name"); } return new WeatherResult(new WeatherData(temp, condition, image, latitude, longitude, location, new Date(), Source.OPEN_WEATHER_MAP), WeatherResult.ERROR_NONE, null, null); } finally { connection.disconnect(); } } catch (Exception ex) { return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, ex.getMessage(), ex); } }
From source file:rogerthat.topdesk.bizz.Util.java
public static byte[] download(String downloadUrl) throws IOException { URL url = new URL(downloadUrl); log.info("Downloading " + downloadUrl); HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(30)); URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = urlFetch.fetch(request); int responseCode = response.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new RuntimeException( "Downloading of image " + downloadUrl + " failed with response code " + responseCode); }/*from w w w . j a v a2 s. c o m*/ return response.getContent(); }
From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java
@Override public RawBinaryNode download(final HttpServletRequest req, final String url, final Account account, final PluginConfig pluginConf) throws IOException { final JenkinsClient client = JenkinsClient.getInstance(account, pluginConf); final HttpRequestBase get = getNewHttpRequest(req, url); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final RawBinaryNode result = new RawBinaryNode(); try {//from w w w . j ava 2 s. c o m final HttpResponse response = client.http.execute(get); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpURLConnection.HTTP_OK) { throw new IOException("HTTP-" + get.getMethod() + " " + url + " failed: status code " + status); } IOUtils.copy(response.getEntity().getContent(), out); for (final Header h : response.getAllHeaders()) { final String headerName = h.getName(); if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { result.setHttpContentType(h.getValue()); } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { result.setSize(Long.parseLong(h.getValue())); } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) { result.setHttpCharacterEncoding(h.getValue()); } } } finally { get.releaseConnection(); } result.setData(new ByteArrayInputStream(out.toByteArray())); return result; }
From source file:com.codepine.api.testrail.Request.java
/** * Execute this request./*from ww w .jav a 2 s .c om*/ * * @return response from TestRail */ public T execute() { try { String url = getUrl(); HttpURLConnection con = (HttpURLConnection) urlConnectionFactory.getUrlConnection(url); con.setRequestMethod(method.name()); if (config.getApplicationName().isPresent()) { con.setRequestProperty("User-Agent", config.getApplicationName().get()); } con.setRequestProperty("Content-Type", "application/json"); String basicAuth = "Basic " + DatatypeConverter.printBase64Binary( (config.getUsername() + ":" + config.getPassword()).getBytes(Charset.forName("UTF-8"))); con.setRequestProperty("Authorization", basicAuth); if (method == Method.POST) { Object content = getContent(); if (content != null) { con.setDoOutput(true); try (OutputStream outputStream = new BufferedOutputStream(con.getOutputStream())) { JSON.writerWithView(this.getClass()).writeValue(outputStream, content); } } } log.debug("Sending " + method + " request to URL : " + url); int responseCode = 0; try { responseCode = con.getResponseCode(); } catch (IOException e) { // swallow it since for 401 getResponseCode throws an IOException responseCode = con.getResponseCode(); } log.debug("Response Code : " + responseCode); if (responseCode != HttpURLConnection.HTTP_OK) { try (InputStream errorStream = con.getErrorStream()) { TestRailException.Builder exceptionBuilder = new TestRailException.Builder() .setResponseCode(responseCode); if (errorStream == null) { throw exceptionBuilder.setError("<server did not send any error message>").build(); } throw JSON.readerForUpdating(exceptionBuilder).<TestRailException.Builder>readValue( new BufferedInputStream(errorStream)).build(); } } try (InputStream responseStream = new BufferedInputStream(con.getInputStream())) { Object supplementForDeserialization = getSupplementForDeserialization(); if (responseClass != null) { if (responseClass == Void.class) { return null; } if (supplementForDeserialization != null) { return JSON .reader(responseClass).with(new InjectableValues.Std() .addValue(responseClass.toString(), supplementForDeserialization)) .readValue(responseStream); } return JSON.readValue(responseStream, responseClass); } else { if (supplementForDeserialization != null) { String supplementKey = responseType.getType().toString(); if (responseType.getType() instanceof ParameterizedType) { Type[] actualTypes = ((ParameterizedType) responseType.getType()) .getActualTypeArguments(); if (actualTypes.length == 1 && actualTypes[0] instanceof Class<?>) { supplementKey = actualTypes[0].toString(); } } return JSON.reader(responseType).with( new InjectableValues.Std().addValue(supplementKey, supplementForDeserialization)) .readValue(responseStream); } return JSON.readValue(responseStream, responseType); } } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.fluidops.iwb.provider.CkanProvider.java
@Override public void gather(List<Statement> res) throws Exception { // Read CKAN location and establish connection URL registryUrl = new URL(config.location); HttpURLConnection registryConnection = (HttpURLConnection) registryUrl.openConnection(); registryConnection.setRequestMethod("GET"); // Check if connection to CKAN could be established if (registryConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { String msg = String.format("Connection to the CKAN registry could not be established. (%s, %s)", registryConnection.getResponseCode(), registryConnection.getResponseMessage()); logger.info(msg);//w ww.java 2s . co m throw new IllegalStateException(msg); } logger.trace("Connection to CKAN established successfully."); String siteContent = GenUtil.readUrl(registryConnection.getInputStream()); JSONObject groupAsJson = null; JSONArray packageListJsonArray = null; try { groupAsJson = new JSONObject(new JSONTokener(siteContent)); packageListJsonArray = groupAsJson.getJSONArray("packages"); } catch (JSONException e) { String msg = String.format("Returned content %s is not valid JSON. Check if the registry URL is valid.", siteContent); logger.debug(msg); throw new IllegalStateException(msg); } logger.trace("Extracted JSON from CKAN successfully"); // Create metadata about LOD catalog res.add(ProviderUtils.createStatement(CKAN.CKAN_CATALOG, RDF.TYPE, Vocabulary.DCAT.CATALOG)); res.add(ProviderUtils.createStatement(CKAN.CKAN_CATALOG, RDFS.LABEL, CKAN.CKAN_CATALOG_LABEL)); // Extract metadata for individual data sets listed in CKAN MultiThreadedHttpConnectionManager connectionManager = null; ExecutorService pool = null; try { pool = Executors.newFixedThreadPool(10); connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(connectionManager); List<Statement> synchedList = Collections.synchronizedList(res); for (int i = 0; i < packageListJsonArray.length(); i++) { String host = "http://www.ckan.net/package/" + packageListJsonArray.get(i).toString(); String baseUri = findBaseUri( "http://www.ckan.net/api/rest/package/" + packageListJsonArray.get(i).toString()); baseUri = (baseUri == null) ? host : baseUri; pool.execute(new MetadataReader(client, host, baseUri, CKAN.CKAN_CATALOG, synchedList)); } } finally { if (pool != null) { pool.shutdown(); pool.awaitTermination(4, TimeUnit.HOURS); } if (connectionManager != null) connectionManager.shutdown(); } }
From source file:de.ub0r.android.websms.connector.fishtext.ConnectorFishtext.java
/** * Login to fishtext.com.//from www .j av a2s . c o m * * @param context * {@link Context} * @param command * {@link ConnectorCommand} * @throws IOException * IOException */ private void doLogin(final Context context, final ConnectorCommand command) throws IOException { final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); ArrayList<BasicNameValuePair> postData = // . new ArrayList<BasicNameValuePair>(NUM_VARS_LOGIN); postData.add(new BasicNameValuePair("action", "login")); String genlogin; if (p.getBoolean(PREFS_LOGIN_WTIH_DEFAULT, false)) { genlogin = command.getDefSender(); } else { genlogin = Utils.getSender(context, command.getDefSender()); } Log.d(TAG, "genlogin: " + genlogin); if (genlogin.startsWith("+")) { genlogin = genlogin.substring(1); } else if (genlogin.startsWith("00")) { genlogin = genlogin.substring(2); } Log.d(TAG, "genlogin: " + genlogin); // postData.add(new BasicNameValuePair("mobile", userlogin)); postData.add(new BasicNameValuePair("mobile", genlogin)); Log.d(TAG, "genlogin: " + genlogin); postData.add(new BasicNameValuePair("password", p.getString(Preferences.PREFS_PASSWORD, ""))); postData.add(new BasicNameValuePair("rememberSession", "yes")); HttpResponse response = Utils.getHttpClient(URL_LOGIN, null, postData, TARGET_AGENT, null, ENCODING, false); postData = null; int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } final String htmlText = Utils.stream2str(response.getEntity().getContent()); Log.d(TAG, "----HTTP RESPONSE---"); Log.d(TAG, htmlText); Log.d(TAG, "----HTTP RESPONSE---"); final int i = htmlText.indexOf(CHECK_BALANCE); if (i < 0) { Utils.clearCookies(); throw new WebSMSException(context, R.string.error_pw); } final int j = htmlText.indexOf("<p>", i); if (j > 0) { final int h = htmlText.indexOf("</p>", j); if (h > 0) { String b = htmlText.substring(j + 3, h); if (b.startsWith("€")) { b = b.substring(6) + "\u20AC"; } b.replaceAll("£ *", "\u00A3"); Log.d(TAG, "balance: " + b); this.getSpec(context).setBalance(b); } } }
From source file:com.mobile.godot.core.controller.CoreController.java
public synchronized void addCoOwner(String carName, String coOwnerUsername, LoginBean login) { String servlet = "AddCoOwner"; List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("carName", carName)); params.add(new BasicNameValuePair("coOwnerUsername", coOwnerUsername)); params.add(new BasicNameValuePair("username", login.getUsername())); params.add(new BasicNameValuePair("password", login.getPassword())); SparseIntArray mMessageMap = new SparseIntArray(); mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.COOWNER_ADDED); mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED); mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Error.NOT_FOUND); GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler); Thread tAction = new Thread(action); tAction.start();/*from w w w . ja va 2s.c o m*/ }