List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:com.omertron.themoviedbapi.tools.ApiUrl.java
/** * Build the URL from the pre-created parameters. * * @param params// w w w . j av a 2 s . com * @return */ public URL buildUrl(final TmdbParameters params) { StringBuilder urlString = new StringBuilder(TMDB_API_BASE); LOG.trace("Method: '{}', Sub-method: '{}', Params: {}", method.getValue(), submethod.getValue(), ToStringBuilder.reflectionToString(params, ToStringStyle.SHORT_PREFIX_STYLE)); // Get the start of the URL, substituting TV for the season or episode methods if (method == MethodBase.SEASON || method == MethodBase.EPISODE) { urlString.append(MethodBase.TV.getValue()); } else { urlString.append(method.getValue()); } // We have either a queury, or a ID request if (params.has(Param.QUERY)) { urlString.append(queryProcessing(params)); } else { urlString.append(idProcessing(params)); } urlString.append(otherProcessing(params)); try { LOG.trace("URL: {}", urlString.toString()); return new URL(urlString.toString()); } catch (MalformedURLException ex) { LOG.warn("Failed to create URL {} - {}", urlString.toString(), ex.getMessage()); return null; } }
From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.AnnualTeachingCreditsDocumentFilter.java
private void patchLinks(Document doc, HttpServletRequest request) { // build basePath String appContext = request.getContextPath(); // patch css link nodes NodeList linkNodes = doc.getElementsByTagName("link"); for (int i = 0; i < linkNodes.getLength(); i++) { Element link = (Element) linkNodes.item(i); String href = link.getAttribute("href"); if (appContext.length() > 0 && href.contains(appContext)) { href = href.substring(appContext.length()); }//from w w w .j av a 2 s .c o m try { String realPath = servletContext.getResource(href).toString(); link.setAttribute("href", realPath); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } } // patch image nodes NodeList imageNodes = doc.getElementsByTagName("img"); for (int i = 0; i < imageNodes.getLength(); i++) { Element img = (Element) imageNodes.item(i); String src = img.getAttribute("src"); if (appContext != null && appContext.length() > 0 && src.contains(appContext)) { src = src.substring(appContext.length() + 1); } try { String realPath = servletContext.getResource(src).toString(); img.setAttribute("src", realPath); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } } }
From source file:hudson.plugins.memegen.MemegeneratorResponseException.java
public boolean instanceCreate(Meme meme) { boolean ret = false; HashMap<String, String> vars = new HashMap(); vars.put("username", username); vars.put("password", password); vars.put("text0", meme.getUpperText()); vars.put("text1", meme.getLowerText()); vars.put("generatorID", "" + meme.getGeneratorID()); vars.put("imageID", "" + meme.getImageID()); try {/*ww w . ja v a 2 s. co m*/ URL url = buildURL("Instance_Create", vars); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); conn.setDoOutput(true); JSONObject obj = parseResponse(conn); JSONObject result = (JSONObject) obj.get("result"); String memeUrl = (String) result.get("instanceImageUrl"); if (memeUrl.matches("^http(.*)") == false) { memeUrl = APIURL + memeUrl; } //Debug the JSON to logs //System.err.println(obj.toJSONString()+", AND "+result.toJSONString()); meme.setImageURL(memeUrl); ret = true; } catch (MalformedURLException me) { String log_warn_prefix = "Memegenerator API malformed URL: "; System.err.println(log_warn_prefix.concat(me.getMessage())); } catch (IOException ie) { String log_warn_prefix = "Memegenerator API IO exception: "; System.err.println(log_warn_prefix.concat(ie.getMessage())); } catch (ParseException pe) { String log_warn_prefix = "Memegenerator API malformed response: "; System.err.println(log_warn_prefix.concat(pe.getMessage())); } catch (MemegeneratorResponseException mre) { String log_warn_prefix = "Memegenerator API failure: "; System.err.println(log_warn_prefix.concat(mre.getMessage())); } catch (MemegeneratorJSONException mje) { String log_warn_prefix = "Memegenerator API malformed JSON: "; System.err.println(log_warn_prefix.concat(mje.getMessage())); } return ret; }
From source file:android.locationprivacy.algorithm.Webservice.java
@Override public Location obfuscate(Location location) { // We do it this way to run network connection in main thread. This // way is not the normal one and does not comply to best practices, // but the main thread must wait for the obfuscation service reply anyway. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);/*from ww w . ja v a2s .com*/ final String HOST_ADDRESS = configuration.getString("host"); String username = configuration.getString("username"); String password = configuration.getString("secret_password"); Location newLoc = new Location(location); double lat = location.getLatitude(); double lon = location.getLongitude(); String urlString = HOST_ADDRESS; urlString += "?lat=" + lat; urlString += "&lon=" + lon; URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { Log.e(TAG, "Error: could not build URL"); Log.e(TAG, e.getMessage()); return null; } HttpsURLConnection connection = null; JSONObject json = null; InputStream is = null; try { connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP)); is = connection.getInputStream(); } catch (IOException e) { Log.e(TAG, "Error while connectiong to " + url.toString()); Log.e(TAG, e.getMessage()); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String line = reader.readLine(); System.out.println("Line " + line); json = new JSONObject(line); newLoc.setLatitude(json.getDouble("lat")); newLoc.setLongitude(json.getDouble("lon")); } catch (IOException e) { Log.e(TAG, "Error: could not read from BufferedReader"); Log.e(TAG, e.getMessage()); return null; } catch (JSONException e) { Log.e(TAG, "Error: could not read from JSON"); Log.e(TAG, e.getMessage()); return null; } connection.disconnect(); return newLoc; }
From source file:by.heap.remark.Main.java
private void checkInput(CommandLine cl, Args result, List<String> error) { List leftover = cl.getArgList(); if (leftover.isEmpty()) { error.add("No input file or URL specified."); } else if (leftover.size() > 1) { error.add("Too many arguments."); } else {/* w w w . ja va2s . co m*/ String arg = (String) leftover.get(0); if (arg.contains("://")) { try { result.urlInput = new URL(arg); } catch (MalformedURLException ex) { error.add("Malformed URL: " + ex.getMessage()); } } else { File input = new File(arg); if (input.isFile()) { if (input.canRead()) { result.fileInput = input; } else { error.add(String.format("Unable to read input file: %s", arg)); } } else { error.add(String.format("Input file does not exist or is not a file: %s", arg)); } } } }
From source file:com.sahana.geosmser.view.ReverseGeocoderView.java
public GeoPoint getGeoByAddress(String searchAddress) { GeoPoint mGeoPoint = null;/*w w w . j a v a 2 s . co m*/ StringBuilder responseBuilder = new StringBuilder(); try { URL url = new URL("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=" + URLEncoder.encode(searchAddress, "UTF-8")); // + "&key=ABQIAAAAi0Qn28OD_1M-BbLsxPRwYBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSdXKLoXxi1NXTY1EpEtAahu1gPgg"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { responseBuilder.append(inputLine); } in.close(); } catch (MalformedURLException me) { // me.printStackTrace(); Toast.makeText(mContext, me.getMessage(), Toast.LENGTH_SHORT).show(); } catch (UnsupportedEncodingException ue) { // ue.printStackTrace(); Toast.makeText(mContext, ue.getMessage(), Toast.LENGTH_SHORT).show(); } catch (IOException ie) { // ie.printStackTrace(); Toast.makeText(mContext, ie.getMessage(), Toast.LENGTH_SHORT).show(); } try { // JSONObject json = new JSONObject(responseBuilder.toString()); JSONObject json = (JSONObject) new JSONTokener(responseBuilder.toString()).nextValue(); JSONObject responseData = json.getJSONObject("responseData"); JSONObject viewport = responseData.getJSONObject("viewport"); JSONObject center = viewport.getJSONObject("center"); Log.d(WhereToMeet.TAG, "" + viewport.toString()); mGeoPoint = new GeoPoint((int) center.getDouble("lat"), (int) center.getDouble("lng")); } catch (JSONException e) { Log.d(WhereToMeet.TAG, "" + e.getMessage()); } return mGeoPoint; }
From source file:ConicWorld.java
public void init() { if (texImage == null) { // the path to the image for an applet try {/* w w w.j ava2s . co m*/ texImage = new java.net.URL(getCodeBase().toString() + "/earth.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(c); u = new SimpleUniverse(c); // 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:OrientedPtTest.java
public void init() { // the paths to the image files for an applet if (earthImage == null) { try {//from w w w .j a v a2 s. co 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()); Canvas3D c = new Canvas3D(SimpleUniverse.getPreferredConfiguration()); add("Center", c); // Create a simple scene and attach it to the virtual universe BranchGroup scene = createSceneGraph(); u = new SimpleUniverse(c); // add mouse behaviors to the ViewingPlatform ViewingPlatform viewingPlatform = u.getViewingPlatform(); // This will move the ViewPlatform back a bit so the // objects in the scene can be viewed. u.getViewingPlatform().setNominalViewingTransform(); // add orbit behavior to the viewing platform OrbitBehavior orbit = new OrbitBehavior(c, OrbitBehavior.REVERSE_ALL); BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); orbit.setSchedulingBounds(bounds); viewingPlatform.setViewPlatformBehavior(orbit); u.addBranchGraph(scene); }
From source file:de.egore911.versioning.deployer.performer.PerformCopy.java
private boolean copy(String uri, String target, String targetFilename) { URL url;/*from w w w.j a v a 2s.c om*/ try { url = new URL(uri); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); return false; } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); int lastSlash = uri.lastIndexOf('/'); if (lastSlash < 0) { LOG.error("Invalid URI: {}", uri); return false; } int lastDot = uri.lastIndexOf('.'); if (lastDot < 0) { LOG.error("Invalid URI: {}", uri); return false; } String filename; if (StringUtils.isEmpty(targetFilename)) { filename = uri.substring(lastSlash + 1); } else { filename = targetFilename; } XmlHolder xmlHolder = XmlHolder.getInstance(); XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()"); if (response == HttpURLConnection.HTTP_OK) { String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename); File downloadFile = new File(downloadFilename); FileUtils.forceMkdir(downloadFile.getParentFile()); try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(downloadFilename)) { IOUtils.copy(in, out); } LOG.debug("Downloaded {} to {}", url, downloadFilename); if (StringUtils.isEmpty(targetFilename)) { // Check if finalName if exists in pom.xml String destFile = null; try (ZipFile zipFile = new ZipFile(downloadFilename)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().endsWith("/pom.xml")) { String finalNameInPom; try (InputStream inputStream = zipFile.getInputStream(entry)) { try { MavenXpp3Reader mavenreader = new MavenXpp3Reader(); Model model = mavenreader.read(inputStream); finalNameInPom = model.getBuild().getFinalName(); } catch (Exception e) { Document doc = xmlHolder.documentBuilder.parse(inputStream); finalNameInPom = (String) finalNameXpath.evaluate(doc, XPathConstants.STRING); } } if (StringUtils.isNotEmpty(finalNameInPom)) { destFile = UrlUtil.concatenateUrlWithSlashes(target, finalNameInPom + "." + uri.substring(lastDot + 1)); } break; } } } // Move file to finalName if existed in pom.xml if (destFile != null) { try { File dest = new File(destFile); if (dest.exists()) { FileUtils.forceDelete(dest); } FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile()); LOG.debug("Moved file from {} to {}", downloadFilename, destFile); } catch (IOException e) { LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e); } } } return true; } else { LOG.error("Could not download file: {}", uri); return false; } } catch (SAXException | IOException | XPathExpressionException e) { LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e); return false; } }
From source file:org.commonjava.maven.galley.transport.htcli.HttpClientTransport.java
private String getUrl(final ConcreteResource resource) throws TransferException { try {/*from www .ja v a 2s. c o m*/ return buildUrl(resource); } catch (final MalformedURLException e) { throw new TransferLocationException(resource.getLocation(), "Failed to build URL for resource: {}. Reason: {}", e, resource, e.getMessage()); } }