List of usage examples for java.net URL toString
public String toString()
From source file:net.a2bsoft.buss.http.SendQuery.java
public static String sendQuery(String query) { try {/*from ww w.ja v a 2 s. c o m*/ query = URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } URL url = null; try { url = new URL( "http://www.atb.no/xmlhttprequest.php?service=routeplannerOracle.getOracleAnswer&question=" + query); } catch (MalformedURLException e) { e.printStackTrace(); } String result = null; HttpParams my_httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(my_httpParams, 30000); HttpConnectionParams.setSoTimeout(my_httpParams, 30000); HttpClient client = new DefaultHttpClient(my_httpParams); HttpGet get = new HttpGet(url.toString()); HttpResponse resp; try { resp = client.execute(get); InputStream data = resp.getEntity().getContent(); result = new BufferedReader(new InputStreamReader(data)).readLine(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return sendQueryBusstuc(query); // return e.getMessage(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return sendQueryBusstuc(query); // return e.getMessage(); } return result; }
From source file:de.alpharogroup.lang.ClassUtils.java
/** * If the given class is in a JAR, WAR or EAR file than the manifest url as String is returned. * * @param clazz/*w w w . j ava 2 s .c om*/ * The class. * @return the manifest url as String if the given class is in a JAR, WAR or EAR file. */ public static String getManifestUrl(final Class<?> clazz) { String manifestUrl = null; final String path = ClassUtils.getPath(clazz); final URL classUrl = ClassUtils.getResource(path); if (classUrl != null) { final String classUrlString = classUrl.toString(); if ((classUrlString.startsWith("jar:") && (classUrlString.indexOf(path) > 0)) || (classUrlString.startsWith("war:") && (classUrlString.indexOf(path) > 0)) || (classUrlString.startsWith("ear:") && (classUrlString.indexOf(path) > 0))) { manifestUrl = classUrlString.replace(path, "/META-INF/MANIFEST.MF"); } } return manifestUrl; }
From source file:org.apache.juddi.v3.client.mapping.wadl.WADL2UDDI.java
/** * Parses a web accessible WADL file/*from w ww . ja v a 2 s .co m*/ * @param weburl * @param username * @param password * @param ignoreSSLErrors if true, SSL errors are ignored * @return a non-null "Application" object, represeting a WADL's application root XML * Sample code:<br> * <pre> * Application app = WADL2UDDI.parseWadl(new URL("http://server/wsdl.wsdl"), "username", "password", * clerkManager.getClientConfig().isX_To_Wsdl_Ignore_SSL_Errors() ); * </pre> */ public static Application parseWadl(URL weburl, String username, String password, boolean ignoreSSLErrors) { DefaultHttpClient httpclient = null; Application unmarshal = null; try { String url = weburl.toString(); if (!url.toLowerCase().startsWith("http")) { return parseWadl(weburl); } boolean usessl = false; int port = 80; if (url.toLowerCase().startsWith("https://")) { port = 443; usessl = true; } if (weburl.getPort() > 0) { port = weburl.getPort(); } if (ignoreSSLErrors && usessl) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", port, new MockSSLSocketFactory())); ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(cm); } else { httpclient = new DefaultHttpClient(); } if (username != null && username.length() > 0 && password != null && password.length() > 0) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(weburl.getHost(), port), new UsernamePasswordCredentials(username, password)); } HttpGet httpGet = new HttpGet(url); try { HttpResponse response1 = httpclient.execute(httpGet); //System.out.println(response1.getStatusLine()); // HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed ResponseHandler<String> responseHandler = new BasicResponseHandler(); String handleResponse = responseHandler.handleResponse(response1); StringReader sr = new StringReader(handleResponse); unmarshal = JAXB.unmarshal(sr, Application.class); } finally { httpGet.releaseConnection(); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return unmarshal; }
From source file:com.centeractive.ws.builder.DefinitionSaveTest.java
public static File getGeneratedFolder(int serviceId) throws WSDLException, IOException { URL wsdlUrl = ServiceComplianceTest.getDefinitionUrl(serviceId); SoapBuilder builder = new SoapBuilder(wsdlUrl); File tempFolder = File.createTempFile("maven-temp", Long.toString(System.nanoTime())); if (!tempFolder.delete()) { throw new RuntimeException("cannot delete tmp file"); }//from www. j a v a 2s . co m if (!tempFolder.mkdir()) { throw new RuntimeException("cannot create tmp folder"); } String fileName = FilenameUtils.getBaseName(wsdlUrl.toString()); builder.saveWsdl(fileName, tempFolder); tempFolder.deleteOnExit(); return tempFolder; }
From source file:com.griddynamics.jagger.JaggerLauncher.java
private static List<String> discoverResources(URL directory, String[] includePatterns, String[] excludePatterns) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( new FileSystemResourceLoader()); List<String> resourceNames = new ArrayList<String>(); PathMatcher matcher = new AntPathMatcher(); try {/*from w ww . j a v a 2s . co m*/ for (String pattern : includePatterns) { Resource[] includeResources = resolver.getResources(directory.toString() + pattern); for (Resource resource : includeResources) { boolean isValid = true; for (String excludePattern : excludePatterns) { if (matcher.match(excludePattern, resource.getFilename())) { isValid = false; break; } } if (isValid) { resourceNames.add(resource.getURI().toString()); } } } } catch (IOException e) { throw new TechnicalException(e); } return resourceNames; }
From source file:com.sun.faban.harness.webclient.ResultAction.java
/** * This method is responsible for uploading the runs to repository. * @param uploadSet/*from ww w . jav a 2 s. co m*/ * @param replaceSet * @return HashSet * @throws java.io.IOException */ public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet) throws IOException { // 3. Upload the run HashSet<String> duplicates = new HashSet<String>(); // Prepare run id set for cross checking. HashSet<String> runIdSet = new HashSet<String>(runIds.length); for (String runId : runIds) { runIdSet.add(runId); } // Prepare the parts for the request. ArrayList<Part> params = new ArrayList<Part>(); params.add(new StringPart("host", Config.FABAN_HOST)); for (String replaceId : replaceSet) { params.add(new StringPart("replace", replaceId)); } for (File jarFile : uploadSet) { params.add(new FilePart("jarfile", jarFile)); } Part[] parts = new Part[params.size()]; parts = params.toArray(parts); // Send the request for each reposotory. for (URL repository : Config.repositoryURLs) { URL repos = new URL(repository, "/controller/uploader/upload_runs"); PostMethod post = new PostMethod(repos.toString()); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(post); if (status == HttpStatus.SC_FORBIDDEN) logger.warning("Server denied permission to upload run !"); else if (status == HttpStatus.SC_NOT_ACCEPTABLE) logger.warning("Run origin error!"); else if (status != HttpStatus.SC_CREATED) logger.warning( "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected."); for (File jarFile : uploadSet) { jarFile.delete(); } String response = post.getResponseBodyAsString(); if (status == HttpStatus.SC_CREATED) { StringTokenizer t = new StringTokenizer(response.trim(), "\n"); while (t.hasMoreTokens()) { String duplicateRun = t.nextToken().trim(); if (duplicateRun.length() > 0) duplicates.add(duplicateRun.trim()); } for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) { String runId = iter.next(); if (!runIdSet.contains(runId)) { logger.warning("Unexpected archive response from " + repos + ": " + runId); iter.remove(); } } } else { logger.warning("Message from repository: " + response); } } return duplicates; }
From source file:com.frostwire.gui.bittorrent.TorrentUtil.java
public static String getMagnetURLParameters(TOTorrent torrent) { StringBuilder sb = new StringBuilder(); //dn//from w w w . j a va 2 s . co m if (StringUtils.isNullOrEmpty(torrent.getUTF8Name())) { sb.append("dn=" + UrlUtils.encode(new String(torrent.getName()))); } else { sb.append("dn=" + UrlUtils.encode(torrent.getUTF8Name())); } TOTorrentAnnounceURLGroup announceURLGroup = torrent.getAnnounceURLGroup(); TOTorrentAnnounceURLSet[] announceURLSets = announceURLGroup.getAnnounceURLSets(); for (TOTorrentAnnounceURLSet set : announceURLSets) { URL[] announceURLs = set.getAnnounceURLs(); for (URL url : announceURLs) { sb.append("&tr="); sb.append(UrlUtils.encode(url.toString())); } } if (torrent.getAnnounceURL() != null) { sb.append("&tr="); sb.append(UrlUtils.encode(torrent.getAnnounceURL().toString())); } //iipp = internal ip port, for lan try { String localAddress = NetworkUtils.getLocalAddress().getHostAddress(); int localPort = TCPNetworkManager.getSingleton().getTCPListeningPortNumber(); if (localPort != -1) { sb.append("&iipp="); sb.append(NetworkUtils.convertIPPortToHex(localAddress, localPort)); } } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); }
From source file:org.coffeeking.controller.service.util.ConnectedCupServiceUtils.java
public static HttpURLConnection getHttpConnection(String urlString) throws DeviceManagementException { URL connectionUrl = null; HttpURLConnection httpConnection; try {/*from ww w .j a v a 2 s . c o m*/ connectionUrl = new URL(urlString); httpConnection = (HttpURLConnection) connectionUrl.openConnection(); } catch (MalformedURLException e) { String errorMsg = "Error occured whilst trying to form HTTP-URL from string: " + urlString; log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } catch (IOException e) { String errorMsg = "Error occured whilst trying to open a connection to: " + connectionUrl.toString(); log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } return httpConnection; }
From source file:com.hdsfed.cometapi.ThreadTrackerDB.java
static private synchronized int genericDBActionOverHttpPUT(String args, Boolean force) { if (!CometProperties.getInstance().getIngestorHeartbeatEnabled()) { ScreenLog.out("....requested heartbeat action, but local heartbeat for ingest is disabled, return 200"); return 200; }/* ww w . jav a 2 s. co m*/ if (CometProperties.isHeartBeatTooSoon() && !force) { ScreenLog.out("....requested heartbeat action, but heartbeat too rapid; skipping args==" + args + " and return 200"); ScreenLog.out("\theartbeat was too soon because cp.isHeartBeatTooSoon returned true"); ScreenLog.out("\tcaused by: (cur time)" + System.currentTimeMillis() + " - (last update)" + CometProperties.getLastHTTPUpdateTimeStamp() + " < (time btwn beats) " + CometProperties.getTimeBetweenBeats()); return 200; } ScreenLog.begin("ThreadTrackerDB::genericDBActionOverHttpPUT(" + args + ")"); HttpResponse httpResponse; URL url; int status = -1; try { HttpClient mHttpClient = HCPUtils.initHttpClient(); url = new URL( "http://localhost" + CometProperties.getInstance().getWebAppPath() + "IngestorThreads" + args); ScreenLog.out("\n\texec put to " + url); HttpPut httpRequest = new HttpPut(url.toString()); httpResponse = mHttpClient.execute(httpRequest); status = HttpCatchError(httpRequest, httpResponse); ScreenLog.out("\n\tresponse from webapp: " + httpResponse.getAllHeaders()); if (httpResponse.getEntity().getContentLength() > 0) { //capture results, if they exist //result=StringHelper.InputStreamToString(is); EntityUtils.consume(httpResponse.getEntity()); } } catch (Exception e) { // TODO Auto-generated catch block ScreenLog.ExceptionOutputHandler(e); } ScreenLog.end("ThreadTrackerDB::genericDBActionOverHttpPUT(" + args + ") returning status=" + status); return status; }
From source file:io.stallion.utils.ResourceHelpers.java
private static File urlToFileMaybe(URL resourceUrl, String pluginName) { Log.finer("Load resource URL={0} plugin={1}", resourceUrl, pluginName); if (!Settings.instance().getDevMode()) { return null; }//from w w w . jav a 2 s . co m // If the resourceUrl points to a local file, and the file exists in the file system, then use that file Log.finer("Resource URL {0}", resourceUrl); if (resourceUrl.toString().startsWith("file:/")) { String path = resourceUrl.toString().substring(5).replace("/target/classes/", "/src/main/resources/"); File file = new File(path); if (file.isFile()) { Log.finest("Load resource from source path {0}", path); return file; } } String[] parts = resourceUrl.toString().split("!", 2); if (parts.length < 2) { return null; } String relativePath = parts[1]; if (!relativePath.startsWith("/")) { relativePath = "/" + relativePath; } if (relativePath.contains("..")) { throw new UsageException("Invalid characters in the URL path: " + resourceUrl.toString()); } List<String> paths = list(); if (empty(pluginName) || "stallion".equals(pluginName)) { paths.add(System.getProperty("user.home") + "/st/core/src/main/resources" + relativePath); paths.add(System.getProperty("user.home") + "/stallion/core/src/main/resources" + relativePath); } else { paths.add(System.getProperty("user.home") + "/st/" + pluginName + "/src/main/resources" + relativePath); paths.add(System.getProperty("user.home") + "/stallion/" + pluginName + "/src/main/resources" + relativePath); } boolean isText = true; for (String path : paths) { File file = new File(path); if (file.isFile()) { Log.finest("Load resource from guessed path {0}", path); return file; } } // All else fails, just return it based on the resourc Log.finest("Could not find a devMode version for resource path {0}", resourceUrl.toString()); return null; }