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.github.jrrdev.mantisbtsync.core.jobs.common.CommonTasklets.java

@Bean
@JobScope//w w w  .j av a  2s. c o m
public MantisConnectBindingStub clientStub(@Value("${mantis.endpoint}") final String endpoint,
        final PortalAuthBuilder authBuilder) throws AxisFault, MalformedURLException {

    if (endpoint == null) {
        throw new MalformedURLException("Mantis endpoint can't be null");
    }

    final MantisConnectLocator loc = new MantisConnectLocator(new BasicClientConfig());
    loc.setMantisConnectPortEndpointAddress(endpoint);
    final MantisConnectBindingStub stub = new MantisConnectBindingStub(new URL(endpoint), loc);
    stub._setProperty(MessageContext.HTTP_TRANSPORT_VERSION, HTTPConstants.HEADER_PROTOCOL_V11);
    stub.setMaintainSession(true);

    return stub;
}

From source file:mitm.common.cifs.SMBURLBuilder.java

private String buildUserInfo(SMBFileParameters parameters)
        throws MalformedURLException, HierarchicalPropertiesException {
    try {/*from  ww  w. ja  va 2 s.  c  o m*/
        StrBuilder sb = new StrBuilder();

        if (StringUtils.isNotBlank(parameters.getDomain())) {
            sb.append(urlEncode(parameters.getDomain())).append(";");
        }

        if (StringUtils.isNotBlank(parameters.getUsername())) {
            sb.append(urlEncode(parameters.getUsername()));

            if (StringUtils.isNotBlank(parameters.getPassword())) {
                sb.append(":").append(urlEncode(parameters.getPassword()));
            }
        }

        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        throw new MalformedURLException("UTF-8 is unsupported.");
    }
}

From source file:org.zaproxy.zap.spider.URLCanonicalizer.java

/**
 * Gets the canonical url, starting from a relative or absolute url found in a given context (baseURL).
 * /*from  w  ww.  j  av  a 2 s.c o  m*/
 * @param url the url string defining the reference
 * @param baseURL the context in which this url was found
 * @return the canonical url
 */
public static String getCanonicalURL(String url, String baseURL) {

    try {
        /* Build the absolute URL, from the url and the baseURL */
        String resolvedURL = URLResolver.resolveUrl(baseURL == null ? "" : baseURL, url);
        log.debug("Resolved URL: " + resolvedURL);
        URI canonicalURI;
        try {
            canonicalURI = new URI(resolvedURL);
        } catch (Exception e) {
            canonicalURI = new URI(URIUtil.encodeQuery(resolvedURL));
        }

        /* Some checking. */
        if (canonicalURI.getScheme() == null) {
            throw new MalformedURLException("Protocol could not be reliably evaluated from uri: " + canonicalURI
                    + " and base url: " + baseURL);
        }

        if (canonicalURI.getRawAuthority() == null) {
            log.debug("Ignoring URI with no authority (host[\":\"port]): " + canonicalURI);
            return null;
        }

        if (canonicalURI.getHost() == null) {
            throw new MalformedURLException("Host could not be reliably evaluated from: " + canonicalURI);
        }

        /*
         * Normalize: no empty segments (i.e., "//"), no segments equal to ".", and no segments equal to
         * ".." that are preceded by a segment not equal to "..".
         */
        String path = canonicalURI.normalize().getRawPath();

        /* Convert '//' -> '/' */
        int idx = path.indexOf("//");
        while (idx >= 0) {
            path = path.replace("//", "/");
            idx = path.indexOf("//");
        }

        /* Drop starting '/../' */
        while (path.startsWith("/../")) {
            path = path.substring(3);
        }

        /* Trim */
        path = path.trim();

        /* Process parameters and sort them. */
        final SortedMap<String, String> params = createParameterMap(canonicalURI.getRawQuery());
        final String queryString;
        String canonicalParams = canonicalize(params);
        queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);

        /* Add starting slash if needed */
        if (path.length() == 0) {
            path = "/" + path;
        }

        /* Drop default port: example.com:80 -> example.com */
        int port = canonicalURI.getPort();
        if (port == 80) {
            port = -1;
        }

        /* Lowercasing protocol and host */
        String protocol = canonicalURI.getScheme().toLowerCase();
        String host = canonicalURI.getHost().toLowerCase();
        String pathAndQueryString = normalizePath(path) + queryString;

        URL result = new URL(protocol, host, port, pathAndQueryString);
        return result.toExternalForm();

    } catch (Exception ex) {
        log.warn("Error while Processing URL in the spidering process (on base " + baseURL + "): "
                + ex.getMessage());
        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.
 * //from  w  ww. j  a  v  a  2  s  .  c  o 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);
    }
}

From source file:org.social.portlet.utils.Utils.java

/**
 * Gets the router from path of file controller.xml
 * /*  www.j  a  v a  2s. co m*/
 * @param path
 * @return
 * @throws IOException
 * @throws RouterConfigException
 * @since 1.2.2
 */
private static Router getRouter(String path) throws IOException, RouterConfigException {
    File f = new File(path);
    if (!f.exists()) {
        throw new MalformedURLException("Could not resolve path " + path);
    }
    if (!f.isFile()) {
        throw new MalformedURLException("Could not resolve path " + path + " to a valid file");
    }
    return getRouter(f.toURI().toURL());
}

From source file:org.apache.cocoon.components.source.impl.XModuleSource.java

/**
 * Create a xmodule source from a 'xmodule:' uri and a the object model.
 * <p>The uri is of the form "xmodule:/attribute-type/attribute-name/xpath</p>
 *//*from   w  w w. jav  a 2s . c  om*/
public XModuleSource(Map objectModel, String uri, ServiceManager manager, Logger logger)
        throws MalformedURLException {

    this.objectModel = objectModel;
    this.manager = manager;
    this.logger = logger;

    setSystemId(uri);

    // Scheme
    int start = 0;
    int end = uri.indexOf(':');
    if (end == -1)
        throw new MalformedURLException("Malformed uri for xmodule source (cannot find scheme) : " + uri);

    String scheme = uri.substring(start, end);
    if (!SCHEME.equals(scheme))
        throw new MalformedURLException("Malformed uri for a xmodule source : " + uri);

    setScheme(scheme);

    // Attribute type
    start = end + 1;
    end = uri.indexOf(':', start);
    if (end == -1) {
        throw new MalformedURLException(
                "Malformed uri for xmodule source (cannot find attribute type) : " + uri);
    }
    this.attributeType = uri.substring(start, end);

    // Attribute name
    start = end + 1;
    end = uri.indexOf('#', start);

    if (end == -1)
        end = uri.length();

    if (end == start)
        throw new MalformedURLException(
                "Malformed uri for xmodule source (cannot find attribute name) : " + uri);

    this.attributeName = uri.substring(start, end);

    // xpath
    start = end + 1;
    this.xPath = start < uri.length() ? uri.substring(start) : "";
}

From source file:org.nordapp.web.servlet.DEVServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from  ww  w .  j a  v a  2  s .co  m*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler (HTTP) and session control (OSGi)
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        //RequestHandler rqHdl = new RequestHandler(context, ctrl);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();
        ctrl.setAll();
        ctrl.saveTempSession();

        //
        // Session service
        //
        String cert = null;

        String[] elem = RequestPath.getPath(req);
        if (elem.length != 1)
            throw new MalformedURLException("The URL needs the form '" + req.getServletPath()
                    + "/[create|load]' but was '" + req.getRequestURI() + "'");

        Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.getCertID());
        if (mSession == null) {
            List<String> list = ctrl.getShortTimePassword();
            if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID())))
                throw new UnavailableException("Needs a valid User-Session.");
        }

        ServiceReference<DeployService> srDeploy = context.getServiceReference(DeployService.class);
        if (srDeploy == null)
            throw new IOException(
                    "The deploy service reference is not available (maybe down or a version conflict).");
        DeployService svDeploy = context.getService(srDeploy);
        if (svDeploy == null)
            throw new IOException("The deploy service is not available (maybe down or a version conflict).");

        String processID = IdGen.getURLSafeString(IdGen.getUUID());
        String mandatorID = ctrl.getMandatorID();
        String groupID = ctrl.getGroupID();
        String artifactID = ctrl.getArtifactID();

        File zip = null;
        if (elem[0].equalsIgnoreCase("create")) {
            zip = svDeploy.createEmptyZip(processID, mandatorID, groupID, artifactID);
        } else if (elem[0].equalsIgnoreCase("load")) {
            zip = svDeploy.zipFromData(processID, mandatorID, groupID, artifactID);
        } else {
            throw new MalformedURLException("The URL needs the form '" + req.getServletPath()
                    + "/[create|load]' but was '" + req.getRequestURI() + "'");
        }

        ResponseHandler rsHdl = new ResponseHandler(context, ctrl);
        rsHdl.avoidCaching(resp);

        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Type", "application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + processID + ".zip\"");
        InputStream is = new FileInputStream(zip);
        try {
            rsHdl.sendFile(is, resp, null);
        } finally {
            is.close();
        }

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.xwiki.environment.internal.ServletEnvironmentTest.java

@Test
public void getResourceWhenMalformedURLException() throws Exception {
    ServletContext servletContext = mock(ServletContext.class);
    when(servletContext.getResource("bad resource")).thenThrow(new MalformedURLException("invalid url"));
    this.environment.setServletContext(servletContext);
    assertNull(this.environment.getResource("bad resource"));
    assertEquals("Error getting resource [bad resource] because of invalid path format. Reason: [invalid url]",
            this.logRule.getMessage(0));
}

From source file:org.tinymediamanager.scraper.util.Url.java

/**
 * Instantiates a new url / httpclient with default user-agent.
 * /* w ww .j a v a 2  s  . c om*/
 * @param url
 *          the url
 */
public Url(String url) throws MalformedURLException {
    if (client == null) {
        client = TmmHttpClient.getHttpClient();
    }
    this.url = url;

    // morph to URI to check syntax of the url
    try {
        this.uri = morphStringToUri(url);
    } catch (URISyntaxException e) {
        throw new MalformedURLException(url);
    }

    // default user agent
    addHeader(HttpHeaders.USER_AGENT, UrlUtil.generateUA());
}

From source file:org.tinymediamanager.scraper.http.Url.java

/**
 * Instantiates a new url / httpclient with default user-agent.
 * /*  w w w.j  a v  a2 s .  co m*/
 * @param url
 *          the url
 */
public Url(String url) throws MalformedURLException {
    if (client == null) {
        client = TmmHttpClient.getHttpClient();
    }
    this.url = url;

    // morph to URI to check syntax of the url
    try {
        uri = morphStringToUri(url);
    } catch (URISyntaxException e) {
        throw new MalformedURLException(url);
    }

    // default user agent
    addHeader(USER_AGENT, UrlUtil.generateUA());
}