List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java
@Override public String call() throws IOException { String response = ""; ReviewInput reviewInput = createReview(); String reviewEndpoint = resolveEndpointURL(); HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint); if (httpPost == null) { return response; }//from ww w . ja v a 2 s .c om CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(AuthScope.ANY, credentials); HttpHost proxy = null; if (httpProxy != null && !httpProxy.isEmpty()) { try { URL url = new URL(httpProxy); proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); if (altLogger != null) { altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage()); } } } HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultCredentialsProvider(credProvider); if (proxy != null) { builder.setProxy(proxy); } CloseableHttpClient httpClient = builder.build(); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase()); if (altLogger != null) { altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase()); } } } catch (Exception e) { logger.error("Failed to submit result to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString()); } } return response; }
From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java
public boolean subscribeContext(String codUser, String nameContext) { HttpURLConnection conn = null; StringBuffer strBOutput = new StringBuffer(); boolean boolOK = true; String input = null;// w w w.j a v a2 s. co m StringBuffer stbInput = new StringBuffer(); try { log.debug("subscribeContext Start "); conn = getEventServiceSEConnection(methodSubscribeContext, endpointEventService, headerContentTypeJSON); stbInput.append("{\"entities\": [{\"type\": \"" + typeContextValue + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\" } ],"); stbInput.append("\"attributes\": [\"" + nameContext + "\"] ,"); stbInput.append("\"reference\": \"" + notificationEndpoint + "\","); stbInput.append("\"duration\": \"P1M\","); stbInput.append("\"notifyConditions\": [ {\"type\": \"ONCHANGE\",\"condValues\": [\"" + nameContext + "\"]}],\"throttling\": \"PT5S\"}"); input = stbInput.toString(); log.debug(input); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() == 200) { log.debug("subscribeContext Response code " + conn.getResponseCode()); } else { if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException( "subscribeContext Failed : HTTP error code : " + conn.getResponseCode()); } } log.debug("subscribeContext OutputStream wrote"); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); log.debug("subscribeContext Waiting server response "); String output; log.debug("subscribeContext Output from Server .... \n"); while ((output = br.readLine()) != null) { strBOutput.append(output); log.debug(output); } conn.disconnect(); boolOK = true; } catch (MalformedURLException e) { log.error("subscribeContext MalformedURLException " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.error("subscribeContext IOException " + e.getMessage()); e.printStackTrace(); } return boolOK; }
From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java
public boolean updateContext(String codUser, String nameContext, String typeContext, String valueContext, boolean valueIsjson) { HttpURLConnection conn = null; StringBuffer strBOutput = new StringBuffer(); boolean boolOK = true; String input = null;//www. j a v a2 s . c o m StringBuffer stbInput = new StringBuffer(); try { log.debug("updateContext Start "); conn = getEventServiceSEConnection(methodUpdateContext, endpointEventService, headerContentTypeJSON); stbInput.append("{\"contextElements\": [{\"type\": \"" + typeContextValue + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\",\"attributes\":"); if (valueIsjson) stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": " + valueContext + "}]}]"); else stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": \"" + valueContext + "\"}]}]"); stbInput.append(",\"updateAction\": \"APPEND\"}"); input = stbInput.toString(); log.debug(input); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() == 200) { log.debug("updateContext Response code " + conn.getResponseCode()); } else { if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException( "updateContext Failed : HTTP error code : " + conn.getResponseCode()); } } log.debug("updateContext OutputStream wrote"); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); log.debug("updateContext Waiting server response "); String output; log.debug("updateContext Output from Server .... \n"); while ((output = br.readLine()) != null) { strBOutput.append(output); log.debug(output); } conn.disconnect(); boolOK = true; } catch (MalformedURLException e) { log.error("updateContext MalformedURLException " + e.getMessage()); e.printStackTrace(); boolOK = false; } catch (IOException e) { log.error("updateContext IOException " + e.getMessage()); e.printStackTrace(); boolOK = false; } return boolOK; }
From source file:com.mobiperf.speedometer.measurements.HttpTask.java
/** * Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off *//*from ww w .ja v a2s. c om*/ @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; String errorMsg = ""; InputStream inputStream = null; 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); Logger.i(">>> success = " + success + " " + statusCode); } else { Logger.i(">>> statusLine is null"); } /* * 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); 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:org.wso2.carbon.analytics.api.internal.client.AnalyticsAPIHttpClient.java
public static void init(AnalyticsDataConfiguration dataConfiguration) throws AnalyticsServiceException { try {/*from w w w .ja va2 s . c o m*/ URL url = new URL(dataConfiguration.getEndpoint()); instance = new AnalyticsAPIHttpClient(url.getProtocol(), url.getHost(), url.getPort(), dataConfiguration.getMaxConnectionsPerRoute(), dataConfiguration.getMaxConnections(), dataConfiguration.getSocketConnectionTimeoutMS(), dataConfiguration.getConnectionTimeoutMS(), getTrustStoreLocation(dataConfiguration.getTrustStoreLocation()), getTrustStorePassword(dataConfiguration.getTrustStorePassword())); } catch (MalformedURLException e) { throw new AnalyticsServiceException( "Error while initializing the analytics http client. " + e.getMessage(), e); } }
From source file:OrientedTest.java
public void init() { // the paths to the image files for an applet if (earthImage == null) { try {/* ww w . ja va 2s . c o m*/ earthImage = new java.net.URL(getCodeBase().toString() + "/earth.jpg"); } catch (java.net.MalformedURLException ex) { System.out.println(ex.getMessage()); System.exit(1); } } if (stoneImage == null) { try { stoneImage = new java.net.URL(getCodeBase().toString() + "/stone.jpg"); } catch (java.net.MalformedURLException ex) { System.out.println(ex.getMessage()); System.exit(1); } } setLayout(new BorderLayout()); GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); Canvas3D c = new Canvas3D(config); add("Center", c); // Create a simple scene and attach it to the virtual universe BranchGroup scene = createSceneGraph(); u = new SimpleUniverse(c, 4); // add mouse behaviors to ViewingPlatform ViewingPlatform viewingPlatform = u.getViewingPlatform(); // there is a special rotate behavior, so can't use the utility // method MouseRotateY rotate = new MouseRotateY(MouseRotateY.INVERT_INPUT); rotate.setTransformGroup(viewingPlatform.getMultiTransformGroup().getTransformGroup(0)); BranchGroup rotateBG = new BranchGroup(); rotateBG.addChild(rotate); viewingPlatform.addChild(rotateBG); BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); rotate.setSchedulingBounds(bounds); MouseZoom zoom = new MouseZoom(c, MouseZoom.INVERT_INPUT); zoom.setTransformGroup(viewingPlatform.getMultiTransformGroup().getTransformGroup(1)); zoom.setSchedulingBounds(bounds); BranchGroup zoomBG = new BranchGroup(); zoomBG.addChild(zoom); viewingPlatform.addChild(zoomBG); MouseTranslate translate = new MouseTranslate(c, MouseTranslate.INVERT_INPUT); translate.setTransformGroup(viewingPlatform.getMultiTransformGroup().getTransformGroup(2)); translate.setSchedulingBounds(bounds); BranchGroup translateBG = new BranchGroup(); translateBG.addChild(translate); viewingPlatform.addChild(translateBG); // This will move the ViewPlatform back a bit so the // objects in the scene can be viewed. u.getViewingPlatform().setNominalViewingTransform(); u.addBranchGraph(scene); }
From source file:fi.laverca.EtsiClient.java
/** * @param msspSignatureUrl Connection URL to the AE for signature requests. * @param msspStatusUrl Connection URL to the AE for status query requests. * @param msspReceiptUrl Connection URL to the AE for receipt requests. * @param msspRegistrationUrl Connection URL to the AE for registration requests. * @param msspProfileUrl Connection URL to the AE for profile query requests. * @param msspHandshakeUrl Connection URL to the AE for handshake requests. *///from w ww . j a v a 2 s . c om public void setAeAddress(String msspSignatureUrl, String msspStatusUrl, String msspReceiptUrl, String msspRegistrationUrl, String msspProfileUrl, String msspHandshakeUrl) throws IllegalArgumentException { try { if (msspSignatureUrl != null) { this.MSSP_SI_URL = new URL(msspSignatureUrl); } if (msspStatusUrl != null) { this.MSSP_ST_URL = new URL(msspStatusUrl); } if (msspReceiptUrl != null) { this.MSSP_RC_URL = new URL(msspReceiptUrl); } if (msspRegistrationUrl != null) { this.MSSP_RG_URL = new URL(msspRegistrationUrl); } if (msspProfileUrl != null) { this.MSSP_PR_URL = new URL(msspProfileUrl); } if (msspHandshakeUrl != null) { this.MSSP_HS_URL = new URL(msspHandshakeUrl); } } catch (MalformedURLException mue) { throw new IllegalArgumentException(mue.getMessage()); } }
From source file:com.fluidops.iwb.deepzoom.ImageLoader.java
/** * Loads an image from a URL to a local file * @param uri - The URL from which to obtain the image * @param file - The file to store the image to * @return//w ww . j av a2 s . c o m */ public boolean loadGoogleImage(URI uri, Map<URI, Set<Value>> facets, File file) { String url; URL u; InputStream is = null; BufferedInputStream dis = null; int b; try { URL googleUrl; ReadDataManager dm = EndpointImpl.api().getDataManager(); String label = dm.getLabel(uri); // TODO: currently hard coded logic for data sets // should find more flexible logic if (uri.stringValue().startsWith("http://www.ckan.net/")) label += " logo"; googleUrl = new URL("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&" + "q=" + URLEncoder.encode(label, "UTF-8")); URLConnection connection = googleUrl.openConnection(); connection.addRequestProperty("Referer", "http://iwb.fluidops.com/"); String content = GenUtil.readUrl(connection.getInputStream()); try { JSONObject json = new JSONObject(content); JSONObject response = json.getJSONObject("responseData"); JSONArray results = response.getJSONArray("results"); JSONObject result = results.getJSONObject(0); url = result.getString("unescapedUrl"); } catch (JSONException e) { return false; } u = new URL(url); try { is = u.openStream(); } catch (IOException e) { System.out.println("File could not be found: " + url); // quick fix: 200px-Image n/a, try smaller pic (for Wikipedia images) url = url.replace("200px", "94px"); u = new URL(url); try { is = u.openStream(); } catch (IOException e2) { System.out.println("also smaller image not available"); return false; } } dis = new BufferedInputStream(is); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); while ((b = dis.read()) != -1) { out.write(b); } out.flush(); } finally { IOUtils.closeQuietly(out); } } catch (MalformedURLException mue) { logger.error(mue.getMessage(), mue); return false; } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); return false; } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(dis); } return true; }
From source file:com.vmware.identity.openidconnect.client.ClientRegistrationHelper.java
private URL buildEndpointWithClientID(URL tenantizedAdminServerURL, ClientID clientID) throws OIDCClientException { Validate.notNull(tenantizedAdminServerURL, "tenantizedAdminServerURL"); Validate.notNull(clientID, "clientID"); StringBuilder sb = new StringBuilder(tenantizedAdminServerURL.toString()); sb.append(clientID.getValue());// w w w .j a v a 2 s . co m try { return new URL(sb.toString()); } catch (MalformedURLException e) { throw new OIDCClientException("Failed to build endpoint with clientID: " + e.getMessage(), e); } }