List of usage examples for java.net URL getHost
public String getHost()
From source file:com.github.egonw.rrdf.RJenaHelper.java
public static StringMatrix sparqlRemoteNoJena(String endpoint, String queryString, String user, String password) throws Exception { StringMatrix table = null;//w w w. j a va 2 s . c o m // use Apache for doing the SPARQL query DefaultHttpClient httpclient = new DefaultHttpClient(); // Set credentials on the client if (user != null) { URL endpointURL = new URL(endpoint); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(endpointURL.getHost(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); httpclient.setCredentialsProvider(credsProvider); } List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("query", queryString)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost httppost = new HttpPost(endpoint); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != 200) throw new HttpException( "Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase()); HttpEntity responseEntity = response.getEntity(); InputStream in = responseEntity.getContent(); // now the Jena part ResultSet results = ResultSetFactory.fromXML(in); // also use Jena for getting the prefixes... Query query = QueryFactory.create(queryString); PrefixMapping prefixMap = query.getPrefixMapping(); table = convertIntoTable(prefixMap, results); in.close(); return table; }
From source file:Models.Geographic.Repository.RepositoryGoogle.java
/** * Method that geocoding a address from google api * @param country/* ww w .j ava 2 s . com*/ * @param adm1 * @param adm2 * @param adm3 * @param local_area * @param locality * @param uncertainty * @return */ public static Location georenferencing(String country, String adm1, String adm2, String adm3, String local_area, String locality, double uncertainty) { Location a = null; String key; try { key = FixData.generateKey(new String[] { country, adm1, adm2, adm3, local_area, locality }); if (RepositoryGoogle.db == null) RepositoryGoogle.db = new HashMap(); if (RepositoryGoogle.db.containsKey(key)) return (Location) RepositoryGoogle.db.get(key); String data = (!locality.equals("") ? locality : "") + (!local_area.equals("") ? local_area + "+,+" : "") + (!adm3.equals("") ? adm3 + "+,+" : "") + (!adm2.equals("") ? adm2 + "+,+" : "") + (!adm1.equals("") ? adm1 + "+,+" : "") + (!country.equals("") ? country + "+,+" : ""); URL url = new URL(Configuration.getParameter("geocoding_google_url_send_xml") + "address=" + data.replace(" ", "%20").replace(".", "").replace(";", "")); URL file_url = new URL( url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery())); // Get information from URL DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Create a proxy to work in CIAT (erase this in another place) //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy2.ciat.cgiar.org", 8080)); DocumentBuilder db = dbf.newDocumentBuilder(); //Document doc = db.parse(file_url.openConnection(proxy).getInputStream()); Document doc = db.parse(file_url.openConnection().getInputStream()); // Document with data if (doc != null) { NodeList locationList = doc.getElementsByTagName("location"); NodeList locationTypeList = doc.getElementsByTagName("location_type"); NodeList viewPortList = doc.getElementsByTagName("viewport"); Node location = null, lat = null, lng = null; if (locationList.getLength() > 0) { for (int i = 0; i < locationList.getLength(); i++) { location = locationList.item(i); if (location.hasChildNodes()) { lat = location.getChildNodes().item(1); lng = location.getChildNodes().item(3); } } Node locationType = null; if (locationTypeList.getLength() > 0) { for (int i = 0; i < locationTypeList.getLength(); i++) locationType = locationTypeList.item(i); } Node viewPort = null, northeast = null, southwest = null, lat_northeast = null, lng_northeast = null, lat_southwest = null, lng_southwest = null; if (viewPortList.getLength() > 0) { for (int i = 0; i < viewPortList.getLength(); i++) { viewPort = viewPortList.item(i); if (viewPort.hasChildNodes()) { northeast = viewPort.getChildNodes().item(1); southwest = viewPort.getChildNodes().item(3); } /* Extract data from viewport field */ if (northeast.hasChildNodes()) { lat_northeast = northeast.getChildNodes().item(1); lng_northeast = northeast.getChildNodes().item(3); } if (southwest.hasChildNodes()) { lat_southwest = southwest.getChildNodes().item(1); lng_southwest = southwest.getChildNodes().item(3); } } } double[] coordValues = new double[] { Double.parseDouble(lat.getTextContent()), Double.parseDouble(lng.getTextContent()) }; double[] coordValuesNortheast = new double[] { Double.parseDouble(lat_northeast.getTextContent()), Double.parseDouble(lng_northeast.getTextContent()) }; double[] coordValuesSouthwest = new double[] { Double.parseDouble(lat_southwest.getTextContent()), Double.parseDouble(lng_southwest.getTextContent()) }; double distance = FixData.getDistance(coordValuesNortheast, coordValuesSouthwest); // Distance - km between Northeast and Southeast if (distance <= uncertainty) a = new Location(coordValues[0], coordValues[1], distance); else { RepositoryGoogle.db.put(key, a); throw new Exception("Exceede uncertainty. " + "Uncertainty: " + distance + " THRESHOLD: " + Configuration.getParameter("geocoding_threshold")); } } } RepositoryGoogle.db.put(key, a); } catch (NoSuchAlgorithmException | InvalidKeyException | URISyntaxException | IOException | ParserConfigurationException | SAXException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } return a; }
From source file:com.twinsoft.convertigo.beans.steps.LDAPAuthenticationStep.java
private static String getHost(String ldap_url) { String host = ""; try {//from w w w.java 2 s. co m URL ldapURL = new URL(ldap_url.toLowerCase().replaceFirst("ldap", "http")); host = ldapURL.getHost(); } catch (Exception e) { e.printStackTrace(); } return host; }
From source file:org.pentaho.reporting.designer.extensions.pentaho.drilldown.PentahoParameterRefreshHandler.java
private static String getParameterServicePath(final AuthenticationData loginData, final PentahoPathModel pathModel) { try {/*from w w w. ja v a2 s.co m*/ final FileObject fileSystemRoot = PublishUtil.createVFSConnection(VFS.getManager(), loginData); final FileSystem fileSystem = fileSystemRoot.getFileSystem(); // as of version 3.7 we do not need to check anything other than that the version information is there // later we may have to add additional checks in here to filter out known broken versions. final String localPath = pathModel.getLocalPath(); final FileObject object = fileSystemRoot.resolveFile(localPath); final FileContent content = object.getContent(); final String majorVersionText = (String) fileSystem.getAttribute(WebSolutionFileSystem.MAJOR_VERSION); if (StringUtils.isEmpty(majorVersionText) == false) { final String paramService = (String) content.getAttribute("param-service-url"); if (StringUtils.isEmpty(paramService)) { return null; } if (paramService.startsWith("http://") || paramService.startsWith("https://")) { return paramService; } try { // Encode the URL (must use URI as URL encoding doesn't work on spaces correctly) final URL target = new URL(loginData.getUrl()); final String host; if (target.getPort() != -1) { host = target.getHost() + ":" + target.getPort(); } else { host = target.getHost(); } return target.getProtocol() + "://" + host + paramService; } catch (MalformedURLException e) { UncaughtExceptionsModel.getInstance().addException(e); return null; } } final String extension = IOUtils.getInstance().getFileExtension(localPath); if (".prpt".equals(extension)) { logger.debug( "Ancient pentaho system detected: parameter service does not deliver valid parameter values"); final String name = pathModel.getName(); final String path = pathModel.getPath(); final String solution = pathModel.getSolution(); final FastMessageFormat messageFormat = new FastMessageFormat( "/content/reporting/?renderMode=XML&solution={0}&path={1}&name={2}"); messageFormat.setNullString(""); return loginData.getUrl() + messageFormat.format(new Object[] { solution, path, name }); } logger.debug("Ancient pentaho system detected: We will not have access to a working parameter service"); return null; } catch (FileSystemException e) { UncaughtExceptionsModel.getInstance().addException(e); return null; } }
From source file:URLUtil.java
/** * Method that tries to get a stream (ideally, optimal one) to read from the * specified URL. Currently it just means creating a simple file input stream * if the URL points to a (local) file, and otherwise relying on URL classes * input stream creation method./* ww w. j av a 2 s .com*/ */ public static InputStream inputStreamFromURL(URL url) throws IOException { if ("file".equals(url.getProtocol())) { /* * As per [WSTX-82], can not do this if the path refers to a network drive * on windows. This fixes the problem; might not be needed on all * platforms (NFS?), but should not matter a lot: performance penalty of * extra wrapping is more relevant when accessing local file system. */ String host = url.getHost(); if (host == null || host.length() == 0) { return new FileInputStream(url.getPath()); } } return url.openStream(); }
From source file:CookieUtils.java
/** * Does the cookie domain match the URL? * /*from w w w . j a v a 2 s. c o m*/ * @param url * URL to match * @param cookie * CookieData object (the cookie) * @return true if the cookie domain matches the URL */ public static boolean inDomain(URL url, CookieData cookie) { String domain = cookie.getDomain(); return url.getHost().toLowerCase().endsWith(domain.toLowerCase()); }
From source file:com.evilisn.DAO.CertMapper.java
public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception { InputStream is = null;/* w ww. j a va 2s . c o m*/ InputStream is_temp = null; try { if (uri == null) return null; URL url = uri.toURL(); if (bActiveCheckUnknownHost) { url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) port = url.getDefaultPort(); InetSocketAddress isa = new InetSocketAddress(host, port); if (isa.isUnresolved()) { //fix JNLP popup error issue throw new UnknownHostException("Host Unknown:" + isa.toString()); } } HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoInput(true); uc.setAllowUserInteraction(false); uc.setInstanceFollowRedirects(true); setTimeout(uc); String contentEncoding = uc.getContentEncoding(); int len = uc.getContentLength(); // is = uc.getInputStream(); if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) { is_temp = uc.getInputStream(); is = new GZIPInputStream(is_temp); } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) { is_temp = uc.getInputStream(); is = new InflaterInputStream(is_temp); } else { is = uc.getInputStream(); } if (len != -1) { int ch = 0, i = 0; byte[] res = new byte[len]; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); } return res; } else { ArrayList<byte[]> buffer = new ArrayList<byte[]>(); int buf_len = 1024; byte[] res = new byte[buf_len]; int ch = 0, i = 0; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); if (i == buf_len) { //rotate buffer.add(res); i = 0; res = new byte[buf_len]; } } int total_len = buffer.size() * buf_len + i; byte[] buf = new byte[total_len]; for (int j = 0; j < buffer.size(); j++) { System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len); } if (i > 0) { System.arraycopy(res, 0, buf, buffer.size() * buf_len, i); } return buf; } } catch (Exception e) { e.printStackTrace(); return null; } finally { closeInputStream(is_temp); closeInputStream(is); } }
From source file:gr.wavesoft.webng.io.web.WebStreams.java
public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException { try {//from ww w . jav a 2 s . c o m // WebRequest connection ClientConnectionRequest connRequest = connectionManager.requestConnection( new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null); ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS); try { // Prepare request BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath()); // Setup headers if (headers != null) { for (String k : headers.keySet()) { request.addHeader(k, headers.get(k)); } } // Send request conn.sendRequestHeader(request); // Fetch response HttpResponse response = conn.receiveResponseHeader(); conn.receiveResponseEntity(response); HttpEntity entity = response.getEntity(); if (entity != null) { BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true); // Replace entity response.setEntity(managedEntity); } // Do something useful with the response // The connection will be released automatically // as soon as the response content has been consumed return response; } catch (IOException ex) { // Abort connection upon an I/O error. conn.abortConnection(); throw ex; } } catch (HttpException ex) { throw new IOException("HTTP Exception occured", ex); } catch (InterruptedException ex) { throw new IOException("InterruptedException", ex); } catch (ConnectionPoolTimeoutException ex) { throw new IOException("ConnectionPoolTimeoutException", ex); } }
From source file:org.wso2.carbon.appfactory.apiManager.integration.utils.Utils.java
public static HttpPost createHttpPostRequest(URL url, List<NameValuePair> params, String path) throws AppFactoryException { URI uri;// w w w . j ava 2 s . c om try { uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), path, URLEncodedUtils.format(params, "UTF-8"), null); } catch (URISyntaxException e) { String msg = "Invalid URL syntax"; log.error(msg, e); throw new AppFactoryException(msg, e); } return new HttpPost(uri); }
From source file:com.atinternet.tracker.Tool.java
/** * Get parameters/*from w w w .j a v a 2s.co m*/ * * @param hit String * @return HashMap */ static LinkedHashMap<String, String> getParameters(String hit) { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); try { URL url = new URL(hit); map.put("ssl", url.getProtocol().equals("http") ? "Off" : "On"); map.put("log", url.getHost()); String[] queryComponents = url.getQuery().split("&"); for (String queryComponent : queryComponents) { String[] elem = queryComponent.split("="); if (elem.length > 1) { elem[1] = Tool.percentDecode(elem[1]); if (Tool.parseJSON(elem[1]) instanceof JSONObject) { JSONObject json = (JSONObject) Tool.parseJSON(elem[1]); if (json != null && elem[0].equals(Hit.HitParam.JSON.stringValue())) { map.put(elem[0], json.toString(3)); } else { map.put(elem[0], elem[1]); } } else { map.put(elem[0], elem[1]); } } else { map.put(elem[0], ""); } } } catch (Exception e) { e.printStackTrace(); } return map; }