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:org.georchestra.security.Proxy.java

/**
 * Main entry point for methods where the request path is encoded in the
 * path of the URL/*  ww w  . j  a  v a 2s. c o m*/
 */
private void handlePathEncodedRequests(HttpServletRequest request, HttpServletResponse response,
        RequestType requestType) {
    try {
        String contextPath = request.getServletPath() + request.getContextPath();
        String forwardRequestURI = buildForwardRequestURL(request);

        logger.debug("handlePathEncodedRequests: -- Handling Request: " + requestType + ":" + forwardRequestURI
                + " from: " + request.getRemoteAddr());

        String sURL = findTarget(forwardRequestURI);

        if (sURL == null) {
            response.sendError(404);
            return;
        }

        URL url;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) {
            throw new MalformedURLException(sURL + " is not a valid URL");
        }

        boolean sameHostAndPort = false;

        try {
            sameHostAndPort = isSameHostAndPort(request, url);
        } catch (UnknownHostException e) {
            logger.error("Unknown host in requested URL", e);
            response.sendError(503);
            return;
        }

        if (sameHostAndPort && (isRecursiveCallToProxy(forwardRequestURI, contextPath)
                || isRecursiveCallToProxy(url.getPath(), contextPath))) {
            response.sendError(403,
                    forwardRequestURI + " is a recursive call to this service.  That is not a legal request");
        }

        if (request.getQueryString() != null && !isFormContentType(request)) {
            StringBuilder query = new StringBuilder("?");
            Enumeration paramNames = request.getParameterNames();
            boolean needCasValidation = false;
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                String[] values = request.getParameterValues(name);
                for (String string : values) {
                    if (query.length() > 1) {
                        query.append('&');
                    }
                    // special case: if we have a ticket parameter and no
                    // authentication principal, we need to validate/open
                    // the session against CAS server
                    if ((request.getUserPrincipal() == null)
                            && (name.equals(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER))) {
                        needCasValidation = true;
                    } else {
                        query.append(name);
                        query.append('=');
                        query.append(URLEncoder.encode(string, "UTF-8"));
                    }
                }
            }
            sURL += query;
            if ((needCasValidation) && (urlIsProtected(request, new URL(sURL)))) {
                // loginUrl: sends a redirect to the client with a ?login (or &login if other arguments)
                // since .*login patterns are protected by the SP, this would trigger an authentication
                // onto CAS (which should succeed if the user is already connected onto the platform).
                String loginUrl = String.format("%s%s%s", request.getPathInfo(), query, "login");
                redirectStrategy.sendRedirect(request, response, loginUrl);
                return;
            }
        }

        handleRequest(request, response, requestType, sURL, true);
    } catch (IOException e) {
        logger.error("Error connecting to client", e);
    }
}

From source file:net.yacy.cora.document.id.MultiProtocolURL.java

public MultiProtocolURL(final MultiProtocolURL baseURL, String relPath) throws MalformedURLException {
    if (baseURL == null)
        throw new MalformedURLException("base URL is null");
    if (relPath == null)
        throw new MalformedURLException("relPath is null");

    this.protocol = baseURL.protocol;
    this.host = baseURL.host;
    this.port = baseURL.port;
    this.userInfo = baseURL.userInfo;
    if (relPath.startsWith("//")) {
        // a "network-path reference" as defined in rfc2396 denotes
        // a relative path that uses the protocol from the base url
        relPath = baseURL.protocol + ":" + relPath;
    }// ww w  .  ja va  2 s . c  o m
    if (relPath.toLowerCase(Locale.ROOT).startsWith("javascript:")) {
        this.path = baseURL.path;
    } else if (isHTTP(relPath) || isHTTPS(relPath) || isFTP(relPath) || isFile(relPath) || isSMB(relPath)) {
        this.path = baseURL.path;
    } else if (relPath.contains(":") && patternMail.matcher(relPath.toLowerCase(Locale.ROOT)).find()) { // discards also any unknown protocol from previous if
        throw new MalformedURLException("relative path malformed: " + relPath);
    } else if (relPath.length() > 0 && relPath.charAt(0) == '/') {
        this.path = relPath;
    } else if (baseURL.path.endsWith("/")) {
        /* According to RFC 3986 example in Appendix B. (https://tools.ietf.org/html/rfc3986) 
           such an URL is valid : http://www.ics.uci.edu/pub/ietf/uri/#Related
                   
           We also find similar usages in the 2016 URL living standard (https://url.spec.whatwg.org/),  
           for example : https://url.spec.whatwg.org/#syntax-url-absolute-with-fragment 
                   
           java.lang.URL constructor also accepts this form.*/
        if (relPath.startsWith("/"))
            this.path = baseURL.path + relPath.substring(1);
        else
            this.path = baseURL.path + relPath;
    } else {
        if (relPath.length() > 0 && (relPath.charAt(0) == '#' || relPath.charAt(0) == '?')) {
            this.path = baseURL.path + relPath;
        } else {
            final int q = baseURL.path.lastIndexOf('/');
            if (q < 0) {
                this.path = relPath;
            } else {
                this.path = baseURL.path.substring(0, q + 1) + relPath;
            }
        }
    }
    this.searchpart = baseURL.searchpart;
    this.anchor = baseURL.anchor;

    this.path = resolveBackpath(this.path);
    identAnchor();
    identSearchpart();
    escape();
}

From source file:org.exist.cocoon.XMLDBSource.java

/**
 * Return an {@link OutputStream} to write to. This method expects an XML document to be
 * written in that stream. To create a binary resource, use {@link #getBinaryOutputStream()}.
 */// w  w  w.ja v  a2s. co  m
public OutputStream getOutputStream() throws IOException, MalformedURLException {
    if (query != null) {
        throw new MalformedURLException("Cannot modify a resource that includes an XPATH expression");
    }
    return new XMLDBOutputStream(false);
}

From source file:org.exist.cocoon.XMLDBSource.java

/**
 * set content as DOM/*  www.java2s .  c  om*/
 * 
 * @see <a href="http://exist.sourceforge.net/api/org/xmldb/api/modules/XMLResource.html#setContentAsDOM(org.w3c.dom.Node)">XMLDB API</a>
 */
public void setContentAsDOM(Node doc) throws IOException, MalformedURLException {
    // author frederic.glorieux@ajlsm.com
    try {
        if (query != null) {
            throw new MalformedURLException("Cannot modify a resource that includes an XPATH expression");
        }
        setup();
        if (status == ST_NO_PARENT) {
            // If there's no parent collection, create it
            collection = createCollection(colPath);
            status = ST_NO_RESOURCE;
        }
        resource = collection.createResource(this.resName, XMLResource.RESOURCE_TYPE);
        ((XMLResource) resource).setContentAsDOM(doc);
        collection.storeResource(resource);
    } catch (XMLDBException e) {
        String message = "Failed to create resource " + resName + ": " + e.errorCode;
        e.printStackTrace(System.out);
        throw new SourceException(message, e);
    }
}

From source file:net.yacy.cora.document.id.MultiProtocolURL.java

/**
* creates MultiProtocolURL/*from w  w  w. j a  va2 s  .  com*/
* if path contains '?' search part is automatically created by splitting input into path and searchpart
* dto for anchor's ('#')
*/
public MultiProtocolURL(final String protocol, String host, final int port, final String path)
        throws MalformedURLException {
    if (protocol == null)
        throw new MalformedURLException("protocol is null");
    if (host.indexOf(':') >= 0 && host.charAt(0) != '[')
        host = '[' + host + ']'; // IPv6 host must be enclosed in square brackets
    this.protocol = protocol;
    this.host = host;
    this.port = port;
    this.path = path;
    this.searchpart = null;
    this.userInfo = null;
    this.anchor = null;
    identAnchor();
    identSearchpart();
    escape();
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHandler.java

/** Get a Resource.
 * If no resource is found, resource aliases are tried.
 * @param uriInContext //from w w  w . j a  v a  2s  .  c  o m
 * @return URL of the resource.
 * @exception MalformedURLException 
 */
public URL getResource(String uriInContext) throws MalformedURLException {
    if (uriInContext == null || !uriInContext.startsWith("/"))
        throw new MalformedURLException(uriInContext);

    try {
        Resource resource = getHttpContext().getResource(uriInContext);
        if (resource != null && resource.exists())
            return resource.getURL();
    } catch (IllegalArgumentException e) {
        LogSupport.ignore(log, e);
    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        log.warn(LogSupport.EXCEPTION, e);
    }
    return null;
}

From source file:org.exist.cocoon.XMLDBSource.java

/**
 * get content as DOM//w  ww.  j  a va2  s .co m
 * @see <a href="http://exist.sourceforge.net/api/org/xmldb/api/modules/XMLResource.html#setContentAsDOM(org.w3c.dom.Node)">XMLDB API</a>
 */
public Node getContentAsDOM() throws IOException, MalformedURLException {
    try {
        setup();
        if (!(resource instanceof XMLResource)) {
            throw new SourceException("Not an XML resource: " + getURI());
        }
        if (query != null) {
            throw new MalformedURLException("Not yet available for queries, only for single resource.");
        }
        String name = this.resName;
        resource = collection.createResource(name, XMLResource.RESOURCE_TYPE);
        return ((XMLResource) resource).getContentAsDOM();
    } catch (XMLDBException e) {
        String message = "Failed to create resource " + resName + ": " + e.errorCode;
        throw new SourceException(message, e);
    }
}

From source file:org.kalypso.ui.wizards.results.editor.EditStyleDialog.java

private Symbolizer[] parseStyle() {
    InputStream inputStream = null;
    try {/* w  w w  .j a  va2 s  .  c o  m*/
        inputStream = m_sldFile.getContents();
        final IUrlResolver2 resolver = new IUrlResolver2() {
            @Override
            @SuppressWarnings("synthetic-access")
            public URL resolveURL(final String relativeOrAbsolute) throws MalformedURLException {
                try {
                    final URL sldURL = ResourceUtilities.createURL(m_sldFile);
                    return new URL(sldURL, relativeOrAbsolute);
                } catch (final URIException e) {
                    e.printStackTrace();
                    throw new MalformedURLException(e.getLocalizedMessage());
                }
            }

        };
        m_sld = SLDFactory.createSLD(resolver, inputStream);
        final NamedLayer[] namedLayers = m_sld.getNamedLayers();
        // get always just the first layer
        final NamedLayer namedLayer = namedLayers[0];

        // get always the first style (we assume there is only one)
        final Style[] styles = namedLayer.getStyles();

        final Style style = styles[0];
        if (style instanceof UserStyle) {
            final UserStyle userStyle = (UserStyle) style;
            final FeatureTypeStyle[] featureTypeStyles = userStyle.getFeatureTypeStyles();
            // we assume, that there is only one feature type style and take the first we can get.
            final FeatureTypeStyle featureTypeStyle = featureTypeStyles[0];

            // we assume, that there is only one rule and take the first we can get.
            m_rules = featureTypeStyle.getRules();

            final List<Symbolizer> symbList = new ArrayList<>();

            for (final Rule rule : m_rules) {
                final Symbolizer[] symbolizers = rule.getSymbolizers();
                // and the first and only symbolizer is taken
                final Symbolizer symb = symbolizers[0];
                symbList.add(symb);
            }

            return symbList.toArray(new Symbolizer[symbList.size()]);
        }
    } catch (final CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final XMLParsingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    finally {
        IOUtils.closeQuietly(inputStream);
    }
    return null;
}

From source file:org.exist.cocoon.XMLDBSource.java

/**
 * Return an {@link OutputStream} to write data to a binary resource.
 *//*  w w  w.j  a  v  a  2s  . c om*/
public OutputStream getBinaryOutputStream() throws IOException, MalformedURLException {
    if (query != null) {
        throw new MalformedURLException("Cannot modify a resource that includes an XPATH expression");
    }
    return new XMLDBOutputStream(true);
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ??/*from w  w  w .j a v a  2s .c  o m*/
 *
 * @param  con    ?
 * @throws IOException
 */
private void checkConnection(HttpURLConnection con) throws MalformedURLException, IOException {
    int responseCode = con.getResponseCode();
    if (HttpURLConnection.HTTP_OK != responseCode) {
        throw new MalformedURLException("" + responseCode);
    }
}