List of usage examples for java.net URL getUserInfo
public String getUserInfo()
From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java
/** * Transfers product and stores information inside the * product before returning it// w ww . j ava 2s.co m */ private URL transfer(String productOrigin, String productPath) { if (productOrigin == null) { return null; } if (!productPath.equals(productOrigin)) { return null; } File dest = incomingManager.getNewProductIncomingPath(); AsyncFileLock afl = null; try { Path path = Paths.get(dest.getParentFile().getAbsolutePath(), ".lock-writing"); afl = new AsyncFileLock(path); afl.obtain(900000); } catch (IOException | InterruptedException | TimeoutException e) { LOGGER.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")"); } try { URL u = new URL(productOrigin); String userInfos = u.getUserInfo(); String username = null; String password = null; if (userInfos != null) { String[] infos = userInfos.split(":"); username = infos[0]; password = infos[1]; } // Hooks to remove the partially transfered product Hook hook = new Hook(dest.getParentFile()); Runtime.getRuntime().addShutdownHook(hook); upload(productOrigin, username, password, dest); Runtime.getRuntime().removeShutdownHook(hook); String local_filename = productOrigin; if (productOrigin.endsWith("/")) { local_filename = local_filename.substring(0, local_filename.length() - 1); } local_filename = local_filename.substring(local_filename.lastIndexOf('/')); File productFile = new File(dest, local_filename); return productFile.toURI().toURL(); } catch (Exception e) { FileUtils.deleteQuietly(dest); throw new DataStoreException("Cannot transfer product \"" + productOrigin + "\".", e); } finally { if (afl != null) { afl.close(); } } }
From source file:com.diablominer.DiabloMiner.DiabloMiner.java
void execute(String[] args) throws Exception { threads.add(Thread.currentThread()); Options options = new Options(); options.addOption("u", "user", true, "bitcoin host username"); options.addOption("p", "pass", true, "bitcoin host password"); options.addOption("o", "host", true, "bitcoin host IP"); options.addOption("r", "port", true, "bitcoin host port"); options.addOption("l", "url", true, "bitcoin host url"); options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>"); options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds"); options.addOption("d", "debug", false, "enable debug output"); options.addOption("dt", "debugtimer", false, "run for 1 minute and quit"); options.addOption("D", "devices", true, "devices to enable, default all"); options.addOption("f", "fps", true, "target GPU execution timing"); options.addOption("na", "noarray", false, "turn GPU kernel array off"); options.addOption("v", "vectors", true, "vector size in GPU kernel"); options.addOption("w", "worksize", true, "override GPU worksize"); options.addOption("ds", "ksource", false, "output GPU kernel source and quit"); options.addOption("h", "help", false, "this help"); PosixParser parser = new PosixParser(); CommandLine line = null;/*from ww w .j av a 2 s . c o m*/ try { line = parser.parse(options, args); if (line.hasOption("help")) { throw new ParseException(""); } } catch (ParseException e) { System.out.println(e.getLocalizedMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options, "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf " + "before starting bitcoind or bitcoin --daemon"); return; } String splitUrl[] = null; String splitUser[] = null; String splitPass[] = null; String splitHost[] = null; String splitPort[] = null; if (line.hasOption("url")) splitUrl = line.getOptionValue("url").split(","); if (line.hasOption("user")) splitUser = line.getOptionValue("user").split(","); if (line.hasOption("pass")) splitPass = line.getOptionValue("pass").split(","); if (line.hasOption("host")) splitHost = line.getOptionValue("host").split(","); if (line.hasOption("port")) splitPort = line.getOptionValue("port").split(","); int networkStatesCount = 0; if (splitUrl != null) networkStatesCount = splitUrl.length; if (splitUser != null) networkStatesCount = Math.max(splitUser.length, networkStatesCount); if (splitPass != null) networkStatesCount = Math.max(splitPass.length, networkStatesCount); if (splitHost != null) networkStatesCount = Math.max(splitHost.length, networkStatesCount); if (splitPort != null) networkStatesCount = Math.max(splitPort.length, networkStatesCount); if (networkStatesCount == 0) { error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r"); System.exit(-1); } int j = 0; for (int i = 0; j < networkStatesCount; i++, j++) { String protocol = "http"; String host = "localhost"; int port = 8332; String path = "/"; String user = "diablominer"; String pass = "diablominer"; byte hostChain = 0; if (splitUrl != null && splitUrl.length > i) { String[] usernameFix = splitUrl[i].split("@", 3); if (usernameFix.length > 2) splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2]; URL url = new URL(splitUrl[i]); if (url.getProtocol() != null && url.getProtocol().length() > 1) protocol = url.getProtocol(); if (url.getHost() != null && url.getHost().length() > 1) host = url.getHost(); if (url.getPort() != -1) port = url.getPort(); if (url.getPath() != null && url.getPath().length() > 1) path = url.getPath(); if (url.getUserInfo() != null && url.getUserInfo().length() > 1) { String[] userPassSplit = url.getUserInfo().split(":"); user = userPassSplit[0].replace("+++++", "@"); if (userPassSplit.length > 1 && userPassSplit[1].length() > 1) pass = userPassSplit[1]; } } if (splitUser != null && splitUser.length > i) user = splitUser[i]; if (splitPass != null && splitPass.length > i) pass = splitPass[i]; if (splitHost != null && splitHost.length > i) host = splitHost[i]; if (splitPort != null && splitPort.length > i) port = Integer.parseInt(splitPort[i]); NetworkState networkState; try { networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass, hostChain); } catch (MalformedURLException e) { throw new DiabloMinerFatalException(this, "Malformed connection paramaters"); } if (networkStateHead == null) { networkStateHead = networkStateTail = networkState; } else { networkStateTail.setNetworkStateNext(networkState); networkStateTail = networkState; } } networkStateTail.setNetworkStateNext(networkStateHead); if (line.hasOption("proxy")) { final String[] proxySettings = line.getOptionValue("proxy").split(":"); if (proxySettings.length >= 2) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1]))); } if (proxySettings.length >= 3) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray()); } }); } } if (line.hasOption("worklifetime")) workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000; if (line.hasOption("debug")) debug = true; if (line.hasOption("debugtimer")) { debugtimer = true; } if (line.hasOption("devices")) { String devices[] = line.getOptionValue("devices").split(","); enabledDevices = new HashSet<String>(); for (String s : devices) { enabledDevices.add(s); if (Integer.parseInt(s) == 0) { error("Do not use 0 with -D, devices start at 1"); System.exit(-1); } } } if (line.hasOption("fps")) { GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps")); if (GPUTargetFPS < 0.1) { error("--fps argument is too low, adjusting to 0.1"); GPUTargetFPS = 0.1; } } if (line.hasOption("noarray")) { GPUNoArray = true; } if (line.hasOption("worksize")) GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize")); if (line.hasOption("vectors")) { String tempVectors[] = line.getOptionValue("vectors").split(","); GPUVectors = new Integer[tempVectors.length]; try { for (int i = 0; i < GPUVectors.length; i++) { GPUVectors[i] = Integer.parseInt(tempVectors[i]); if (GPUVectors[i] > 16) { error("DiabloMiner now uses comma-seperated vector layouts, use those instead"); System.exit(-1); } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4 && GPUVectors[i] != 8 && GPUVectors[i] != 16) { error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16"); System.exit(-1); } } Arrays.sort(GPUVectors, Collections.reverseOrder()); } catch (NumberFormatException e) { error("Cannot parse --vector argument(s)"); System.exit(-1); } } else { GPUVectors = new Integer[1]; GPUVectors[0] = 1; } if (line.hasOption("ds")) GPUDebugSource = true; info("Started"); StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString()); NetworkState networkState = networkStateHead.getNetworkStateNext(); while (networkState != networkStateHead) { list.append(", " + networkState.getQueryUrl()); networkState = networkState.getNetworkStateNext(); } info("Connecting to: " + list); long previousHashCount = 0; double previousAdjustedHashCount = 0.0; long previousAdjustedStartTime = startTime = (now()) - 1; StringBuilder hashMeter = new StringBuilder(80); Formatter hashMeterFormatter = new Formatter(hashMeter); int deviceCount = 0; List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>(); List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates(); deviceCount += GPUDeviceStates.size(); allDeviceStates.add(GPUDeviceStates); while (running.get()) { for (List<? extends DeviceState> deviceStates : allDeviceStates) { for (DeviceState deviceState : deviceStates) { deviceState.checkDevice(); } } long now = now(); long currentHashCount = hashCount.get(); double adjustedHashCount = (double) (currentHashCount - previousHashCount) / (double) (now - previousAdjustedStartTime); double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0; if (now - startTime > TIME_OFFSET * 2) { double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0; hashMeter.setLength(0); if (!debug) { hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d", averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get()); } else { hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get()); double basisAverage = 0.0; for (List<? extends DeviceState> deviceStates : allDeviceStates) { for (DeviceState deviceState : deviceStates) { hashMeterFormatter.format("%.1f ", deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0); basisAverage += deviceState.getBasis(); } } basisAverage = 1000 / (basisAverage / deviceCount); hashMeterFormatter.format("| fps: %.1f", basisAverage); } System.out.print(hashMeter); } else { System.out.print("\rWaiting..."); } if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) { previousHashCount = currentHashCount; previousAdjustedHashCount = adjustedHashCount; previousAdjustedStartTime = now - 1; } if (debugtimer && now() > startTime + 60 * 1000) { System.out.print("\n"); info("Debug timer is up, quitting..."); System.exit(0); } try { if (now - startTime > TIME_OFFSET) Thread.sleep(1000); else Thread.sleep(1); } catch (InterruptedException e) { } } hashMeterFormatter.close(); }
From source file:sce.RESTCheckSLAJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { Connection conn = null;/* w ww . j av a2 s. c om*/ try { //required parameters #url, #slaId, #slaTimestamp JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String url1 = jobDataMap.getString("#url"); // e.g. http://kb-read:icaro@192.168.0.106:8080/IcaroKB/sparql if (url1 == null) { throw new JobExecutionException("#url parameter must be not null"); } String slaId = jobDataMap.getString("#slaId"); if (slaId == null) { throw new JobExecutionException("#slaId parameter must be not null"); } String slaTimestamp = jobDataMap.getString("#slaTimestamp"); // e.g. 2014-09-10T16:30:00 //if timestamp is not defined, use current if (slaTimestamp == null) { //throw new JobExecutionException("#slaTimestamp parameter must be not null"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); slaTimestamp = sdf.format(new Date()); } //first SPARQL query to retrieve services, metrics and thresholds in the SLA String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(slaId), "UTF-8"); URL u = new URL(url); final String usernamePassword = u.getUserInfo(); if (usernamePassword != null) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(usernamePassword.split(":")[0], usernamePassword.split(":")[1].toCharArray()); } }); } this.urlConnection = u.openConnection(); this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json"); HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(), HashMap.class); HashMap<String, Object> r = (HashMap<String, Object>) res.get("results"); ArrayList<Object> list = (ArrayList<Object>) r.get("bindings"); int bindings = list.size(); ArrayList<String[]> lst = new ArrayList<>(); for (Object obj : list) { HashMap<String, Object> o = (HashMap<String, Object>) obj; String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); String p = (String) ((HashMap<String, Object>) o.get("p")).get("value"); String callUrl = (String) ((HashMap<String, Object>) o.get("act")).get("value"); String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); lst.add(new String[] { mn, v, sm, p, callUrl, bc }); } //second SPARQL query to retrieve alerts for SLA url = url1 + "?query=" + URLEncoder.encode(getAlertsForSLA(lst, slaTimestamp), "UTF-8"); u = new URL(url); //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false); //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream); //out.write(getAlertsForSLA(lst, slaTimestamp)); //out.close(); this.urlConnection = u.openConnection(); this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json"); //format the result HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(), HashMap.class); HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results"); ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings"); //ArrayList<String[]> lst1 = new ArrayList<>(); //int counter = 0; String vv_temp; String result = ""; //LOAD QUARTZ PROPERTIES Properties prop = new Properties(); prop.load(this.getClass().getResourceAsStream("quartz.properties")); //MYSQL CONNECTION conn = Main.getConnection(); // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close() int counter = 0; //SET timestamp FOR MYSQL ROW Date dt = new java.util.Date(); SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = sdf.format(dt); //Hashmap to store callUrls to be called in case of alarm HashMap<String, Integer> callUrlMap = new HashMap<>(); // JSON to be sent to the SM JSONArray jsonArray = new JSONArray(); boolean notify = false; // whether notify the SM or not // Business Configuration String bc = ""; for (Object obj : list1) { //JSON to insert into database //JSONArray jsonArray = new JSONArray(); boolean alarm; //set to true if there is an alarm on sla HashMap<String, Object> o = (HashMap<String, Object>) obj; String y = (String) ((HashMap<String, Object>) o.get("y")).get("value"); //metric String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //timestamp //String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); String vm = (String) ((HashMap<String, Object>) o.get("vm")).get("value"); //virtual_machine String vmn = (String) ((HashMap<String, Object>) o.get("vmn")).get("value"); //virtual_machine_name String hm = o.get("hm") != null ? (String) ((HashMap<String, Object>) o.get("hm")).get("value") : ""; //host_machine //String na = (String) ((HashMap<String, Object>) o.get("na")).get("value"); //String ip = (String) ((HashMap<String, Object>) o.get("ip")).get("value"); String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //threshold String p = (String) ((HashMap<String, Object>) o.get("p")).get("value"); //relation (<,>,=) vv_temp = (String) ((HashMap<String, Object>) o.get("vv")).get("value"); //value String callUrl = (String) ((HashMap<String, Object>) o.get("callUrl")).get("value"); //call url bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business configuration /*JSONObject object = new JSONObject(); object.put("metric", y); object.put("metric_name", mn); object.put("metric_unit", mu); object.put("timestamp", mt); //object.put("service", sm); object.put("virtual_machine", vm); object.put("virtual_machine_name", vmn); object.put("host_machine", hm); object.put("value", vv_temp); object.put("relation", getProperty(p)); object.put("threshold", v); jsonArray.add(object);*/ //CHECK IF THE SLA IS VIOLATED alarm = checkSLA(Double.parseDouble(vv_temp), Double.parseDouble(v), p); // if alarm is true, then put the callUrl in a HashMap // and build the json object to be added to the json array to be sent to the SM if (alarm) { callUrlMap.put(callUrl, 1); notify = true; JSONObject object = new JSONObject(); object.put("sla", slaId); object.put("metric", y); object.put("metric_name", mn); object.put("metric_unit", mu); object.put("metric_timestamp", mt); object.put("virtual_machine", vm); object.put("virtual_machine_name", vmn); object.put("host_machine", hm); object.put("value", vv_temp); object.put("relation", p.substring(p.lastIndexOf("#") + 1)); object.put("threshold", v); object.put("call_url", callUrl); jsonArray.add(object); } //INSERT THE DATA INTO DATABASE PreparedStatement preparedStatement = conn.prepareStatement( "INSERT INTO quartz.QRTZ_SPARQL (timestamp, sla, alarm, metric, metric_name, metric_unit, metric_timestamp, virtual_machine, virtual_machine_name, host_machine, value, relation, threshold, call_url, business_configuration) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?"); preparedStatement.setString(1, timestamp); // date preparedStatement.setString(2, slaId); // sla preparedStatement.setInt(3, alarm ? 1 : 0); // alarm preparedStatement.setString(4, y); // metric preparedStatement.setString(5, mn); // metric_name preparedStatement.setString(6, mu); // metric_unit preparedStatement.setString(7, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00) preparedStatement.setString(8, vm); // virtual_machine preparedStatement.setString(9, vmn); // virtual_machine_name preparedStatement.setString(10, hm); // host_machine preparedStatement.setString(11, vv_temp); // value preparedStatement.setString(12, p.substring(p.lastIndexOf("#") + 1)); //relation (e.g., http://www.cloudicaro.it/cloud_ontology/core#hasMetricValueLessThan) preparedStatement.setString(13, v); // threshold preparedStatement.setString(14, callUrl); // callUrl preparedStatement.setString(15, bc); // business configuration preparedStatement.setString(16, timestamp); // date preparedStatement.executeUpdate(); preparedStatement.close(); //lst1.add(new String[]{y, mt, vv_temp}); result += "\nService Metric: " + y + "\n"; result += "\nMetric Name: " + mn + "\n"; result += "\nMetric Unit: " + mu + "\n"; result += "Timestamp: " + mt + "\n"; //result += "Service: " + sm + "\n"; result += "Virtual Machine: " + vm + "\n"; result += "Virtual Machine Name: " + vmn + "\n"; result += "Host Machine: " + hm + "\n"; //result += "Network Adapter: " + na + "\n"; //result += "IP: " + ip + "\n"; result += "Value" + (counter + 1) + ": " + vv_temp + "\n"; result += "Threshold: " + getProperty(lst.get(counter)[3]) + " " + lst.get(counter)[1] + "\n"; result += "Call Url: " + callUrl + "\n"; result += "Business Configuration: " + bc + "\n"; counter++; } // if the notify is true, then send the JSON to the SM if (notify) { JSONObject object = new JSONObject(); object.put("metric", jsonArray); object.put("business_configuration", bc); object.put("timestamp", timestamp); object.put("sla", slaId); sendPostRequest(object.toJSONString()); } //call the callUrls in the HashMap Iterator it = callUrlMap.entrySet().iterator(); while (it.hasNext()) { try { Map.Entry pairs = (Map.Entry) it.next(); URL u_callUrl = new URL((String) pairs.getKey()); //get user credentials from URL, if present final String usernamePasswordCallUrl = u_callUrl.getUserInfo(); //set the basic authentication credentials for the connection if (usernamePasswordCallUrl != null) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(usernamePasswordCallUrl.split(":")[0], usernamePasswordCallUrl.split(":")[1].toCharArray()); } }); } //call the callUrl URLConnection connection = u_callUrl.openConnection(); getUrlContents(connection); } catch (Exception e) { } it.remove(); // avoids a ConcurrentModificationException } //clean the callUrl map callUrlMap.clear(); //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener) context.setResult(result); if (jobDataMap.containsKey("#notificationEmail")) { sendEmail(context, jobDataMap.getString("#notificationEmail")); } jobChain(context); } catch (MalformedURLException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (IOException | SQLException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (!conn.isClosed()) { conn.close(); } } catch (SQLException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:org.broad.igv.util.HttpUtils.java
/** * Open a connection stream for the URL. * * @param url// w w w. j a v a 2s .c o m * @return * @throws IOException */ public InputStream openConnectionStream(URL url) throws IOException { log.debug("Opening connection stream to " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { String userInfo = url.getUserInfo(); String host = url.getHost(); String file = url.getPath(); FTPClient ftp = FTPUtils.connect(host, userInfo, new UserPasswordInputImpl()); ftp.pasv(); ftp.retr(file); return new FTPStream(ftp); } else { return openConnectionStream(url, null); } }
From source file:org.georchestra.security.Proxy.java
private URI buildUri(URL url) throws URISyntaxException { // Let URI constructor encode Path part URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), null, // Don't use query part because URI constructor will try to double encode it // (query part is already encoded in sURL) url.getRef());/*w ww. j a v a2s.c o m*/ // Reconstruct URL with encoded path from URI class and others parameters from URL class StringBuilder rawUrl = new StringBuilder(url.getProtocol() + "://" + url.getHost()); if (url.getPort() != -1) rawUrl.append(":" + String.valueOf(url.getPort())); rawUrl.append(uri.getRawPath()); // Use encoded version from URI class if (url.getQuery() != null) rawUrl.append("?" + url.getQuery()); // Use already encoded query part return new URI(rawUrl.toString()); }
From source file:com.connectsdk.service.DLNAService.java
String encodeURL(String mediaURL) throws MalformedURLException, URISyntaxException, UnsupportedEncodingException { if (mediaURL == null || mediaURL.isEmpty()) { return ""; }// w w w.j a va 2s . c o m String decodedURL = URLDecoder.decode(mediaURL, "UTF-8"); if (decodedURL.equals(mediaURL)) { URL url = new URL(mediaURL); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); return uri.toASCIIString(); } return mediaURL; }
From source file:org.sakaiproject.util.impl.FormattedTextImpl.java
public String sanitizeHrefURL(String urlToSanitize) { if (urlToSanitize == null) return null; if (StringUtils.isBlank(urlToSanitize)) return null; if (ABOUT_BLANK.equals(urlToSanitize)) return ABOUT_BLANK; boolean trimProtocol = false; boolean trimHost = false; // For a protocol-relative URL, we validate with protocol attached // RFC 1808 Section 4 if ((urlToSanitize.startsWith("//")) && (urlToSanitize.indexOf("://") == -1)) { urlToSanitize = PROTOCOL_PREFIX + urlToSanitize; trimProtocol = true;/*from www . j a va 2 s .c o m*/ } // For a site-relative URL, we validate with host name and protocol attached // SAK-13787 SAK-23752 if ((urlToSanitize.startsWith("/")) && (urlToSanitize.indexOf("://") == -1)) { urlToSanitize = HOST_PREFIX + urlToSanitize; trimHost = true; } // KNL-1105 try { URL rawUrl = new URL(urlToSanitize); URI uri = new URI(rawUrl.getProtocol(), rawUrl.getUserInfo(), rawUrl.getHost(), rawUrl.getPort(), rawUrl.getPath(), rawUrl.getQuery(), rawUrl.getRef()); URL encoded = uri.toURL(); String retval = encoded.toString(); // Un-trim the added bits if (trimHost && retval.startsWith(HOST_PREFIX)) { retval = retval.substring(HOST_PREFIX.length()); } if (trimProtocol && retval.startsWith(PROTOCOL_PREFIX)) { retval = retval.substring(PROTOCOL_PREFIX.length()); } // http://stackoverflow.com/questions/7731919/why-doesnt-uri-escape-escape-single-quotes // We want these to be usable in JavaScript string values so we map single quotes retval = retval.replace("'", "%27"); // We want anchors to work retval = retval.replace("%23", "#"); // Sorry - these just need to come out - they cause to much trouble // Note that ampersand is not encoded as it is used for parameters. retval = retval.replace("&#", ""); retval = retval.replace("%25", "%"); return retval; } catch (java.net.URISyntaxException e) { M_log.info("Failure during encode of href url: " + e); return null; } catch (java.net.MalformedURLException e) { M_log.info("Failure during encode of href url: " + e); return null; } }
From source file:org.mule.transport.soap.axis.extensions.MuleHttpSender.java
/** * Send the soap request message to the server * * @param msgContext message context/*ww w . j ava2 s.c om*/ * @param tmpURL url to connect to * @param otherHeaders other headers if any * @param host host name * @param port port * @param useFullURL flag to indicate if the whole url needs to be sent * @throws IOException */ private InputStream writeToSocket(SocketHolder sockHolder, MessageContext msgContext, URL tmpURL, StringBuffer otherHeaders, String host, int port, int timeout, BooleanHolder useFullURL) throws Exception { String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { StringBuffer tmpBuf = new StringBuffer(64); tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd); otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION).append(": Basic ") .append(Base64.encode(tmpBuf.toString().getBytes())).append("\r\n"); } // don't forget the cookies! // mmm... cookies if (msgContext.getMaintainSession()) { String cookie = msgContext.getStrProp(HTTPConstants.HEADER_COOKIE); String cookie2 = msgContext.getStrProp(HTTPConstants.HEADER_COOKIE2); if (cookie != null) { otherHeaders.append(HTTPConstants.HEADER_COOKIE).append(": ").append(cookie).append("\r\n"); } if (cookie2 != null) { otherHeaders.append(HTTPConstants.HEADER_COOKIE2).append(": ").append(cookie2).append("\r\n"); } } StringBuffer header2 = new StringBuffer(64); String webMethod = null; boolean posting = true; Message reqMessage = msgContext.getRequestMessage(); boolean http10 = true; // True if this is to use HTTP 1.0 / false HTTP // 1.1 boolean httpChunkStream = false; // Use HTTP chunking or not. boolean httpContinueExpected = false; // Under HTTP 1.1 if false you // *MAY* need to wait for a 100 // rc, // if true the server MUST reply with 100 continue. String httpConnection = null; String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (null == httpver) { httpver = HTTPConstants.HEADER_PROTOCOL_V10; } httpver = httpver.trim(); if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) { http10 = false; } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { if (null == otherHeaders) { otherHeaders = new StringBuffer(1024); } for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { java.util.Map.Entry me = (java.util.Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) { if (!http10) { String val = me.getValue().toString(); if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { httpChunkStream = true; } } } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) { if (!http10) { String val = me.getValue().toString(); if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE)) { httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE; } } // HTTP 1.0 will always close. // HTTP 1.1 will use persistent. //no need to specify } else { if (!http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) { String val = me.getValue().toString(); if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) { httpContinueExpected = true; } } otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n"); } } } if (!http10) { // Force close for now. // TODO HTTP/1.1 httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE; } header2.append(" "); header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 : HTTPConstants.HEADER_PROTOCOL_11).append("\r\n"); MimeHeaders mimeHeaders = reqMessage.getMimeHeaders(); if (posting) { String contentType; if (mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) { contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0]; } else { contentType = reqMessage.getContentType(msgContext.getSOAPConstants()); } header2.append(HTTPConstants.HEADER_CONTENT_TYPE).append(": ").append(contentType).append("\r\n"); } header2.append(ACCEPT_HEADERS).append(HTTPConstants.HEADER_HOST) // used for virtual connections .append(": ").append(host).append((port == -1) ? ("") : (":" + port)).append("\r\n") .append(CACHE_HEADERS).append(HTTPConstants.HEADER_SOAP_ACTION) // The SOAP action. .append(": \"").append(action).append("\"\r\n"); if (posting) { if (!httpChunkStream) { // Content length MUST be sent on HTTP 1.0 requests. header2.append(HTTPConstants.HEADER_CONTENT_LENGTH).append(": ") .append(reqMessage.getContentLength()).append("\r\n"); } else { // Do http chunking. header2.append(CHUNKED_HEADER); } } // Transfer MIME headers of SOAPMessage to HTTP headers. if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) { continue; } header2.append(mimeHeader.getName()).append(": ").append(mimeHeader.getValue()).append("\r\n"); } } if (null != httpConnection) { header2.append(HTTPConstants.HEADER_CONNECTION); header2.append(": "); header2.append(httpConnection); header2.append("\r\n"); } getSocket(sockHolder, msgContext, targetURL.getProtocol(), host, port, timeout, otherHeaders, useFullURL); if (null != otherHeaders) { // Add other headers to the end. // for pre java1.4 support, we have to turn the string buffer // argument into // a string before appending. header2.append(otherHeaders.toString()); } header2.append("\r\n"); // The empty line to start the BODY. StringBuffer header = new StringBuffer(128); // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); } if (webMethod == null) { webMethod = HTTPConstants.HEADER_POST; } else { posting = webMethod.equals(HTTPConstants.HEADER_POST); } header.append(webMethod).append(" "); if (useFullURL.value) { header.append(tmpURL.toExternalForm()); } else { header.append(StringUtils.isEmpty(tmpURL.getFile()) ? "/" : tmpURL.getFile()); } header.append(header2.toString()); OutputStream out = sockHolder.getSocket().getOutputStream(); if (!posting) { out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING)); out.flush(); return null; } InputStream inp = null; if (httpChunkStream || httpContinueExpected) { out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING)); } if (httpContinueExpected) { // We need to get a reply from the server as // to whether // it wants us send anything more. out.flush(); Hashtable cheaders = new Hashtable(); inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders); int returnCode = -1; Integer Irc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE); if (null != Irc) { returnCode = Irc.intValue(); } if (100 == returnCode) { // got 100 we may continue. // Need TODO a little msgContext house keeping.... msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE); msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE); } else { // If no 100 Continue then we must not send anything! String statusMessage = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString(Messages.getMessage("return01", String.valueOf(returnCode), "")); throw fault; } } ByteArrayOutputStream baos = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("xmlSent00")); log.debug("---------------------------------------------------"); baos = new ByteArrayOutputStream(); } if (httpChunkStream) { ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out); out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE); try { if (baos != null) { out = new TeeOutputStream(out, baos); } reqMessage.writeTo(out); } catch (SOAPException e) { log.error(Messages.getMessage("exception00"), e); } out.flush(); chunkedOutputStream.eos(); } else { out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE); try { if (!httpContinueExpected) { out.write(header.toString().getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING)); } if (baos != null) { out = new TeeOutputStream(out, baos); } reqMessage.writeTo(out); } catch (SOAPException e) { throw e; } finally { // Flush ONLY once. out.flush(); } } if (log.isDebugEnabled() && baos != null) { log.debug(header + new String(baos.toByteArray())); } return inp; }