List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestURLhandlerImpl.java
/** * This location will vary depending on if the ingest is running as a task. * A task will put the reports into a temporary directory prior to performing * the finalization of the ingest (e-mailing results, posting rest responses). * //from w ww . jav a 2 s. com * @see edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestOptions#isRunningAsRemoteTask() */ public URL getIngestReportLocationURL() { URL ingestReportURL = null; ingestReportURL = this.getLogFilesFolderURL(); String host = ingestReportURL.getHost(); String protocol = ingestReportURL.getProtocol(); int port = ingestReportURL.getPort(); String filePath = ingestReportURL.getFile(); try { ingestReportURL = new URL(protocol, host, port, filePath + this.getUniqueBatchRunName() + FedoraAppConstants.BATCH_INGEST_REPORT_FILE_EXT); } catch (MalformedURLException e) { // the original url has already been checked so this should never happen. throw new RuntimeException(e.getMessage()); } return ingestReportURL; }
From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestURLhandlerImpl.java
/** * This location will vary depending on if the ingest is running as a task. * A task will put the reports into a temporary directory prior to performing * the finalization of the ingest (e-mailing results, posting rest responses). * //from w w w. java 2s . c om * @see edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestOptions#isRunningAsRemoteTask() */ public URL getPidReportLocationURL() { URL pidReportURL = null; pidReportURL = this.getLogFilesFolderURL(); String host = pidReportURL.getHost(); String protocol = pidReportURL.getProtocol(); int port = pidReportURL.getPort(); String filePath = pidReportURL.getFile(); try { pidReportURL = new URL(protocol, host, port, filePath + this.getUniqueBatchRunName() + FedoraAppConstants.BATCH_INGEST_PID_REPORT_FILE_EXT); } catch (MalformedURLException e) { // the original url has already been checked so this should never happen. throw new RuntimeException(e.getMessage()); } return pidReportURL; }
From source file:org.commonjava.util.jhttpc.HttpFactory.java
public HttpClientContext createContext(final SiteConfig location) throws JHttpCException { HttpClientContext ctx = HttpClientContext.create(); if (location != null) { final AuthScope as; try {/* w w w . j av a2 s . c o m*/ as = new AuthScope(location.getHost(), location.getPort()); } catch (MalformedURLException e) { throw new JHttpCException( "Failed to parse site URL for host and port: %s (site id: %s). Reason: %s", e, location.getUri(), location.getId(), e.getMessage()); } if (location.getUser() != null) { if (authenticator != null) { ctx = authenticator.decoratePrototypeContext(as, location, PasswordType.USER, ctx); } } if (location.getProxyHost() != null && location.getProxyUser() != null) { if (authenticator != null) { ctx = authenticator.decoratePrototypeContext( new AuthScope(location.getProxyHost(), getProxyPort(location)), location, PasswordType.PROXY, ctx); } } } return ctx; }
From source file:com.gmt2001.TwitchAPIv2.java
private JSONObject GetData(request_type type, String url, String post, String oauth) { JSONObject j = new JSONObject(); try {/*from w ww .jav a 2 s . c om*/ URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(timeout); c.connect(); if (!post.isEmpty()) { IOUtils.write(post, c.getOutputStream()); } String content; if (c.getResponseCode() == 200) { content = IOUtils.toString(c.getInputStream(), c.getContentEncoding()); } else { content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding()); } j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_exception", ""); j.put("_exceptionMessage", ""); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); } return j; }
From source file:net.sourceforge.cobertura.test.util.WebappServer.java
public void pingServer() { String webappResponse = null; try {/*ww w . ja v a2s.co m*/ webappResponse = IOUtils .toString(new URL("http://localhost:" + webappPort + "/" + appName + "/SimpleServlet") .openConnection().getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } assertNotNull(webappResponse); assertEquals("Webapp response was incorrect", "Hi", webappResponse.trim()); }
From source file:net.sourceforge.cobertura.test.util.WebappServer.java
public void pingCoberturaServer() { //flush the cobertura data by doing an HTTP get String flushing = null;/*from w w w. j a va2 s .co m*/ try { flushing = IOUtils .toString(new java.net.URL("http://localhost:" + webappPort + "/coberturaFlush/flushCobertura") .openConnection().getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } assertNotNull(flushing); assertEquals("", flushing.trim()); }
From source file:com.nec.harvest.controller.PettyCashbookReportController.java
/** * PDF??//from w w w.j a v a 2s . co m * * @param pdfUUID * String * @param request * HttpServletRequest * @param response * HttpServletResponse * @param orgCode * String * @param model * Model * @param userOrgCode * String */ @RequestMapping(value = "/{orgCode}/{pdfUUID}", method = RequestMethod.GET) public void viewReport(@PathVariable String orgCode, @PathVariable String pdfUUID, final HttpServletResponse response) throws IOException { if (logger.isDebugEnabled()) { logger.debug("PDF??"); } String fileURL = jasperReportResolver.getReportPath() + File.separator + pdfUUID + PDF_EXTENSION; String reportName = URLEncoder.encode(getTitleName(), HttpServletContentType.DEFAULT_ENCODING); // ?? response.setHeader("Content-disposition", "inline; filename=" + reportName + PDF_EXTENSION); response.setContentType(HttpServletContentType.APPLICATION_PDF); response.setCharacterEncoding(HttpServletContentType.DEFAULT_ENCODING); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new File(fileURL).toURI().toURL(); // Use Buffered Stream for reading/writing. bis = new BufferedInputStream(url.openStream()); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final MalformedURLException ex) { logger.warn(ex.getMessage()); throw ex; } catch (final IOException ex) { logger.warn(ex.getMessage()); throw ex; } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } }
From source file:com.mobilyzer.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *//* w w w. j a v a 2 s . c o m*/ @Override 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; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; long currentRxTx = Util.getCurrentRxTxBytes(); 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()); 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(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* 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); } } duration = System.currentTimeMillis() - startTime;//TODO check this } 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(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx); if (taskProgress == TaskProgress.COMPLETED) { 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)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } 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:com.mobilyzer.measurements.HttpTask_original.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *///from www .j a va 2 s. c o m @Override 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_original.MAX_BODY_SIZE_TO_UPLOAD); // boolean success = false; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; long currentRxTx = Util.getCurrentRxTxBytes(); 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()); 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(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* 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); } } duration = System.currentTimeMillis() - startTime;//TODO check this } 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(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx); if (taskProgress == TaskProgress.COMPLETED) { 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)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } 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:com.ironiacorp.scm.subversion.SubversionRepositoryTransaction.java
/** * Set the URL used to access the repository. * /*from w w w. j a v a 2 s . c om*/ * @param url The address that will be used to access the repository. * * @throws RepositoryTransactionError The URL is invalid. */ private void setUrl(String url) { try { new URL(url); } catch (MalformedURLException e) { log.debug(e.getMessage()); throw new RepositoryTransactionError("exception.repositoryTransaction.invalidRepositoryURL", e); } this.url = url; }