List of usage examples for java.net MalformedURLException MalformedURLException
public MalformedURLException(String msg)
From source file:org.apache.cocoon.components.source.impl.ContextSourceFactory.java
/** * @see org.apache.excalibur.source.SourceFactory#getSource(java.lang.String, java.util.Map) *//*from w w w . ja va2 s . co m*/ public Source getSource(String location, Map parameters) throws IOException { if (getLogger().isDebugEnabled()) { getLogger().debug("Creating source object for " + location); } // Lookup resolver SourceResolver resolver = null; try { resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE); // Remove the protocol and the first '/' final int pos = location.indexOf(":/"); final String scheme = location.substring(0, pos); final String path = location.substring(pos + 2); // fix for #24093, we don't give access to files outside the context: if (path.indexOf("../") != -1) { throw new MalformedURLException("Invalid path ('../' is not allowed) : " + path); } URL u; // Try to get a file first and fall back to a resource URL String actualPath = this.servletContext.getRealPath(path); if (actualPath != null) { u = new File(actualPath).toURL(); } else { u = this.servletContext.getResource(path); } if (u != null) { Source source = resolver.resolveURI(u.toExternalForm()); if (parameters != null && BooleanUtils.toBoolean("force-traversable") && this.servletContext != null && !(source instanceof TraversableSource)) { final Set children = this.servletContext.getResourcePaths(path + '/'); if (children != null) { source = new TraversableContextSource(source, children, this, path, scheme); } } return source; } final String message = location + " could not be found. (possible context problem)"; getLogger().info(message); throw new MalformedURLException(message); } catch (ServiceException se) { throw new SourceException("Unable to lookup source resolver.", se); } finally { this.manager.release(resolver); } }
From source file:org.apache.maven.report.projectinfo.LicenseReport.java
/** * @param project not null/*w w w.j a v a 2s. c o m*/ * @param url not null * @return a valid URL object from the url string * @throws IOException if any */ protected static URL getLicenseURL(MavenProject project, String url) throws IOException { URL licenseUrl; UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES); // UrlValidator does not accept file URLs because the file // URLs do not contain a valid authority (no hostname). // As a workaround accept license URLs that start with the // file scheme. if (urlValidator.isValid(url) || StringUtils.defaultString(url).startsWith("file://")) { try { licenseUrl = new URL(url); } catch (MalformedURLException e) { throw new MalformedURLException( "The license url '" + url + "' seems to be invalid: " + e.getMessage()); } } else { File licenseFile = new File(project.getBasedir(), url); if (!licenseFile.exists()) { // Workaround to allow absolute path names while // staying compatible with the way it was... licenseFile = new File(url); } if (!licenseFile.exists()) { throw new IOException("Maven can't find the file '" + licenseFile + "' on the system."); } try { licenseUrl = licenseFile.toURI().toURL(); } catch (MalformedURLException e) { throw new MalformedURLException( "The license url '" + url + "' seems to be invalid: " + e.getMessage()); } } return licenseUrl; }
From source file:org.apache.fop.apps.FOURIResolver.java
/** * Checks if the given base URL is acceptable. It also normalizes the URL. * @param base the base URL to check//from ww w.j ava 2s . com * @return the normalized URL * @throws MalformedURLException if there's a problem with a file URL */ public String checkBaseURL(String base) throws MalformedURLException { // replace back slash with forward slash to ensure windows file:/// URLS are supported base = base.replace('\\', '/'); if (!base.endsWith("/")) { // The behavior described by RFC 3986 regarding resolution of relative // references may be misleading for normal users: // file://path/to/resources + myResource.res -> file://path/to/myResource.res // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res // We assume that even when the ending slash is missing, users have the second // example in mind base += "/"; } File dir = new File(base); if (dir.isDirectory()) { return dir.toURI().toASCIIString(); } else { URI baseURI; try { baseURI = new URI(base); String scheme = baseURI.getScheme(); boolean directoryExists = true; if ("file".equals(scheme)) { dir = FileUtils.toFile(baseURI.toURL()); directoryExists = dir.isDirectory(); } if (scheme == null || !directoryExists) { String message = "base " + base + " is not a valid directory"; if (throwExceptions) { throw new MalformedURLException(message); } log.error(message); } return baseURI.toASCIIString(); } catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); } } }
From source file:usd.edu.btlbetsstatistics.BetsStatistics.java
/** * Creates a list of all JSONObjects in database using the RESTful endpoint * from the osmonds.usd.edu server. This is the list of BETS for all tools. * * @return List<JSONObject>/*from www. j ava 2s . co m*/ */ public static List<JSONObject> createToolsListFromREST() { List<JSONObject> list = new ArrayList<>(); for (int i = FIRST_TOOL_ID; i <= LAST_TOOL_ID; i++) { //Calls REST one at a time for all tools in database String output = ""; try { //URL url = new URL("http://osmonds.usd.edu/BTL-REST/resources/bets/" + i); URL url = new URL("http://localhost:8080/BTL-REST/resources/bets/" + i); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { //Some Tools may have been removed from Database and id will not exist throw new MalformedURLException("No Tool exists for id: " + i); //return list; } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String line; while ((line = br.readLine()) != null) { output += line; //Gets all of the bets specification returned by REST request } conn.disconnect(); JSONObject object = new JSONObject(output); //Turn it into a JSONObject and add to list list.add(object); } catch (MalformedURLException e) { //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return list; }
From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java
/** * Constructor for AzkabanWorkflowClient * @param url The url of the workflow/*from w ww. ja v a 2s. co m*/ * @throws URISyntaxException * @throws MalformedURLException */ public AzkabanWorkflowClient(String url) throws URISyntaxException, MalformedURLException { if (url == null || url.isEmpty()) { throw new MalformedURLException("The Azkaban url is malformed"); } this.setAzkabanServerUrl(url); this.setExecutionId(url); this._workflowExecutionUrl = url; this.jobIdToLog = new HashMap<String, AzkabanJobLogAnalyzer>(); }
From source file:com.nesscomputing.jms.activemq.ServiceDiscoveryTransportFactory.java
/** * Extract the query string from a connection URI into a Map *//*from w w w .j a v a2 s .c o m*/ @SuppressWarnings("PMD.PreserveStackTrace") private Map<String, String> findParameters(URI location) throws MalformedURLException { final Map<String, String> params; try { params = URISupport.parseParameters(location); } catch (final URISyntaxException e) { throw new MalformedURLException(e.getMessage()); } return params; }
From source file:org.apache.nutch.watchlist.burberry.BurberryParser.java
/** * Scan the HTML document looking at product information *//*from w w w. j av a2 s . c o m*/ public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { // Step 1: ignore non-product pages from Burberry String itemNumber = null; String productTitle = null; URL baseURL; try { baseURL = new URL(content.getBaseUrl()); LOG.info("Start parsing: " + baseURL.toString()); Matcher matcher = urlRegexp.matcher(baseURL.toString()); if (matcher.find()) { if (!matcher.group(1).equalsIgnoreCase(matcher.group(3))) { throw new MalformedURLException("Burberry product title doesn't match."); } itemNumber = matcher.group(2); productTitle = matcher.group(3).replace('-', ' '); } else { // matcher cannot find it, so this is not a burberry product page throw new MalformedURLException("URL is not a Burberry Product Page."); } } catch (Exception e) { // Print out the message and move on to the next filter LOG.info("Exception: " + e.getMessage()); return parseResult; } // Step 2: Extract the product details (image URL and price) LOG.info("Parse Burberry product " + itemNumber + " (" + productTitle + ")"); try { Parser parser = new Parser(doc, itemNumber); String price = parser.getPrice(); String imgURL = parser.getImageURL(); if (price != null && imgURL != null) { // Parse successful, fill out the metadata Parse parse = parseResult.get(content.getUrl()); Metadata meta = parse.getData().getContentMeta(); meta.add(META_BRAND, "burberry"); meta.add(META_ID, itemNumber); meta.add(META_NAME, productTitle); meta.add(META_PRICE, price); meta.add(META_IMG_URL, imgURL); meta.add(META_PAGE_TITLE, parse.getData().getTitle()); // TODO(jyang): Write these information into database } else { // At least something wrong LOG.warn("Partially parsed " + baseURL + ": "); if (price == null) { LOG.warn("price is null."); } if (imgURL == null) { LOG.warn("imgURL is null."); } } } catch (Exception e) { LOG.warn("Failed to parse " + baseURL + ": " + e); e.printStackTrace(); return parseResult; } // Finally, log the finish of parsing this product LOG.info("Finish parsing Burberry product: " + itemNumber); return parseResult; }
From source file:eu.eubrazilcc.lvl.core.util.UrlUtils.java
/** * Parses a URL from a String. This method supports file-system paths * (e.g. /foo/bar).//from w w w. j ava 2s . c o m * @param str - String representation of an URL * @return an URL. * @throws IOException If an input/output error occurs. */ public static @Nullable URL parseURL(final String str) throws MalformedURLException { URL url = null; if (isNotBlank(str)) { try { url = new URL(str); } catch (MalformedURLException e) { url = null; if (!str.matches("^[a-zA-Z]+[/]*:[^\\\\]")) { // convert path to UNIX path String path = separatorsToUnix(str.trim()); final Pattern pattern = Pattern.compile("^([a-zA-Z]:/)"); final Matcher matcher = pattern.matcher(path); path = matcher.replaceFirst("/"); // convert relative paths to absolute paths if (!path.startsWith("/")) { path = path.startsWith("~") ? path.replaceFirst("~", System.getProperty("user.home")) : concat(System.getProperty("user.dir"), path); } // normalize path path = normalize(path, true); if (isNotBlank(path)) { url = new File(path).toURI().toURL(); } else { throw new MalformedURLException("Invalid path: " + path); } } else { throw e; } } } return url; }
From source file:de.sanandrew.core.manpack.managers.SAPUpdateManager.java
private void check() { Runnable threadProcessor = new Runnable() { @Override/*from w w w . j a v a 2s .c o m*/ public void run() { try { ModCntManPack.UPD_LOG.printf(Level.INFO, "Checking for %s update", SAPUpdateManager.this.getModName()); if (SAPUpdateManager.this.getUpdateURL() == null) { throw new MalformedURLException("[NULL]"); } Gson gson = new GsonBuilder() .registerTypeAdapter(UpdateFile.class, new AnnotatedDeserializer<UpdateFile>()) .create(); try (BufferedReader in = new BufferedReader( new InputStreamReader(SAPUpdateManager.this.getUpdateURL().openStream()))) { SAPUpdateManager.this.updInfo = gson.fromJson(in, UpdateFile.class); } catch (IOException | JsonSyntaxException ex) { ModCntManPack.UPD_LOG.printf(Level.WARN, "Check for Update failed!", ex); } if (SAPUpdateManager.this.updInfo.version == null || SAPUpdateManager.this.updInfo.version.length() < 1) { SAPUpdateManager.setChecked(SAPUpdateManager.this.getId()); return; } Version webVersion = SAPUpdateManager.this.updInfo.getVersionInst(); SAPUpdateManager.this.updInfo.version = webVersion.toString(); // reformat the version number to the format major.minor.revision Version currVersion = SAPUpdateManager.this.getVersion(); String currModName = SAPUpdateManager.this.getModName(); if (webVersion.versionType != EnumVersionType.RELEASE) { if (ConfigurationManager.subscribeToUnstable || currVersion.versionType != EnumVersionType.RELEASE) { if (webVersion.versionType.ordinal() > currVersion.versionType.ordinal()) { switch (webVersion.versionType) { case BETA: ModCntManPack.UPD_LOG.printf(Level.INFO, "A beta for %s is available: %s", currModName, webVersion); break; case RELEASECANDIDATE: ModCntManPack.UPD_LOG.printf(Level.INFO, "A release candidate for %s is available: %s", currModName, webVersion); break; default: ModCntManPack.UPD_LOG.printf(Level.INFO, "No new update for %s is available.", currModName); SAPUpdateManager.setChecked(SAPUpdateManager.this.getId()); return; } SAPUpdateManager.setHasUpdate(SAPUpdateManager.this.mgrId, webVersion.toString()); return; } else if (webVersion.preVersionNr > currVersion.preVersionNr) { switch (webVersion.versionType) { case ALPHA: ModCntManPack.UPD_LOG.printf(Level.INFO, "A new alpha for %s is out: %s", currModName, webVersion); break; case BETA: ModCntManPack.UPD_LOG.printf(Level.INFO, "A new beta for %s is out: %s", currModName, webVersion); break; case RELEASECANDIDATE: ModCntManPack.UPD_LOG.printf(Level.INFO, "A new release candidate for %s is out: %s", currModName, webVersion); break; default: ModCntManPack.UPD_LOG.printf(Level.INFO, "No new update for %s is available.", currModName); SAPUpdateManager.setChecked(SAPUpdateManager.this.getId()); return; } SAPUpdateManager.setHasUpdate(SAPUpdateManager.this.mgrId, webVersion.toString()); return; } } } else { if (webVersion.major > currVersion.major) { ModCntManPack.UPD_LOG.printf(Level.INFO, "New major update for %s is out: %s", currModName, webVersion); SAPUpdateManager.setHasUpdate(SAPUpdateManager.this.mgrId, webVersion.toString()); return; } else if (webVersion.major == currVersion.major) { if (webVersion.minor > currVersion.minor) { ModCntManPack.UPD_LOG.printf(Level.INFO, "New minor update for %s is out: %s", currModName, webVersion); SAPUpdateManager.setHasUpdate(SAPUpdateManager.this.mgrId, webVersion.toString()); return; } else if (webVersion.minor == currVersion.minor) { if (webVersion.revision > currVersion.revision) { ModCntManPack.UPD_LOG.printf(Level.INFO, "New bugfix update for %s is out: %s", currModName, webVersion); SAPUpdateManager.setHasUpdate(SAPUpdateManager.this.mgrId, webVersion.toString()); return; } else if (webVersion.revision == currVersion.revision && currVersion.versionType != EnumVersionType.RELEASE) { ModCntManPack.UPD_LOG.printf(Level.INFO, "A stable release for %s is available: %s", currModName, webVersion); SAPUpdateManager.setHasUpdate(SAPUpdateManager.this.mgrId, webVersion.toString()); return; } } } } ModCntManPack.UPD_LOG.printf(Level.INFO, "No new update for %s is available.", currModName); } catch (IOException ioex) { ModCntManPack.UPD_LOG.printf(Level.WARN, String.format("Update Check for %s failed!", SAPUpdateManager.this.modName), ioex); } SAPUpdateManager.setChecked(SAPUpdateManager.this.getId()); } }; new Thread(threadProcessor, "SAPUpdateThread").start(); }
From source file:pt.webdetails.cda.filetests.DataserviceTest.java
@Test public void testDatasourceDataserviceDriverConnectionProviderException() throws Exception { CdaTestingContentAccessFactory factory = new CdaTestingContentAccessFactory(); IDataservicesLocalConnection dataserviceLocalConnection = mock(IDataservicesLocalConnection.class); when(dataserviceLocalConnection.getDriverConnectionProvider()) .thenThrow(new MalformedURLException("wrong url")); CdaTestEnvironment testEnvironment = spy(new CdaTestEnvironment(factory)); when(testEnvironment.getDataServicesLocalConnection()).thenReturn(dataserviceLocalConnection); CdaEngine.init(testEnvironment);/*from w w w. ja va 2 s. c om*/ final CdaSettings cdaSettings = spy(parseSettingsFile("sample-dataservice.cda")); final QueryOptions queryOptions = new QueryOptions(); String dataAccessId = "1"; queryOptions.setDataAccessId(dataAccessId); CdaEngine engine = getEngine(); try { engine.doQuery(cdaSettings, queryOptions); Assert.fail("no exception"); } catch (QueryException e) { String msg = ExceptionUtils.getRootCauseMessage(e.getCause()); Assert.assertEquals("MalformedURLException: wrong url", msg); } }