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.sonicle.webtop.core.app.servlet.ResourceRequest.java

private String[] splitPath(String pathInfo) throws MalformedURLException {
    String[] tokens = StringUtils.split(pathInfo, "/", 2);
    if (tokens.length != 2)
        throw new MalformedURLException("URL does not esplicitate service ID");
    return tokens;
}

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

/**
 * Get a <code>Source</code> object.
 * @param parameters This is optional.//  www.  j a v a 2s .c  o  m
 */
public Source getSource(final String location, final Map parameters) throws IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("Creating source " + location);
    }

    // snip the cache protocol
    int index = location.indexOf(':');
    if (index == -1) {
        throw new MalformedURLException("This Source requires a subprotocol to be specified.");
    }

    String uri = location.substring(index + 1);

    // parse the query string
    SourceParameters sp = null;
    index = uri.indexOf('?');
    if (index != -1) {
        sp = new SourceParameters(uri.substring(index + 1));
        uri = uri.substring(0, index);
    }

    // put caching source specific query string parameters
    // into a Parameters object
    final Parameters params = new Parameters();
    if (sp != null) {
        SourceParameters remainingParameters = (SourceParameters) sp.clone();
        final Iterator names = sp.getParameterNames();
        while (names.hasNext()) {
            String name = (String) names.next();
            if (name.startsWith("cocoon:cache")) {
                params.setParameter(name.substring("cocoon:".length()), sp.getParameter(name));
                remainingParameters.removeParameter(name);
            }
        }
        String queryString = remainingParameters.getEncodedQueryString();
        if (queryString != null) {
            uri += "?" + queryString;
        }
    }

    int expires = params.getParameterAsInteger(CachingSource.CACHE_EXPIRES_PARAM, this.defaultExpires);
    String cacheName = params.getParameter(CachingSource.CACHE_NAME_PARAM, null);
    boolean fail = params.getParameterAsBoolean(CachingSource.CACHE_FAIL_PARAM, false);

    return createCachingSource(location, uri, this.resolver.resolveURI(uri), expires, cacheName, fail);
}

From source file:com.ecomnext.rest.ning.NingRestRequestHolder.java

/**
 * Sets the authentication header for the current request using BASIC authentication.
 *//*from   ww w  .  j a  va 2s . co  m*/
@Override
public RestRequestHolder setAuth(String userInfo) {
    this.scheme = RestAuthScheme.BASIC;

    if (userInfo.equals("")) {
        throw new RuntimeException(new MalformedURLException("userInfo should not be empty"));
    }

    int split = userInfo.indexOf(":");

    if (split == 0) { // We only have a password without user
        this.username = "";
        this.password = userInfo.substring(1);
    } else if (split == -1) { // We only have a username without password
        this.username = userInfo;
        this.password = "";
    } else {
        this.username = userInfo.substring(0, split);
        this.password = userInfo.substring(split + 1);
    }

    return this;
}

From source file:org.apache.webdav.lib.WebdavFile.java

public URL toURL() throws MalformedURLException {
    if (relPath != null)
        return null;
    try {/* ww  w.  j ava 2s .co m*/
        return new URL(httpUrl.getURI());
    } catch (URIException e) {
        throw new MalformedURLException(e.getMessage());
    }
}

From source file:org.ofbiz.testtools.seleniumxml.SeleniumXml.java

private static void initConfig(URL url) throws IOException {
    try {/*from www.j a v a  2  s. c  o m*/
        if (url == null) {
            String errMsg = "The Java environment (-Dxxx=yyy) variable with name " + url.toString()
                    + " is not set, cannot resolve location.";
            throw new MalformedURLException(errMsg);
        }
        props = UtilProperties.getProperties(url);
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.opensextant.xtext.collectors.web.HyperLink.java

/**
 * URL wrangling, mainly to take a found URL and adapt it so it looks like a file path safe for a file system.
 *
 * @param link/*from ww  w  . j a  v a  2  s.  co m*/
 *            found link
 * @param referringLink
 *            - Normalized, absolute URL string
 * @param site
 *            top level site
 * @throws MalformedURLException
 *             on err
 * @throws NoSuchAlgorithmException
 *             on err
 * @throws UnsupportedEncodingException
 *             on err, when URL contains poorly encoded characters
 */
public HyperLink(String link, URL referringLink, URL site)
        throws MalformedURLException, NoSuchAlgorithmException, UnsupportedEncodingException {
    urlValue = link;
    urlNominal = link;
    siteURL = site;
    siteValue = site.toString();
    referrerURL = referringLink;
    String url_lc = urlNominal.toLowerCase();
    String site_lc = siteValue.toLowerCase();
    // If referrer, e.g. page containing this link is a folder or file, detect that.
    //   "/a/b/c"  is a folder but ensure referrer is tracked as "/a/b/c/" with trailing slash here.
    //  Otherwise, url is a page.
    String base_lc = referrerURL.toString().toLowerCase();
    boolean isReferrerFolder = false;
    String urlPath = null;

    isAbsolute = (url_lc.startsWith("http:") || url_lc.startsWith("https:"));

    if (!isAbsolute) {
        absoluteURL = new URL(referrerURL, urlValue);
        urlValue = absoluteURL.toString();
    } else {
        absoluteURL = new URL(urlValue);
    }

    // Use this to represent the object identity.
    linkId = TextUtils.text_id(getAbsoluteURL());
    query = absoluteURL.getQuery();

    urlPath = absoluteURL.getPath().toLowerCase();
    pathExtension = FilenameUtils.getExtension(urlPath);
    String referrerExt = FilenameUtils.getExtension(base_lc);

    isFolder = isFolder(url_lc, pathExtension);
    isReferrerFolder = isFolder(referrerURL.getPath(), referrerExt);

    String abs_lc = absoluteURL.toString().toLowerCase();

    String path = absoluteURL.getPath();
    if (isBlank(path)) {
        normalizedPath = "./";
        isFolder = true;
    } else {
        normalizedPath = path;
        if (normalizedPath.endsWith("/")) {
            normalizedPath = normalizedPath.substring(0, normalizedPath.length() - 1);
        }
    }

    // Optional
    boolean derivedPath = deriveFilepathFromQuery();

    if (!derivedPath) {
        String p = FilenameUtils.normalize(normalizedPath);
        if (p == null) {
            throw new MalformedURLException("Unable to parse/normalize path for: " + normalizedPath);
        }
        normalizedPath = p;
    }

    if (isFolder) {
        directory = new File(normalizedPath).getPath();
    } else {
        directory = new File(normalizedPath).getParent();
    }

    if (directory == null) {
        directory = path;
    }

    if (!isFolder) {
        archiveFileExtension = FilenameUtils.getExtension(normalizedPath);
    }

    // If base/referring page is a directory see if it is in same folder
    // as current link
    //
    String dirB = base_lc;
    if (isReferrerFolder && !dirB.endsWith("/")) {
        dirB = dirB + "/";
    } else if (!isReferrerFolder) {
        int b = base_lc.lastIndexOf('/');
        dirB = base_lc.substring(0, b);
    }

    int s = site_lc.lastIndexOf('/');
    String siteDir = site_lc.substring(0, s);

    isCurrentSite = abs_lc.startsWith(siteDir);
    if (isCurrentSite) {
        if (isFolder) {
            isCurrentPage = abs_lc.startsWith(dirB);
        } else {
            int a = abs_lc.lastIndexOf('/');
            String dirA = abs_lc.substring(0, a) + "/";
            isCurrentPage = dirA.startsWith(dirB);
        }
    }
    String linkHost = absoluteURL.getHost();
    String siteHost = siteURL.getHost();
    isCurrentHost = linkHost.equalsIgnoreCase(siteHost);
}

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * Connect to WebSocketServer with additional Header.
 * When unsubscribe is called, the observable will disconnect automatically.
 * <p>/* www.j a v a2 s. c o m*/
 * Caution: This method run on same thread of caller. So if you want to run on NOT UI THREAD,
 * you have to use subscribeOn to specify thread model.
 *
 * @param uri
 * @param extraHeaders
 * @return
 */
public Observable<Event> connect(Uri uri, List<Pair<String, String>> extraHeaders) {
    this.disconnect(false);

    this.mUri = uri;
    this.mExtraHeaders = extraHeaders;
    this.mParser = new HybiParser(this);

    this.mHandlerThread = new HandlerThread(getClass().getName());
    this.mHandlerThread.start();
    this.mHandler = new Handler(mHandlerThread.getLooper());

    return Observable.create(new Observable.OnSubscribe<Event>() {
        @Override
        public void call(Subscriber<? super Event> subscriber) {
            try {
                mSubscriber = subscriber;
                String secret = createSecret();
                String scheme = mUri.getScheme();

                // uri have invalid scheme throw MalformedURLException
                if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) {
                    new MalformedURLException("Url scheme has to be specified as \"ws\" or \"wss\".");
                }

                int port = (mUri.getPort() != -1) ? mUri.getPort() : (scheme.equals("wss") ? 443 : 80);
                String path = TextUtils.isEmpty(mUri.getPath()) ? "/" : mUri.getPath();
                if (!TextUtils.isEmpty(mUri.getQuery())) {
                    path += "?" + mUri.getQuery();
                }

                String originScheme = scheme.equals("wss") ? "https" : "http";
                Uri origin = Uri.parse(originScheme + "://" + mUri.getHost());

                SocketFactory factory = scheme.equals("wss") ? getSSLSocketFactory()
                        : SocketFactory.getDefault();
                mSocket = factory.createSocket(mUri.getHost(), port);

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mUri.getHost() + "\r\n");
                out.print("Origin: " + origin.toString() + "\r\n");
                out.print("Sec-WebSocket-Key: " + secret + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (Pair<String, String> pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.first, pair.second));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                        mSocket.getInputStream());

                // Read HTTP response status line.
                StatusLine statusLine = parseStatusLine(readLine(stream));
                if (statusLine == null) {
                    throw new ConnectException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new ProtocolException(
                            "Server sent invalid response code " + statusLine.getStatusCode()
                                    + ". WebSocket server must return " + HttpStatus.SC_SWITCHING_PROTOCOLS);
                }

                // Read HTTP response headers.
                String line;
                boolean validated = false;

                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        String expected = createSecretValidation(secret);
                        String actual = header.getValue().trim();

                        if (!expected.equals(actual)) {
                            throw new ProtocolException("Bad Sec-WebSocket-Accept header value.");
                        }

                        validated = true;
                    }
                }

                if (!validated) {
                    throw new ProtocolException("No Sec-WebSocket-Accept header.");
                }

                mIsConnected = true;
                emitterOnNext(new Event(EventType.CONNECT));

                // Now decode websocket frames.
                mParser.start(stream);
            } catch (Exception e) {
                emitterOnError(e);
            }
        }
    }).doOnUnsubscribe(new Action0() {
        @Override
        public void call() {
            RxWebSocketClient.this.disconnect(false);
        }
    });
}

From source file:edina.eframework.gefcdemo.controllers.ProcessErosionController.java

/**
 * Brokers the WPS request and response. Supports two different WPS requests,
 * the landcover preview and the process soil erosion model requests.
 * /* www.ja  va 2  s . c  o m*/
 * @param params parameters used when calculating the soil erosion model
 * @param wpsResponse results from the WPS process are written to this object
 * @param template the VM template to use to generate the WPS request
 * @param wpsOutputFile the filename to write the TIFF result file
 * @throws IOException
 * @throws JAXBException
 */
private void generateWpsRequest(SoilErosionWps params, WpsResponse wpsResponse, String template,
        String wpsOutputFile) throws IOException, JAXBException {

    Writer wpsRequest = new StringWriter();
    Map<String, Object> velocityMap = new HashMap<String, Object>();

    velocityMap.put("params", params);

    VelocityEngineUtils.mergeTemplate(velocityEngine, template, velocityMap, wpsRequest);
    wpsRequest.close();

    log.debug(wpsRequest.toString());
    log.debug("Submitting to " + wpsServer);

    RequestEntity entity = null;
    try {
        entity = new StringRequestEntity(wpsRequest.toString(), "text/xml", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new MalformedURLException("Apparantly 'UTF-8' is an unsupported encoding type.");
    }

    PostMethod post = new PostMethod(wpsServer.toString());
    post.setRequestEntity(entity);

    HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

    client.getHttpConnectionManager().getParams().setSoTimeout(0);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(0);

    client.executeMethod(post);

    JAXBContext jaxbContext = JAXBContext.newInstance("edina.eframework.gefcdemo.generated.wps");
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    ExecuteResponse executeResponse = null;
    // First save post data into a String so we can log any potential errors.
    // Response isn't very large from the WPS so this shouldn't be a problem.
    // Trying to access post data if a direct InputStream is passed to unmarshal
    // doesn't work.
    String postData = post.getResponseBodyAsString();
    try {
        executeResponse = (ExecuteResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(postData.getBytes()));
    } catch (ClassCastException e) {
        log.error("Error from WPS:\n" + postData);
        throw e;
    }

    //executeResponse.getStatus().getProcessAccepted(); // TODO check for failed
    String resultUrl = executeResponse.getProcessOutputs().getOutput().get(0).getReference().getHref();

    log.debug("Output " + resultUrl);
    wpsResponse.setOutputUrl(new URL(resultUrl));
    wpsResponse.setOutputId(resultUrl.substring(resultUrl.lastIndexOf("id=") + 3, resultUrl.length()));
    wpsResponse.setStatus(200);

    // Save the WPS output data to a file mapserver can use
    File resultOutputFile = new File(wpsOutputFile);
    resultOutputFile.getParentFile().mkdirs();
    FileOutputStream resultFileStream = new FileOutputStream(resultOutputFile);
    InputStream resultInputFile = null;
    try {
        resultInputFile = wpsResponse.getOutputUrl().openStream();
        byte[] buffer = new byte[4096];
        int i;
        while ((i = resultInputFile.read(buffer)) != -1) {
            resultFileStream.write(buffer, 0, i);
        }
        resultFileStream.flush();
    } finally {
        try {
            resultInputFile.close();
        } catch (Exception e) {
        }
        try {
            resultFileStream.close();
        } catch (Exception e) {
        }
    }

    log.debug("Result saved to " + resultOutputFile);
}

From source file:sit.web.client.HttpHelper.java

/**
 *
 *
 * @param method//from w  w w.  ja  v a  2 s. c om
 * @param host
 * @param port
 * @param path
 * @param payload
 * @param mimeType mimetype as string e.g. "application/json" will be added
 * to the content type of the http call
 * @param charSet set charSet to null to omit sending a char flag (e.g. for
 * binary files)
 * @param isHTTPS
 * @param unamePword64
 * @return
 * @throws MalformedURLException
 * @throws ProtocolException
 * @throws IOException
 */
public HTTPResponse doHTTPRequest(String method, String host, int port, String path, String payload,
        String mimeType, Charset charSet, boolean isHTTPS, String unamePword64)
        throws MalformedURLException, ProtocolException, IOException {

    if (mimeType == null || mimeType.length() == 0) {
        mimeType = MimeTypes.getMimeType(""); //get unknown mime type if mimetype not set
    }
    String contentType = mimeType;
    if (charSet != null) {
        contentType += HttpConstants.SUB_FIELD_SEPARATOR + HttpConstants.CHARSET_CONTENT_TYPE_TAG
                + charSet.name(); //text/html; charset=utf-8
        //##CHARSET_MARKER##            
    } else {
        charSet = Charset.defaultCharset();
    }

    try {
        return doHTTPRequest(method, host, port, path, payload.getBytes(charSet), contentType, isHTTPS,
                unamePword64);
    } catch (URISyntaxException ex) {

        throw new MalformedURLException(ex.getMessage());
    }

}

From source file:org.mitre.mpf.mvc.controller.MediaController.java

@RequestMapping(value = "/saveURL", method = RequestMethod.POST)
@ResponseBody/*www.  j  a  v  a 2s  .  c  om*/
public Map<String, String> saveMedia(@RequestParam(value = "urls", required = true) String[] urls,
        @RequestParam(value = "desiredpath", required = true) String desiredpath, HttpServletResponse response)
        throws WfmProcessingException, MpfServiceException {
    log.debug("URL Upload to Directory:" + desiredpath + " urls:" + urls.length);

    String err = "Illegal or missing desiredpath";
    if (desiredpath == null) {
        log.error(err);
        throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err);
    }
    ;
    String webTmpDirectory = propertiesUtil.getRemoteMediaCacheDirectory().getAbsolutePath();
    //verify the desired path
    File desiredPath = new File(desiredpath);
    if (!desiredPath.exists() || !desiredPath.getAbsolutePath().startsWith(webTmpDirectory)) {//make sure it is valid and within the remote-media directory
        log.error(err);
        throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err);
    }

    //passing in urls as a list of Strings
    //download the media to the server
    //build a map of success or failure for each file with a custom response object
    Map<String, String> urlResultMap = new HashMap<String, String>();
    for (String enteredURL : urls) {
        enteredURL = enteredURL.trim();
        URI uri;
        try {
            uri = new URI(enteredURL);
            //the check for absolute URI determines if any scheme is present, regardless of validity
            //(which is checked in both this and the next try block)
            if (!uri.isAbsolute()) {
                uri = new URI("http://" + uri.toASCIIString());
            }
        } catch (URISyntaxException incorrectUriTranslation) {
            log.error("The string {} did not translate cleanly to a URI.", enteredURL, incorrectUriTranslation);
            urlResultMap.put(enteredURL, "String did not cleanly convert to URI");
            continue;
        }
        File newFile = null;
        String localName = null;
        try {
            URL url = uri.toURL(); //caught by MalformedURLException
            //will throw an IOException,which is already caught 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            connection.connect();
            connection.disconnect();

            String filename = url.getFile();
            if (filename.isEmpty()) {
                String err2 = "The filename does not exist when uploading from the url '" + url + "'";
                log.error(err2);
                urlResultMap.put(enteredURL, err2);
                continue;
            }

            if (!ioUtils.isApprovedFile(url)) {
                String contentType = ioUtils.getMimeType(url);
                String msg = "The media is not a supported type. Please add a whitelist." + contentType
                        + " entry to the mediaType.properties file.";
                log.error(msg + " URL:" + url);
                urlResultMap.put(enteredURL, msg);
                continue;
            }

            localName = uri.getPath();
            //we consider no path to be malformed for our purposes
            if (localName.isEmpty()) {
                throw new MalformedURLException(String.format("%s does not have valid path", uri));
            }

            //use the full path name for the filename to allow for more unique filenames
            localName = localName.substring(1);//remove the leading '/'
            localName = localName.replace("/", "-");//replace the rest of the path with -

            //get a new unique filename incase the name currently exists
            newFile = ioUtils.getNewFileName(desiredpath, localName);

            //save the file
            FileUtils.copyURLToFile(url, newFile);
            log.info("Completed write of {} to {}", uri.getPath(), newFile.getAbsolutePath());
            urlResultMap.put(enteredURL, "successful write to: " + newFile.getAbsolutePath());
        } catch (MalformedURLException badUrl) {
            log.error("URI {} could not be converted. ", uri, badUrl);
            urlResultMap.put(enteredURL, "Unable to locate media at the provided address.");
        } catch (IOException badWrite) {
            log.error("Error writing media to temp file from {}.", enteredURL, badWrite);
            urlResultMap.put(enteredURL,
                    "Unable to save media from this url. Please view the server logs for more information.");
            if (newFile != null && newFile.exists()) {
                newFile.delete();
            }
        } catch (Exception failure) { //catch the remaining exceptions
            //this is most likely a failed connection 
            log.error("Exception thrown while saving media from the url {}.", enteredURL, failure);
            urlResultMap.put(enteredURL,
                    "Error while saving media from this url. Please view the server logs for more information.");
        }
    }
    return urlResultMap;
}