List of usage examples for java.net MalformedURLException toString
public String toString()
From source file:it.cicolella.phwswethv2.ProgettiHwSwEthv2.java
private void changeRelayStatus(Board board, Command c) { try {//from w w w.j av a 2 s . c om URL url = null; URLConnection urlConnection; String delimiter = configuration.getProperty("address-delimiter"); String[] address = c.getProperty("address").split(delimiter); String relayNumber = HexIntConverter.convert(Integer.parseInt(address[1]) - 1); // if required set the authentication if (board.getAuthentication().equalsIgnoreCase("true")) { String authString = board.getUsername() + ":" + board.getPassword(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/protect/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("behavior")); urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } else { //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("behavior")); urlConnection = url.openConnection(); } LOG.info("Freedomotic sends the command " + url); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int numCharsRead; char[] charArray = new char[1024]; StringBuffer sb = new StringBuffer(); while ((numCharsRead = isr.read(charArray)) > 0) { sb.append(charArray, 0, numCharsRead); } String result = sb.toString(); } catch (MalformedURLException e) { LOG.severe("Change relay status malformed URL " + e.toString()); } catch (IOException e) { LOG.severe("Change relay status IOexception" + e.toString()); } }
From source file:pagelyzer.Capture.java
/** * This function is a adaptation from the initWebDriver() method from BrowserShot_mapred proyect * Initialize the webdriver given the capability object * @param capability//w w w. j av a 2s . c o m * @return */ public void initWebDriver() { String msg = ""; boolean done = false; int attemptNo = 0; while (!done && attemptNo < ATTEMPTMAX) {// to limit attempts to 10 ZP attemptNo++; try { System.out.println("Attempt = " + attemptNo); if (config.getString("selenium.run.mode").equals(JPagelyzer.LOCAL)) { this.browser.setLocalDriver(); } else { this.browser.setRemoteDriver(config.getString("selenium.server.url")); } this.browser.resize(config.getInt("selenium.client.width"), config.getInt("selenium.client.height")); done = true; } catch (MalformedURLException e) { throw new RuntimeException("Invalid Selenium driver URL", e); } catch (IOException e) { if (config.getBoolean("pagelyzer.run.verbose")) { msg = e.toString(); } System.out.println("Attempt failed sleeping for 10s." + msg); try { Thread.sleep(10 * 1000); } catch (InterruptedException ex) { Logger.getLogger(Capture.class.getName()).log(Level.SEVERE, null, ex); } } catch (WebDriverException e) { if (config.getBoolean("pagelyzer.run.verbose")) { msg = e.toString(); } System.out.println("Attempt failed sleeping for 10s." + msg); try { Thread.sleep(10 * 1000); } catch (InterruptedException ex) { Logger.getLogger(Capture.class.getName()).log(Level.SEVERE, null, ex); } } catch (Exception e) { if (config.getBoolean("pagelyzer.run.verbose")) { msg = e.toString(); } System.out.println("Some proble arrived :(" + msg); } } }
From source file:com.ptts.sync.SyncAdapter.java
/** * Called by the Android system in response to a request to run the sync adapter. The work * required to read data from the network, parse it, and store it in the content provider is * done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter * run on a background thread. For this reason, blocking I/O and other long-running tasks can be * run <em>in situ</em>, and you don't have to set up a separate thread for them. . * * <p>This is where we actually perform any work required to perform a sync. * {@link AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread, * so it is safe to peform blocking I/O here. * * <p>The syncResult argument allows you to pass information back to the method that triggered * the sync./*ww w . j a v a2s . c o m*/ */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.i(TAG, "Beginning network synchronization"); try { final URL location = new URL(FEED_URL); InputStream stream = null; try { Log.i(TAG, "Streaming data from network: " + location); stream = downloadUrl(location); updateLocalFeedData(stream, syncResult); // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (stream != null) { stream.close(); } } } catch (MalformedURLException e) { Log.wtf(TAG, "Feed URL is malformed", e); syncResult.stats.numParseExceptions++; return; } catch (IOException e) { Log.e(TAG, "Error reading from network: " + e.toString()); syncResult.stats.numIoExceptions++; return; } catch (JSONException e) { Log.e(TAG, "Error parsing feed: " + e.toString()); syncResult.stats.numParseExceptions++; return; } catch (ParseException e) { Log.e(TAG, "Error parsing feed: " + e.toString()); syncResult.stats.numParseExceptions++; return; } catch (RemoteException e) { Log.e(TAG, "Error updating database: " + e.toString()); syncResult.databaseError = true; return; } catch (OperationApplicationException e) { Log.e(TAG, "Error updating database: " + e.toString()); syncResult.databaseError = true; return; } catch (Throwable t) { Log.i(TAG, "thrown error"); } Log.i(TAG, "Network synchronization complete"); }
From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java
/** * Constructs a temporary file that merges together the requested filename as * it is found in different artifacts (jars). The URL to the merged file is * returned./* w ww. j a va 2 s.c om*/ * * @param filename * The file to look for in the classloader. * @return The merged result of the found filenames. * @throws IOException */ private URL constructUrl(final String xml, final String filename) throws IOException { if (debug) LOG.debug(filename + " " + xml); // The base directory must be empty since JPA will scan it searching for // classes. final File file = new File(System.getProperty("java.io.tmpdir") + "/sakai/" + filename); if (file.getParentFile().mkdirs()) { if (debug) LOG.debug("Created " + file); } final PrintWriter pw = new PrintWriter(new FileWriter(file)); pw.print(xml); pw.close(); URL url = null; try { url = file.toURI().toURL(); } catch (MalformedURLException e) { LOG.error("cannot convert file to URL " + e.toString()); } if (debug) LOG.debug("URL: " + url); final URL urlout = url; return urlout; }
From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.java
private void changeRelayStatus(Board board, Command c) { try {//from w w w . java2 s. c o m URL url = null; URLConnection urlConnection; String delimiter = configuration.getProperty("address-delimiter"); String[] address = c.getProperty("address").split(delimiter); String relayNumber = HexIntConverter.convert(Integer.parseInt(address[1]) - 1); // if required set the authentication if (board.getAuthentication().equalsIgnoreCase("true")) { String authString = board.getUsername() + ":" + board.getPassword(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/protect/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("status")); urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } else { //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("status")); urlConnection = url.openConnection(); } LOG.info("Freedomotic sends the command " + url); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int numCharsRead; char[] charArray = new char[1024]; StringBuffer sb = new StringBuffer(); while ((numCharsRead = isr.read(charArray)) > 0) { sb.append(charArray, 0, numCharsRead); } String result = sb.toString(); } catch (MalformedURLException e) { LOG.severe("Change relay status malformed URL " + e.toString()); } catch (IOException e) { LOG.severe("Change relay status IOexception" + e.toString()); } }
From source file:org.lockss.crawler.FuncArcExploder.java
private void checkCrawlRules() { if (multipleStemsPerAu) { String testUrl = expectedStems[1] + "branch1/index.html"; CachedUrl cu = pluginMgr.findCachedUrl(testUrl); assertNotNull("No CU for " + testUrl, cu); ArchivalUnit au = cu.getArchivalUnit(); assertNotNull(au);/* w ww . j a v a 2 s. c om*/ for (int i = 0; i < yes.length; i++) { assertTrue(yes[i] + " should be cached", au.shouldBeCached(yes[i])); } for (int i = 0; i < no.length; i++) { assertFalse(no[i] + " should not be cached", au.shouldBeCached(no[i])); } } else { for (int i = 0; i < yes.length; i++) { CachedUrl cu = null; String testUrl = null; try { testUrl = UrlUtil.getUrlPrefix(yes[i]) + "branch1/index.html"; cu = pluginMgr.findCachedUrl(testUrl); } catch (MalformedURLException ex) { fail(ex.toString() + " " + testUrl); } assertNotNull("No CU for " + testUrl, cu); ArchivalUnit au = cu.getArchivalUnit(); assertNotNull(au); assertTrue(yes[i] + " should be cached", au.shouldBeCached(yes[i])); } } }
From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.java
private void toggleRelay(Board board, Command c) { try {/*from w w w. j a va 2s . c o m*/ URL url = null; URLConnection urlConnection; String delimiter = configuration.getProperty("address-delimiter"); String[] address = c.getProperty("address").split(delimiter); String relayNumber = address[1]; int time = Integer.parseInt(c.getProperty("time-in-ms")); int seconds = time / 1000; String relayLine = configuration.getProperty("TOGGLE" + seconds + "S" + relayNumber); // if required set the authentication if (board.getAuthentication().equalsIgnoreCase("true")) { String authString = board.getUsername() + ":" + board.getPassword(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/protect/" + TOGGLE_RELAY_URL + relayLine); urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } else { //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/" + TOGGLE_RELAY_URL + relayLine); urlConnection = url.openConnection(); } LOG.info("Freedomotic sends the command " + url); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int numCharsRead; char[] charArray = new char[1024]; StringBuffer sb = new StringBuffer(); while ((numCharsRead = isr.read(charArray)) > 0) { sb.append(charArray, 0, numCharsRead); } String result = sb.toString(); } catch (MalformedURLException e) { LOG.severe("Change relay status malformed URL " + e.toString()); } catch (IOException e) { LOG.severe("Change relay status IOexception" + e.toString()); } }
From source file:com.intuit.tank.http.BaseRequest.java
/** * Execute the POST.//from w ww . j a v a 2s . c om */ public void doPost(BaseResponse response) { PostMethod httppost = null; String theUrl = null; try { URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables); theUrl = url.toExternalForm(); httppost = new PostMethod(url.toString()); String requestBody = getBody(); StringRequestEntity entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet); httppost.setRequestEntity(entity); sendRequest(response, httppost, requestBody); } catch (MalformedURLException e) { logger.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e); // swallowing error. validatin will check if there is no response // and take appropriate action throw new RuntimeException(e); } catch (Exception ex) { // logger.error(LogUtil.getLogMessage(ex.toString()), ex); // swallowing error. validatin will check if there is no response // and take appropriate action throw new RuntimeException(ex); } finally { if (null != httppost) { httppost.releaseConnection(); } if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) { logger.info(LogUtil.getLogMessage("Response from POST to " + theUrl + " got status code " + response.httpCode + " BODY { " + response.response + " }", LogEventType.Informational)); } } }
From source file:com.owly.srv.RemoteBasicStatItfImpl.java
public boolean getStatusRemoteServer(String ipSrv, int clientPort) { URL url = null;//from w ww. j a va 2 s. c o m BufferedReader reader = null; StringBuilder stringBuilder; JSONObject objJSON = new JSONObject(); JSONParser objParser = new JSONParser(); String statusServer = "Enable"; // Check status of remote server with healthCheck logger.debug("Check status of remote server with healthCheck"); // Url to send to remote server // for example : // http://135.1.128.127:5000/healthCheck String urlToSend = "http://" + ipSrv + ":" + clientPort + "/healthCheck"; logger.debug("URL for HTTP request : " + urlToSend); HttpURLConnection connection; try { url = new URL(urlToSend); connection = (HttpURLConnection) url.openConnection(); // just want to do an HTTP GET here connection.setRequestMethod("GET"); // uncomment this if you want to write output to this url // connection.setDoOutput(true); // give it 2 second to respond connection.setReadTimeout(1 * 1000); connection.connect(); // read the output from the server reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } logger.debug("Response received : " + stringBuilder.toString()); // map the response into a JSON object objJSON = (JSONObject) objParser.parse(stringBuilder.toString()); // Check the response of the sever with the previous request String resServer = (String) objJSON.get("StatusServer"); // If we dont receive the correct health checl we will save the // disable state in the database if (resServer.equals("OK")) { statusServer = "Enable"; } else { statusServer = "Disable"; } logger.debug("Status of the Server: " + statusServer); } catch (MalformedURLException e1) { logger.error("MalformedURLException : " + e1.getMessage()); logger.error("Exception ::", e1); statusServer = "Disable"; logger.debug("Status of the Server: " + statusServer); } catch (IOException e1) { logger.error("IOException : " + e1.toString()); logger.error("Exception ::", e1); e1.printStackTrace(); statusServer = "Disable"; logger.debug("Status of the Server: " + statusServer); } catch (ParseException e1) { logger.error("ParseException : " + e1.toString()); logger.error("Exception ::", e1); statusServer = "Disable"; logger.debug("Status of the Server: " + statusServer); } finally { logger.debug("Save Status of Server in Database: " + statusServer); } if (statusServer.equals("Enable")) { return true; } else { return false; } }
From source file:gov.usda.DataCatalogClient.Distribution.java
private void setAccessURL(String accessURL_String) throws DistributionException { if (accessURL_String != null) { try {// www .j a v a 2s . co m this.accessURL = new URL(accessURL_String); } catch (MalformedURLException e) { throw new DistributionException("Invalid accessUrl" + e.toString()); } } }