Example usage for java.net MalformedURLException getMessage

List of usage examples for java.net MalformedURLException getMessage

Introduction

In this page you can find the example usage for java.net MalformedURLException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.ubicompforall.cityexplorer.gui.ImportWebTab.java

/***
 * Extract database URLs from the web-page source code, given as the string text
 * @param text   the web-page source code
 * @return      new web-page source code with multiple "<A HREF='databaseX.sqlite'>databaseX</A>" only
 *//*from  w ww  .jav  a 2  s  .com*/
public static CopyOnWriteArrayList<DB> extractDBs(String text, String SERVER_URL) {
    webDBs = new CopyOnWriteArrayList<DB>(); //To avoid duplicates!
    Matcher m = Pattern.compile("<a.* href=\"([^>]+(sqlite|db|db3))\">([^<]+)</a>", Pattern.CASE_INSENSITIVE)
            .matcher(text);
    while (m.find()) {
        String filename = m.group(1);
        if (filename.charAt(0) == '/') {
            filename = SERVER_URL + filename;
        }
        //webDBs.add( new DB(URL.getParentFile().getParent(), URL.getParentFile().getName(), URL.getName(), m.group(3) ) );
        // group 0 is everything, group 1 is (www.and.so.on)
        try {
            URL url = new URL(filename);
            File file = new File(filename);
            debug(1, "URL is  " + url);
            webDBs.add(new DB(file.getParentFile().getParent(), file.getParentFile().getName(), file.getName(),
                    url));
            debug(1, "Added: " + filename + " " + m.group(3));
        } catch (MalformedURLException e) {
            debug(-1, e.getMessage());
        }
    }
    return webDBs;
}

From source file:org.commonjava.redhat.maven.rv.util.InputUtils.java

public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting)
        throws ValidationException {
    if (client == null) {
        final DefaultHttpClient hc = new DefaultHttpClient();
        hc.setRedirectStrategy(new DefaultRedirectStrategy());

        final String proxyHost = System.getProperty("http.proxyHost");
        final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));

        if (proxyHost != null && proxyPort > 0) {
            final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }//from  w  ww  . j  a v a 2  s  .  c o  m

        client = hc;
    }

    File result = null;

    if (location.startsWith("http")) {
        LOGGER.info("Downloading: '" + location + "'...");

        try {
            final URL url = new URL(location);
            final String userpass = url.getUserInfo();
            if (!isEmpty(userpass)) {
                final AuthScope scope = new AuthScope(url.getHost(), url.getPort());
                final Credentials creds = new UsernamePasswordCredentials(userpass);

                client.getCredentialsProvider().setCredentials(scope, creds);
            }
        } catch (final MalformedURLException e) {
            LOGGER.error("Malformed URL: '" + location + "'", e);
            throw new ValidationException("Failed to download: %s. Reason: %s", e, location, e.getMessage());
        }

        final File downloaded = new File(downloadsDir, new File(location).getName());
        if (deleteExisting && downloaded.exists()) {
            downloaded.delete();
        }

        if (!downloaded.exists()) {
            HttpGet get = new HttpGet(location);
            OutputStream out = null;
            try {
                HttpResponse response = client.execute(get);
                // Work around for scenario where we are loading from a server
                // that does a refresh e.g. gitweb
                if (response.containsHeader("Cache-control")) {
                    LOGGER.info("Waiting for server to generate cache...");
                    try {
                        Thread.sleep(5000);
                    } catch (final InterruptedException e) {
                    }
                    get.abort();
                    get = new HttpGet(location);
                    response = client.execute(get);
                }
                final int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    final InputStream in = response.getEntity().getContent();
                    out = new FileOutputStream(downloaded);

                    copy(in, out);
                } else {
                    LOGGER.info(String.format("Received status: '%s' while downloading: %s",
                            response.getStatusLine(), location));

                    throw new ValidationException("Received status: '%s' while downloading: %s",
                            response.getStatusLine(), location);
                }
            } catch (final ClientProtocolException e) {
                throw new ValidationException("Failed to download: '%s'. Error: %s", e, location,
                        e.getMessage());
            } catch (final IOException e) {
                throw new ValidationException("Failed to download: '%s'. Error: %s", e, location,
                        e.getMessage());
            } finally {
                closeQuietly(out);
                get.abort();
            }
        }

        result = downloaded;
    } else {
        LOGGER.info("Using local file: '" + location + "'...");

        result = new File(location);
    }

    return result;
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceInitializer.java

/**
 * Initializes the security service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar.// ww  w  .jav a 2  s  . c  o  m
 *
 * @param configFile - The security configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param startConnections - Configure, load and start repository connections
 * @throws SecurityServiceException @{link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean startConnections) throws SecurityServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ClassLoader classLoader = SecurityServiceInitializer.class.getClassLoader();
    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("configFileFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("secLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = classLoader.getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(serviceConfig).toURI().toURL();
        }

        context = JAXBContext.newInstance(SecurityConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

        SecurityServiceInitializer.svcBean.setConfigData(configData);

        if (startConnections) {
            DAOInitializer.configureAndCreateAuthConnection(
                    new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                    false, SecurityServiceInitializer.svcBean);

            Map<String, DataSource> dsMap = SecurityServiceInitializer.svcBean.getDataSources();

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            if (configData.getResourceConfig() != null) {
                if (dsMap == null) {
                    dsMap = new HashMap<String, DataSource>();
                }

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    if (!(dsMap.containsKey(mgr.getDsName()))) {
                        StringBuilder sBuilder = new StringBuilder()
                                .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                                .append("zeroDateTimeBehavior=convertToNull");

                        if (DEBUG) {
                            DEBUGGER.debug("StringBuilder: {}", sBuilder);
                        }

                        BasicDataSource dataSource = new BasicDataSource();
                        dataSource.setDriverClassName(mgr.getDriver());
                        dataSource.setUrl(mgr.getDataSource());
                        dataSource.setUsername(mgr.getDsUser());
                        dataSource.setConnectionProperties(sBuilder.toString());
                        dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getDsSalt(),
                                configData.getSecurityConfig().getSecretAlgorithm(),
                                configData.getSecurityConfig().getIterations(),
                                configData.getSecurityConfig().getKeyBits(),
                                configData.getSecurityConfig().getEncryptionAlgorithm(),
                                configData.getSecurityConfig().getEncryptionInstance(),
                                configData.getSystemConfig().getEncoding()));

                        if (DEBUG) {
                            DEBUGGER.debug("BasicDataSource: {}", dataSource);
                        }

                        dsMap.put(mgr.getDsName(), dataSource);
                    }
                }

                if (DEBUG) {
                    DEBUGGER.debug("dsMap: {}", dsMap);
                }

                SecurityServiceInitializer.svcBean.setDataSources(dsMap);
            }
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new SecurityServiceException(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        fnfx.printStackTrace();
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new SecurityServiceException(mux.getMessage(), mux);
    } catch (SecurityException sx) {
        sx.printStackTrace();
        throw new SecurityServiceException(sx.getMessage(), sx);
    }
}

From source file:com.feilong.core.net.URLUtil.java

/**
 * ?url./*from   w  w w.  j  a  va  2 s.  com*/
 * 
 * <h3>:</h3>
 * <blockquote>
 * <ol>
 * <li>? check exception,? uncheck exception</li>
 * <li>new URL ,? {@link #toFileURL(String)}</li>
 * </ol>
 * </blockquote>
 * 
 * <h3>?:</h3>
 * 
 * <blockquote>
 * 
 * <p>
 *  {@link URL#URL(String)} ,, 
 * </p>
 * 
 * <pre class="code">
 * 
 * String spec = "C:/Users/feilong/feilong/train//warmReminder/20160704141057.html";
 * 
 * URL newURL = new URL(spec);
 * </pre>
 * 
 * ,
 * 
 * <pre class="code">
 * Caused by: java.net.MalformedURLException: <span style="color:red"><b>unknown protocol: c</b></span>
 * at java.net.URL.{@code <init>}(URL.java:593)
 * at java.net.URL.{@code <init>}(URL.java:483)
 * at java.net.URL.{@code <init>}(URL.java:432)
 * ... 24 more
 * </pre>
 * 
 *  ,??
 * 
 * <pre class="code">
 * 
 * String spec = "file://C:/Users/feilong/feilong/train//warmReminder/20160704141057.html";
 * 
 * URL newURL = new URL(spec);
 * </pre>
 * 
 * ,???? (file URI scheme),?? url?, {@link #toFileURL(String)}
 * </blockquote>
 * 
 * @param spec
 *            the <code>String</code> to parse as a URL.
 * @return  <code>spec</code> null, {@link NullPointerException}<br>
 *          <code>spec</code> blank, {@link IllegalArgumentException}<br>
 * @see java.net.URL#URL(String)
 * @see "org.apache.cxf.common.util.StringUtils#getURL(String)"
 * @see "org.springframework.util.ResourceUtils#getURL(String)"
 * @see <a href="https://en.wikipedia.org/wiki/File_URI_scheme">File_URI_scheme</a>
 * @see "org.apache.xml.resolver.readers.TextCatalogReader#readCatalog(Catalog, String)"
 * @see <a href="https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html">Creating a URL</a>
 * @since 1.8.0
 */
public static URL toURL(String spec) {
    Validate.notBlank(spec, "spec can't be blank!");
    try {
        return new URL(spec);
    } catch (MalformedURLException e) {
        // no URL -> treat as file path
        LOGGER.info("[new URL(\"{}\")] exception,cause by :[{}],will try call [toFileURL(\"{}\")]", spec,
                e.getMessage(), spec);
        return toFileURL(spec);
    }
}

From source file:AIR.Common.Web.FileFtpHandler.java

public static boolean exists(URI requestUri) {
    try {// w  w  w.  j  av a  2  s . co  m
        requestUri.toURL().openConnection();
    } catch (MalformedURLException e) {
        throw new FtpResourceException(e);
    } catch (IOException e) {
        final String NON_EXISTENT_MESSAGE = "The system cannot find the file specified";
        if (StringUtils.contains(e.getMessage(), NON_EXISTENT_MESSAGE)) {
            // TODO Shiva this part is highly specific to the ftp server AIR uses on
            // its webservices.
            return false;
        }
        throw new FtpResourceException(e);
    }
    return true;
}

From source file:io.fabric8.maven.core.util.MavenUtil.java

private static URL pathToUrl(String path) {
    try {/*w w w.j av a  2s  . c  o  m*/
        File file = new File(path);
        return file.toURI().toURL();
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(
                String.format("Cannot convert %s to a an URL: %s", path, e.getMessage()), e);
    }
}

From source file:org.codehaus.griffon.commons.GriffonResourceUtils.java

public static Resource getAppDir(Resource resource) {
    if (resource == null)
        return null;

    try {/*www. j  a v a 2  s. com*/
        String url = resource.getURL().toString();

        int i = url.lastIndexOf(GRIFFON_APP_DIR);
        if (i > -1) {
            url = url.substring(0, i + 10);
            return new UrlResource(url);
        }

        return null;
    } catch (MalformedURLException e) {
        return null;
    } catch (IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error reading URL whilst resolving app dir from [" + resource + "]: " + e.getMessage(),
                    e);
        }
        return null;
    }
}

From source file:com.celamanzi.liferay.portlets.rails286.Rails286PortletFunctions.java

public static java.net.URL getRequestURL(java.net.URL railsBaseURL, String servlet, String route) {
    try {//from  www .j  a  v  a  2s.  c  o  m
        RouteAnalyzer routeAnalyzer = new RouteAnalyzer(railsBaseURL, servlet);
        URL requestURL = routeAnalyzer.getFullURL(route);
        log.debug("Request URL: " + requestURL.toString());
        return requestURL;

    } catch (java.net.MalformedURLException e) {
        log.error("getRequestURL: " + e.getMessage());
    }
    return null;
}

From source file:com.sun.identity.openid.provider.Codec.java

/**
 * TODO: Description./*  w w  w  . j a  v  a2s . c o  m*/
 * 
 * @param value
 *            TODO.
 * @return TODO.
 * @throws DecodeException
 *             TODO.
 */
public static URL decodeURL(String value) throws DecodeException {
    if (value == null) {
        return null;
    }

    if (!WEB.matcher(value).matches()) {
        throw new DecodeException("URL could not be decoded");
    }

    try {
        return new URL(value);
    }

    catch (MalformedURLException mue) {
        throw new DecodeException(mue.getMessage());
    }
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * checks if GRIT can connect to the remote SVN server.
 *
 * @param svnRepoAdress//from   w ww  .  j ava2  s .  c o  m
 *            the adress of the remote
 * @return true if GRIT can connect to the SVN.
 * @throws SubmissionFetchingException
 *             If the URL to the SVN is invalid.
 */
private static boolean checkConnectionToRemoteSVN(String svnRepoAdress) throws SubmissionFetchingException {
    try {
        int connectionTimeoutMillis = 10000;
        if (!svnRepoAdress.startsWith("file://")) {
            URL svnRepoLocation = new URL(svnRepoAdress);
            URLConnection svnRepoConnection = svnRepoLocation.openConnection();
            svnRepoConnection.setConnectTimeout(connectionTimeoutMillis);
            svnRepoConnection.connect();
        }
        return true;
    } catch (MalformedURLException e) {
        throw new SubmissionFetchingException(
                "Bad URL specified. Can not connect to this URL: " + svnRepoAdress + e.getMessage());
    } catch (IOException e) {
        return false;
    }
}