List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:cz.vsb.gis.ruz76.gt.Examples.java
public String overlayWMS(String pointString, double distance) { long milis = System.currentTimeMillis(); String workspace = "w" + String.valueOf(milis); String geoserverpath = "/data/install/gis/geoserver/geoserver-2.8.2"; try {/*ww w . j ava 2 s . c o m*/ //SHP Read ShapefileDataStore sfds = new ShapefileDataStore( new URL("file://" + geoserverpath + "/data_dir/data/sf/restricted.shp")); SimpleFeatureSource fs = sfds.getFeatureSource("restricted"); SimpleFeatureType TYPE = fs.getSchema(); //double distance = 10000.0d; GeometryFactory gf = new GeometryFactory(); String xy[] = pointString.split(" "); Point point = gf.createPoint(new Coordinate(Double.parseDouble(xy[0]), Double.parseDouble(xy[1]))); Polygon p1 = (Polygon) point.buffer(distance); List<SimpleFeature> features = new ArrayList<>(); SimpleFeatureIterator sfi = fs.getFeatures().features(); while (sfi.hasNext()) { SimpleFeature sf = sfi.next(); MultiPolygon mp2 = (MultiPolygon) sf.getDefaultGeometry(); Polygon p2 = (Polygon) mp2.getGeometryN(0); Polygon p3 = (Polygon) p2.intersection(p1); if (p3.getArea() > 0) { sf.setDefaultGeometry(p3); features.add(sf); } } new File(geoserverpath + "/data_dir/data/" + workspace + "/overlay/").mkdirs(); saveFeatureCollectionToShapefile(geoserverpath + "/data_dir/data/" + workspace + "/overlay/overlay.shp", features, TYPE); } catch (MalformedURLException ex) { System.out.println(ex.getMessage()); Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex2) { System.out.println(ex2.getMessage()); Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex2); } addWorkspace(workspace); publishShapefile(workspace, "overlay", "file://" + geoserverpath + "/data_dir/data/" + workspace + "/overlay/overlay.shp"); return "http://localhost:8080/geoserver/" + workspace + "/wms?service=WMS&version=1.3.0&request=GetCapabilities"; }
From source file:com.panet.imeta.cluster.SlaveServer.java
/** * Contact the server and get back the reply as a string * @return the requested information//from w w w .ja v a2 s . c om * @throws Exception in case something goes awry */ public String getContentFromServer(String service) throws Exception { // Following variable hides class variable. MB 7/10/07 // LogWriter log = LogWriter.getInstance(); String urlToUse = constructUrl(service); URL server; StringBuffer result = new StringBuffer(); try { String beforeProxyHost = System.getProperty("http.proxyHost"); //$NON-NLS-1$ String beforeProxyPort = System.getProperty("http.proxyPort"); //$NON-NLS-1$ String beforeNonProxyHosts = System.getProperty("http.nonProxyHosts"); //$NON-NLS-1$ BufferedReader input = null; try { if (log.isBasic()) log.logBasic(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlToUse)); //$NON-NLS-1$ if (proxyHostname != null) { System.setProperty("http.proxyHost", environmentSubstitute(proxyHostname)); //$NON-NLS-1$ System.setProperty("http.proxyPort", environmentSubstitute(proxyPort)); //$NON-NLS-1$ if (nonProxyHosts != null) System.setProperty("http.nonProxyHosts", environmentSubstitute(nonProxyHosts)); //$NON-NLS-1$ } if (username != null && username.length() > 0) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(environmentSubstitute(username), password != null ? environmentSubstitute(password).toCharArray() : new char[] {}); } }); } // Get a stream for the specified URL server = new URL(urlToUse); URLConnection connection = server.openConnection(); log.logDetailed(toString(), Messages.getString("SlaveServer.StartReadingReply")); //$NON-NLS-1$ // Read the result from the server... InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 1000); input = new BufferedReader(new InputStreamReader(inputStream)); long bytesRead = 0L; String line; while ((line = input.readLine()) != null) { result.append(line).append(Const.CR); bytesRead += line.length(); } if (log.isBasic()) log.logBasic(toString(), Messages.getString("SlaveServer.FinishedReadingResponse"), bytesRead); //$NON-NLS-1$ if (log.isDebug()) log.logDebug(toString(), "response from the webserver: {0}", result); } catch (MalformedURLException e) { log.logError(toString(), Messages.getString("SlaveServer.UrlIsInvalid", urlToUse, e.getMessage())); //$NON-NLS-1$ log.logError(toString(), Const.getStackTracker(e)); } catch (IOException e) { log.logError(toString(), Messages.getString("SlaveServer.CannotSaveDueToIOError", e.getMessage())); //$NON-NLS-1$ log.logError(toString(), Const.getStackTracker(e)); } catch (Exception e) { log.logError(toString(), Messages.getString("SlaveServer.ErrorReceivingFile", e.getMessage())); //$NON-NLS-1$ log.logError(toString(), Const.getStackTracker(e)); } finally { // Close it all try { if (input != null) input.close(); } catch (Exception e) { log.logError(toString(), Messages.getString("SlaveServer.CannotCloseStream", e.getMessage())); //$NON-NLS-1$ log.logError(toString(), Const.getStackTracker(e)); } } // Set the proxy settings back as they were on the system! System.setProperty("http.proxyHost", Const.NVL(beforeProxyHost, "")); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("http.proxyPort", Const.NVL(beforeProxyPort, "")); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("http.nonProxyHosts", Const.NVL(beforeNonProxyHosts, "")); //$NON-NLS-1$ //$NON-NLS-2$ // Get the result back... return result.toString(); } catch (Exception e) { throw new Exception(Messages.getString("SlaveServer.CannotContactURLForSecurityInformation", urlToUse), //$NON-NLS-1$ e); } }
From source file:info.magnolia.cms.exchange.simple.SimpleSyndicator.java
/** * deactivate from a specified subscriber * * @param subscriber/* w w w. jav a 2 s .c o m*/ * @throws ExchangeException */ private synchronized void doDeActivate(Subscriber subscriber) throws ExchangeException { if (!isSubscribed(subscriber)) { return; } String handle = getDeactivationURL(subscriber); try { URL url = new URL(handle); URLConnection urlConnection = url.openConnection(); this.addDeactivationHeaders(urlConnection); urlConnection.getContent(); } catch (MalformedURLException e) { throw new ExchangeException("Incorrect URL for subscriber " + subscriber + "[" + handle + "]"); } catch (IOException e) { throw new ExchangeException( "Not able to send the deactivation request [" + handle + "]: " + e.getMessage()); } catch (Exception e) { throw new ExchangeException(e); } }
From source file:com.sikulix.core.SX.java
public static URL getJarURL(Object... args) { File aFile = getFile(args);/* w ww. j a v a2 s . c o m*/ if (isNotSet(aFile)) { return null; } String sSub = ""; if (args.length > 2) { sSub = args[2].toString(); } try { return new URL("jar:file:" + aFile.toString() + "!/" + sSub); } catch (MalformedURLException e) { error("getJarURL: %s %s error(%s)", aFile, sSub, e.getMessage()); return null; } }
From source file:com.googlecode.fightinglayoutbugs.DetectInvalidImageUrls.java
private void checkStyleAttributes() { for (WebElement element : _webPage.findElements(By.xpath("//*[@style]"))) { final String css = element.getAttribute("style"); for (String importUrl : getImportUrlsFrom(css)) { checkCssResourceAsync(//from w w w. ja va 2 s .c om importUrl + " (imported in style attribute of <" + element.getTagName() + "> element)", importUrl, _baseUrl, _documentCharset); } for (String url : extractUrlsFrom(css)) { try { checkImageUrl(url, "Detected <" + element.getTagName() + "> element with invalid image URL \"" + url + "\" in its style attribute"); } catch (MalformedURLException e) { addLayoutBugIfNotPresent( "Detected <" + element.getTagName() + "> element with invalid image URL \"" + url + "\" in its style attribute -- " + e.getMessage()); } } } }
From source file:net.sf.jabref.importer.fetcher.IEEEXploreFetcher.java
@Override public boolean processQuery(String query, ImportInspector dialog, OutputPrinter status) { //IEEE API seems to use .QT. as a marker for the quotes for exact phrase searching String terms = query.replaceAll("\"", "\\.QT\\."); shouldContinue = true;/*from ww w . ja v a 2 s.c o m*/ int parsed = 0; int pageNumber = 1; String postData = makeSearchPostRequestPayload(pageNumber, terms); try { //open the search URL URLDownload dl = new URLDownload(IEEEXploreFetcher.URL_SEARCH); //add request header dl.addParameters("Accept", "application/json"); dl.addParameters("Content-Type", "application/json"); // set post data dl.setPostData(postData); //retrieve the search results String page = dl.downloadToString(StandardCharsets.UTF_8); //the page can be blank if the search did not work (not sure the exact conditions that lead to this, but declaring it an invalid search for now) if (page.isEmpty()) { status.showMessage(Localization.lang("You have entered an invalid search '%0'.", query), DIALOG_TITLE, JOptionPane.INFORMATION_MESSAGE); return false; } //parses the JSON data returned by the query //TODO: a faster way would be to parse the JSON tokens one at a time just to extract the article number, but this seems to be fast enough... JSONObject searchResultsJson = new JSONObject(page); int hits = searchResultsJson.getInt("totalRecords"); //if no search results were found if (hits == 0) { status.showMessage(Localization.lang("No entries found for the search string '%0'", query), DIALOG_TITLE, JOptionPane.INFORMATION_MESSAGE); return false; } //if max hits were exceeded, display the warning if (hits > IEEEXploreFetcher.MAX_FETCH) { status.showMessage( Localization.lang("%0 entries found. To reduce server load, only %1 will be downloaded.", String.valueOf(hits), String.valueOf(IEEEXploreFetcher.MAX_FETCH)), DIALOG_TITLE, JOptionPane.INFORMATION_MESSAGE); } //fetch the raw Bibtex results from IEEEXplore String bibtexPage = new URLDownload(createBibtexQueryURL(searchResultsJson)) .downloadToString(Globals.prefs.getDefaultEncoding()); //preprocess the result (eg. convert HTML escaped characters to latex and do other formatting not performed by BibtexParser) bibtexPage = preprocessBibtexResultsPage(bibtexPage); //parse the page into Bibtex entries Collection<BibEntry> parsedBibtexCollection = BibtexParser.fromString(bibtexPage); if (parsedBibtexCollection == null) { status.showMessage(Localization.lang("Error while fetching from %0", getTitle()), DIALOG_TITLE, JOptionPane.INFORMATION_MESSAGE); return false; } int nEntries = parsedBibtexCollection.size(); Iterator<BibEntry> parsedBibtexCollectionIterator = parsedBibtexCollection.iterator(); while (parsedBibtexCollectionIterator.hasNext() && shouldContinue) { dialog.addEntry(cleanup(parsedBibtexCollectionIterator.next())); dialog.setProgress(parsed, nEntries); parsed++; } return true; } catch (MalformedURLException e) { LOGGER.warn("Bad URL", e); } catch (ConnectException | UnknownHostException e) { status.showMessage(Localization.lang("Could not connect to %0", getTitle()), DIALOG_TITLE, JOptionPane.ERROR_MESSAGE); } catch (IOException | JSONException e) { status.showMessage(e.getMessage(), DIALOG_TITLE, JOptionPane.ERROR_MESSAGE); LOGGER.warn("Search IEEEXplore: " + e.getMessage(), e); } return false; }
From source file:org.commonjava.couch.db.CouchManager.java
public void deleteAttachment(final CouchDocument doc, final String attachmentName) throws CouchDBException { doc.setCouchDocRev(null);// w w w. j a v a 2 s . c om if (!documentRevisionExists(doc)) { throw new CouchDBException("Cannot delete attachment from a non-existent document: %s", doc.getCouchDocId()); } String url; try { url = buildUrl(config.getDatabaseUrl(), Collections.singletonMap(REV, doc.getCouchDocRev()), doc.getCouchDocId(), attachmentName); } catch (final MalformedURLException e) { throw new CouchDBException("Failed to format attachment URL for: %s to document: %s. Error: %s", e, attachmentName, doc.getCouchDocId(), e.getMessage()); } final HttpDelete request = new HttpDelete(url); client.executeHttp(request, SC_OK, "Failed to delete attachment"); }
From source file:org.commonjava.couch.db.CouchManager.java
public Attachment getAttachment(final CouchDocument doc, final String attachmentName) throws CouchDBException { String url;//from ww w . j a va 2s .c om try { url = buildUrl(config.getDatabaseUrl(), doc.getCouchDocId(), attachmentName); } catch (final MalformedURLException e) { throw new CouchDBException("Failed to format attachment URL for: %s to document: %s. Error: %s", e, attachmentName, doc.getCouchDocId(), e.getMessage()); } final HttpGet request = new HttpGet(url); final HttpResponse response = client.executeHttpWithResponse(request, "Failed to retrieve attachment."); if (response.getStatusLine().getStatusCode() == SC_NOT_FOUND) { return null; } else if (response.getStatusLine().getStatusCode() != SC_OK) { throw new CouchDBException("Failed to retrieve attachment: %s from: %s. Reason: %s", attachmentName, doc.getCouchDocId(), response.getStatusLine()); } return new AttachmentDownload(attachmentName, request, response, client); }
From source file:com.fluidops.iwb.provider.CkanProvider.java
/** * Retrieves the base URI from a given host. Returns null if retrieval * fails.//from w ww .j ava 2 s .c om */ private String findBaseUri(String host) { HttpURLConnection conn = null; // Read the base URI from the JSON, located in the "url" key-value pair try { URL url = new URL(host); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String content = GenUtil.readUrl(conn.getInputStream()); Object ob = getJson(content); String baseUrl = ((JSONObject) ob).getString("url"); return baseUrl == null ? null : baseUrl; } conn.disconnect(); } catch (MalformedURLException e) { logger.warn("Supplied host is not a valid URL: " + host); // ignore warning (affects only a single dataset) } catch (IOException e) { logger.warn("IOException while retrieving base URI: " + host); // ignore warning (affects only a single dataset) } catch (JSONException e) { logger.warn(String.format("No base URL found for: %s!%n%s", host, e.getMessage())); // ignore warning (affects only a single dataset) } return null; }
From source file:edu.lternet.pasta.datamanager.EMLEntity.java
/** * Constructs an EMLEntity object with a specified * 'edu.lternet.pasta.dml.parser.Entity' object. EMLEntity acts as a * wrapper that encapsulates its Data Manager Library entity object. * // ww w . j ava 2s .co m * @param entity An entity object as defined by the Data Manager Library. */ public EMLEntity(Entity entity) throws MalformedURLException, UnsupportedEncodingException { this.entity = entity; this.dataFormat = entity.getDataFormat(); this.entityName = entity.getName(); if (entityName != null) { entityId = edu.lternet.pasta.common.eml.Entity.entityIdFromEntityName(entityName); } this.packageId = entity.getPackageId(); this.url = entity.getURL(); try { URL aURL = new URL(url); if (aURL != null) { logger.debug("Constructed URL object: " + aURL.toString()); } } catch (MalformedURLException e) { String message = null; if (url == null || url.equals("")) { message = String.format("Error when attempting to process entity \"%s\". " + "All data entities in PASTA must specify an online URL. " + "No online URL value was found at this XPath: " + "\"dataset/[entity-type]/physical/distribution/online/url\". " + "(PASTA will use only the first occurrence of this XPath.)", entityName); } else { message = String.format("Error when attempting to process entity \"%s\" with entity URL \"%s\": %s", entityName, url, e.getMessage()); } logger.error(message); throw new MalformedURLException(message); } }