List of usage examples for java.net MalformedURLException getLocalizedMessage
public String getLocalizedMessage()
From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java
@Override public String validateConfig(final HttpServletRequest req, final Account account, final PluginConfig pluginConf) throws TwoPhaseAuthenticationRequiredException { try {/*w w w . j a v a 2s. c om*/ final JenkinsClient client = JenkinsClient.getInstance(account, pluginConf); final ViewList views = client.getViewList(req); if (views == null || views.getViews() == null || views.getViews().size() <= 0) { return "Unable to retrieve views from Jenkins at " + pluginConf.getUrl(); } } catch (final MalformedURLException e) { return "Invalid Jenkins Server URL:\n" + pluginConf.getUrl(); } catch (final TwoPhaseAuthenticationRequiredException e) { throw e; } catch (final IOException e) { final String localizedMessage = e.getLocalizedMessage(); return "Error contacting Jenkins at " + pluginConf.getUrl() + (localizedMessage != null ? "\n" + localizedMessage : ""); } return null; }
From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java
private ArrayList<URL> getCrlUrl(final Certificate cert) { ArrayList<URL> urls = new ArrayList<URL>(); if (StringUtils.isNotEmpty(this.crlUrl)) { try {//from www .ja v a2 s .c o m urls.add(new URL(this.crlUrl)); } catch (MalformedURLException e) { if (log.isDebugEnabled()) { log.debug("Failed to parse '" + this.crlUrl + "' as a URL. " + e.getLocalizedMessage()); } } } Collection<URL> crlUrlFromExtension = CertTools.getCrlDistributionPoints((X509Certificate) cert); urls.addAll(crlUrlFromExtension); return urls; }
From source file:com.networkmanagerapp.JSONBackgroundDownloaderService.java
/** * Delegate method to run the specified intent in another thread. * @param arg0 The intent to run in the background *//*ww w . ja v a 2s. c o m*/ @Override protected void onHandleIntent(Intent arg0) { mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); String filename = arg0.getStringExtra("FILENAME"); String jsonFile = arg0.getStringExtra("JSONFILE"); try { String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); Log.d("password", password); String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"); String enc = URLEncoder.encode(ip, "UTF-8"); String scriptUrl = "http://" + enc + ":1080" + filename; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(params, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 20000; HttpConnectionParams.setSoTimeout(params, timeoutSocket); HttpHost targetHost = new HttpHost(enc, 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(params); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpGet request = new HttpGet(scriptUrl); HttpResponse response = client.execute(targetHost, request); Log.d("JBDS", response.getStatusLine().toString()); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); if (str.toString().equals("Success\n")) { String xmlUrl = "http://" + enc + ":1080/json" + jsonFile; request = new HttpGet(xmlUrl); HttpResponse jsonData = client.execute(targetHost, request); in = jsonData.getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(in)); str = new StringBuilder(); line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); FileOutputStream fos = openFileOutput(jsonFile.substring(1), Context.MODE_PRIVATE); fos.write(str.toString().getBytes()); fos.close(); } } catch (MalformedURLException ex) { Log.e("NETWORKMANAGER_XBD_MUE", ex.getMessage()); } catch (IOException e) { try { Log.e("NETWORK_MANAGER_XBD_IOE", e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (int i = 0; i < st.length; i++) { Log.e("NETWORK_MANAGER_XBD_IOE", st[i].toString()); } } catch (NullPointerException ex) { Log.e("Network_manager_xbd_npe", ex.getLocalizedMessage()); } } finally { mNM.cancel(R.string.download_service_started); Intent bci = new Intent(NEW_DATA_AVAILABLE); sendBroadcast(bci); stopSelf(); } }
From source file:ws.argo.responder.ProbeHandlerThread.java
/** * If the probe yields responses from the handler, then send this method will * send the responses to the given respondTo addresses. * /* w ww.j av a 2 s .c o m*/ * @param respondToURL - address to send the response to * @param payloadType - JSON or XML * @param payload - the actual service records to return * @return true if the send was successful */ private boolean sendResponse(String respondToURL, String payloadType, ResponseWrapper payload) { // This method will likely need some thought and care in the error handling // and error reporting // It's a had job at the moment. String responseStr = null; String contentType = null; // MIME type boolean success = true; switch (payloadType) { case "XML": { responseStr = payload.toXML(); contentType = "application/xml"; break; } case "JSON": { responseStr = payload.toJSON(); contentType = "application/json"; break; } default: responseStr = payload.toJSON(); } try { HttpPost postRequest = new HttpPost(respondToURL); StringEntity input = new StringEntity(responseStr); input.setContentType(contentType); postRequest.setEntity(input); LOGGER.debug("Sending response"); LOGGER.debug("Response payload:"); LOGGER.debug(responseStr); CloseableHttpResponse httpResponse = httpClient.execute(postRequest); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode > 300) { throw new RuntimeException( "Failed : HTTP error code : " + httpResponse.getStatusLine().getStatusCode()); } if (statusCode != 204) { BufferedReader br = new BufferedReader( new InputStreamReader((httpResponse.getEntity().getContent()))); LOGGER.debug("Successful response from response target - " + respondToURL); String output; LOGGER.debug("Output from Listener .... \n"); while ((output = br.readLine()) != null) { LOGGER.debug(output); } br.close(); } } finally { httpResponse.close(); } LOGGER.info("Successfully handled probeID: " + probe.getProbeId() + " sending response to: " + respondToURL); } catch (MalformedURLException e) { success = false; LOGGER.error("MalformedURLException occured for probeID [" + payload.getProbeID() + "]" + "\nThe respondTo URL was a no good. respondTo URL is: " + respondToURL); } catch (IOException e) { success = false; LOGGER.error("An IOException occured for probeID [" + payload.getProbeID() + "]" + " - " + e.getLocalizedMessage()); LOGGER.debug("Stack trace for IOException for probeID [" + payload.getProbeID() + "]", e); } catch (Exception e) { success = false; LOGGER.error("Some other error occured for probeID [" + payload.getProbeID() + "]" + ". respondTo URL is: " + respondToURL + " - " + e.getLocalizedMessage()); LOGGER.debug("Stack trace for probeID [" + payload.getProbeID() + "]", e); } return success; }
From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java
/** * @param uri/*w w w. ja v a 2 s .c o m*/ * @param parameters * @return */ public boolean fetchPageContent(String uri, List<NameValuePair> parameters) { // Set login, ssl, port, host etc; applyConfig(); mErrorText = ""; mErrorTextId = -1; mError = false; mBytes = new byte[0]; if (!uri.startsWith("/")) { uri = "/".concat(uri); } HttpURLConnection conn = null; try { if (mProfile.getSessionId() != null) parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId())); URL url = new URL(buildUrl(uri, parameters)); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(mConnectionTimeoutMillis); if (DreamDroid.featurePostRequest()) conn.setRequestMethod("POST"); setAuth(conn); if (conn.getResponseCode() != 200) { if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) { // Method not allowed, the target device either can't handle // POST or GET requests (old device or Anti-Hijack enabled) DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest()); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD; return fetchPageContent(uri, parameters); } if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) { createSession(); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED; return fetchPageContent(uri, parameters); } mRememberedReturnCode = 0; Log.e(LOG_TAG, Integer.toString(conn.getResponseCode())); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_UNAUTHORIZED: mErrorTextId = R.string.auth_error; break; default: mErrorTextId = -1; } mErrorText = conn.getResponseMessage(); mError = true; return false; } BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; int bufSize = 512; byte[] buffer = new byte[bufSize]; while ((read = bis.read(buffer)) != -1) { baf.append(buffer, 0, read); } mBytes = baf.toByteArray(); if (DreamDroid.dumpXml()) dumpToFile(url); return true; } catch (MalformedURLException e) { mError = true; mErrorTextId = R.string.illegal_host; } catch (UnknownHostException e) { mError = true; mErrorText = null; mErrorTextId = R.string.host_not_found; } catch (ProtocolException e) { mError = true; mErrorText = e.getLocalizedMessage(); } catch (ConnectException e) { mError = true; mErrorTextId = R.string.host_unreach; } catch (IOException e) { e.printStackTrace(); mError = true; mErrorText = e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); if (mError) if (mErrorText == null) mErrorText = "Error text is null"; Log.e(LOG_TAG, mErrorText); } return false; }
From source file:eu.codeplumbers.cosi.services.CosiContactService.java
public void sendChangesToCozy() { List<Contact> unSyncedContacts = Contact.getAllUnsynced(); int i = 0;//from w ww . j a va 2s . co m for (Contact contact : unSyncedContacts) { URL urlO = null; try { JSONObject jsonObject = contact.toJsonObject(); System.out.println(jsonObject.toString()); mBuilder.setProgress(unSyncedContacts.size(), i + 1, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new ContactSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_contacts_ongoing_sync))); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(syncUrl); requestMethod = "POST"; } else { urlO = new URL(syncUrl + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); long objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); contact.setRemoteId(result); contact.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } i++; } }
From source file:org.kalypso.ogc.gml.wms.provider.images.AbstractDeegreeImageProvider.java
/** * This function parses a String into an URL to the WMS service. * /* ww w . jav a 2 s.c om*/ * @param service * The String representation of the URL to the WMS service. * @return The URL to the WMS service. */ private URL parseServiceUrl(final String service) throws CoreException { try { final String resolvedService = VariableUtils.resolveVariablesQuietly(service); return new URL(resolvedService); } catch (final MalformedURLException e) { throw new CoreException(StatusUtilities.statusFromThrowable(e, Messages.getString("org.kalypso.ogc.gml.wms.provider.images.AbstractDeegreeImageProvider.3", //$NON-NLS-1$ service, e.getLocalizedMessage()))); } }
From source file:com.qut.middleware.deployer.logic.RegisterESOELogic.java
private String generateSubjectDN(String dn) { try {//from w w w .j av a 2 s. co m String result = new String(); URL serviceURL = new URL(dn); String[] components = serviceURL.getHost().split("\\."); for (String component : components) { if (result.length() != 0) result = result + ","; result = result + "dc=" + component; } return result; } catch (MalformedURLException e) { this.logger.error("Error attempting to generate certificate subjectDN " + e.getLocalizedMessage()); this.logger.debug(e.toString()); return "dc=" + dn; } }
From source file:TimestreamsTests.java
/** * Tests calling the API documentation page *//*from w w w. j ava 2s. c o m*/ @Test public void testGetDocumentation() { try { URL url = new URL(BASEURL); getTest(url); } catch (MalformedURLException e) { fail(e.getLocalizedMessage()); } }
From source file:TimestreamsTests.java
/** * Tests calling the API time//from w w w .jav a 2s.c om */ @Test public void testGetTime() { try { URL url = new URL(BASEURL + "/time"); getTest(url); } catch (MalformedURLException e) { fail(e.getLocalizedMessage()); } }