List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:com.omertron.slackbot.utils.HttpTools.java
/** * Create a URL from a string//w ww . ja va 2 s . co m * * @param urlString * @return * @throws ApiException */ public static URL createUrl(String urlString) throws ApiException { try { return new URL(urlString); } catch (MalformedURLException ex) { throw new ApiException(ApiExceptionType.INVALID_URL, ex.getMessage(), urlString, ex); } }
From source file:illab.nabal.util.ParameterHelper.java
/** * Parse a URL query and fragment parameters into a key-value bundle. * /*w w w.j a va 2 s .c om*/ * @param url - the URL to parse * @return bundle - a dictionary bundle of keys and values */ public static Bundle parseGetParams(String url) { // prepare a bundle Bundle bundle = null; try { URL u = new URL(url); bundle = decodeGetParams(u.getQuery()); bundle.putAll(decodeGetParams(u.getRef())); } catch (MalformedURLException e) { Log.e(TAG, "malformed URL"); Log.e(TAG, e.getMessage()); } return bundle; }
From source file:cn.ctyun.amazonaws.regions.RegionUtils.java
/** * Searches through all known regions to find one with any service at the * specified endpoint. If no region is found with a service at that * endpoint, an exception is thrown./* w w w. ja v a2 s. c o m*/ * * @param endpoint * The endpoint for any service residing in the desired region. * @return The region containing any service running at the specified * endpoint, otherwise an exception is thrown if no region is found * with a service at the specified endpoint. * @throws MalformedURLException * If the given URL is malformed, or if the one of the service * URLs on record is malformed. */ public static Region getRegionByEndpoint(String endpoint) throws MalformedURLException { URL targetEndpointUrl = null; try { targetEndpointUrl = new URL(endpoint); } catch (MalformedURLException e) { throw new RuntimeException("Unable to parse service endpoint: " + e.getMessage()); } String targetHost = targetEndpointUrl.getHost(); for (Region region : getRegions()) { for (String serviceEndpoint : region.getServiceEndpoints().values()) { URL serviceEndpointUrl = new URL(serviceEndpoint); if (serviceEndpointUrl.getHost().equals(targetHost)) return region; } } throw new RuntimeException("No region found with any service for endpoint " + endpoint); }
From source file:de.egore911.versioning.deployer.Main.java
private static void perform(String arg, CommandLine line) throws IOException { URL url;/*from w w w. j a v a 2s .c o m*/ try { url = new URL(arg); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); System.exit(1); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response != HttpURLConnection.HTTP_OK) { LOG.error("Could not download {}", url); connection.disconnect(); System.exit(1); return; } } catch (ConnectException e) { LOG.error("Error during download from URI {}: {}", url, e.getMessage()); System.exit(1); return; } XmlHolder xmlHolder = XmlHolder.getInstance(); DocumentBuilder documentBuilder = xmlHolder.documentBuilder; XPath xPath = xmlHolder.xPath; try { XPathExpression serverNameXpath = xPath.compile("/server/name/text()"); XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()"); XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment"); Document doc = documentBuilder.parse(connection.getInputStream()); connection.disconnect(); String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING); LOG.info("Deploying {}", serverName); boolean shouldPerformCopy = !line.hasOption('r'); PerformCopy performCopy = new PerformCopy(xPath); boolean shouldPerformExtraction = !line.hasOption('r'); PerformExtraction performExtraction = new PerformExtraction(xPath); boolean shouldPerformCheckout = !line.hasOption('r'); PerformCheckout performCheckout = new PerformCheckout(xPath); boolean shouldPerformReplacement = true; PerformReplacement performReplacement = new PerformReplacement(xPath); String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING); FileUtils.forceMkdir(new File(targetdir)); NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc, XPathConstants.NODESET); int max = serverDeploymentsDeploymentNodes.getLength(); for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) { Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i); // Copy if (shouldPerformCopy) { performCopy.perform(serverDeploymentsDeploymentNode); } // Extraction if (shouldPerformExtraction) { performExtraction.perform(serverDeploymentsDeploymentNode); } // Checkout if (shouldPerformCheckout) { performCheckout.perform(serverDeploymentsDeploymentNode); } // Replacement if (shouldPerformReplacement) { performReplacement.perform(serverDeploymentsDeploymentNode); } logPercent(i + 1, max); } // validate that "${versioning:" is not present Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE, TrueFileFilter.INSTANCE); for (File file : files) { String content; try { content = FileUtils.readFileToString(file); } catch (IOException e) { continue; } if (content.contains("${versioning:")) { LOG.error("{} contains placeholders even after applying the replacements", file.getAbsolutePath()); } } LOG.info("Done deploying {}", serverName); } catch (SAXException | IOException | XPathExpressionException e) { LOG.error("Error performing deployment: {}", e.getMessage(), e); } }
From source file:ict.servlet.UploadToServer.java
public static int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null;//from w w w.j av a2s.c o m DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close streams m_log.info("Upload file to server" + fileName + " File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { // ex.printStackTrace(); m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { // e.printStackTrace(); } //this block will give the response of upload link /* try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { m_log.info("Huzza" + "RES Message: " + line); } rd.close(); } catch (IOException ioex) { m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex); }*/ return serverResponseCode; // like 200 (Ok) }
From source file:net.yacy.cora.federate.opensearch.SRURSSConnector.java
/** * send a query to a yacy public search interface * @param rssSearchServiceURL the target url base (everything before the ? that follows the SRU request syntax properties). can null, then the local peer is used * @param query the query as string//from www . j a va 2 s . c o m * @param startRecord number of first record * @param maximumRecords maximum number of records * @param verify if true, result entries are verified using the snippet fetch (slow); if false simply the result is returned * @param global if true also search results from other peers are included * @return */ public static RSSFeed loadSRURSS(final String rssSearchServiceURL, final String query, final int startRecord, final int maximumRecords, final CacheStrategy cacheStrategy, final boolean global, final ClientIdentification.Agent agent) throws IOException { MultiProtocolURL uri = null; try { uri = new MultiProtocolURL(rssSearchServiceURL); } catch (final MalformedURLException e) { throw new IOException( "cora.Search failed asking peer '" + rssSearchServiceURL + "': bad url, " + e.getMessage()); } // send request byte[] result = new byte[0]; try { final LinkedHashMap<String, ContentBody> parts = new LinkedHashMap<String, ContentBody>(); parts.put("query", UTF8.StringBody(query)); parts.put("startRecord", UTF8.StringBody(Integer.toString(startRecord))); parts.put("maximumRecords", UTF8.StringBody(Long.toString(maximumRecords))); parts.put("verify", cacheStrategy == null ? UTF8.StringBody("false") : UTF8.StringBody(cacheStrategy.toName())); parts.put("resource", UTF8.StringBody(global ? "global" : "local")); parts.put("nav", UTF8.StringBody("none")); // result = HTTPConnector.getConnector(userAgent == null ? MultiProtocolURI.yacybotUserAgent : userAgent).post(new MultiProtocolURI(rssSearchServiceURL), (int) timeout, uri.getHost(), parts); final HTTPClient httpClient = new HTTPClient(agent); result = httpClient.POSTbytes(new MultiProtocolURL(rssSearchServiceURL), uri.getHost(), parts, false, false); final RSSReader reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result); if (reader == null) { throw new IOException("cora.Search failed asking peer '" + uri.getHost() + "': probably bad response from remote peer (1), reader == null"); } final RSSFeed feed = reader.getFeed(); if (feed == null) { // case where the rss reader does not understand the content throw new IOException("cora.Search failed asking peer '" + uri.getHost() + "': probably bad response from remote peer (2)"); } return feed; } catch (final IOException e) { throw new IOException("cora.Search error asking peer '" + uri.getHost() + "':" + e.toString()); } }
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImpl.java
private static URLClassLoader getOxalisClassLoaderForJdbc(String jdbcDriverClassPath) { URLClassLoader urlClassLoader = null; try {/*w w w .ja v a 2s . c o m*/ urlClassLoader = new URLClassLoader(new URL[] { new URL(jdbcDriverClassPath) }, Thread.currentThread().getContextClassLoader()); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid jdbc driver class path: '" + jdbcDriverClassPath + "', check property oxalis.jdbc.class.path. Cause: " + e.getMessage(), e); } return urlClassLoader; }
From source file:com.brobwind.brodm.NetworkUtils.java
public static void deviceInfo(String path, OnMessage callback) { try {//from w ww . ja v a2s .c om URL url = new URL(path + "/privet/info"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic anonymous"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.connect(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader bufReader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); for (String line = bufReader.readLine(); line != null;) { sb.append(line).append("\n"); line = bufReader.readLine(); } callback.onMessage(sb.toString(), null); return; } finally { urlConnection.disconnect(); } } catch (MalformedURLException muex) { Log.e(TAG, "Malformed url: " + path); callback.onMessage(null, muex.getMessage()); } catch (Exception e) { e.printStackTrace(); callback.onMessage(null, e.getMessage()); } }
From source file:com.abiquo.am.services.TemplateConventions.java
/** * Gets an URL from the hRef attribute on a File's (References section). Try to interpret the * hRef attribute as an absolute URL (like http://some.where.com/file.vmdk), and if it fails try * to interpret the hRef as OVF package URI relative. * /*from www.j av a 2s. c o m*/ * @param relativeFilePath, the value on the hRef attribute for the File. * @param ovfId, the OVF Package identifier (and locator). * @throws DownloadException, it the URL can not be created. */ public static String getFileUrl(final String relativeFilePath, final String ovfId) { URL fileURL; try { fileURL = new URL(relativeFilePath); } catch (MalformedURLException e1) { // its a relative path if (e1.getMessage().startsWith("no protocol")) { try { String packageURL = ovfId.substring(0, ovfId.lastIndexOf('/')); fileURL = new URL(packageURL + '/' + relativeFilePath); } catch (MalformedURLException e) { final String msg = "Invalid file reference " + ovfId + '/' + relativeFilePath; throw new DownloadException(msg, e1); } } else { final String msg = "Invalid file reference " + relativeFilePath; throw new DownloadException(msg, e1); } } return fileURL.toExternalForm(); }
From source file:com.ecofactor.qa.automation.platform.util.SeleniumDriverUtil.java
/** * Creates the remote driver for Selenium hub. * @param capability the capability/* ww w.j a v a2 s . com*/ * @return the remote web driver */ private static RemoteWebDriver createRemoteDriverForHub(final DesiredCapabilities capability) { try { setHubCapabilities(capability); return new SwipeableWebDriver(new URL(createHostUrl()), capability); } catch (final MalformedURLException e) { setLogString("Cannot reach Selenium Hub. Reason = " + e.getMessage(), true); } return null; }