List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:com.collabnet.ccf.pt.schemageneration.PTLayoutExtractor.java
public PTrackerWebServicesClient connect(String repositoryId) { if (StringUtils.isEmpty(repositoryId)) { throw new IllegalArgumentException("Repository Id cannot be null"); }//from ww w.ja v a 2s.c o m String username = getUsername(); String password = getPassword(); String projectName = null; if (repositoryId != null) { String[] splitProjectName = repositoryId.split(":"); if (splitProjectName != null) { if (splitProjectName.length >= 1) { projectName = splitProjectName[0]; } else { throw new IllegalArgumentException( "Repository id is not valid." + " Could not extract project name from repository id"); } } } String connectionInfo = getServerUrl(); String url = connectionInfo.substring(0, connectionInfo.indexOf("://") + 3) + projectName + "." + connectionInfo.substring(connectionInfo.indexOf("://") + 3); PTrackerWebServicesClient twsclient = null; try { twsclient = TrackerClientManager.getInstance().createClient(url, username, password, null, null); } catch (MalformedURLException e) { String message = "Exception when trying to get the Web Services client: " + e.getMessage(); // log.error(message, e); throw new CCFRuntimeException(message, e); } return twsclient; }
From source file:com.mobiperf.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */ @Override/*w ww. ja va2 s .c o m*/ public MeasurementResult call() throws MeasurementError { int statusCode = HttpTask.DEFAULT_STATUS_CODE; long duration = 0; long originalHeadersLen = 0; long originalBodyLen; String headers = null; ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD); boolean success = false; String errorMsg = ""; InputStream inputStream = null; // This is not the ideal way of doing things, as we can pick up data // from other processes and be overly cautious in running measurements. // However, taking the packet sizes is completely inaccurate, and it's hard to // come up with a consistent expected value, unlike with DNS RRCTask.PacketMonitor packetmonitor = new RRCTask.PacketMonitor(); packetmonitor.setBySize(); packetmonitor.readCurrentPacketValues(); try { // set the download URL, a URL that points to a file on the Internet // this is the file to be downloaded HttpDesc task = (HttpDesc) this.measurementDesc; String urlStr = task.url; // TODO(Wenjie): Need to set timeout for the HTTP methods httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent)); HttpRequestBase request = null; if (task.method.compareToIgnoreCase("head") == 0) { request = new HttpHead(urlStr); } else if (task.method.compareToIgnoreCase("get") == 0) { request = new HttpGet(urlStr); } else if (task.method.compareToIgnoreCase("post") == 0) { request = new HttpPost(urlStr); HttpPost postRequest = (HttpPost) request; postRequest.setEntity(new StringEntity(task.body)); } else { // Use GET by default request = new HttpGet(urlStr); } if (task.headers != null && task.headers.trim().length() > 0) { for (String headerLine : task.headers.split("\r\n")) { String tokens[] = headerLine.split(":"); if (tokens.length == 2) { request.addHeader(tokens[0], tokens[1]); } else { throw new MeasurementError("Incorrect header line: " + headerLine); } } } byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE]; int readLen; int totalBodyLen = 0; long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(request); /* TODO(Wenjie): HttpClient does not automatically handle the following codes * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY * 303 See Other. HttpStatus.SC_SEE_OTHER * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT * * We may want to fetch instead from the redirected page. */ StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); success = (statusCode == 200); } /* For HttpClient to work properly, we still want to consume the entire response even if * the status code is not 200 */ HttpEntity responseEntity = response.getEntity(); originalBodyLen = responseEntity.getContentLength(); long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE; // getContentLength() returns negative number if body length is unknown if (originalBodyLen > 0) { expectedResponseLen = originalBodyLen; } if (responseEntity != null) { inputStream = responseEntity.getContent(); while ((readLen = inputStream.read(readBuffer)) > 0 && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) { totalBodyLen += readLen; // Fill in the body to report up to MAX_BODY_SIZE if (body.remaining() > 0) { int putLen = body.remaining() < readLen ? body.remaining() : readLen; body.put(readBuffer, 0, putLen); } this.progress = (int) (100 * totalBodyLen / expectedResponseLen); this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress); broadcastProgressForUser(this.progress); } duration = System.currentTimeMillis() - startTime; } Header[] responseHeaders = response.getAllHeaders(); if (responseHeaders != null) { headers = ""; for (Header hdr : responseHeaders) { /* * TODO(Wenjie): There can be preceding and trailing white spaces in * each header field. I cannot find internal methods that return the * number of bytes in a header. The solution here assumes the encoding * is one byte per character. */ originalHeadersLen += hdr.toString().length(); headers += hdr.toString() + "\r\n"; } } PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils(); MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId, phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success, this.measurementDesc); result.addResult("code", statusCode); dataConsumed = packetmonitor.getPacketsSentDiff(); if (success) { result.addResult("time_ms", duration); result.addResult("headers_len", originalHeadersLen); result.addResult("body_len", totalBodyLen); result.addResult("headers", headers); result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT)); } Logger.i(MeasurementJsonConvertor.toJsonString(result)); return result; } catch (MalformedURLException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } catch (IOException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Logger.e("Fails to close the input stream from the HTTP response"); } } if (httpClient != null) { httpClient.close(); } } throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg); }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public double testDownload() { double bw = 0.0; try {/*from w ww . j a va 2 s . c o m*/ Date oldTime = new Date(); URL obj = new URL(amazonDomain + "/download_test.bin"); HttpURLConnection httpGetCon = (HttpURLConnection) obj.openConnection(); // optional default is GET httpGetCon.setRequestMethod("GET"); httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds httpGetCon.setReadTimeout(5000); //add request header httpGetCon.setRequestProperty("User-Agent", USER_AGENT); if (httpGetCon.getResponseCode() == 200) { Date newTime = new Date(); double milliseconds = newTime.getTime() - oldTime.getTime(); int lenght = httpGetCon.getContentLength(); bw = ((double) lenght * 8) / (milliseconds * (double) 1000); } // BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); // String inputLine; // StringBuffer response = new StringBuffer(); // while ((inputLine = in.readLine()) != null) { // response.append(inputLine); // } // in.close(); // // //print result // System.out.println(response.toString()); } catch (MalformedURLException e) { System.out.println("MalformedURLException is fired!"); } catch (IOException e) { System.out.println("Exception is fired in download test. error:" + e.getMessage()); } return bw; }
From source file:InterleavedNIOBuffer.java
public void init() { // create textures if (texImage1 == null) { // the path to the image for an applet try {/*w w w.j a v a 2 s . c o m*/ texImage1 = new java.net.URL(getCodeBase().toString() + "/bg.jpg"); } catch (java.net.MalformedURLException ex) { System.out.println(ex.getMessage()); System.exit(1); } } if (texImage2 == null) { // the path to the image for an applet try { texImage2 = new java.net.URL(getCodeBase().toString() + "/one.jpg"); } catch (java.net.MalformedURLException ex) { System.out.println(ex.getMessage()); System.exit(1); } } Container contentPane = getContentPane(); Canvas3D c = new Canvas3D(SimpleUniverse.getPreferredConfiguration()); contentPane.add("Center", c); BranchGroup scene = createSceneGraph(); // SimpleUniverse is a Convenience Utility class u = new SimpleUniverse(c); // add mouse behaviors to the viewingPlatform ViewingPlatform viewingPlatform = u.getViewingPlatform(); // This will move the ViewPlatform back a bit so the // objects in the scene can be viewed. viewingPlatform.setNominalViewingTransform(); // add Orbit behavior to the viewing platform OrbitBehavior orbit = new OrbitBehavior(c, OrbitBehavior.REVERSE_ALL); BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); orbit.setSchedulingBounds(bounds); viewingPlatform.setViewPlatformBehavior(orbit); u.addBranchGraph(scene); // Create GUI JPanel p = new JPanel(); BoxLayout boxlayout = new BoxLayout(p, BoxLayout.Y_AXIS); p.add(createGeometryByReferencePanel()); p.setLayout(boxlayout); contentPane.add("South", p); }
From source file:com.google.wireless.speed.speedometer.measurements.PingTask.java
/** * Use the HTTP Head method to emulate ping. The measurement from this method can be * substantially (2x) greater than the first two methods and inaccurate. This is because, * depending on the implementing of the destination web server, either a quick HTTP * response is replied or some actual heavy lifting will be done in preparing the response * *//* w ww.jav a 2s.c om*/ private MeasurementResult executeHttpPingTask() throws MeasurementError { long pingStartTime = 0; long pingEndTime = 0; ArrayList<Double> rrts = new ArrayList<Double>(); PingDesc pingTask = (PingDesc) this.measurementDesc; String errorMsg = ""; MeasurementResult result = null; try { long totalPingDelay = 0; HttpClient client = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent)); HttpHead headMethod = new HttpHead("http://" + targetIp); headMethod.addHeader(new BasicHeader("Connection", "close")); headMethod.setParams(new BasicHttpParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000)); int timeOut = (int) (1000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT); HttpConnectionParams.setConnectionTimeout(headMethod.getParams(), timeOut); for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) { pingStartTime = System.currentTimeMillis(); HttpResponse response = client.execute(headMethod); pingEndTime = System.currentTimeMillis(); rrts.add((double) (pingEndTime - pingStartTime)); this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT; broadcastProgressForUser(progress); } Log.i(SpeedometerApp.TAG, "HTTP get ping succeeds"); double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT); result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT); } catch (MalformedURLException e) { Log.e(SpeedometerApp.TAG, e.getMessage()); errorMsg += e.getMessage() + "\n"; } catch (IOException e) { Log.e(SpeedometerApp.TAG, e.getMessage()); errorMsg += e.getMessage() + "\n"; } if (result != null) { return result; } else { Log.i(SpeedometerApp.TAG, "HTTP get ping fails"); throw new MeasurementError(errorMsg); } }
From source file:com.mobiperf_library.measurements.PingTask.java
/** * Use the HTTP Head method to emulate ping. The measurement from this method can be * substantially (2x) greater than the first two methods and inaccurate. This is because, * depending on the implementing of the destination web server, either a quick HTTP * response is replied or some actual heavy lifting will be done in preparing the response * *//* w w w . java2s .c o m*/ private MeasurementResult executeHttpPingTask() throws MeasurementError { long pingStartTime = 0; long pingEndTime = 0; ArrayList<Double> rrts = new ArrayList<Double>(); PingDesc pingTask = (PingDesc) this.measurementDesc; String errorMsg = ""; MeasurementResult result = null; try { long totalPingDelay = 0; URL url = new URL("http://" + pingTask.target); int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT); for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) { pingStartTime = System.currentTimeMillis(); HttpURLConnection httpClient = (HttpURLConnection) url.openConnection(); httpClient.setRequestProperty("Connection", "close"); httpClient.setRequestMethod("HEAD"); httpClient.setReadTimeout(timeOut); httpClient.setConnectTimeout(timeOut); httpClient.connect(); pingEndTime = System.currentTimeMillis(); httpClient.disconnect(); rrts.add((double) (pingEndTime - pingStartTime)); this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT; broadcastProgressForUser(progress); } Logger.i("HTTP get ping succeeds"); Logger.i("RTT is " + rrts.toString()); double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT); result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP); } catch (MalformedURLException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } catch (IOException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } if (result != null) { return result; } else { Logger.i("HTTP get ping fails"); throw new MeasurementError(errorMsg); } }
From source file:org.commonjava.indy.core.ctl.ReplicationController.java
private List<? extends ArtifactStore> getRemoteStores(final ReplicationDTO dto) throws IndyWorkflowException { final String apiUrl = dto.getApiUrl(); String remotesUrl = null;//w w w .ja v a 2 s . co m String groupsUrl = null; String hostedUrl = null; try { remotesUrl = buildUrl(apiUrl, "/admin/remotes"); groupsUrl = buildUrl(apiUrl, "/admin/groups"); hostedUrl = buildUrl(apiUrl, "/admin/hosted"); } catch (final MalformedURLException e) { throw new IndyWorkflowException( "Failed to construct store definition-retrieval URL from api-base: {}. Reason: {}", e, apiUrl, e.getMessage()); } // logger.info( "\n\n\n\n\n[AutoProx] Checking URL: {} from:", new Throwable(), url ); final List<ArtifactStore> result = new ArrayList<ArtifactStore>(); addStoresFrom(result, remotesUrl, dto, RemoteRepository.class); addStoresFrom(result, groupsUrl, dto, Group.class); addStoresFrom(result, hostedUrl, dto, HostedRepository.class); return result; }
From source file:org.commonjava.indy.core.ctl.ReplicationController.java
private List<EndpointView> getEndpoints(final ReplicationDTO dto) throws IndyWorkflowException { final String apiUrl = dto.getApiUrl(); String url = null;//from ww w . j a v a 2 s . c o m try { url = buildUrl(apiUrl, "/stats/all-endpoints"); } catch (final MalformedURLException e) { throw new IndyWorkflowException( "Failed to construct endpoint-retrieval URL from api-base: {}. Reason: {}", e, apiUrl, e.getMessage()); } final HttpGet req = newGet(url, dto); CloseableHttpClient client = null; try { String siteId = new URL(url).getHost(); client = http.createClient(siteId); CloseableHttpResponse response = client.execute(req, http.createContext(siteId)); final StatusLine statusLine = response.getStatusLine(); final int status = statusLine.getStatusCode(); if (status == HttpStatus.SC_OK) { final String json = HttpResources.entityToString(response); final EndpointViewListing listing = serializer.readValue(json, EndpointViewListing.class); return listing.getItems(); } throw new IndyWorkflowException(status, "Endpoint request failed: {}", statusLine); } catch (final IOException | IndyHttpException e) { throw new IndyWorkflowException("Failed to retrieve endpoints from: {}. Reason: {}", e, url, e.getMessage()); } finally { IOUtils.closeQuietly(client); } }
From source file:com.celamanzi.liferay.portlets.rails286.BodyTagVisitor.java
/** an URL may be: * a) http://foobar/baz.png/*from w w w .ja v a 2 s . c om*/ * b) /baz.png * c) baz.png * * The URL may point to external location and therefore it should be determined wheter it should be translated. * 1) test if the src contains '://', and if true, convert it to java.net.URL * 2) if false, or if the host of the URL equals to baseUrl, the src should be translated */ private boolean isExternal(String src) { log.debug("Checking externality"); Pattern p = Pattern.compile("://"); Matcher m = p.matcher(src); if (!m.find()) { return false; } else { // convert the src to URL try { java.net.URL srcUrl = new java.net.URL(src); log.debug("Comparing " + srcUrl.getHost() + " with " + baseUrl.getHost()); if (srcUrl.getHost().equals(baseUrl.getHost())) { return false; } else { log.debug(src + " is an external URL"); return true; } } catch (java.net.MalformedURLException e) { log.error(e.getMessage()); return false; } } }