Example usage for java.net MalformedURLException MalformedURLException

List of usage examples for java.net MalformedURLException MalformedURLException

Introduction

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

Prototype

public MalformedURLException(String msg) 

Source Link

Document

Constructs a MalformedURLException with the specified detail message.

Usage

From source file:com.redhat.red.build.koji.KojiClient.java

private String encodeParam(String param, String value) throws MalformedURLException {
    try {/*from  w ww.  j  av  a  2s  .c  o  m*/
        return URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String msg = String.format("Failed to encode %s parameter: %s. Reason: %s", param, value,
                e.getMessage());

        Logger logger = LoggerFactory.getLogger(getClass());
        logger.error(msg, e);

        throw new MalformedURLException(msg);
    }
}

From source file:com.remobile.file.FileUtils.java

public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
    try {// w  ww  . ja v  a 2s  . c o  m
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        return fs.filesystemPathForURL(inputURL);
    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public FileResource getFileResource(URL url) throws URISyntaxException, MalformedURLException {
    if (!url.getProtocol().equals("file"))
        throw new MalformedURLException("Protocol must be 'file'");
    File file = new File(url.toURI());
    if (file.exists() && file.isFile()) {
        return new FileResource(file);
    } else {/*from   ww  w  . j av a 2 s  .com*/
        return null;
    }
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public JarFileResource getJarResource(URL url) throws URISyntaxException, MalformedURLException, IOException {
    if (!url.getProtocol().equals("jar"))
        throw new MalformedURLException("Protocol must be 'jar'");

    String surl = url.toString();
    int ix = surl.lastIndexOf("!/");
    if (ix < 0)
        throw new MalformedURLException("URL must contains '!/'");

    String jarFileName, jarEntryName;
    try {// w w w  . jav a  2s. co  m
        jarFileName = URLDecoder.decode(surl.substring(4 + 5, ix), getSystemCharset().name());
        jarEntryName = surl.substring(ix + 2);
    } catch (UnsupportedEncodingException ex) {
        throw new WTRuntimeException(ex, "{0} encoding not supported", getSystemCharset().name());
    }

    File file = new File(jarFileName);
    return new JarFileResource(new JarFile(file), jarEntryName);
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java

/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * @param srcAttribute the source attribute from the script tag
 * @param charset the charset attribute from the script tag
 * @return the result of loading the specified external JavaScript file
 * @throws FailingHttpStatusCodeException if the request's status code indicates a request
 *         failure and the {@link WebClient} was configured to throw exceptions on failing
 *         HTTP status codes//from w  ww .  ja va2 s . c  o  m
 */
JavaScriptLoadResult loadExternalJavaScriptFile(final String srcAttribute, final String charset)
        throws FailingHttpStatusCodeException {

    final WebClient client = getWebClient();
    if (StringUtils.isBlank(srcAttribute) || !client.getOptions().isJavaScriptEnabled()) {
        return JavaScriptLoadResult.NOOP;
    }

    final URL scriptURL;
    try {
        scriptURL = getFullyQualifiedUrl(srcAttribute);
        final String protocol = scriptURL.getProtocol();
        if ("javascript".equals(protocol)) {
            LOG.info("Ignoring script src [" + srcAttribute + "]");
            return JavaScriptLoadResult.NOOP;
        }
        if (!"http".equals(protocol) && !"https".equals(protocol) && !"data".equals(protocol)
                && !"file".equals(protocol)) {
            LOG.error("Unable to build URL for script src tag [" + srcAttribute + "] (protocol: '" + protocol
                    + "')");
            final JavaScriptErrorListener javaScriptErrorListener = client.getJavaScriptErrorListener();
            if (javaScriptErrorListener != null) {
                javaScriptErrorListener.malformedScriptURL(this, srcAttribute,
                        new MalformedURLException("unknown protocol: '" + protocol + "'"));
            }
            return JavaScriptLoadResult.NOOP;
        }
    } catch (final MalformedURLException e) {
        LOG.error("Unable to build URL for script src tag [" + srcAttribute + "]");
        final JavaScriptErrorListener javaScriptErrorListener = client.getJavaScriptErrorListener();
        if (javaScriptErrorListener != null) {
            javaScriptErrorListener.malformedScriptURL(this, srcAttribute, e);
        }
        return JavaScriptLoadResult.NOOP;
    }

    final Script script;
    try {
        script = loadJavaScriptFromUrl(scriptURL, charset);
    } catch (final IOException e) {
        LOG.error("Error loading JavaScript from [" + scriptURL + "].", e);
        final JavaScriptErrorListener javaScriptErrorListener = client.getJavaScriptErrorListener();
        if (javaScriptErrorListener != null) {
            javaScriptErrorListener.loadScriptError(this, scriptURL, e);
        }
        return JavaScriptLoadResult.DOWNLOAD_ERROR;
    } catch (final FailingHttpStatusCodeException e) {
        LOG.error("Error loading JavaScript from [" + scriptURL + "].", e);
        final JavaScriptErrorListener javaScriptErrorListener = client.getJavaScriptErrorListener();
        if (javaScriptErrorListener != null) {
            javaScriptErrorListener.loadScriptError(this, scriptURL, e);
        }
        throw e;
    }

    if (script == null) {
        return JavaScriptLoadResult.COMPILATION_ERROR;
    }

    client.getJavaScriptEngine().execute(this, script);
    return JavaScriptLoadResult.SUCCESS;
}

From source file:com.remobile.file.FileUtils.java

/**
 * Allows the user to look up the Entry for a file or directory referred to by a local URI.
 *
 * @param uriString of the file/directory to look up
 * @return a JSONObject representing a Entry from the filesystem
 * @throws MalformedURLException if the url is not valid
 * @throws FileNotFoundException if the file does not exist
 * @throws IOException if the user can't read the file
 * @throws JSONException//from  www. j  a v  a  2 s .co  m
 */
private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException {
    if (uriString == null) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
    Uri uri = Uri.parse(uriString);

    LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
    if (inputURL == null) {
        /* Check for file://, content:// urls */
        inputURL = resolveNativeUri(uri);
    }

    try {
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        if (fs.exists(inputURL)) {
            return fs.getEntryForLocalURL(inputURL);
        }
    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
    throw new FileNotFoundException();
}

From source file:com.remobile.file.FileUtils.java

/**
 * Read the list of files from this directory.
 *
 * @return a JSONArray containing JSONObjects that represent Entry objects.
 * @throws FileNotFoundException if the directory is not found.
 * @throws JSONException/*from   ww  w.j a v  a 2 s  . c  o  m*/
 * @throws MalformedURLException 
 */
private JSONArray readEntries(String baseURLstr)
        throws FileNotFoundException, JSONException, MalformedURLException {
    try {
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        return fs.readEntriesAtLocalURL(inputURL);

    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Opens input stream for given resource. This method behaves differently for different URL
 * types://from   ww w . jav a 2  s  .  c  om
 * <ul>
 * <li>for <b>local files</b> it returns buffered file input stream;</li>
 * <li>for <b>local JAR files</b> it reads resource content into memory buffer and returns byte
 * array input stream that wraps those buffer (this prevents locking JAR file);</li>
 * <li>for <b>common URL's</b> this method simply opens stream to that URL using standard URL
 * API.</li>
 * </ul>
 * It is not recommended to use this method for big resources within JAR files.
 * 
 * @param url resource URL
 * @return input stream for given resource
 * @throws IOException if any I/O error has occurred
 */
public static InputStream getResourceInputStream(final URL url) throws IOException {
    File file = url2file(url);
    if (file != null) {
        return new BufferedInputStream(new FileInputStream(file));
    }
    if (!"jar".equalsIgnoreCase(url.getProtocol())) {
        return url.openStream();
    }
    String urlStr = url.toExternalForm();
    if (urlStr.endsWith("!/")) {
        // JAR URL points to a root entry
        throw new FileNotFoundException(url.toExternalForm());
    }
    int p = urlStr.indexOf("!/");
    if (p == -1) {
        throw new MalformedURLException(url.toExternalForm());
    }
    String path = urlStr.substring(p + 2);
    file = url2file(new URL(urlStr.substring(4, p)));
    if (file == null) {// non-local JAR file URL
        return url.openStream();
    }
    JarFile jarFile = new JarFile(file);
    try {
        ZipEntry entry = jarFile.getEntry(path);
        if (entry == null) {
            throw new FileNotFoundException(url.toExternalForm());
        }
        InputStream in = jarFile.getInputStream(entry);
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            copyFile(in, out);
            return new ByteArrayInputStream(out.toByteArray());
        } finally {
            in.close();
        }
    } finally {
        jarFile.close();
    }
}

From source file:com.remobile.file.FileUtils.java

/**
 * Deletes a directory and all of its contents, if any. In the event of an error
 * [e.g. trying to delete a directory that contains a file that cannot be removed],
 * some of the contents of the directory may be deleted.
 * It is an error to attempt to delete the root directory of a filesystem.
 *
 * @return a boolean representing success of failure
 * @throws FileExistsException//from   ww w  .ja v  a  2  s.  co  m
 * @throws NoModificationAllowedException 
 * @throws MalformedURLException 
 */
private boolean removeRecursively(String baseURLstr)
        throws FileExistsException, NoModificationAllowedException, MalformedURLException {
    try {
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
        // You can't delete the root directory.
        if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
            throw new NoModificationAllowedException("You can't delete the root directory");
        }

        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        return fs.recursiveRemoveFileAtLocalURL(inputURL);

    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
}

From source file:edu.kit.dama.staging.util.DataOrganizationUtils.java

/**
 * Generate a map of zip entries that have to be considered when zipping
 * pNode. This method calls itself recursively to traverse through
 * sub-directories. The provided map finally contains all files and folders
 * that have to be in the zip file. For files, the value of a map entry is
 * defined, for (empty) folders the value is null. The returned value is the
 * summed size of all files and can be used to decide whether or not the zip
 * should be finally created.//  w w w .ja v a2s .co  m
 *
 * @param pNode The node that should be handled. Filenodes will be directly
 * added to pMap, CollectionNodes will be traversed.
 * @param pPath The current part that is accessed.
 * @param pMap The map of resulting entries.
 *
 * @return The overall amount of data.
 */
private static long generateZipEntries(IDataOrganizationNode pNode, String pPath, Map<String, File> pMap) {
    long size = 0;
    String basePath = (pPath == null) ? pNode.getName() : pPath + "/" + pNode.getName();
    if (pNode instanceof ICollectionNode) {
        ICollectionNode node = (ICollectionNode) pNode;
        if (!node.getChildren().isEmpty()) {
            for (IDataOrganizationNode childNode : node.getChildren()) {
                size += generateZipEntries(childNode, basePath, pMap);
            }
        } else {
            //empty node
            pMap.put(basePath, null);
        }
    } else if (pNode instanceof IFileNode) {
        IFileNode node = (IFileNode) pNode;
        File f = null;
        String lfn = node.getLogicalFileName().asString();
        try {
            URL lfnUrl = new URL(lfn);
            if ("file".equals(lfnUrl.getProtocol())) {
                f = new File(lfnUrl.toURI());
                size += f.length();
            } else {
                throw new MalformedURLException(
                        "Protocol " + lfnUrl.getProtocol() + " currently not supported.");
            }
            pMap.put(basePath, f);
        } catch (MalformedURLException | URISyntaxException ex) {
            LOGGER.warn("Unsupported LFN " + lfn
                    + ". Only LFNs refering to locally accessible files are supported.");
        }
    } else {
        throw new IllegalArgumentException("Argument " + pNode
                + " is not a supported argument. Only nodes of type ICollectionNode or IFileNode are supported.");
    }
    return size;
}